text stringlengths 54 60.6k |
|---|
<commit_before>#include "util.h"
#include <mysql++.h>
#include <iostream>
using namespace std;
int
main(int argc, char *argv[])
{
try {
mysqlpp::Connection con(mysqlpp::use_exceptions);
if (!connect_to_db(argc, argv, con, "")) {
return 1;
}
bool created = false;
try {
con.select_db(kpcSampleDatabase);
}
catch (mysqlpp::BadQuery &) {
// Couldn't switch to the sample database, so assume that it
// doesn't exist and create it. If that doesn't work, exit
// with an error.
if (con.create_db(kpcSampleDatabase)) {
cerr << "Failed to create sample database." << endl;
return 1;
}
else if (!con.select_db(kpcSampleDatabase)) {
cerr << "Failed to select sample database." << endl;
return 1;
}
else {
created = true;
}
}
mysqlpp::Query query = con.query(); // create a new query object
try {
query.execute("drop table stock");
}
catch (mysqlpp::BadQuery&) {
// ignore any errors
}
// Send the query to create the table and execute it.
query << "create table stock (item char(20) not null, num bigint,"
<< "weight double, price double, sdate date)";
query.execute();
// Set up the template query to insert the data. The parse
// call tells the query object that this is a template and
// not a literal query string.
query << "insert into %5:table values (%0q, %1q, %2, %3, %4q)";
query.parse();
// This is setting the parameter named table to stock.
query.def["table"] = "stock";
// The last parameter "table" is not specified here. Thus the
// default value for "table" is used, which is "stock". Also,
// the bad grammar in the second row is intentional -- it is
// fixed by the custom3 example.
query.execute("Hamburger Buns", 56, 1.25, 1.1, "1998-04-26");
query.execute("Hotdogs' Buns", 65, 1.1, 1.1, "1998-04-23");
query.execute("Dinner Rolls", 75, .95, .97, "1998-05-25");
query.execute("White Bread", 87, 1.5, 1.75, "1998-09-04");
if (created) {
cout << "Created";
}
else {
cout << "Reinitialized";
}
cout << " sample database successfully." << endl;
}
catch (mysqlpp::BadQuery& er) {
// Handle any connection or query errors that may come up
cerr << "Error: " << er.what() << endl;
return -1;
}
catch (mysqlpp::BadConversion& er) {
// Handle bad conversions
cerr << "Error: " << er.what() << "\"." << endl
<< "retrieved data size: " << er.retrieved
<< " actual data size: " << er.actual_size << endl;
return -1;
}
catch (exception& er) {
cerr << "Error: " << er.what() << endl;
return -1;
}
}
<commit_msg>De-nested exception handling. Fixes crashes with g++ on Solaris, at least.<commit_after>#include "util.h"
#include <mysql++.h>
#include <iostream>
using namespace std;
int
main(int argc, char *argv[])
{
mysqlpp::Connection con(mysqlpp::use_exceptions);
try {
if (!connect_to_db(argc, argv, con, "")) {
return 1;
}
}
catch (exception& er) {
cerr << "Connection failed: " << er.what() << endl;
return 1;
}
bool created = false;
try {
con.select_db(kpcSampleDatabase);
}
catch (mysqlpp::BadQuery &) {
// Couldn't switch to the sample database, so assume that it
// doesn't exist and create it. If that doesn't work, exit
// with an error.
if (con.create_db(kpcSampleDatabase)) {
cerr << "Failed to create sample database." << endl;
return 1;
}
else if (!con.select_db(kpcSampleDatabase)) {
cerr << "Failed to select sample database." << endl;
return 1;
}
else {
created = true;
}
}
mysqlpp::Query query = con.query(); // create a new query object
try {
query.execute("drop table stock");
}
catch (mysqlpp::BadQuery&) {
// ignore any errors
}
try {
// Send the query to create the table and execute it.
query << "create table stock (item char(20) not null, num bigint,"
<< "weight double, price double, sdate date)";
query.execute();
// Set up the template query to insert the data. The parse
// call tells the query object that this is a template and
// not a literal query string.
query << "insert into %5:table values (%0q, %1q, %2, %3, %4q)";
query.parse();
// This is setting the parameter named table to stock.
query.def["table"] = "stock";
// The last parameter "table" is not specified here. Thus the
// default value for "table" is used, which is "stock". Also,
// the bad grammar in the second row is intentional -- it is
// fixed by the custom3 example.
query.execute("Hamburger Buns", 56, 1.25, 1.1, "1998-04-26");
query.execute("Hotdogs' Buns", 65, 1.1, 1.1, "1998-04-23");
query.execute("Dinner Rolls", 75, .95, .97, "1998-05-25");
query.execute("White Bread", 87, 1.5, 1.75, "1998-09-04");
if (created) {
cout << "Created";
}
else {
cout << "Reinitialized";
}
cout << " sample database successfully." << endl;
}
catch (mysqlpp::BadQuery& er) {
// Handle any connection or query errors that may come up
cerr << "Error: " << er.what() << endl;
return 1;
}
catch (mysqlpp::BadConversion& er) {
// Handle bad conversions
cerr << "Error: " << er.what() << "\"." << endl
<< "retrieved data size: " << er.retrieved
<< " actual data size: " << er.actual_size << endl;
return 1;
}
catch (exception& er) {
cerr << "Error: " << er.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "ccode.hpp"
#include <kdblogger.h>
namespace
{
/**
* @brief Cast a character to an unsigned character.
*
* @param character This parameter specifies the character this function casts to an unsigned value.
*
* @return A unsigned character corresponding to the given argument
*/
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
return static_cast<unsigned char> (character);
}
/**
* @brief This function maps hex characters to integer numbers.
*
* @pre The specified character has to be between
*
* - `'0'`–`'9'`,
* - `'a'`-`'f'`, or
* - `'A'`-`'F'`
*
* .
*
* @param character This argument specifies the (hexadecimal) character this function converts.
*
* @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
*/
inline int elektraHexcodeConvFromHex (char character)
{
if (character >= '0' && character <= '9') return character - '0';
if (character >= 'a' && character <= 'f') return character - 'a' + 10;
if (character >= 'A' && character <= 'F') return character - 'A' + 10;
return 0; /* Unknown escape char */
}
/**
* @brief This function returns a key set containing the contract of this plugin.
*
* @return A contract describing the functionality of this plugin.
*/
inline KeySet * contract (void)
{
return ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/ccode/exports", KEY_END),
keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
}
/**
* @brief Retrieve the mapping data and initialize the buffer if it is empty.
*
* @return The mapping data stored by this plugin.
*/
CCodeData * retrieveMapping (Plugin * handle)
{
CCodeData * const mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buffer)
{
mapping->bufferSize = 1000;
mapping->buffer = new unsigned char[mapping->bufferSize];
}
return mapping;
}
/**
* @brief This function sets default values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with default values.
*/
void setDefaultConfig (CCodeData * const mapping)
{
unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc }, { '\v'_uc, 'v'_uc },
{ '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
{ '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };
for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
{
unsigned char character = pairs[pair][0];
unsigned char replacement = pairs[pair][1];
mapping->encode[character] = replacement;
mapping->decode[replacement] = character;
}
}
/**
* @brief This function sets values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with the values specified in `config`.
* @param config This key set stores the character mappings this function stores inside `mappings`.
* @param root This key stores the root key for the character mapping stored in `config`.
*/
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
Key const * key = 0;
while ((key = ksNext (config)) != 0)
{
/* Ignore keys that are not directly below the config root key or have an incorrect size */
if (keyRel (root, key) != 1 || keyGetBaseNameSize (key) != 3 || keyGetValueSize (key) != 3) continue;
int character = elektraHexcodeConvFromHex (keyBaseName (key)[1]);
character += elektraHexcodeConvFromHex (keyBaseName (key)[0]) * 16;
int replacement = elektraHexcodeConvFromHex (keyString (key)[1]);
replacement += elektraHexcodeConvFromHex (keyString (key)[0]) * 16;
/* Hexencode this character! */
mapping->encode[character & 255] = replacement;
mapping->decode[replacement & 255] = character;
}
}
} // end namespace
using namespace ckdb;
extern "C" {
/**
* @brief This function replaces escaped character in a key value with unescaped characters.
*
* The function stores the unescaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be as large as the key value’s size.
*
* @param key This key holds the value this function decodes.
* @param mapping This variable stores the buffer and the character mapping this function uses to decode the value of the given key.
*/
void elektraCcodeDecode (Key * key, CCodeData * mapping)
{
const char * value = static_cast<const char *> (keyValue (key));
if (!value) return;
size_t const size = keyGetValueSize (key) - 1;
size_t out = 0;
for (size_t in = 0; in < size; ++in)
{
unsigned char character = value[in];
if (character == mapping->escape)
{
++in; /* Advance twice */
character = value[in];
mapping->buffer[out] = mapping->decode[character & 255];
}
else
{
mapping->buffer[out] = character;
}
++out; /* Only one char is written */
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (key, mapping->buffer, out + 1);
}
/**
* @brief This function replaces unescaped character in a key value with escaped characters.
*
* The function stores the escaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be twice as large as the key value’s size.
*
* @param key This key stores the value this function escapes.
* @param mapping This variable stores the buffer and the character mapping this function uses to encode the value of the given key.
*/
void elektraCcodeEncode (Key * key, CCodeData * mapping)
{
const char * value = static_cast<const char *> (keyValue (key));
if (!value) return;
size_t const size = keyGetValueSize (key);
size_t out = 0;
for (size_t in = 0; in < size - 1; ++in)
{
unsigned char character = value[in];
if (mapping->encode[character])
{
mapping->buffer[out + 1] = mapping->encode[character];
// Escape char
mapping->buffer[out] = mapping->escape;
out += 2;
}
else
{
// just copy one character
mapping->buffer[out] = value[in];
// advance out cursor
out++;
}
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (key, mapping->buffer, out + 1);
}
// ====================
// = Plugin Interface =
// ====================
/** @see elektraDocOpen */
int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * const mapping = new CCodeData ();
/* Store for later use...*/
elektraPluginSetData (handle, mapping);
KeySet * const config = elektraPluginGetConfig (handle);
Key const * const escape = ksLookupByName (config, "/escape", 0);
mapping->escape = '\\';
if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
{
int escapeChar = elektraHexcodeConvFromHex (keyString (escape)[1]);
escapeChar += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;
mapping->escape = escapeChar & 255;
}
ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);
Key const * const root = ksLookupByName (config, "/chars", 0);
if (root)
{
readConfig (mapping, config, root);
}
else
{
setDefaultConfig (mapping);
}
return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}
/** @see elektraDocClose */
int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * const mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
delete[](mapping->buffer);
delete (mapping);
return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}
/** @see elektraDocGet */
int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
{
KeySet * const pluginConfig = contract ();
ksAppend (returned, pluginConfig);
ksDel (pluginConfig);
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
CCodeData * const mapping = retrieveMapping (handle);
Key * key;
ksRewind (returned);
while ((key = ksNext (returned)) != 0)
{
size_t const valsize = keyGetValueSize (key);
if (valsize > mapping->bufferSize)
{
mapping->bufferSize = valsize;
mapping->buffer = new unsigned char[mapping->bufferSize];
}
elektraCcodeDecode (key, mapping);
}
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
/** @see elektraDocSet */
int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
CCodeData * const mapping = retrieveMapping (handle);
Key * key;
ksRewind (returned);
while ((key = ksNext (returned)) != 0)
{
size_t const valsize = keyGetValueSize (key);
if (valsize * 2 > mapping->bufferSize)
{
mapping->bufferSize = valsize * 2;
mapping->buffer = new unsigned char[mapping->bufferSize];
}
elektraCcodeEncode (key, mapping);
}
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
// clang-format off
return elektraPluginExport("ccode",
ELEKTRA_PLUGIN_OPEN, &elektraCcodeOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraCcodeClose,
ELEKTRA_PLUGIN_GET, &elektraCcodeGet,
ELEKTRA_PLUGIN_SET, &elektraCcodeSet,
ELEKTRA_PLUGIN_END);
}
} // end extern "C"
<commit_msg>CCode: Update variable names<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "ccode.hpp"
#include <kdblogger.h>
namespace
{
/**
* @brief Cast a character to an unsigned character.
*
* @param character This parameter specifies the character this function casts to an unsigned value.
*
* @return A unsigned character corresponding to the given argument
*/
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
return static_cast<unsigned char> (character);
}
/**
* @brief This function maps hex characters to integer numbers.
*
* @pre The specified character has to be between
*
* - `'0'`–`'9'`,
* - `'a'`-`'f'`, or
* - `'A'`-`'F'`
*
* .
*
* @param character This argument specifies the (hexadecimal) character this function converts.
*
* @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
*/
inline int elektraHexcodeConvFromHex (char character)
{
if (character >= '0' && character <= '9') return character - '0';
if (character >= 'a' && character <= 'f') return character - 'a' + 10;
if (character >= 'A' && character <= 'F') return character - 'A' + 10;
return 0; /* Unknown escape char */
}
/**
* @brief This function returns a key set containing the contract of this plugin.
*
* @return A contract describing the functionality of this plugin.
*/
inline KeySet * contract (void)
{
return ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/ccode/exports", KEY_END),
keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
}
/**
* @brief Retrieve the mapping data and initialize the buffer if it is empty.
*
* @return The mapping data stored by this plugin.
*/
CCodeData * retrieveMapping (Plugin * handle)
{
CCodeData * const mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buffer)
{
mapping->bufferSize = 1000;
mapping->buffer = new unsigned char[mapping->bufferSize];
}
return mapping;
}
/**
* @brief This function sets default values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with default values.
*/
void setDefaultConfig (CCodeData * const mapping)
{
unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc }, { '\v'_uc, 'v'_uc },
{ '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
{ '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };
for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
{
unsigned char character = pairs[pair][0];
unsigned char replacement = pairs[pair][1];
mapping->encode[character] = replacement;
mapping->decode[replacement] = character;
}
}
/**
* @brief This function sets values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with the values specified in `config`.
* @param config This key set stores the character mappings this function stores inside `mappings`.
* @param root This key stores the root key for the character mapping stored in `config`.
*/
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
Key const * key = 0;
while ((key = ksNext (config)) != 0)
{
/* Ignore keys that are not directly below the config root key or have an incorrect size */
if (keyRel (root, key) != 1 || keyGetBaseNameSize (key) != 3 || keyGetValueSize (key) != 3) continue;
int character = elektraHexcodeConvFromHex (keyBaseName (key)[1]);
character += elektraHexcodeConvFromHex (keyBaseName (key)[0]) * 16;
int replacement = elektraHexcodeConvFromHex (keyString (key)[1]);
replacement += elektraHexcodeConvFromHex (keyString (key)[0]) * 16;
/* Hexencode this character! */
mapping->encode[character & 255] = replacement;
mapping->decode[replacement & 255] = character;
}
}
} // end namespace
using namespace ckdb;
extern "C" {
/**
* @brief This function replaces escaped character in a key value with unescaped characters.
*
* The function stores the unescaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be as large as the key value’s size.
*
* @param key This key holds the value this function decodes.
* @param mapping This variable stores the buffer and the character mapping this function uses to decode the value of the given key.
*/
void elektraCcodeDecode (Key * key, CCodeData * mapping)
{
const char * value = static_cast<const char *> (keyValue (key));
if (!value) return;
size_t const size = keyGetValueSize (key) - 1;
size_t out = 0;
for (size_t in = 0; in < size; ++in)
{
unsigned char character = value[in];
if (character == mapping->escape)
{
++in; /* Advance twice */
character = value[in];
mapping->buffer[out] = mapping->decode[character & 255];
}
else
{
mapping->buffer[out] = character;
}
++out; /* Only one char is written */
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (key, mapping->buffer, out + 1);
}
/**
* @brief This function replaces unescaped character in a key value with escaped characters.
*
* The function stores the escaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be twice as large as the key value’s size.
*
* @param key This key stores the value this function escapes.
* @param mapping This variable stores the buffer and the character mapping this function uses to encode the value of the given key.
*/
void elektraCcodeEncode (Key * key, CCodeData * mapping)
{
const char * value = static_cast<const char *> (keyValue (key));
if (!value) return;
size_t const size = keyGetValueSize (key);
size_t out = 0;
for (size_t in = 0; in < size - 1; ++in)
{
unsigned char character = value[in];
if (mapping->encode[character])
{
mapping->buffer[out + 1] = mapping->encode[character];
// Escape char
mapping->buffer[out] = mapping->escape;
out += 2;
}
else
{
// just copy one character
mapping->buffer[out] = value[in];
// advance out cursor
out++;
}
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (key, mapping->buffer, out + 1);
}
// ====================
// = Plugin Interface =
// ====================
/** @see elektraDocOpen */
int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * const mapping = new CCodeData ();
/* Store for later use...*/
elektraPluginSetData (handle, mapping);
KeySet * const config = elektraPluginGetConfig (handle);
Key const * const escape = ksLookupByName (config, "/escape", 0);
mapping->escape = '\\';
if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
{
int escapeChar = elektraHexcodeConvFromHex (keyString (escape)[1]);
escapeChar += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;
mapping->escape = escapeChar & 255;
}
ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);
Key const * const root = ksLookupByName (config, "/chars", 0);
if (root)
{
readConfig (mapping, config, root);
}
else
{
setDefaultConfig (mapping);
}
return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}
/** @see elektraDocClose */
int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * const mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
delete[](mapping->buffer);
delete (mapping);
return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}
/** @see elektraDocGet */
int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
{
KeySet * const pluginConfig = contract ();
ksAppend (returned, pluginConfig);
ksDel (pluginConfig);
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
CCodeData * const mapping = retrieveMapping (handle);
Key * key;
ksRewind (returned);
while ((key = ksNext (returned)) != 0)
{
size_t const size = keyGetValueSize (key);
if (size > mapping->bufferSize)
{
mapping->bufferSize = size;
mapping->buffer = new unsigned char[mapping->bufferSize];
}
elektraCcodeDecode (key, mapping);
}
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
/** @see elektraDocSet */
int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
CCodeData * const mapping = retrieveMapping (handle);
Key * key;
ksRewind (returned);
while ((key = ksNext (returned)) != 0)
{
size_t const size = keyGetValueSize (key) * 2;
if (size > mapping->bufferSize)
{
mapping->bufferSize = size;
mapping->buffer = new unsigned char[mapping->bufferSize];
}
elektraCcodeEncode (key, mapping);
}
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
// clang-format off
return elektraPluginExport("ccode",
ELEKTRA_PLUGIN_OPEN, &elektraCcodeOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraCcodeClose,
ELEKTRA_PLUGIN_GET, &elektraCcodeGet,
ELEKTRA_PLUGIN_SET, &elektraCcodeSet,
ELEKTRA_PLUGIN_END);
}
} // end extern "C"
<|endoftext|> |
<commit_before>// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// illarionserver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include "db/ConnectionManager.hpp"
#include "db/Connection.hpp"
#include <sstream>
#include <string>
#include <stdexcept>
#include <boost/cstdint.hpp>
#include <pqxx/connection.hxx>
using namespace Database;
ConnectionManager ConnectionManager::instance;
PConnectionManager ConnectionManager::getInstance() {
return &ConnectionManager::instance;
}
PConnection ConnectionManager::getConnection() {
if (!this->isReady) {
throw new std::domain_error("Connection Manager is yet not setup");
}
return new Connection(new pqxx::connection(*(this->connectString)));
}
void ConnectionManager::releaseConnection(const PConnection conn) {
delete conn;
}
ConnectionManager::ConnectionManager() {
this->isReady = false;
};
ConnectionManager::ConnectionManager(const ConnectionManager &org) {
throw new std::domain_error("Copy constructor not supported.");
}
void ConnectionManager::setupManager(const std::string &user, const std::string &password,
const std::string &database, const std::string &host) {
this->setupManager(user, password, database, host, "");
}
void ConnectionManager::setupManager(const std::string &user, const std::string &password,
const std::string &database, const std::string &host,
const uint16_t port) {
std::stringstream ss;
ss << port;
std::string portString;
portString = ss.str();
setupManager(user, password, database, host, portString);
}
void ConnectionManager::setupManager(const std::string &user,
const std::string &password, const std::string &database,
const std::string &host, const std::string &port) {
std::stringstream ss;
if (user.size() > 0) {
ss << " user=" << user << " ";
}
if (password.size() > 0) {
ss << " password=" << password << " ";
}
if (database.size() > 0) {
ss << " dbname=" << database << " ";
}
if (host.size() > 0) {
ss << " host=" << host << " ";
}
if (port.size() > 0) {
ss << " port=" << port << " ";
}
this->connectString = new std::string(ss.str());
this->isReady = true;
}
}
<commit_msg>remove explicit this pointers<commit_after>// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// illarionserver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include "db/ConnectionManager.hpp"
#include "db/Connection.hpp"
#include <sstream>
#include <string>
#include <stdexcept>
#include <boost/cstdint.hpp>
#include <pqxx/connection.hxx>
using namespace Database;
ConnectionManager ConnectionManager::instance;
PConnectionManager ConnectionManager::getInstance() {
return &ConnectionManager::instance;
}
PConnection ConnectionManager::getConnection() {
if (!isReady) {
throw new std::domain_error("Connection Manager is yet not setup");
}
return new Connection(new pqxx::connection(*(connectString)));
}
void ConnectionManager::releaseConnection(const PConnection conn) {
delete conn;
}
ConnectionManager::ConnectionManager() {
isReady = false;
};
ConnectionManager::ConnectionManager(const ConnectionManager &org) {
throw new std::domain_error("Copy constructor not supported.");
}
void ConnectionManager::setupManager(const std::string &user, const std::string &password,
const std::string &database, const std::string &host) {
setupManager(user, password, database, host, "");
}
void ConnectionManager::setupManager(const std::string &user, const std::string &password,
const std::string &database, const std::string &host,
const uint16_t port) {
std::stringstream ss;
ss << port;
std::string portString;
portString = ss.str();
setupManager(user, password, database, host, portString);
}
void ConnectionManager::setupManager(const std::string &user,
const std::string &password, const std::string &database,
const std::string &host, const std::string &port) {
std::stringstream ss;
if (user.size() > 0) {
ss << " user=" << user << " ";
}
if (password.size() > 0) {
ss << " password=" << password << " ";
}
if (database.size() > 0) {
ss << " dbname=" << database << " ";
}
if (host.size() > 0) {
ss << " host=" << host << " ";
}
if (port.size() > 0) {
ss << " port=" << port << " ";
}
connectString = new std::string(ss.str());
isReady = true;
}
}
<|endoftext|> |
<commit_before>// 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.
#ifndef __STOUT_OS_WINDOWS_SHELL_HPP__
#define __STOUT_OS_WINDOWS_SHELL_HPP__
#include <process.h>
#include <stdarg.h> // For va_list, va_start, etc.
#include <ostream>
#include <string>
#include <stout/try.hpp>
namespace os {
namespace Shell {
// Canonical constants used as platform-dependent args to `exec` calls.
// `name` is the command name, `arg0` is the first argument received
// by the callee, usually the command name and `arg1` is the second
// command argument received by the callee.
constexpr const char* name = "cmd.exe";
constexpr const char* arg0 = "cmd";
constexpr const char* arg1 = "/c";
} // namespace Shell {
// Runs a shell command formatted with varargs and return the return value
// of the command. Optionally, the output is returned via an argument.
// TODO(vinod): Pass an istream object that can provide input to the command.
template <typename... T>
Try<std::string> shell(const std::string& fmt, const T... t) = delete;
// Executes a command by calling "cmd /c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error
inline int system(const std::string& command)
{
return ::_spawnlp(
_P_WAIT, Shell::name, Shell::arg0, Shell::arg1, command.c_str(), NULL);
}
template<typename... T>
inline int execlp(const char* file, T... t)
{
exit(::_spawnlp(_P_WAIT, file, t...));
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_SHELL_HPP__
<commit_msg>Windows: Implemented `os::shell`.<commit_after>// 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.
#ifndef __STOUT_OS_WINDOWS_SHELL_HPP__
#define __STOUT_OS_WINDOWS_SHELL_HPP__
#include <process.h>
#include <stdarg.h> // For va_list, va_start, etc.
#include <ostream>
#include <string>
#include <stout/try.hpp>
namespace os {
namespace Shell {
// Canonical constants used as platform-dependent args to `exec` calls.
// `name` is the command name, `arg0` is the first argument received
// by the callee, usually the command name and `arg1` is the second
// command argument received by the callee.
constexpr const char* name = "cmd.exe";
constexpr const char* arg0 = "cmd";
constexpr const char* arg1 = "/c";
} // namespace Shell {
/**
* Runs a shell command with optional arguments.
*
* This assumes that a successful execution will result in the exit code
* for the command to be `EXIT_SUCCESS`; in this case, the contents
* of the `Try` will be the contents of `stdout`.
*
* If the exit code is non-zero or the process was signaled, we will
* return an appropriate error message; but *not* `stderr`.
*
* If the caller needs to examine the contents of `stderr` it should
* be redirected to `stdout` (using, e.g., "2>&1 || true" in the command
* string). The `|| true` is required to obtain a success exit
* code in case of errors, and still obtain `stderr`, as piped to
* `stdout`.
*
* @param fmt the formatting string that contains the command to execute
* in the underlying shell.
* @param t optional arguments for `fmt`.
*
* @return the output from running the specified command with the shell; or
* an error message if the command's exit code is non-zero.
*/
template <typename... T>
Try<std::string> shell(const std::string& fmt, const T&... t)
{
const Try<std::string> command = strings::internal::format(fmt, t...);
if (command.isError()) {
return Error(command.error());
}
FILE* file;
std::ostringstream stdoutstr;
if ((file = _popen(command.get().c_str(), "r")) == NULL) {
return Error("Failed to run '" + command.get() + "'");
}
char line[1024];
// NOTE(vinod): Ideally the if and while loops should be interchanged. But
// we get a broken pipe error if we don't read the output and simply close.
while (fgets(line, sizeof(line), file) != NULL) {
stdoutstr << line;
}
if (ferror(file) != 0) {
_pclose(file); // Ignoring result since we already have an error.
return Error("Error reading output of '" + command.get() + "'");
}
int status;
if ((status = _pclose(file)) == -1) {
return Error("Failed to get status of '" + command.get() + "'");
}
return stdoutstr.str();
}
// Executes a command by calling "cmd /c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error
inline int system(const std::string& command)
{
return ::_spawnlp(
_P_WAIT, Shell::name, Shell::arg0, Shell::arg1, command.c_str(), NULL);
}
template<typename... T>
inline int execlp(const char* file, T... t)
{
exit(::_spawnlp(_P_WAIT, file, t...));
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_SHELL_HPP__
<|endoftext|> |
<commit_before>///
/// @file iterator.cpp
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/imath.hpp>
#include <primesieve/PrimeFinder.hpp>
#include <primesieve.hpp>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
namespace primesieve {
iterator::iterator(uint64_t start, uint64_t stop_hint)
{
skipto(start, stop_hint);
}
void iterator::set_stop_hint(uint64_t stop_hint)
{
stop_hint_ = stop_hint;
}
void iterator::clear()
{
skipto(0);
}
void iterator::skipto(uint64_t start, uint64_t stop_hint)
{
if (start_ > get_max_stop())
throw primesieve_error("start must be <= " + PrimeFinder::getMaxStopString());
start_ = start;
stop_ = start;
stop_hint_ = stop_hint;
i_ = 0;
last_idx_ = 0;
count_ = 0;
primes_.clear();
}
uint64_t add_overflow_safe(uint64_t a, uint64_t b)
{
uint64_t max_stop = get_max_stop();
return (a < max_stop - b) ? a + b : max_stop;
}
uint64_t subtract_underflow_safe(uint64_t a, uint64_t b)
{
return (a > b) ? a - b : 0;
}
void iterator::generate_next_primes()
{
bool first = primes_.empty();
uint64_t max_stop = get_max_stop();
primes_.clear();
while (primes_.empty())
{
if (!first)
start_ = add_overflow_safe(stop_, 1);
first = false;
stop_ = add_overflow_safe(start_, get_interval_size(start_));
if (start_ <= stop_hint_ && stop_ >= stop_hint_)
stop_ = add_overflow_safe(stop_hint_, max_prime_gap(stop_hint_));
primesieve::generate_primes(start_, stop_, &primes_);
if (primes_.empty() && stop_ >= max_stop)
throw primesieve_error("next_prime() > " + PrimeFinder::getMaxStopString());
}
last_idx_ = primes_.size() - 1;
i_ = 0;
}
void iterator::generate_previous_primes()
{
bool first = primes_.empty();
primes_.clear();
while (primes_.empty())
{
if (!first)
stop_ = subtract_underflow_safe(start_, 1);
first = false;
uint64_t interval_size = get_interval_size(stop_);
start_ = subtract_underflow_safe(stop_, interval_size);
if (start_ <= stop_hint_ && stop_ >= stop_hint_)
start_ = subtract_underflow_safe(stop_hint_, max_prime_gap(stop_hint_));
primesieve::generate_primes(start_, stop_, &primes_);
if (primes_.empty() && start_ < 2)
throw primesieve_error("previous_prime(): smallest prime is 2");
}
last_idx_ = primes_.size() - 1;
i_ = last_idx_;
}
/// Calculate an interval size that ensures a good load balance.
/// @param n Start or stop number.
///
uint64_t iterator::get_interval_size(uint64_t n)
{
double x = std::max(static_cast<double>(n), 10.0);
double sqrtx = std::sqrt(x);
uint64_t sqrtx_primes = static_cast<uint64_t>(sqrtx / (std::log(sqrtx) - 1));
uint64_t cache_max_primes = config::ITERATOR_CACHE_LARGE / sizeof(uint64_t);
uint64_t cache_bytes = (count_++ < 10) ? 1024 << count_ : config::ITERATOR_CACHE_MEDIUM;
uint64_t cache_primes = cache_bytes / sizeof(uint64_t);
uint64_t primes = std::min(std::max(cache_primes, sqrtx_primes), cache_max_primes);
return static_cast<uint64_t>(primes * std::log(x));
}
} // end namespace
<commit_msg>Refactoring<commit_after>///
/// @file iterator.cpp
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/imath.hpp>
#include <primesieve/PrimeFinder.hpp>
#include <primesieve.hpp>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
namespace primesieve {
iterator::iterator(uint64_t start, uint64_t stop_hint)
{
skipto(start, stop_hint);
}
void iterator::set_stop_hint(uint64_t stop_hint)
{
stop_hint_ = stop_hint;
}
void iterator::clear()
{
skipto(0);
}
void iterator::skipto(uint64_t start, uint64_t stop_hint)
{
if (start_ > get_max_stop())
throw primesieve_error("start must be <= " + PrimeFinder::getMaxStopString());
start_ = start;
stop_ = start;
stop_hint_ = stop_hint;
i_ = 0;
last_idx_ = 0;
count_ = 0;
primes_.clear();
}
uint64_t add_overflow_safe(uint64_t a, uint64_t b)
{
uint64_t max_stop = get_max_stop();
return (a < max_stop - b) ? a + b : max_stop;
}
uint64_t subtract_underflow_safe(uint64_t a, uint64_t b)
{
return (a > b) ? a - b : 0;
}
void iterator::generate_next_primes()
{
bool first = primes_.empty();
uint64_t max_stop = get_max_stop();
primes_.clear();
while (primes_.empty())
{
if (!first)
start_ = add_overflow_safe(stop_, 1);
first = false;
stop_ = add_overflow_safe(start_, get_interval_size(start_));
if (start_ <= stop_hint_ && stop_ >= stop_hint_)
stop_ = add_overflow_safe(stop_hint_, max_prime_gap(stop_hint_));
primesieve::generate_primes(start_, stop_, &primes_);
if (primes_.empty() && stop_ >= max_stop)
throw primesieve_error("next_prime() > " + PrimeFinder::getMaxStopString());
}
last_idx_ = primes_.size() - 1;
i_ = 0;
}
void iterator::generate_previous_primes()
{
bool first = primes_.empty();
primes_.clear();
while (primes_.empty())
{
if (!first)
stop_ = subtract_underflow_safe(start_, 1);
first = false;
uint64_t interval_size = get_interval_size(stop_);
start_ = subtract_underflow_safe(stop_, interval_size);
if (start_ <= stop_hint_ && stop_ >= stop_hint_)
start_ = subtract_underflow_safe(stop_hint_, max_prime_gap(stop_hint_));
primesieve::generate_primes(start_, stop_, &primes_);
if (primes_.empty() && start_ < 2)
throw primesieve_error("previous_prime(): smallest prime is 2");
}
last_idx_ = primes_.size() - 1;
i_ = last_idx_;
}
/// Calculate an interval size that ensures a good load balance.
/// @param n Start or stop number.
///
uint64_t iterator::get_interval_size(uint64_t n)
{
double x = std::max(static_cast<double>(n), 10.0);
double sqrtx = std::sqrt(x);
uint64_t sqrtx_primes = static_cast<uint64_t>(sqrtx / (std::log(sqrtx) - 1));
uint64_t cache_max_primes = config::ITERATOR_CACHE_LARGE / sizeof(uint64_t);
uint64_t cache_bytes = (count_++ < 10) ? 1024 << count_ : config::ITERATOR_CACHE_MEDIUM;
uint64_t cache_primes = cache_bytes / sizeof(uint64_t);
uint64_t primes = std::min(std::max(cache_primes, sqrtx_primes), cache_max_primes);
return static_cast<uint64_t>(primes * std::log(x));
}
} // end namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: config.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2005-02-16 17:57:48 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXSIDS_HRC //autogen
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef CONFIG_HXX
#include "config.hxx"
#endif
#ifndef FORMAT_HXX
#include "format.hxx"
#endif
#ifndef _SMMOD_HXX
#include "smmod.hxx"
#endif
#ifndef _STARMATH_HRC
#include "starmath.hrc"
#endif
/////////////////////////////////////////////////////////////////
SmConfig::SmConfig()
{
}
SmConfig::~SmConfig()
{
}
void SmConfig::ItemSetToConfig(const SfxItemSet &rSet)
{
const SfxPoolItem *pItem = NULL;
UINT16 nU16;
BOOL bVal;
if (rSet.GetItemState(SID_PRINTSIZE, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintSize( (SmPrintSize) nU16 );
}
if (rSet.GetItemState(SID_PRINTZOOM, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintZoomFactor( nU16 );
}
if (rSet.GetItemState(SID_PRINTTITLE, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintTitle( bVal );
}
if (rSet.GetItemState(SID_PRINTTEXT, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFormulaText( bVal );
}
if (rSet.GetItemState(SID_PRINTFRAME, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFrame( bVal );
}
if (rSet.GetItemState(SID_AUTOREDRAW, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetAutoRedraw( bVal );
}
if (rSet.GetItemState(SID_NO_RIGHT_SPACES, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
if (IsIgnoreSpacesRight() != bVal)
{
SetIgnoreSpacesRight( bVal );
// (angezeigte) Formeln muessen entsprechen neu formatiert werden.
// Das erreichen wir mit:
Broadcast(SfxSimpleHint(HINT_FORMATCHANGED));
}
}
}
void SmConfig::ConfigToItemSet(SfxItemSet &rSet) const
{
const SfxItemPool *pPool = rSet.GetPool();
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTSIZE),
(UINT16) GetPrintSize()));
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTZOOM),
(UINT16) GetPrintZoomFactor()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTITLE), IsPrintTitle()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTEXT), IsPrintFormulaText()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTFRAME), IsPrintFrame()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_AUTOREDRAW), IsAutoRedraw()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_NO_RIGHT_SPACES), IsIgnoreSpacesRight()));
}
/////////////////////////////////////////////////////////////////
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.76); FILE MERGED 2005/09/05 17:37:29 rt 1.8.76.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: config.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-07 15:05:21 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXSIDS_HRC //autogen
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef CONFIG_HXX
#include "config.hxx"
#endif
#ifndef FORMAT_HXX
#include "format.hxx"
#endif
#ifndef _SMMOD_HXX
#include "smmod.hxx"
#endif
#ifndef _STARMATH_HRC
#include "starmath.hrc"
#endif
/////////////////////////////////////////////////////////////////
SmConfig::SmConfig()
{
}
SmConfig::~SmConfig()
{
}
void SmConfig::ItemSetToConfig(const SfxItemSet &rSet)
{
const SfxPoolItem *pItem = NULL;
UINT16 nU16;
BOOL bVal;
if (rSet.GetItemState(SID_PRINTSIZE, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintSize( (SmPrintSize) nU16 );
}
if (rSet.GetItemState(SID_PRINTZOOM, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintZoomFactor( nU16 );
}
if (rSet.GetItemState(SID_PRINTTITLE, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintTitle( bVal );
}
if (rSet.GetItemState(SID_PRINTTEXT, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFormulaText( bVal );
}
if (rSet.GetItemState(SID_PRINTFRAME, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFrame( bVal );
}
if (rSet.GetItemState(SID_AUTOREDRAW, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetAutoRedraw( bVal );
}
if (rSet.GetItemState(SID_NO_RIGHT_SPACES, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
if (IsIgnoreSpacesRight() != bVal)
{
SetIgnoreSpacesRight( bVal );
// (angezeigte) Formeln muessen entsprechen neu formatiert werden.
// Das erreichen wir mit:
Broadcast(SfxSimpleHint(HINT_FORMATCHANGED));
}
}
}
void SmConfig::ConfigToItemSet(SfxItemSet &rSet) const
{
const SfxItemPool *pPool = rSet.GetPool();
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTSIZE),
(UINT16) GetPrintSize()));
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTZOOM),
(UINT16) GetPrintZoomFactor()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTITLE), IsPrintTitle()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTEXT), IsPrintFormulaText()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTFRAME), IsPrintFrame()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_AUTOREDRAW), IsAutoRedraw()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_NO_RIGHT_SPACES), IsIgnoreSpacesRight()));
}
/////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANMEMORYMANAGEMENT_HEADER_GUARD_1357924680)
#define XALANMEMORYMANAGEMENT_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <cstddef>
#include <new>
#include <xercesc/framework/MemoryManager.hpp>
XALAN_CPP_NAMESPACE_BEGIN
typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager MemoryManagerType;
class XalanAllocationGuard
{
public:
#if defined(XALAN_STRICT_ANSI_HEADERS)
typedef std::size_t size_type;
#else
typedef size_t size_type;
#endif
XalanAllocationGuard(
MemoryManagerType& theMemoryManager,
void* thePointer) :
m_memoryManager(theMemoryManager),
m_pointer(thePointer)
{
}
XalanAllocationGuard(
MemoryManagerType& theMemoryManager,
size_type theSize) :
m_memoryManager(theMemoryManager),
m_pointer(theMemoryManager.allocate(theSize))
{
}
~XalanAllocationGuard()
{
if (m_pointer != 0)
{
m_memoryManager.deallocate(m_pointer);
}
}
void*
get() const
{
return m_pointer;
}
void
release()
{
m_pointer = 0;
}
private:
// Data members...
MemoryManagerType& m_memoryManager;
void* m_pointer;
};
template<class Type>
void
XalanDestroy(Type& theArg)
{
theArg.~Type();
}
template<class Type>
void
XalanDestroy(Type* theArg)
{
if (theArg != 0)
{
theArg->~Type();
}
}
template<class Type>
void
XalanDestroy(
MemoryManagerType& theMemoryManager,
Type* theArg)
{
if (theArg != 0)
{
XalanDestroy(*theArg);
theMemoryManager.deallocate(theArg);
}
}
template<class Type>
void
XalanDestroy(
MemoryManagerType& theMemoryManager,
Type& theArg)
{
XalanDestroy(theArg);
theMemoryManager.deallocate(&theArg);
}
template<class Type>
Type*
XalanConstruct(
MemoryManagerType& theMemoryManager,
Type*& theInstance)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type;
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type>
Type*
XalanConstruct(
MemoryManagerType& theMemoryManager,
Type*& theInstance,
const Param1Type& theParam1)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type>
Type*
XalanConstruct(
MemoryManagerType& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type>
Type*
XalanConstruct(
MemoryManagerType& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
const Param2Type& theParam2)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type,
class Param3Type>
Type*
XalanConstruct(
MemoryManagerType& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
const Param2Type& theParam2,
Param3Type& theParam3)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2, theParam3);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type,
class Param3Type,
class Param4Type,
class Param5Type>
Type*
XalanConstruct(
MemoryManagerType& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
Param2Type& theParam2,
const Param3Type& theParam3,
const Param4Type& theParam4,
const Param5Type& theParam5)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2, theParam3, theParam4, theParam5);
theGuard.release();
return theInstance;
}
template<class Type>
Type*
XalanCopyConstruct(
MemoryManagerType& theMemoryManager,
const Type& theSource)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
Type* const theInstance =
new (theGuard.get()) Type(theSource);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type>
Type*
XalanCopyConstruct(
MemoryManagerType& theMemoryManager,
const Type& theSource,
Param1Type& theParam1)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
Type* const theInstance =
new (theGuard.get()) Type(theSource, theParam1);
theGuard.release();
return theInstance;
}
class XALAN_PLATFORM_EXPORT XalanMemMgrs
{
public:
static MemoryManagerType&
getDummyMemMgr();
static MemoryManagerType&
getDefaultXercesMemMgr();
static MemoryManagerType&
getDefault()
{
return getDefaultXercesMemMgr();
}
};
#if defined (XALAN_DEVELOPMENT)
#define XALAN_DEFAULT_CONSTRACTOR_MEMORY_MGR
#define XALAN_DEFAULT_MEMMGR = XalanMemMgrs::getDummyMemMgr()
#else
#define XALAN_DEFAULT_CONSTRACTOR_MEMORY_MGR = XalanMemMgrs::getDefaultXercesMemMgr()
#define XALAN_DEFAULT_MEMMGR = XalanMemMgrs::getDefaultXercesMemMgr()
#endif
template <class C>
struct ConstructValueWithNoMemoryManager
{
ConstructValueWithNoMemoryManager(MemoryManagerType& /*mgr*/) :
value()
{
}
C value;
};
template <class C>
struct ConstructValueWithMemoryManager
{
ConstructValueWithMemoryManager(MemoryManagerType& mgr) :
value(mgr)
{
}
C value;
};
template <class C>
struct ConstructWithNoMemoryManager
{
typedef ConstructValueWithNoMemoryManager<C> ConstructableType;
static C* construct(C* address, MemoryManagerType& /* mgr */)
{
return (C*) new (address) C;
}
static C* construct(C* address, const C& theRhs, MemoryManagerType& /* mgr */)
{
return (C*) new (address) C(theRhs);
}
};
template <class C>
struct ConstructWithMemoryManager
{
typedef ConstructValueWithMemoryManager<C> ConstructableType;
static C* construct(C* address, MemoryManagerType& mgr)
{
return (C*) new (address) C(mgr);
}
static C* construct(C* address, const C& theRhs, MemoryManagerType& mgr)
{
return (C*) new (address) C(theRhs, mgr);
}
};
template <class C>
struct MemoryManagedConstructionTraits
{
typedef ConstructWithNoMemoryManager<C> Constructor;
};
#define XALAN_USES_MEMORY_MANAGER(Type) \
template<> \
struct MemoryManagedConstructionTraits<Type> \
{ \
typedef ConstructWithMemoryManager<Type> Constructor; \
};
template <class C>
struct ConstructWithMemoryManagerTraits
{
typedef ConstructWithMemoryManager<C> Constructor;
};
template <class C>
struct ConstructWithNoMemoryManagerTraits
{
typedef ConstructWithNoMemoryManager<C> Constructor;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANMEMORYMANAGEMENT_HEADER_GUARD_1357924680
<commit_msg>Added extra XalanConstruct overload and cleaned up a bit.<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANMEMORYMANAGEMENT_HEADER_GUARD_1357924680)
#define XALANMEMORYMANAGEMENT_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <cstddef>
#include <new>
#include <xercesc/framework/MemoryManager.hpp>
XALAN_CPP_NAMESPACE_BEGIN
typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager MemoryManagerType;
XALAN_USING_XERCES(MemoryManager)
class XalanAllocationGuard
{
public:
#if defined(XALAN_STRICT_ANSI_HEADERS)
typedef std::size_t size_type;
#else
typedef size_t size_type;
#endif
XalanAllocationGuard(
MemoryManager& theMemoryManager,
void* thePointer) :
m_memoryManager(theMemoryManager),
m_pointer(thePointer)
{
}
XalanAllocationGuard(
MemoryManager& theMemoryManager,
size_type theSize) :
m_memoryManager(theMemoryManager),
m_pointer(theMemoryManager.allocate(theSize))
{
}
~XalanAllocationGuard()
{
if (m_pointer != 0)
{
m_memoryManager.deallocate(m_pointer);
}
}
void*
get() const
{
return m_pointer;
}
void
release()
{
m_pointer = 0;
}
private:
// Data members...
MemoryManager& m_memoryManager;
void* m_pointer;
};
template<class Type>
void
XalanDestroy(Type& theArg)
{
theArg.~Type();
}
template<class Type>
void
XalanDestroy(Type* theArg)
{
if (theArg != 0)
{
theArg->~Type();
}
}
template<class Type>
void
XalanDestroy(
MemoryManager& theMemoryManager,
Type* theArg)
{
if (theArg != 0)
{
XalanDestroy(*theArg);
theMemoryManager.deallocate(theArg);
}
}
template<class Type>
void
XalanDestroy(
MemoryManager& theMemoryManager,
Type& theArg)
{
XalanDestroy(theArg);
theMemoryManager.deallocate(&theArg);
}
template<class Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type;
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance,
const Param1Type& theParam1)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
const Param2Type& theParam2)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type,
class Param3Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
const Param2Type& theParam2,
Param3Type& theParam3)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2, theParam3);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type,
class Param3Type,
class Param4Type,
class Param5Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
Param2Type& theParam2,
const Param3Type& theParam3,
const Param4Type& theParam4,
const Param5Type& theParam5)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2, theParam3, theParam4, theParam5);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type,
class Param2Type,
class Param3Type,
class Param4Type,
class Param5Type,
class Param6Type>
Type*
XalanConstruct(
MemoryManager& theMemoryManager,
Type*& theInstance,
Param1Type& theParam1,
Param2Type& theParam2,
const Param3Type& theParam3,
const Param4Type& theParam4,
const Param5Type& theParam5,
const Param6Type& theParam6)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
theInstance =
new (theGuard.get()) Type(theParam1, theParam2, theParam3, theParam4, theParam5, theParam6);
theGuard.release();
return theInstance;
}
template<class Type>
Type*
XalanCopyConstruct(
MemoryManager& theMemoryManager,
const Type& theSource)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
Type* const theInstance =
new (theGuard.get()) Type(theSource);
theGuard.release();
return theInstance;
}
template<
class Type,
class Param1Type>
Type*
XalanCopyConstruct(
MemoryManager& theMemoryManager,
const Type& theSource,
Param1Type& theParam1)
{
XalanAllocationGuard theGuard(
theMemoryManager,
sizeof(Type));
Type* const theInstance =
new (theGuard.get()) Type(theSource, theParam1);
theGuard.release();
return theInstance;
}
class XALAN_PLATFORM_EXPORT XalanMemMgrs
{
public:
static MemoryManager&
getDummyMemMgr();
static MemoryManager&
getDefaultXercesMemMgr();
static MemoryManager&
getDefault()
{
return getDefaultXercesMemMgr();
}
};
#if defined (XALAN_DEVELOPMENT)
#define XALAN_DEFAULT_CONSTRUCTOR_MEMORY_MGR
#define XALAN_DEFAULT_CONSTRACTOR_MEMORY_MGR
#define XALAN_DEFAULT_MEMMGR = XalanMemMgrs::getDummyMemMgr()
#else
#define XALAN_DEFAULT_CONSTRUCTOR_MEMORY_MGR = XalanMemMgrs::getDefaultXercesMemMgr()
#define XALAN_DEFAULT_CONSTRACTOR_MEMORY_MGR XALAN_DEFAULT_CONSTRUCTOR_MEMORY_MGR
#define XALAN_DEFAULT_MEMMGR = XalanMemMgrs::getDefaultXercesMemMgr()
#endif
template <class C>
struct ConstructValueWithNoMemoryManager
{
ConstructValueWithNoMemoryManager(MemoryManager& /*mgr*/) :
value()
{
}
C value;
};
template <class C>
struct ConstructValueWithMemoryManager
{
ConstructValueWithMemoryManager(MemoryManager& mgr) :
value(mgr)
{
}
C value;
};
template <class C>
struct ConstructWithNoMemoryManager
{
typedef ConstructValueWithNoMemoryManager<C> ConstructableType;
static C* construct(C* address, MemoryManager& /* mgr */)
{
return (C*) new (address) C;
}
static C* construct(C* address, const C& theRhs, MemoryManager& /* mgr */)
{
return (C*) new (address) C(theRhs);
}
};
template <class C>
struct ConstructWithMemoryManager
{
typedef ConstructValueWithMemoryManager<C> ConstructableType;
static C* construct(C* address, MemoryManager& mgr)
{
return (C*) new (address) C(mgr);
}
static C* construct(C* address, const C& theRhs, MemoryManager& mgr)
{
return (C*) new (address) C(theRhs, mgr);
}
};
template <class C>
struct MemoryManagedConstructionTraits
{
typedef ConstructWithNoMemoryManager<C> Constructor;
};
#define XALAN_USES_MEMORY_MANAGER(Type) \
template<> \
struct MemoryManagedConstructionTraits<Type> \
{ \
typedef ConstructWithMemoryManager<Type> Constructor; \
};
template <class C>
struct ConstructWithMemoryManagerTraits
{
typedef ConstructWithMemoryManager<C> Constructor;
};
template <class C>
struct ConstructWithNoMemoryManagerTraits
{
typedef ConstructWithNoMemoryManager<C> Constructor;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANMEMORYMANAGEMENT_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
* $Log$
* Revision 1.8 2004/01/29 11:46:29 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.7 2003/05/29 11:18:37 gareth
* Added macros in so we can determine whether to do things like iostream as opposed to iostream.h and whether to use std:: or not.
*
* Revision 1.6 2003/01/24 20:20:22 tng
* Add method flush to XMLFormatTarget
*
* Revision 1.5 2003/01/09 18:58:29 tng
* [Bug 15427] DOMWriter dose not flush the output stream.
*
* Revision 1.4 2002/11/22 14:25:59 tng
* Got a number of compilation erros for those non-ANSI C++ compliant compiler like xlC v3.
* Since the previous fix is just for fixing a "warning", I think it doesn't worth to break users who
* are not ANSI C++ ready yet.
*
* Revision 1.3 2002/11/21 15:45:34 gareth
* gcc 3.2 now issues a warning for use of iostream.h. Removed the .h and prefixed cout with std::.
*
* Revision 1.2 2002/11/04 15:00:21 tng
* C++ Namespace Support.
*
* Revision 1.1 2002/05/28 22:40:46 peiyongz
* DOM3 Save Interface: DOMWriter/DOMWriterFilter
*
*/
#include <xercesc/framework/StdOutFormatTarget.hpp>
#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else
#include <iostream.h>
#endif
XERCES_CPP_NAMESPACE_BEGIN
StdOutFormatTarget::StdOutFormatTarget()
{}
StdOutFormatTarget::~StdOutFormatTarget()
{}
void StdOutFormatTarget::flush()
{
XERCES_STD_QUALIFIER cout.flush();
}
void StdOutFormatTarget::writeChars(const XMLByte* const toWrite
, const unsigned int count
, XMLFormatter* const)
{
// Surprisingly, Solaris was the only platform on which
// required the char* cast to print out the string correctly.
// Without the cast, it was printing the pointer value in hex.
// Quite annoying, considering every other platform printed
// the string with the explicit cast to char* below.
XERCES_STD_QUALIFIER cout.write((char *) toWrite, (int) count);
XERCES_STD_QUALIFIER cout.flush();
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Bug#20684: patch from carbe771@student.liu.se (C-J Berg)<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
* $Log$
* Revision 1.9 2004/02/09 23:01:43 peiyongz
* Bug#20684: patch from carbe771@student.liu.se (C-J Berg)
*
* Revision 1.8 2004/01/29 11:46:29 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.7 2003/05/29 11:18:37 gareth
* Added macros in so we can determine whether to do things like iostream as opposed to iostream.h and whether to use std:: or not.
*
* Revision 1.6 2003/01/24 20:20:22 tng
* Add method flush to XMLFormatTarget
*
* Revision 1.5 2003/01/09 18:58:29 tng
* [Bug 15427] DOMWriter dose not flush the output stream.
*
* Revision 1.4 2002/11/22 14:25:59 tng
* Got a number of compilation erros for those non-ANSI C++ compliant compiler like xlC v3.
* Since the previous fix is just for fixing a "warning", I think it doesn't worth to break users who
* are not ANSI C++ ready yet.
*
* Revision 1.3 2002/11/21 15:45:34 gareth
* gcc 3.2 now issues a warning for use of iostream.h. Removed the .h and prefixed cout with std::.
*
* Revision 1.2 2002/11/04 15:00:21 tng
* C++ Namespace Support.
*
* Revision 1.1 2002/05/28 22:40:46 peiyongz
* DOM3 Save Interface: DOMWriter/DOMWriterFilter
*
*/
#include <xercesc/framework/StdOutFormatTarget.hpp>
#include <stdio.h>
XERCES_CPP_NAMESPACE_BEGIN
StdOutFormatTarget::StdOutFormatTarget()
{}
StdOutFormatTarget::~StdOutFormatTarget()
{}
void StdOutFormatTarget::flush()
{
fflush(stdout);
}
void StdOutFormatTarget::writeChars(const XMLByte* const toWrite
, const unsigned int count
, XMLFormatter* const)
{
// Surprisingly, Solaris was the only platform on which
// required the char* cast to print out the string correctly.
// Without the cast, it was printing the pointer value in hex.
// Quite annoying, considering every other platform printed
// the string with the explicit cast to char* below.
fwrite(toWrite, sizeof(XMLByte), (size_t)count, stdout);
fflush(stdout);
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZConnectionWrapper.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:16:56 $
*
* 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 _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#define _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CONNECTIVITY_ZCONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif
namespace connectivity
{
//==========================================================================
//= OConnectionWeakWrapper - wraps all methods to the real connection from the driver
//= but when disposed it doesn't dispose the real connection
//==========================================================================
typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection
> OConnectionWeakWrapper_BASE;
class OConnectionWeakWrapper : public ::comphelper::OBaseMutex
,public OConnectionWeakWrapper_BASE
, public OConnectionWrapper
{
protected:
// OComponentHelper
virtual void SAL_CALL disposing(void);
virtual ~OConnectionWeakWrapper();
public:
OConnectionWeakWrapper(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _xConnection);
// XServiceInfo
DECLARE_SERVICE_INFO();
DECLARE_XTYPEPROVIDER()
DECLARE_XINTERFACE( )
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
#endif // _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.7.372); FILE MERGED 2008/04/01 15:08:32 thb 1.7.372.3: #i85898# Stripping all external header guards 2008/04/01 10:52:46 thb 1.7.372.2: #i85898# Stripping all external header guards 2008/03/28 15:23:22 rt 1.7.372.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZConnectionWrapper.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#define _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#include <cppuhelper/compbase1.hxx>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <comphelper/broadcasthelper.hxx>
#include <comphelper/uno3.hxx>
#include "connectivity/ConnectionWrapper.hxx"
namespace connectivity
{
//==========================================================================
//= OConnectionWeakWrapper - wraps all methods to the real connection from the driver
//= but when disposed it doesn't dispose the real connection
//==========================================================================
typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection
> OConnectionWeakWrapper_BASE;
class OConnectionWeakWrapper : public ::comphelper::OBaseMutex
,public OConnectionWeakWrapper_BASE
, public OConnectionWrapper
{
protected:
// OComponentHelper
virtual void SAL_CALL disposing(void);
virtual ~OConnectionWeakWrapper();
public:
OConnectionWeakWrapper(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _xConnection);
// XServiceInfo
DECLARE_SERVICE_INFO();
DECLARE_XTYPEPROVIDER()
DECLARE_XINTERFACE( )
// XConnection
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
#endif // _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
<|endoftext|> |
<commit_before>//********************************************************************
// Example (very naive for the moment) of using the ESD classes
// It demonstrates the idea of the "combined PID".
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//********************************************************************
#if !defined( __CINT__) || defined(__MAKECINT__)
#include <TMath.h>
#include <TError.h>
#include <Riostream.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TParticle.h>
#include <TCanvas.h>
#include <TBenchmark.h>
#include <TFile.h>
#include <TTree.h>
#include <TROOT.h>
#include <AliStack.h>
#include <AliRunLoader.h>
#include <AliRun.h>
#include <AliESD.h>
#endif
extern AliRun *gAlice;
extern TBenchmark *gBenchmark;
extern TROOT *gROOT;
static Int_t allpisel=0;
static Int_t allkasel=0;
static Int_t allprsel=0;
static Int_t allnsel=0;
Int_t AliESDComparison(const Char_t *dir=".") {
gBenchmark->Start("AliESDComparison");
::Info("AliESDComparison.C","Doing comparison...");
Double_t pi=0.2,pa=3;
TH2F *tpcHist=(TH2F*)gROOT->FindObject("tpcHist");
if (!tpcHist)
tpcHist=new TH2F("tpcHist","TPC dE/dX vs momentum",100,pi,pa,100,0.,300.);
tpcHist->SetXTitle("p (GeV/c)"); tpcHist->SetYTitle("dE/dx (Arb. Units)");
tpcHist->SetMarkerStyle(8);
tpcHist->SetMarkerSize(0.3);
const Char_t *hname[]={
"piG","piR","piF","piGood","piFake",
"kaG","kaR","kaF","kaGood","kaFake",
"prG","prR","prF","prGood","prFake"
};
Int_t nh=sizeof(hname)/sizeof(const Char_t *);
TH1F **hprt=new TH1F*[nh];
for (Int_t i=0; i<nh; i++) {
hprt[i]=(TH1F*)gROOT->FindObject(hname[i]);
if (hprt[i]==0) {hprt[i]=new TH1F(hname[i],"",20,pi,pa);hprt[i]->Sumw2();}
}
TH1F *piG=hprt[0];
TH1F *piR=hprt[1];
TH1F *piF=hprt[2];
TH1F *piGood=hprt[3];
piGood->SetTitle("Combined PID for pions");
piGood->SetLineColor(4); piGood->SetXTitle("p (GeV/c)");
TH1F *piFake=hprt[4];
piFake->SetLineColor(2);
TH1F *kaG=hprt[5];
TH1F *kaR=hprt[6];
TH1F *kaF=hprt[7];
TH1F *kaGood=hprt[8];
kaGood->SetTitle("Combined PID for kaons");
kaGood->SetLineColor(4); kaGood->SetXTitle("p (GeV/c)");
TH1F *kaFake=hprt[9];
kaFake->SetLineColor(2);
TH1F *prG=hprt[10];
TH1F *prR=hprt[11];
TH1F *prF=hprt[12];
TH1F *prGood=hprt[13];
prGood->SetTitle("Combined PID for protons");
prGood->SetLineColor(4); prGood->SetXTitle("p (GeV/c)");
TH1F *prFake=hprt[14];
prFake->SetLineColor(2);
delete[] hprt;
Char_t fname[100];
if (gAlice) {
delete gAlice->GetRunLoader();
delete gAlice;
gAlice=0;
}
sprintf(fname,"%s/galice.root",dir);
AliRunLoader *rl = AliRunLoader::Open(fname);
if (rl == 0x0) {
::Error("AliESDComparison.C","Can not open session !");
return 1;
}
if (rl->LoadgAlice()) {
::Error("AliESDComparison.C","LoadgAlice returned error !");
delete rl;
return 1;
}
if (rl->LoadHeader()) {
::Error("AliESDComparison.C","LoadHeader returned error !");
delete rl;
return 1;
}
rl->LoadKinematics();
sprintf(fname,"%s/AliESDs.root",dir);
TFile *ef=TFile::Open(fname);
if (!ef || !ef->IsOpen()) {
::Error("AliESDComparison.C","Can't AliESDs.root !");
delete rl;
return 1;
}
AliESD* event = new AliESD;
TTree* tree = (TTree*) ef->Get("esdTree");
if (!tree) {
::Error("AliESDComparison.C", "no ESD tree found");
delete rl;
return 1;
}
tree->SetBranchAddress("ESD", &event);
//****** Tentative particle type "concentrations"
Double_t c[5]={0.01, 0.01, 0.85, 0.10, 0.05};
//Double_t c[5]={0.2, 0.2, 0.2, 0.2, 0.2};
AliPID::SetPriors(c);
//******* The loop over events
Int_t e=0;
while (tree->GetEvent(e)) {
cout<<endl<<endl<<"********* Processing event number: "<<e<<"*******\n";
rl->GetEvent(e);
e++;
Int_t ntrk=event->GetNumberOfTracks();
cerr<<"Number of ESD tracks : "<<ntrk<<endl;
Int_t pisel=0,kasel=0,prsel=0,nsel=0;
AliStack *stack = rl->Stack();
while (ntrk--) {
AliESDtrack *t=event->GetTrack(ntrk);
UInt_t status=AliESDtrack::kESDpid;
status|=AliESDtrack::kITSpid;
status|=AliESDtrack::kTPCpid;
//status|=AliESDtrack::kTRDpid;
//status|=AliESDtrack::kTOFpid;
if ((t->GetStatus()&status) == status) {
nsel++;
Double_t p=t->GetP();
Double_t dedx=t->GetTPCsignal();
tpcHist->Fill(p,dedx,1);
Int_t lab=TMath::Abs(t->GetLabel());
TParticle *part=stack->Particle(lab);
Int_t code=part->GetPdgCode();
Double_t r[10]; t->GetESDpid(r);
//t->GetTRDpid(r);
//t->GetTPCpid(r);
AliPID pid(r);
Double_t w[10];
w[0]=pid.GetProbability(AliPID::kElectron);
w[1]=pid.GetProbability(AliPID::kMuon);
w[2]=pid.GetProbability(AliPID::kPion);
w[3]=pid.GetProbability(AliPID::kKaon);
w[4]=pid.GetProbability(AliPID::kProton);
if (TMath::Abs(code)==2212) prR->Fill(p);
if (w[4]>w[3] && w[4]>w[2] && w[4]>w[1] && w[4]>w[0]) {//proton
prsel++;
prG->Fill(p);
if (TMath::Abs(code)!=2212) prF->Fill(p);
}
if (TMath::Abs(code)==321) kaR->Fill(p);
if (w[3]>w[4] && w[3]>w[2] && w[3]>w[1] && w[3]>w[0]) {//kaon
kasel++;
kaG->Fill(p);
if (TMath::Abs(code)!=321) kaF->Fill(p);
}
if (TMath::Abs(code)==211) piR->Fill(p);
if (w[2]>w[4] && w[2]>w[3] && w[2]>w[0] && w[2]>w[1]) {//pion
pisel++;
piG->Fill(p);
if (TMath::Abs(code)!=211) piF->Fill(p);
}
}
}
cout<<"Number of selected ESD tracks : "<<nsel<<endl;
cout<<"Number of selected pion ESD tracks : "<<pisel<<endl;
cout<<"Number of selected kaon ESD tracks : "<<kasel<<endl;
cout<<"Number of selected proton ESD tracks : "<<prsel<<endl;
allnsel+=nsel; allpisel+=pisel; allkasel+=kasel; allprsel+=prsel;
} // ***** End of the loop over events
delete event;
ef->Close();
TCanvas *c1=(TCanvas*)gROOT->FindObject("c1");
if (!c1) {
c1=new TCanvas("c1","",0,0,600,1200);
c1->Divide(1,4);
}
c1->cd(1);
tpcHist->Draw();
c1->cd(2);
//piG->Sumw2(); piF->Sumw2(); piR->Sumw2();
piGood->Add(piG,piF,1,-1);
piGood->Divide(piGood,piR,1,1,"b");
piFake->Divide(piF,piG,1,1,"b");
piGood->Draw("hist");
piFake->Draw("same");
c1->cd(3);
//kaG->Sumw2(); kaF->Sumw2(); kaR->Sumw2();
kaGood->Add(kaG,kaF,1,-1);
kaGood->Divide(kaGood,kaR,1,1,"b");
kaFake->Divide(kaF,kaG,1,1,"b");
kaGood->Draw("hist");
kaFake->Draw("same");
c1->cd(4);
//prG->Sumw2(); prF->Sumw2(); prR->Sumw2();
prGood->Add(prG,prF,1,-1);
prGood->Divide(prGood,prR,1,1,"b");
prFake->Divide(prF,prG,1,1,"b");
prGood->Draw("hist");
prFake->Draw("same");
c1->Update();
cout<<endl;
cout<<endl;
e=(Int_t)piR->GetEntries();
Int_t o=(Int_t)piG->GetEntries();
if (e*o) cout<<"Efficiency (contamination) for pions : "<<
piGood->GetEntries()/e<<'('<<piF->GetEntries()/o<<')'<<endl;
e=(Int_t)kaR->GetEntries();
o=(Int_t)kaG->GetEntries();
if (e*o) cout<<"Efficiency (contamination) for kaons : "<<
kaGood->GetEntries()/e<<'('<<kaF->GetEntries()/o<<')'<<endl;
e=(Int_t)prR->GetEntries();
o=(Int_t)prG->GetEntries();
if (e*o) cout<<"Efficiency (contamination) for protons : "<<
prGood->GetEntries()/e<<'('<<prF->GetEntries()/o<<')'<<endl;
cout<<endl;
cout<<"Total number of selected ESD tracks : "<<allnsel<<endl;
cout<<"Total number of selected pion ESD tracks : "<<allpisel<<endl;
cout<<"Total number of selected kaon ESD tracks : "<<allkasel<<endl;
cout<<"Total number of selected proton ESD tracks : "<<allprsel<<endl;
ef->Close();
TFile fc("AliESDComparison.root","RECREATE");
c1->Write();
fc.Close();
gBenchmark->Stop("AliESDComparison");
gBenchmark->Show("AliESDComparison");
delete rl;
return 0;
}
<commit_msg>Comparison for all detectors<commit_after>//********************************************************************
// Example (very naive for the moment) of using the ESD classes
// It demonstrates the idea of the "combined PID".
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//********************************************************************
#if !defined( __CINT__) || defined(__MAKECINT__)
#include <TMath.h>
#include <TError.h>
#include <Riostream.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TParticle.h>
#include <TCanvas.h>
#include <TBenchmark.h>
#include <TFile.h>
#include <TTree.h>
#include <TROOT.h>
#include <AliStack.h>
#include <AliRunLoader.h>
#include <AliRun.h>
#include <AliESD.h>
#endif
extern AliRun *gAlice;
extern TBenchmark *gBenchmark;
extern TROOT *gROOT;
static Int_t allpisel=0;
static Int_t allkasel=0;
static Int_t allprsel=0;
static Int_t allnsel=0;
Int_t AliESDComparison(const Char_t *dir=".") {
gBenchmark->Start("AliESDComparison");
::Info("AliESDComparison.C","Doing comparison...");
Double_t pi=0.2,pa=3;
TH2F *tpcHist=(TH2F*)gROOT->FindObject("tpcHist");
if (!tpcHist)
tpcHist=new TH2F("tpcHist","TPC dE/dX vs momentum",100,pi,pa,100,0.,300.);
tpcHist->SetXTitle("p (GeV/c)"); tpcHist->SetYTitle("dE/dx (Arb. Units)");
tpcHist->SetMarkerStyle(8);
tpcHist->SetMarkerSize(0.3);
const Char_t *hname[]={
"piG","piR","piF","piGood","piFake",
"kaG","kaR","kaF","kaGood","kaFake",
"prG","prR","prF","prGood","prFake"
};
Int_t nh=sizeof(hname)/sizeof(const Char_t *);
TH1F **hprt=new TH1F*[nh];
for (Int_t i=0; i<nh; i++) {
hprt[i]=(TH1F*)gROOT->FindObject(hname[i]);
if (hprt[i]==0) {hprt[i]=new TH1F(hname[i],"",20,pi,pa);hprt[i]->Sumw2();}
}
TH1F *piG=hprt[0];
TH1F *piR=hprt[1];
TH1F *piF=hprt[2];
TH1F *piGood=hprt[3];
piGood->SetTitle("Combined PID for pions");
piGood->SetLineColor(4); piGood->SetXTitle("p (GeV/c)");
TH1F *piFake=hprt[4];
piFake->SetLineColor(2);
TH1F *kaG=hprt[5];
TH1F *kaR=hprt[6];
TH1F *kaF=hprt[7];
TH1F *kaGood=hprt[8];
kaGood->SetTitle("Combined PID for kaons");
kaGood->SetLineColor(4); kaGood->SetXTitle("p (GeV/c)");
TH1F *kaFake=hprt[9];
kaFake->SetLineColor(2);
TH1F *prG=hprt[10];
TH1F *prR=hprt[11];
TH1F *prF=hprt[12];
TH1F *prGood=hprt[13];
prGood->SetTitle("Combined PID for protons");
prGood->SetLineColor(4); prGood->SetXTitle("p (GeV/c)");
TH1F *prFake=hprt[14];
prFake->SetLineColor(2);
delete[] hprt;
Char_t fname[100];
if (gAlice) {
delete gAlice->GetRunLoader();
delete gAlice;
gAlice=0;
}
sprintf(fname,"%s/galice.root",dir);
AliRunLoader *rl = AliRunLoader::Open(fname);
if (rl == 0x0) {
::Error("AliESDComparison.C","Can not open session !");
return 1;
}
if (rl->LoadgAlice()) {
::Error("AliESDComparison.C","LoadgAlice returned error !");
delete rl;
return 1;
}
if (rl->LoadHeader()) {
::Error("AliESDComparison.C","LoadHeader returned error !");
delete rl;
return 1;
}
rl->LoadKinematics();
sprintf(fname,"%s/AliESDs.root",dir);
TFile *ef=TFile::Open(fname);
if (!ef || !ef->IsOpen()) {
::Error("AliESDComparison.C","Can't AliESDs.root !");
delete rl;
return 1;
}
AliESD* event = new AliESD;
TTree* tree = (TTree*) ef->Get("esdTree");
if (!tree) {
::Error("AliESDComparison.C", "no ESD tree found");
delete rl;
return 1;
}
tree->SetBranchAddress("ESD", &event);
//****** Tentative particle type "concentrations"
Double_t c[5]={0.01, 0.01, 0.85, 0.10, 0.05};
//Double_t c[5]={0.2, 0.2, 0.2, 0.2, 0.2};
AliPID::SetPriors(c);
//******* The loop over events
Int_t e=0;
while (tree->GetEvent(e)) {
cout<<endl<<endl<<"********* Processing event number: "<<e<<"*******\n";
rl->GetEvent(e);
e++;
Int_t ntrk=event->GetNumberOfTracks();
cerr<<"Number of ESD tracks : "<<ntrk<<endl;
Int_t pisel=0,kasel=0,prsel=0,nsel=0;
AliStack *stack = rl->Stack();
while (ntrk--) {
AliESDtrack *t=event->GetTrack(ntrk);
UInt_t status=AliESDtrack::kESDpid;
status|=AliESDtrack::kITSpid;
status|=AliESDtrack::kTPCpid;
status|=AliESDtrack::kTRDpid;
status|=AliESDtrack::kTOFpid;
if ((t->GetStatus()&status) == status) {
nsel++;
Double_t p=t->GetP();
Double_t dedx=t->GetTPCsignal();
tpcHist->Fill(p,dedx,1);
Int_t lab=TMath::Abs(t->GetLabel());
TParticle *part=stack->Particle(lab);
Int_t code=part->GetPdgCode();
Double_t r[10]; t->GetESDpid(r);
//t->GetTRDpid(r);
//t->GetTPCpid(r);
AliPID pid(r);
Double_t w[10];
w[0]=pid.GetProbability(AliPID::kElectron);
w[1]=pid.GetProbability(AliPID::kMuon);
w[2]=pid.GetProbability(AliPID::kPion);
w[3]=pid.GetProbability(AliPID::kKaon);
w[4]=pid.GetProbability(AliPID::kProton);
if (TMath::Abs(code)==2212) prR->Fill(p);
if (w[4]>w[3] && w[4]>w[2] && w[4]>w[1] && w[4]>w[0]) {//proton
prsel++;
prG->Fill(p);
if (TMath::Abs(code)!=2212) prF->Fill(p);
}
if (TMath::Abs(code)==321) kaR->Fill(p);
if (w[3]>w[4] && w[3]>w[2] && w[3]>w[1] && w[3]>w[0]) {//kaon
kasel++;
kaG->Fill(p);
if (TMath::Abs(code)!=321) kaF->Fill(p);
}
if (TMath::Abs(code)==211) piR->Fill(p);
if (w[2]>w[4] && w[2]>w[3] && w[2]>w[0] && w[2]>w[1]) {//pion
pisel++;
piG->Fill(p);
if (TMath::Abs(code)!=211) piF->Fill(p);
}
}
}
cout<<"Number of selected ESD tracks : "<<nsel<<endl;
cout<<"Number of selected pion ESD tracks : "<<pisel<<endl;
cout<<"Number of selected kaon ESD tracks : "<<kasel<<endl;
cout<<"Number of selected proton ESD tracks : "<<prsel<<endl;
allnsel+=nsel; allpisel+=pisel; allkasel+=kasel; allprsel+=prsel;
} // ***** End of the loop over events
delete event;
ef->Close();
TCanvas *c1=(TCanvas*)gROOT->FindObject("c1");
if (!c1) {
c1=new TCanvas("c1","",0,0,600,1200);
c1->Divide(1,4);
}
c1->cd(1);
tpcHist->Draw();
c1->cd(2);
//piG->Sumw2(); piF->Sumw2(); piR->Sumw2();
piGood->Add(piG,piF,1,-1);
piGood->Divide(piGood,piR,1,1,"b");
piFake->Divide(piF,piG,1,1,"b");
piGood->Draw("hist");
piFake->Draw("same");
c1->cd(3);
//kaG->Sumw2(); kaF->Sumw2(); kaR->Sumw2();
kaGood->Add(kaG,kaF,1,-1);
kaGood->Divide(kaGood,kaR,1,1,"b");
kaFake->Divide(kaF,kaG,1,1,"b");
kaGood->Draw("hist");
kaFake->Draw("same");
c1->cd(4);
//prG->Sumw2(); prF->Sumw2(); prR->Sumw2();
prGood->Add(prG,prF,1,-1);
prGood->Divide(prGood,prR,1,1,"b");
prFake->Divide(prF,prG,1,1,"b");
prGood->Draw("hist");
prFake->Draw("same");
c1->Update();
cout<<endl;
cout<<endl;
e=(Int_t)piR->GetEntries();
Int_t o=(Int_t)piG->GetEntries();
if (e*o) cout<<"Efficiency (contamination) for pions : "<<
piGood->GetEntries()/e<<'('<<piF->GetEntries()/o<<')'<<endl;
e=(Int_t)kaR->GetEntries();
o=(Int_t)kaG->GetEntries();
if (e*o) cout<<"Efficiency (contamination) for kaons : "<<
kaGood->GetEntries()/e<<'('<<kaF->GetEntries()/o<<')'<<endl;
e=(Int_t)prR->GetEntries();
o=(Int_t)prG->GetEntries();
if (e*o) cout<<"Efficiency (contamination) for protons : "<<
prGood->GetEntries()/e<<'('<<prF->GetEntries()/o<<')'<<endl;
cout<<endl;
cout<<"Total number of selected ESD tracks : "<<allnsel<<endl;
cout<<"Total number of selected pion ESD tracks : "<<allpisel<<endl;
cout<<"Total number of selected kaon ESD tracks : "<<allkasel<<endl;
cout<<"Total number of selected proton ESD tracks : "<<allprsel<<endl;
ef->Close();
TFile fc("AliESDComparison.root","RECREATE");
c1->Write();
fc.Close();
gBenchmark->Stop("AliESDComparison");
gBenchmark->Show("AliESDComparison");
delete rl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "curlftpuploader.h"
#include <QDebug>
#include <QCoreApplication>
#include <QFileInfo>
#include <sys/stat.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <curl/curl.h>
#include "ftphelpers.h"
#include "../Common/defines.h"
#define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 2
namespace Conectivity {
/* this is how the CURLOPT_XFERINFOFUNCTION callback works */
static int xferinfo(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
Q_UNUSED(dltotal);
Q_UNUSED(dlnow);
CurlProgressReporter *progressReporter = (CurlProgressReporter *)p;
CURL *curl = progressReporter->getCurl();
double curtime = 0;
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime);
/* under certain circumstances it may be desirable for certain functionality
to only run every N seconds, in order to do this the transaction time can
be used */
if ((curtime - progressReporter->getLastTime()) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) {
progressReporter->setLastTime(curtime);
progressReporter->updateProgress((double)ultotal, (double)ulnow);
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
int result = progressReporter->cancelRequested() ? 1 : 0;
if (result) {
qDebug() << "xferinfo #" << "Cancelling upload from the progress callback...";
}
return result;
}
/* for libcurl older than 7.32.0 (CURLOPT_PROGRESSFUNCTION) */
static int older_progress(void *p,
double dltotal, double dlnow,
double ultotal, double ulnow)
{
return xferinfo(p,
(curl_off_t)dltotal,
(curl_off_t)dlnow,
(curl_off_t)ultotal,
(curl_off_t)ulnow);
}
void setCurlProgressCallback(CURL *curlHandle, CurlProgressReporter *progressReporter) {
curl_easy_setopt(curlHandle, CURLOPT_PROGRESSFUNCTION, older_progress);
/* pass the struct pointer into the progress function */
curl_easy_setopt(curlHandle, CURLOPT_PROGRESSDATA, progressReporter);
#if LIBCURL_VERSION_NUM >= 0x072000
/* xferinfo was introduced in 7.32.0, no earlier libcurl versions will
compile as they won't have the symbols around.
If built with a newer libcurl, but running with an older libcurl:
curl_easy_setopt() will fail in run-time trying to set the new
callback, making the older callback get used.
New libcurls will prefer the new callback and instead use that one even
if both callbacks are set. */
curl_easy_setopt(curlHandle, CURLOPT_XFERINFOFUNCTION, xferinfo);
/* pass the struct pointer into the xferinfo function, note that this is
an alias to CURLOPT_PROGRESSDATA */
curl_easy_setopt(curlHandle, CURLOPT_XFERINFODATA, progressReporter);
#endif
curl_easy_setopt(curlHandle, CURLOPT_NOPROGRESS, 0L);
}
bool uploadFile(CURL *curlHandle, UploadContext *context, CurlProgressReporter *progressReporter,
const QString &filepath, const QString &remoteUrl) {
bool result = false;
FILE *f;
long uploaded_len = 0;
CURLcode r = CURLE_GOT_NOTHING;
struct stat file_info;
int c;
curl_off_t fsize;
/* get the file size of the local file */
if (stat(filepath.toLocal8Bit().data(), &file_info)) {
qWarning() << "uploadFile #" << "Failed to stat file" << filepath;
return result;
}
fsize = (curl_off_t) file_info.st_size;
f = fopen(filepath.toLocal8Bit().data(), "rb");
if (f == NULL) {
qWarning() << "uploadFile #" << "Failed to open file" << filepath;
return result;
}
fillCurlOptions(curlHandle, context, remoteUrl);
setCurlProgressCallback(curlHandle, progressReporter);
curl_easy_setopt(curlHandle, CURLOPT_READDATA, f);
curl_easy_setopt(curlHandle, CURLOPT_INFILESIZE_LARGE,
(curl_off_t)fsize);
curl_easy_setopt(curlHandle, CURLOPT_HEADERDATA, &uploaded_len);
for (c = 0; (r != CURLE_OK) && (c < context->m_RetriesCount); c++) {
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
if (r == CURLE_ABORTED_BY_CALLBACK) {
qInfo() << "uploadFile #" << "Upload aborted by user...";
break;
}
/* are we resuming? */
if (c) { /* yes */
qDebug() << "uploadFile #" << "Attempting to resume upload" << uploaded_len << "try #" << c;
/* determine the length of the file already written */
/*
* With NOBODY and NOHEADER, libcurl will issue a SIZE
* command, but the only way to retrieve the result is
* to parse the returned Content-Length header. Thus,
* getcontentlengthfunc(). We need discardfunc() above
* because HEADER will dump the headers to stdout
* without it.
*/
curl_easy_setopt(curlHandle, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curlHandle, CURLOPT_HEADER, 1L);
r = curl_easy_perform(curlHandle);
if (r != CURLE_OK) {
continue;
}
curl_easy_setopt(curlHandle, CURLOPT_NOBODY, 0L);
curl_easy_setopt(curlHandle, CURLOPT_HEADER, 0L);
fseek(f, uploaded_len, SEEK_SET);
curl_easy_setopt(curlHandle, CURLOPT_APPEND, 1L);
}
else { /* no */
curl_easy_setopt(curlHandle, CURLOPT_APPEND, 0L);
}
r = curl_easy_perform(curlHandle);
}
fclose(f);
result = (r == CURLE_OK);
if (!result) {
qWarning() << "uploadFile #" << "Upload failed! Curl error:" << curl_easy_strerror(r);
}
return result;
}
CurlProgressReporter::CurlProgressReporter(void *curl):
QObject(),
m_LastTime(0.0),
m_Curl(curl),
m_Cancel(false)
{
}
void CurlProgressReporter::updateProgress(double ultotal, double ulnow) {
if (fabs(ultotal) > 1e-6) {
double progress = ulnow * 100.0 / ultotal;
emit progressChanged(progress);
}
}
void CurlProgressReporter::cancelHandler() {
m_Cancel = true;
qDebug() << "CurlProgressReporter::cancelHandler #" << "Cancelled in the progress reporter...";
}
CurlFtpUploader::CurlFtpUploader(UploadBatch *batchToUpload, QObject *parent) :
QObject(parent),
m_BatchToUpload(batchToUpload),
m_UploadedCount(0),
m_Cancel(false),
m_LastPercentage(0.0)
{
m_TotalCount = batchToUpload->getFilesToUpload().length();
}
void CurlFtpUploader::uploadBatch() {
CURL *curlHandle = NULL;
bool anyErrors = false;
UploadContext *context = m_BatchToUpload->getContext();
if (m_Cancel) {
qWarning() << "CurlFtpUploader::uploadBatch #" << "Cancelled before upload." << context->m_Host;
return;
}
const QStringList &filesToUpload = m_BatchToUpload->getFilesToUpload();
int size = filesToUpload.size();
QString host = sanitizeHost(context->m_Host);
// curl_global_init should be done from coordinator
curlHandle = curl_easy_init();
CurlProgressReporter progressReporter(curlHandle);
QObject::connect(&progressReporter, SIGNAL(progressChanged(double)),
this, SLOT(reportCurrentFileProgress(double)));
QObject::connect(this, SIGNAL(cancelCurrentUpload()), &progressReporter, SLOT(cancelHandler()));
// temporary do not emit started signal: not used
//emit uploadStarted();
qDebug() << "CurlFtpUploader::uploadBatch #" << "Uploading" << size << "file(s) started for" << host << "Passive mode =" << context->m_UsePassiveMode;
for (int i = 0; i < size; ++i) {
if (m_Cancel) {
qWarning() << "CurlFtpUploader::uploadBatch #" << "Cancelled. Breaking..." << host;
break;
}
reportCurrentFileProgress(0.0);
const QString &filepath = filesToUpload.at(i);
QFileInfo fi(filepath);
QString remoteUrl = host + fi.fileName();
bool uploadSuccess = false;
try {
uploadSuccess = uploadFile(curlHandle, context, &progressReporter, filepath, remoteUrl);
} catch (...) {
qWarning() << "CurlFtpUploader::uploadBatch #" << "CRASHED for file" << filepath << "for host" << host;
}
if (!uploadSuccess) {
anyErrors = true;
emit transferFailed(filepath, host);
}
// TODO: only update progress of not-failed uploads
if (uploadSuccess) {
m_UploadedCount++;
}
}
reportCurrentFileProgress(0.0);
emit uploadFinished(anyErrors);
qDebug() << "CurlFtpUploader::uploadBatch #" << "Uploading finished for" << host;
curl_easy_cleanup(curlHandle);
// curl_global_cleanup should be done from coordinator
}
void CurlFtpUploader::cancel() {
m_Cancel = true;
emit cancelCurrentUpload();
}
void CurlFtpUploader::reportCurrentFileProgress(double percent) {
double newProgress = m_UploadedCount*100.0 + percent;
newProgress /= m_TotalCount;
emit progressChanged(m_LastPercentage, newProgress);
m_LastPercentage = newProgress;
}
}
<commit_msg>Added more loggin for retrying in libcurl<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "curlftpuploader.h"
#include <QDebug>
#include <QCoreApplication>
#include <QFileInfo>
#include <sys/stat.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <curl/curl.h>
#include "ftphelpers.h"
#include "../Common/defines.h"
#define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 2
namespace Conectivity {
/* this is how the CURLOPT_XFERINFOFUNCTION callback works */
static int xferinfo(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
Q_UNUSED(dltotal);
Q_UNUSED(dlnow);
CurlProgressReporter *progressReporter = (CurlProgressReporter *)p;
CURL *curl = progressReporter->getCurl();
double curtime = 0;
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime);
/* under certain circumstances it may be desirable for certain functionality
to only run every N seconds, in order to do this the transaction time can
be used */
if ((curtime - progressReporter->getLastTime()) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) {
progressReporter->setLastTime(curtime);
progressReporter->updateProgress((double)ultotal, (double)ulnow);
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
int result = progressReporter->cancelRequested() ? 1 : 0;
if (result) {
qDebug() << "xferinfo #" << "Cancelling upload from the progress callback...";
}
return result;
}
/* for libcurl older than 7.32.0 (CURLOPT_PROGRESSFUNCTION) */
static int older_progress(void *p,
double dltotal, double dlnow,
double ultotal, double ulnow)
{
return xferinfo(p,
(curl_off_t)dltotal,
(curl_off_t)dlnow,
(curl_off_t)ultotal,
(curl_off_t)ulnow);
}
void setCurlProgressCallback(CURL *curlHandle, CurlProgressReporter *progressReporter) {
curl_easy_setopt(curlHandle, CURLOPT_PROGRESSFUNCTION, older_progress);
/* pass the struct pointer into the progress function */
curl_easy_setopt(curlHandle, CURLOPT_PROGRESSDATA, progressReporter);
#if LIBCURL_VERSION_NUM >= 0x072000
/* xferinfo was introduced in 7.32.0, no earlier libcurl versions will
compile as they won't have the symbols around.
If built with a newer libcurl, but running with an older libcurl:
curl_easy_setopt() will fail in run-time trying to set the new
callback, making the older callback get used.
New libcurls will prefer the new callback and instead use that one even
if both callbacks are set. */
curl_easy_setopt(curlHandle, CURLOPT_XFERINFOFUNCTION, xferinfo);
/* pass the struct pointer into the xferinfo function, note that this is
an alias to CURLOPT_PROGRESSDATA */
curl_easy_setopt(curlHandle, CURLOPT_XFERINFODATA, progressReporter);
#endif
curl_easy_setopt(curlHandle, CURLOPT_NOPROGRESS, 0L);
}
bool uploadFile(CURL *curlHandle, UploadContext *context, CurlProgressReporter *progressReporter,
const QString &filepath, const QString &remoteUrl) {
bool result = false;
FILE *f;
long uploaded_len = 0;
CURLcode r = CURLE_GOT_NOTHING;
struct stat file_info;
int c;
curl_off_t fsize;
/* get the file size of the local file */
if (stat(filepath.toLocal8Bit().data(), &file_info)) {
qWarning() << "uploadFile #" << "Failed to stat file" << filepath;
return result;
}
fsize = (curl_off_t) file_info.st_size;
f = fopen(filepath.toLocal8Bit().data(), "rb");
if (f == NULL) {
qWarning() << "uploadFile #" << "Failed to open file" << filepath;
return result;
}
fillCurlOptions(curlHandle, context, remoteUrl);
setCurlProgressCallback(curlHandle, progressReporter);
curl_easy_setopt(curlHandle, CURLOPT_READDATA, f);
curl_easy_setopt(curlHandle, CURLOPT_INFILESIZE_LARGE,
(curl_off_t)fsize);
curl_easy_setopt(curlHandle, CURLOPT_HEADERDATA, &uploaded_len);
for (c = 0; (r != CURLE_OK) && (c < context->m_RetriesCount); c++) {
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
if (r == CURLE_ABORTED_BY_CALLBACK) {
qInfo() << "uploadFile #" << "Upload aborted by user...";
break;
}
/* are we resuming? */
if (c) { /* yes */
qDebug() << "uploadFile #" << "Attempting to resume upload" << uploaded_len << "try #" << c;
/* determine the length of the file already written */
/*
* With NOBODY and NOHEADER, libcurl will issue a SIZE
* command, but the only way to retrieve the result is
* to parse the returned Content-Length header. Thus,
* getcontentlengthfunc(). We need discardfunc() above
* because HEADER will dump the headers to stdout
* without it.
*/
curl_easy_setopt(curlHandle, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curlHandle, CURLOPT_HEADER, 1L);
r = curl_easy_perform(curlHandle);
if (r != CURLE_OK) {
qWarning() << "uploadFile #" << "Attempt failed! Curl error:" << curl_easy_strerror(r);
continue;
}
curl_easy_setopt(curlHandle, CURLOPT_NOBODY, 0L);
curl_easy_setopt(curlHandle, CURLOPT_HEADER, 0L);
fseek(f, uploaded_len, SEEK_SET);
curl_easy_setopt(curlHandle, CURLOPT_APPEND, 1L);
}
else { /* no */
curl_easy_setopt(curlHandle, CURLOPT_APPEND, 0L);
}
r = curl_easy_perform(curlHandle);
}
fclose(f);
result = (r == CURLE_OK);
if (!result) {
qWarning() << "uploadFile #" << "Upload failed! Curl error:" << curl_easy_strerror(r);
}
return result;
}
CurlProgressReporter::CurlProgressReporter(void *curl):
QObject(),
m_LastTime(0.0),
m_Curl(curl),
m_Cancel(false)
{
}
void CurlProgressReporter::updateProgress(double ultotal, double ulnow) {
if (fabs(ultotal) > 1e-6) {
double progress = ulnow * 100.0 / ultotal;
emit progressChanged(progress);
}
}
void CurlProgressReporter::cancelHandler() {
m_Cancel = true;
qDebug() << "CurlProgressReporter::cancelHandler #" << "Cancelled in the progress reporter...";
}
CurlFtpUploader::CurlFtpUploader(UploadBatch *batchToUpload, QObject *parent) :
QObject(parent),
m_BatchToUpload(batchToUpload),
m_UploadedCount(0),
m_Cancel(false),
m_LastPercentage(0.0)
{
m_TotalCount = batchToUpload->getFilesToUpload().length();
}
void CurlFtpUploader::uploadBatch() {
CURL *curlHandle = NULL;
bool anyErrors = false;
UploadContext *context = m_BatchToUpload->getContext();
if (m_Cancel) {
qWarning() << "CurlFtpUploader::uploadBatch #" << "Cancelled before upload." << context->m_Host;
return;
}
const QStringList &filesToUpload = m_BatchToUpload->getFilesToUpload();
int size = filesToUpload.size();
QString host = sanitizeHost(context->m_Host);
// curl_global_init should be done from coordinator
curlHandle = curl_easy_init();
CurlProgressReporter progressReporter(curlHandle);
QObject::connect(&progressReporter, SIGNAL(progressChanged(double)),
this, SLOT(reportCurrentFileProgress(double)));
QObject::connect(this, SIGNAL(cancelCurrentUpload()), &progressReporter, SLOT(cancelHandler()));
// temporary do not emit started signal: not used
//emit uploadStarted();
qDebug() << "CurlFtpUploader::uploadBatch #" << "Uploading" << size << "file(s) started for" << host << "Passive mode =" << context->m_UsePassiveMode;
for (int i = 0; i < size; ++i) {
if (m_Cancel) {
qWarning() << "CurlFtpUploader::uploadBatch #" << "Cancelled. Breaking..." << host;
break;
}
reportCurrentFileProgress(0.0);
const QString &filepath = filesToUpload.at(i);
QFileInfo fi(filepath);
QString remoteUrl = host + fi.fileName();
bool uploadSuccess = false;
try {
uploadSuccess = uploadFile(curlHandle, context, &progressReporter, filepath, remoteUrl);
} catch (...) {
qWarning() << "CurlFtpUploader::uploadBatch #" << "CRASHED for file" << filepath << "for host" << host;
}
if (!uploadSuccess) {
anyErrors = true;
emit transferFailed(filepath, host);
}
// TODO: only update progress of not-failed uploads
if (uploadSuccess) {
m_UploadedCount++;
}
}
reportCurrentFileProgress(0.0);
emit uploadFinished(anyErrors);
qDebug() << "CurlFtpUploader::uploadBatch #" << "Uploading finished for" << host;
curl_easy_cleanup(curlHandle);
// curl_global_cleanup should be done from coordinator
}
void CurlFtpUploader::cancel() {
m_Cancel = true;
emit cancelCurrentUpload();
}
void CurlFtpUploader::reportCurrentFileProgress(double percent) {
double newProgress = m_UploadedCount*100.0 + percent;
newProgress /= m_TotalCount;
emit progressChanged(m_LastPercentage, newProgress);
m_LastPercentage = newProgress;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Author: Panos Christakoglou. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------
// AliTagAnalysis class
// This is the class to deal with the tag analysis
// Origin: Panos Christakoglou, UOA-CERN, Panos.Christakoglou@cern.ch
//-----------------------------------------------------------------
//ROOT
#include <TSystem.h>
#include <TChain.h>
#include <TFile.h>
#include <TEventList.h>
#include <TFileInfo.h>
//ROOT-AliEn
#include <TGridResult.h>
#include "AliLog.h"
#include "AliRunTag.h"
#include "AliEventTag.h"
#include "AliTagAnalysis.h"
#include "AliEventTagCuts.h"
class TTree;
ClassImp(AliTagAnalysis)
TChain *AliTagAnalysis::fgChain = 0;
//______________________________________________________________________________
AliTagAnalysis::AliTagAnalysis(): TObject()//local mode
{
//==============Default constructor for a AliTagAnalysis==================
ftagresult = 0;
}
//______________________________________________________________________________
AliTagAnalysis::~AliTagAnalysis()
{
//================Default destructor for a AliTagAnalysis=======================
}
//______________________________________________________________________________
void AliTagAnalysis::ChainLocalTags(const char *dirname) //local version
{
//Searches the entries of the provided direcory
//Chains the tags that are stored locally
fTagDirName = dirname;
TString fTagFilename;
TChain *fgChain = new TChain("T");
fChain = fgChain;
const char * tagPattern = "tag";
// Open the working directory
void * dirp = gSystem->OpenDirectory(fTagDirName);
const char * name = 0x0;
// Add all files matching *pattern* to the chain
while((name = gSystem->GetDirEntry(dirp)))
{
if (strstr(name,tagPattern))
{
fTagFilename = fTagDirName;
fTagFilename += "/";
fTagFilename += name;
TFile * fTag = TFile::Open(fTagFilename);
if((!fTag) || (!fTag->IsOpen()))
{
AliError(Form("Tag file not opened!!!"));
continue;
}
fChain->Add(fTagFilename);
fTag->Close();
delete fTag;
}//pattern check
}//directory loop
AliInfo(Form("Chained tag files: %d ",fChain->GetEntries()));
}
//______________________________________________________________________________
void AliTagAnalysis::ChainGridTags(TGridResult *res)
{
//Loops overs the entries of the TGridResult
//Chains the tags that are stored in the GRID
ftagresult = res;
Int_t nEntries = ftagresult->GetEntries();
TChain *fgChain = new TChain("T");
fChain = fgChain;
TString gridname = "alien://";
TString alienUrl;
for(Int_t i = 0; i < nEntries; i++)
{
alienUrl = ftagresult->GetKey(i,"turl");
TFile *f = TFile::Open(alienUrl,"READ");
fChain->Add(alienUrl);
//f->Close();
delete f;
}//grid result loop
}
//______________________________________________________________________________
TChain *AliTagAnalysis::QueryTags(AliEventTagCuts *EvTagCuts)
{
//Queries the tag chain using the defined
//event tag cuts from the AliEventTagCuts object
AliInfo(Form("Querying the tags........"));
//ESD file chain
TChain *fESDchain = new TChain("esdTree");
//Event list
TEventList *fEventList = new TEventList();
//Defining tag objects
AliRunTag *tag = new AliRunTag;
AliEventTag *evTag = new AliEventTag;
fChain->SetBranchAddress("AliTAG",&tag);
Long64_t size = -1;
const char* md5 = 0;
const char* guid = 0;
const char* turl = 0;
Int_t iAccepted = 0;
for(Int_t iTagFiles = 0; iTagFiles < fChain->GetEntries(); iTagFiles++) {
fChain->GetEntry(iTagFiles);
Int_t iEvents = tag->GetNEvents();
const TClonesArray *tagList = tag->GetEventTags();
for(Int_t i = 0; i < iEvents; i++) {
evTag = (AliEventTag *) tagList->At(i);
size = evTag->GetSize();
md5 = evTag->GetMD5();
guid = evTag->GetGUID();
turl = evTag->GetTURL();
if(EvTagCuts->IsAccepted(evTag)) fEventList->Enter(iAccepted+i);
}//event loop
iAccepted += iEvents;
fESDchain->Add(turl);
}//tag file loop
AliInfo(Form("Accepted events: %d",fEventList->GetN()));
fESDchain->SetEventList(fEventList);
return fESDchain;
}
<commit_msg>i) Removed the TFileInfo.h which was there since the previous version where it was used. ii) Added the possibility to use the event tag system with locally stored ESDs by modifying the AliTagAnalysis::QueryTags method.<commit_after>/**************************************************************************
* Author: Panos Christakoglou. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------
// AliTagAnalysis class
// This is the class to deal with the tag analysis
// Origin: Panos Christakoglou, UOA-CERN, Panos.Christakoglou@cern.ch
//-----------------------------------------------------------------
//ROOT
#include <TSystem.h>
#include <TChain.h>
#include <TFile.h>
#include <TEventList.h>
//ROOT-AliEn
#include <TGridResult.h>
#include "AliLog.h"
#include "AliRunTag.h"
#include "AliEventTag.h"
#include "AliTagAnalysis.h"
#include "AliEventTagCuts.h"
class TTree;
ClassImp(AliTagAnalysis)
TChain *AliTagAnalysis::fgChain = 0;
//___________________________________________________________________________
AliTagAnalysis::AliTagAnalysis():
TObject(),
ftagresult(0)
{
//Default constructor for a AliTagAnalysis
}
//___________________________________________________________________________
AliTagAnalysis::~AliTagAnalysis() {
//Default destructor for a AliTagAnalysis
}
//___________________________________________________________________________
void AliTagAnalysis::ChainLocalTags(const char *dirname) {
//Searches the entries of the provided direcory
//Chains the tags that are stored locally
fTagDirName = dirname;
TString fTagFilename;
TChain *fgChain = new TChain("T");
fChain = fgChain;
const char * tagPattern = "tag";
// Open the working directory
void * dirp = gSystem->OpenDirectory(fTagDirName);
const char * name = 0x0;
// Add all files matching *pattern* to the chain
while((name = gSystem->GetDirEntry(dirp))) {
if (strstr(name,tagPattern)) {
fTagFilename = fTagDirName;
fTagFilename += "/";
fTagFilename += name;
TFile * fTag = TFile::Open(fTagFilename);
if((!fTag) || (!fTag->IsOpen())) {
AliError(Form("Tag file not opened!!!"));
continue;
}
fChain->Add(fTagFilename);
fTag->Close();
delete fTag;
}//pattern check
}//directory loop
AliInfo(Form("Chained tag files: %d ",fChain->GetEntries()));
}
//___________________________________________________________________________
void AliTagAnalysis::ChainGridTags(TGridResult *res) {
//Loops overs the entries of the TGridResult
//Chains the tags that are stored in the GRID
ftagresult = res;
Int_t nEntries = ftagresult->GetEntries();
TChain *fgChain = new TChain("T");
fChain = fgChain;
TString gridname = "alien://";
TString alienUrl;
for(Int_t i = 0; i < nEntries; i++) {
alienUrl = ftagresult->GetKey(i,"turl");
TFile *f = TFile::Open(alienUrl,"READ");
fChain->Add(alienUrl);
delete f;
}//grid result loop
}
//___________________________________________________________________________
TChain *AliTagAnalysis::QueryTags(AliEventTagCuts *EvTagCuts) {
//Queries the tag chain using the defined
//event tag cuts from the AliEventTagCuts object
AliInfo(Form("Querying the tags........"));
//ESD file chain
TChain *fESDchain = new TChain("esdTree");
//Event list
TEventList *fEventList = new TEventList();
//Defining tag objects
AliRunTag *tag = new AliRunTag;
AliEventTag *evTag = new AliEventTag;
fChain->SetBranchAddress("AliTAG",&tag);
Long64_t size = -1;
const char* md5 = 0;
const char* guid = 0;
const char* turl = 0;
const char* path = 0;
Int_t iAccepted = 0;
for(Int_t iTagFiles = 0; iTagFiles < fChain->GetEntries(); iTagFiles++) {
fChain->GetEntry(iTagFiles);
Int_t iEvents = tag->GetNEvents();
const TClonesArray *tagList = tag->GetEventTags();
for(Int_t i = 0; i < iEvents; i++) {
evTag = (AliEventTag *) tagList->At(i);
size = evTag->GetSize();
md5 = evTag->GetMD5();
guid = evTag->GetGUID();
turl = evTag->GetTURL();
path = evTag->GetPath();
if(EvTagCuts->IsAccepted(evTag)) fEventList->Enter(iAccepted+i);
}//event loop
iAccepted += iEvents;
if(path != NULL) fESDchain->Add(path);
else if(turl != NULL) fESDchain->Add(turl);
}//tag file loop
AliInfo(Form("Accepted events: %d",fEventList->GetN()));
fESDchain->SetEventList(fEventList);
return fESDchain;
}
<|endoftext|> |
<commit_before>#include <sodium.h>
#include <fstream>
#include "base64.h"
#include "deltacommon.h"
path& path_append(path &_this, path::iterator begin, path::iterator end)
{
for (; begin != end; ++begin)
_this /= *begin;
return _this;
}
path make_path_relative(path a_From, path a_To)
{
a_From = absolute(a_From); a_To = absolute(a_To);
path ret;
path::const_iterator itrFrom(a_From.begin()), itrTo(a_To.begin());
for (path::const_iterator toEnd(a_To.end()), fromEnd(a_From.end());
itrFrom != fromEnd && itrTo != toEnd && *itrFrom == *itrTo;
++itrFrom, ++itrTo);
for (path::const_iterator fromEnd(a_From.end()); itrFrom != fromEnd; ++itrFrom)
{
if ((*itrFrom) != ".")
ret /= "..";
}
return path_append(ret, itrTo, a_To.end());
}
void process_tree(path &p, std::function<void(path &path, recursive_directory_iterator &i)> f)
{
recursive_directory_iterator end;
for (recursive_directory_iterator i(p); i != end; ++i) {
file_type type = i->status().type();
if (!is_directory(i->status()) && !is_regular_file(i->status()) && !is_symlink(i->status())) {
continue;
}
path rel_path(make_path_relative(p, i->path()));
if (!rel_path.empty())
f(rel_path, i);
}
}
void hash_delta_info(std::string &p, struct delta_info &di, crypto_generichash_state &state)
{
crypto_generichash_update(&state, (const unsigned char *) p.c_str(), sizeof(di.hash.c_str()));
crypto_generichash_update(&state, (const unsigned char *) &di.type, sizeof(decltype(di.type)));
crypto_generichash_update(&state, (const unsigned char *) &di.size, sizeof(decltype(di.size)));
crypto_generichash_update(&state, (const unsigned char *) di.hash.c_str(), sizeof(di.hash.c_str()));
}
void hash_entry(recursive_directory_iterator &i, crypto_generichash_state &state)
{
auto &path = i->path();
size_t size = 0;
if (is_regular_file(i->status()))
size = (size_t)file_size(i->path());
if (is_regular(i->status()) || is_symlink(i->status())) {
char chunk_buffer[16 * 1024];
size_t chunk_buffer_size = sizeof(chunk_buffer);
size_t chunk_cnt = size / chunk_buffer_size;
size_t last_chunk_size = size % chunk_buffer_size;
std::ifstream file(path.generic_string(), std::ifstream::binary);
if (last_chunk_size != 0)
++chunk_cnt;
else
last_chunk_size = chunk_buffer_size;
for (size_t chunk = 0; chunk < chunk_cnt; ++chunk) {
size_t chunk_size = chunk_buffer_size;
if (chunk == chunk_cnt - 1)
chunk_size = last_chunk_size;
file.read(&chunk_buffer[0], chunk_size);
crypto_generichash_update(&state, (unsigned char *)&chunk_buffer[0], chunk_size);
}
return;
}
if (is_directory(i->status())) {
crypto_generichash_update(&state, (const unsigned char *)"d", 1);
}
}
std::string hash_entry(recursive_directory_iterator &i)
{
crypto_generichash_state state;
unsigned char hash[crypto_generichash_BYTES];
crypto_generichash_init(&state, NULL, 0, sizeof(hash));
hash_entry(i, state);
crypto_generichash_final(&state, hash, sizeof(hash));
return std::string(base64_encode(&hash[0], sizeof(hash)));
}
path get_temp_directory() {
path p(unique_path());
return temp_directory_path() / p;
}<commit_msg>Fix bug in hashing<commit_after>#include <sodium.h>
#include <fstream>
#include "base64.h"
#include "deltacommon.h"
path& path_append(path &_this, path::iterator begin, path::iterator end)
{
for (; begin != end; ++begin)
_this /= *begin;
return _this;
}
path make_path_relative(path a_From, path a_To)
{
a_From = absolute(a_From); a_To = absolute(a_To);
path ret;
path::const_iterator itrFrom(a_From.begin()), itrTo(a_To.begin());
for (path::const_iterator toEnd(a_To.end()), fromEnd(a_From.end());
itrFrom != fromEnd && itrTo != toEnd && *itrFrom == *itrTo;
++itrFrom, ++itrTo);
for (path::const_iterator fromEnd(a_From.end()); itrFrom != fromEnd; ++itrFrom)
{
if ((*itrFrom) != ".")
ret /= "..";
}
return path_append(ret, itrTo, a_To.end());
}
void process_tree(path &p, std::function<void(path &path, recursive_directory_iterator &i)> f)
{
recursive_directory_iterator end;
for (recursive_directory_iterator i(p); i != end; ++i) {
file_type type = i->status().type();
if (!is_directory(i->status()) && !is_regular_file(i->status()) && !is_symlink(i->status())) {
continue;
}
path rel_path(make_path_relative(p, i->path()));
if (!rel_path.empty())
f(rel_path, i);
}
}
void hash_delta_info(std::string &p, struct delta_info &di, crypto_generichash_state &state)
{
crypto_generichash_update(&state, (const unsigned char *) p.c_str(), strlen(p.c_str()));
crypto_generichash_update(&state, (const unsigned char *) &di.type, sizeof(decltype(di.type)));
crypto_generichash_update(&state, (const unsigned char *) &di.size, sizeof(decltype(di.size)));
crypto_generichash_update(&state, (const unsigned char *) di.hash.c_str(), strlen(di.hash.c_str()));
}
void hash_entry(recursive_directory_iterator &i, crypto_generichash_state &state)
{
auto &path = i->path();
size_t size = 0;
if (is_regular_file(i->status()))
size = (size_t)file_size(i->path());
if (is_regular(i->status()) || is_symlink(i->status())) {
char chunk_buffer[16 * 1024];
size_t chunk_buffer_size = sizeof(chunk_buffer);
size_t chunk_cnt = size / chunk_buffer_size;
size_t last_chunk_size = size % chunk_buffer_size;
std::ifstream file(path.native(), std::ifstream::binary);
if (last_chunk_size != 0)
++chunk_cnt;
else
last_chunk_size = chunk_buffer_size;
for (size_t chunk = 0; chunk < chunk_cnt; ++chunk) {
size_t chunk_size = chunk_buffer_size;
if (chunk == chunk_cnt - 1)
chunk_size = last_chunk_size;
file.read(&chunk_buffer[0], chunk_size);
crypto_generichash_update(&state, (unsigned char *)&chunk_buffer[0], chunk_size);
}
return;
}
if (is_directory(i->status())) {
crypto_generichash_update(&state, (const unsigned char *)"d", 1);
}
}
std::string hash_entry(recursive_directory_iterator &i)
{
crypto_generichash_state state;
unsigned char hash[crypto_generichash_BYTES];
crypto_generichash_init(&state, NULL, 0, sizeof(hash));
hash_entry(i, state);
crypto_generichash_final(&state, hash, sizeof(hash));
return std::string(base64_encode(&hash[0], sizeof(hash)));
}
path get_temp_directory() {
path p(unique_path());
return temp_directory_path() / p;
}<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_APPLY_VECTOR_UNARY_HPP
#define STAN_MATH_REV_FUNCTOR_APPLY_VECTOR_UNARY_HPP
#include <stan/math/prim/functor/apply_vector_unary.hpp>
#include <stan/math/rev/core/var.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Specialisation for use with `var_value<T>` types where T inherits from
* EigenBase. Inputs are passed through unmodified.
*/
template <typename T>
struct apply_vector_unary<T, require_var_matrix_t<T>> {
/**
* Member function for applying a functor to a `var_value<T>` and
* subsequently returning a `var_value<T>`.
*
* @tparam T Type of argument to which functor is applied.
* @tparam F Type of functor to apply.
* @param x input to which operation is applied.
* @param f functor to apply to Eigen input.
* @return object with result of applying functor to input
*/
template <typename F>
static inline T apply(const T& x, const F& f) {
return f(x);
}
/**
* Member function for applying a functor to a `var_value<T>` and
* subsequently returning a var. The reduction to a var needs
* to be implemented in the definition of the functor.
*
* @tparam T Type of argument to which functor is applied.
* @tparam F Type of functor to apply.
* @param x input to which operation is applied.
* @param f functor to apply to input.
* @return scalar result of applying functor to input.
*/
template <typename F>
static inline var reduce(const T& x, const F& f) {
return f(x);
}
};
} // namespace math
} // namespace stan
#endif
<commit_msg>bugfix rev apply_vector_unary<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_APPLY_VECTOR_UNARY_HPP
#define STAN_MATH_REV_FUNCTOR_APPLY_VECTOR_UNARY_HPP
#include <stan/math/prim/functor/apply_vector_unary.hpp>
#include <stan/math/rev/core/var.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Specialisation for use with `var_value<T>` types where T inherits from
* EigenBase. Inputs are passed through unmodified.
*/
template <typename T>
struct apply_vector_unary<T, require_var_matrix_t<T>> {
/**
* Member function for applying a functor to a `var_value<T>` and
* subsequently returning a `var_value<T>`.
*
* @tparam T Type of argument to which functor is applied.
* @tparam F Type of functor to apply.
* @param x input to which operation is applied.
* @param f functor to apply to Eigen input.
* @return object with result of applying functor to input
*/
template <typename F>
static inline T apply(const T& x, const F& f) {
return f(x);
}
/**
* Member function for applying a functor to a `var_value<T>` and
* subsequently returning a `var_value<T>`.
*
* @tparam T Type of argument to which functor is applied.
* @tparam F Type of functor to apply.
* @param x input to which operation is applied.
* @param f functor to apply to Eigen input.
* @return object with result of applying functor to input
*/
template <typename F>
static inline T apply_no_holder(const T& x, const F& f) {
return f(x);
}
/**
* Member function for applying a functor to a `var_value<T>` and
* subsequently returning a var. The reduction to a var needs
* to be implemented in the definition of the functor.
*
* @tparam T Type of argument to which functor is applied.
* @tparam F Type of functor to apply.
* @param x input to which operation is applied.
* @param f functor to apply to input.
* @return scalar result of applying functor to input.
*/
template <typename F>
static inline var reduce(const T& x, const F& f) {
return f(x);
}
};
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/**
* An example program utilizing most/all calls from the CUDA
* Runtime API module:
*
* Device Management
*
* but does not include the API calls relating to IPC (inter-
* process communication) - sharing pointers to device memory
* and events among operating system process. That should be
* covered by a different program.
*
*/
#include <cuda/api/device.hpp>
#include <cuda/api/devices.hpp>
#include <cuda/api/error.hpp>
#include <cuda/api/miscellany.hpp>
#include <cuda/api/pci_id_impl.hpp>
#include <cuda/api/peer_to_peer.hpp>
#include <cuda_runtime_api.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cassert>
[[noreturn]] void die_(const std::string& message)
{
std::cerr << message << "\n";
exit(EXIT_FAILURE);
}
int main(int argc, char **argv)
{
if (cuda::device::count() == 0) {
die_("No CUDA devices on this system");
}
// TODO: cudaChooseDevice
// Being very cavalier about our command-line arguments here...
cuda::device::id_t device_id = (argc > 1) ?
std::stoi(argv[1]) : cuda::device::default_device_id;
if (cuda::device::count() <= device_id) {
die_("No CUDA device with ID " + std::to_string(device_id));
}
auto device = cuda::device::get(device_id);
std::cout << "Using CUDA device " << device.name() << " (having device ID " << device.id() << ")\n";
if (device.id() != device_id) {
die_("The device's reported ID and the ID for which we created the device differ: "
+ std::to_string(device.id()) + " !=" + std::to_string(device_id));
}
if (device.id() != device.memory().device_id()) {
die_("The device's reported ID and the device's memory object's reported device ID differ: "
+ std::to_string(device.id()) + " !=" + std::to_string(device.memory().device_id()));
}
// Attributes and properties
// ---------------------------
auto max_registers_per_block = device.get_attribute(cudaDevAttrMaxRegistersPerBlock);
std::cout
<< "Maximum number of registers per block on this device: "
<< max_registers_per_block << "\n";
assert(device.properties().regsPerBlock == max_registers_per_block);
// PCI bus IDs
// --------------------
auto pci_id = device.pci_id();
std::string pci_id_str(pci_id);
cuda::outstanding_error::ensure_none(cuda::do_clear_errors);
auto re_obtained_device = cuda::device::get(pci_id_str);
assert(re_obtained_device == device);
// Memory - total and available
// -----------------------------------
auto device_global_mem = device.memory();
auto total_memory = device_global_mem.amount_total();
auto free_memory = device_global_mem.amount_total();
std::cout
<< "Device " << std::to_string(device.id()) << " reports it has:\n"
<< free_memory << " Bytes free out of " << total_memory << " Bytes total global memory.\n";
assert(free_memory <= total_memory);
// Specific attributes and properties with their own API calls:
// L1/shared mem (CacheConfig), shared memory bank size (SharedMemConfig)
// and stream priority range
// ----------------------------------------------------------------
std::string cache_preference_names[] = {
"No preference",
"Equal L1 and shared memory",
"Prefer shared memory over L1",
"Prefer L1 over shared memory",
};
auto cache_preference = device.cache_preference();
std::cout << "The cache preference for device " << device.id() << " is: "
<< cache_preference_names[(unsigned) cache_preference] << ".\n";
auto new_cache_preference =
cache_preference == cuda::multiprocessor_cache_preference_t::prefer_l1_over_shared_memory ?
cuda::multiprocessor_cache_preference_t::prefer_shared_memory_over_l1 :
cuda::multiprocessor_cache_preference_t::prefer_l1_over_shared_memory;
device.set_cache_preference(new_cache_preference);
cache_preference = device.cache_preference();
assert(cache_preference == new_cache_preference);
auto shared_mem_bank_size = device.shared_memory_bank_size();
shared_mem_bank_size =
(shared_mem_bank_size == cudaSharedMemBankSizeFourByte) ?
cudaSharedMemBankSizeEightByte : cudaSharedMemBankSizeFourByte;
device.set_shared_memory_bank_size(shared_mem_bank_size);
auto stream_priority_range = device.stream_priority_range();
if (stream_priority_range.is_trivial()) {
std::cout << "Device " << device.id() << " does not support stream priorities. "
"All streams will have the same (default) priority.\n";
}
else {
std::cout << "Streams on device " << device.id() << " have priorities between "
<< stream_priority_range.least << " (highest numeric value, least prioritized) and "
<< std::to_string(stream_priority_range.greatest) << "(lowest numeric values, most prioritized).\n";
assert(stream_priority_range.least > stream_priority_range.greatest);
}
// Resource limits
// --------------------
auto printf_fifo_size = device.get_resource_limit(cudaLimitPrintfFifoSize);
std::cout << "The printf FIFO size for device " << device_id << " is " << printf_fifo_size << ".\n";
decltype(printf_fifo_size) new_printf_fifo_size =
(printf_fifo_size <= 1024) ? 2 * printf_fifo_size : printf_fifo_size - 512;
device.set_resource_limit(cudaLimitPrintfFifoSize, new_printf_fifo_size);
printf_fifo_size = device.get_resource_limit(cudaLimitPrintfFifoSize);
assert(printf_fifo_size == new_printf_fifo_size);
// Flags - yes, yet another kind of attribute/property
// ----------------------------------------------------
std::cout << "Device " << device.id() << " uses a"
<< (device.synch_scheduling_policy() ? " synchronous" : "n asynchronous")
<< " scheduling policy.\n";
std::cout << "Device " << device.id() << " is set to "
<< (device.keeping_larger_local_mem_after_resize() ? "keeps" : "discards")
<< " shared memory allocation after launch.\n";
std::cout << "Device " << device.id()
<< " is set " << (device.can_map_host_memory() ? "to allow" : "not to allow")
<< " pinned mapped memory.\n";
// TODO: Change the settings as well obtaining them
// Peer-to-peer
// --------------------
auto device_count = cuda::device::count();
if (device_count > 1) {
// This makes assumptions about the valid IDs and their use
auto peer_id = (argc > 2) ?
std::stoi(argv[2]): (device.id() + 1) % cuda::device::count();
auto peer_device = cuda::device::get(peer_id);
if (device.can_access(peer_device)) {
auto atomics_supported_over_link = cuda::device::peer_to_peer::get_attribute(
cudaDevP2PAttrNativeAtomicSupported, cuda::device::get(device_id), cuda::device::get(peer_id));
std::cout
<< "Native atomics are " << (atomics_supported_over_link ? "" : "not ")
<< "supported over the link from device " << device_id
<< " to device " << peer_id << ".\n";
device.disable_access_to(peer_device);
// TODO: Try some device-to-device access here, expect an exception
device.enable_access_to(peer_device);
// TODO: Try some device-to-device access here
}
}
// Current device manipulation
// ----------------------------
if (device_count > 1) {
auto device_0 = cuda::device::get(0);
auto device_1 = cuda::device::get(1);
cuda::device::current::set(device_0);
assert(cuda::device::current::get() == device_0);
assert(cuda::device::current::detail_::get_id() == device_0.id());
cuda::device::current::set(device_1);
assert(cuda::device::current::get() == device_1);
assert(cuda::device::current::detail_::get_id() == device_1.id());
}
try {
cuda::device::current::detail_::set(device_count);
die_("Should not have been able to set the current device to "
+ std::to_string(device_count) + " since that's the device count, and "
+ "the maximum valid ID should be " + std::to_string(device_count - 1)
+ " (one less)");
}
catch(cuda::runtime_error& e) {
assert(e.code() == cuda::status::invalid_device);
// We expected to get this exception, just clear it
cuda::outstanding_error::clear();
}
// Iterate over all devices
// ------------------------
auto devices = cuda::devices();
assert(devices.size() == cuda::device::count());
std::cout << "There are " << devices.size() << " 'elements' in devices().\n";
std::cout << "Let's count the device IDs... ";
for(auto device : cuda::devices()) {
std::cout << (int) device.id() << ' ';
device.synchronize();
}
std::cout << '\n';
// Synchronize and reset
// --------------------
device.synchronize();
device.reset();
std::cout << "\nSUCCESS\n";
return EXIT_SUCCESS;
}
<commit_msg>Refactoring the `device_management.cu` example program into multiple smaller functions.<commit_after>/**
* An example program utilizing most/all calls from the CUDA
* Runtime API module:
*
* Device Management
*
* but does not include the API calls relating to IPC (inter-
* process communication) - sharing pointers to device memory
* and events among operating system process. That should be
* covered by a different program.
*
*/
#include <cuda/api/device.hpp>
#include <cuda/api/devices.hpp>
#include <cuda/api/error.hpp>
#include <cuda/api/miscellany.hpp>
#include <cuda/api/pci_id_impl.hpp>
#include <cuda/api/peer_to_peer.hpp>
#include <cuda_runtime_api.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cassert>
[[noreturn]] void die_(const std::string& message)
{
std::cerr << message << "\n";
exit(EXIT_FAILURE);
}
namespace tests {
void basics(cuda::device::id_t device_id)
{
// TODO: cudaChooseDevice
// Being very cavalier about our command-line arguments here...
if (cuda::device::count() <= device_id) {
die_("No CUDA device with ID " + std::to_string(device_id));
}
auto device = cuda::device::get(device_id);
std::cout << "Using CUDA device " << device.name() << " (having device ID " << device.id() << ")\n";
if (device.id() != device_id) {
die_("The device's reported ID and the ID for which we created the device differ: "
+ std::to_string(device.id()) + " !=" + std::to_string(device_id));
}
if (device.id() != device.memory().device_id()) {
die_("The device's reported ID and the device's memory object's reported device ID differ: "
+ std::to_string(device.id()) + " !=" + std::to_string(device.memory().device_id()));
}
}
void attributes_and_properties()
{
auto device = cuda::device::current::get();
auto max_registers_per_block = device.get_attribute(cudaDevAttrMaxRegistersPerBlock);
std::cout
<< "Maximum number of registers per block on this device: "
<< max_registers_per_block << "\n";
assert(device.properties().regsPerBlock == max_registers_per_block);
}
void pci_bus_id()
{
auto device = cuda::device::current::get();
auto pci_id = device.pci_id();
std::string pci_id_str(pci_id);
cuda::outstanding_error::ensure_none(cuda::do_clear_errors);
auto re_obtained_device = cuda::device::get(pci_id_str);
assert(re_obtained_device == device);
}
void global_memory()
{
auto device = cuda::device::current::get();
auto device_global_mem = device.memory();
auto total_memory = device_global_mem.amount_total();
auto free_memory = device_global_mem.amount_total();
std::cout
<< "Device " << std::to_string(device.id()) << " reports it has:\n"
<< free_memory << " Bytes free out of " << total_memory << " Bytes total global memory.\n";
assert(free_memory <= total_memory);
}
// Specific attributes and properties with their own API calls:
// L1/shared mem (CacheConfig), shared memory bank size (SharedMemConfig)
// and stream priority range
void shared_memory()
{
auto device = cuda::device::current::get();
std::string cache_preference_names[] = {
"No preference",
"Equal L1 and shared memory",
"Prefer shared memory over L1",
"Prefer L1 over shared memory",
};
auto cache_preference = device.cache_preference();
std::cout << "The cache preference for device " << device.id() << " is: "
<< cache_preference_names[(unsigned) cache_preference] << ".\n";
auto new_cache_preference =
cache_preference == cuda::multiprocessor_cache_preference_t::prefer_l1_over_shared_memory ?
cuda::multiprocessor_cache_preference_t::prefer_shared_memory_over_l1 :
cuda::multiprocessor_cache_preference_t::prefer_l1_over_shared_memory;
device.set_cache_preference(new_cache_preference);
cache_preference = device.cache_preference();
assert(cache_preference == new_cache_preference);
auto shared_mem_bank_size = device.shared_memory_bank_size();
shared_mem_bank_size =
(shared_mem_bank_size == cudaSharedMemBankSizeFourByte) ?
cudaSharedMemBankSizeEightByte : cudaSharedMemBankSizeFourByte;
device.set_shared_memory_bank_size(shared_mem_bank_size);
}
void stream_priority_range()
{
auto device = cuda::device::current::get();
auto stream_priority_range = device.stream_priority_range();
if (stream_priority_range.is_trivial()) {
std::cout << "Device " << device.id() << " does not support stream priorities. "
"All streams will have the same (default) priority.\n";
}
else {
std::cout << "Streams on device " << device.id() << " have priorities between "
<< std::to_string(stream_priority_range.greatest) << " (lowest value, most prioritized) and "
<< stream_priority_range.least << " (highest value, least prioritized)\n";
assert(stream_priority_range.least > stream_priority_range.greatest);
}
}
void resource_limits()
{
auto device = cuda::device::current::get();
auto printf_fifo_size = device.get_resource_limit(cudaLimitPrintfFifoSize);
std::cout << "The printf FIFO size for device " << device.id() << " is " << printf_fifo_size << ".\n";
decltype(printf_fifo_size) new_printf_fifo_size =
(printf_fifo_size <= 1024) ? 2 * printf_fifo_size : printf_fifo_size - 512;
device.set_resource_limit(cudaLimitPrintfFifoSize, new_printf_fifo_size);
printf_fifo_size = device.get_resource_limit(cudaLimitPrintfFifoSize);
assert(printf_fifo_size == new_printf_fifo_size);
}
// Flags - yes, they're yet another kind of attribute/property
void flags()
{
auto device = cuda::device::current::get() ;
std::cout << "Device " << device.id() << " uses a"
<< (device.synch_scheduling_policy() ? " synchronous" : "n asynchronous")
<< " scheduling policy.\n";
std::cout << "Device " << device.id() << " is set to "
<< (device.keeping_larger_local_mem_after_resize() ? "keeps" : "discards")
<< " shared memory allocation after launch.\n";
std::cout << "Device " << device.id()
<< " is set " << (device.can_map_host_memory() ? "to allow" : "not to allow")
<< " pinned mapped memory.\n";
// TODO: Change the settings as well obtaining them
}
void peer_to_peer(std::pair<cuda::device::id_t,cuda::device::id_t> peer_ids)
{
// Assumes at least two devices are available
auto device = cuda::device::get(peer_ids.first);
// This makes assumptions about the valid IDs and their use
auto peer = cuda::device::get(peer_ids.second);
if (device.can_access(peer)) {
auto atomics_supported_over_link = cuda::device::peer_to_peer::get_attribute(
cudaDevP2PAttrNativeAtomicSupported, device, peer);
std::cout
<< "Native atomics are " << (atomics_supported_over_link ? "" : "not ")
<< "supported over the link from device " << device.id()
<< " to device " << peer.id() << ".\n";
device.disable_access_to(peer);
// TODO: Try some device-to-device access here, expect an exception
device.enable_access_to(peer);
// TODO: Try some device-to-device access here
}
}
void current_device_manipulation()
{
auto device_count = cuda::device::count();
if (device_count > 1) {
auto device_0 = cuda::device::get(0);
auto device_1 = cuda::device::get(1);
cuda::device::current::set(device_0);
assert(cuda::device::current::get() == device_0);
assert(cuda::device::current::detail_::get_id() == device_0.id());
cuda::device::current::set(device_1);
assert(cuda::device::current::get() == device_1);
assert(cuda::device::current::detail_::get_id() == device_1.id());
}
try {
cuda::device::current::detail_::set(device_count);
die_("Should not have been able to set the current device to "
+ std::to_string(device_count) + " since that's the device count, and "
+ "the maximum valid ID should be " + std::to_string(device_count - 1)
+ " (one less)");
}
catch(cuda::runtime_error& e) {
assert(e.code() == cuda::status::invalid_device);
// We expected to get this exception, just clear it
cuda::outstanding_error::clear();
}
// Iterate over all devices
// ------------------------
auto devices = cuda::devices();
assert(devices.size() == cuda::device::count());
std::cout << "There are " << devices.size() << " 'elements' in devices().\n";
std::cout << "Let's count the device IDs... ";
for(auto device : cuda::devices()) {
std::cout << (int) device.id() << ' ';
device.synchronize();
}
std::cout << '\n';
}
} // namespace tests
int main(int argc, char **argv)
{
if (cuda::device::count() == 0) {
die_("No CUDA devices on this system");
}
cuda::device::id_t device_id = (argc > 1) ?
std::stoi(argv[1]) : cuda::device::default_device_id;
tests::basics(device_id);
tests::attributes_and_properties();
tests::pci_bus_id();
tests::global_memory();
tests::shared_memory();
tests::stream_priority_range();
tests::resource_limits();
if (cuda::devices().size() > 1) {
auto peer_id = (argc > 2) ?
std::stoi(argv[2]) : (cuda::device::current::get().id() + 1) % cuda::device::count();
tests::peer_to_peer({device_id, peer_id});
tests::current_device_manipulation();
}
for (auto device : cuda::devices()) {
device.synchronize();
device.reset();
}
std::cout << "\nSUCCESS\n";
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#if BOOST_VERSION >= 103900
#include <boost/make_shared.hpp>
#else // BOOST_VERSION >= 103900
#include <boost/shared_ptr.hpp>
#endif // BOOST_VERSION >= 103900
// StdAir
#include <stdair/basic/BasConst_General.hpp>
#include <stdair/basic/BasConst_Event.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/OptimisationNotificationStruct.hpp>
#include <stdair/bom/SnapshotStruct.hpp>
#include <stdair/bom/CancellationStruct.hpp>
#include <stdair/bom/RMEventStruct.hpp>
#include <stdair/bom/EventStruct.hpp>
namespace stdair {
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct()
: _eventType (EventType::BKG_REQ), _eventTimeStamp (0) {
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
BookingRequestPtr_T ioRequestPtr)
: _eventType (iEventType) {
//
assert (ioRequestPtr != NULL);
#if BOOST_VERSION >= 103900
_bookingRequest = boost::make_shared<BookingRequestStruct> (*ioRequestPtr);
#else // BOOST_VERSION >= 103900
_bookingRequest = ioRequestPtr;
#endif // BOOST_VERSION >= 103900
assert (_bookingRequest != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the booking request and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_bookingRequest->getRequestDateTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
CancellationPtr_T ioCancellationPtr)
: _eventType (iEventType) {
//
assert (ioCancellationPtr != NULL);
#if BOOST_VERSION >= 103900
_cancellation = boost::make_shared<CancellationStruct> (*ioCancellationPtr);
#else // BOOST_VERSION >= 103900
_cancellation = ioCancellationPtr;
#endif // BOOST_VERSION >= 103900
assert (_cancellation != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the cancellation and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_cancellation->getCancellationDateTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::
EventStruct (const EventType::EN_EventType& iEventType,
const DateTime_T& iDCPDate,
OptimisationNotificationPtr_T ioOptimisationNotificationPtr)
: _eventType (iEventType) {
//
assert (ioOptimisationNotificationPtr != NULL);
#if BOOST_VERSION >= 103900
_optimisationNotification =
boost::make_shared<OptimisationNotificationStruct> (*ioOptimisationNotificationPtr);
#else // BOOST_VERSION >= 103900
_optimisationNotification = ioOptimisationNotificationPtr;
#endif // BOOST_VERSION >= 103900
assert (_optimisationNotification != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the booking request and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration = iDCPDate - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
SnapshotPtr_T ioSnapshotPtr)
: _eventType (iEventType) {
//
assert (ioSnapshotPtr != NULL);
#if BOOST_VERSION >= 103900
_snapshot = boost::make_shared<SnapshotStruct> (*ioSnapshotPtr);
#else // BOOST_VERSION >= 103900
_snapshot = ioSnapshotPtr;
#endif // BOOST_VERSION >= 103900
assert (_snapshot != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the snapshot and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_snapshot->getSnapshotTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
RMEventPtr_T ioRMEventPtr)
: _eventType (iEventType) {
//
assert (ioRMEventPtr != NULL);
#if BOOST_VERSION >= 103900
_rmEvent = boost::make_shared<RMEventStruct> (*ioRMEventPtr);
#else // BOOST_VERSION >= 103900
_rmEvent = ioRMEventPtr;
#endif // BOOST_VERSION >= 103900
assert (_rmEvent != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the RM event and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_rmEvent->getRMEventTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventStruct& iEventStruct)
: _eventType (iEventStruct._eventType),
_eventTimeStamp (iEventStruct._eventTimeStamp) {
//
if (iEventStruct._bookingRequest != NULL) {
#if BOOST_VERSION >= 103900
_bookingRequest =
boost::make_shared<BookingRequestStruct>(*iEventStruct._bookingRequest);
#else // BOOST_VERSION >= 103900
_bookingRequest = iEventStruct._bookingRequest;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._cancellation != NULL) {
#if BOOST_VERSION >= 103900
_cancellation =
boost::make_shared<CancellationStruct>(*iEventStruct._cancellation);
#else // BOOST_VERSION >= 103900
_cancellation = iEventStruct._cancellation;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._optimisationNotification != NULL) {
#if BOOST_VERSION >= 103900
_optimisationNotification =
boost::make_shared<OptimisationNotificationStruct> (*iEventStruct._optimisationNotification);
#else // BOOST_VERSION >= 103900
_optimisationNotification = iEventStruct._optimisationNotification;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._snapshot != NULL) {
#if BOOST_VERSION >= 103900
_snapshot = boost::make_shared<SnapshotStruct> (*iEventStruct._snapshot);
#else // BOOST_VERSION >= 103900
_snapshot = iEventStruct._snapshot;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._rmEvent != NULL) {
#if BOOST_VERSION >= 103900
_rmEvent = boost::make_shared<RMEventStruct> (*iEventStruct._rmEvent);
#else // BOOST_VERSION >= 103900
_rmEvent = iEventStruct._rmEvent;
#endif // BOOST_VERSION >= 103900
}
}
// //////////////////////////////////////////////////////////////////////
EventStruct::~EventStruct() {
}
// //////////////////////////////////////////////////////////////////////
void EventStruct::fromStream (std::istream& ioIn) {
}
// //////////////////////////////////////////////////////////////////////
const std::string EventStruct::describe() const {
std::ostringstream oStr;
//
const Duration_T lEventDateTimeDelta =
boost::posix_time::milliseconds (_eventTimeStamp);
const DateTime_T lEventDateTime (DEFAULT_EVENT_OLDEST_DATETIME
+ lEventDateTimeDelta);
oStr << lEventDateTime;
//
switch (_eventType) {
case EventType::BKG_REQ: {
assert (_bookingRequest != NULL);
oStr << ", " << _eventType << ", " << _bookingRequest->describe();
break;
}
case EventType::CX: {
assert (_cancellation != NULL);
oStr << ", " << _eventType << ", " << _cancellation->describe();
break;
}
case EventType::OPT_NOT_4_FD: {
assert (_optimisationNotification != NULL);
oStr << ", " << _eventType
<< ", " << _optimisationNotification->describe();
break;
}
case EventType::SNAPSHOT: {
assert (_snapshot != NULL);
oStr << ", " << _eventType
<< ", " << _snapshot->describe();
break;
}
case EventType::RM: {
assert (_rmEvent != NULL);
oStr << ", " << _eventType
<< ", " << _rmEvent->describe();
break;
}
default: {
oStr << ", " << _eventType << " (not yet recognised)";
break;
}
}
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
const DateTime_T& EventStruct::getEventTime() const {
const DateTime_T& lDateTime (DEFAULT_EVENT_OLDEST_DATETIME);
//
switch (_eventType) {
case EventType::BKG_REQ: {
assert (_bookingRequest != NULL);
return _bookingRequest->getRequestDateTime();
break;
}
case EventType::CX: {
assert (_cancellation != NULL);
return _cancellation->getCancellationDateTime() ;
break;
}
case EventType::OPT_NOT_4_FD: {
assert (_optimisationNotification != NULL);
return _optimisationNotification->getNotificationDateTime();
break;
}
case EventType::SNAPSHOT: {
assert (_snapshot != NULL);
return _snapshot->getSnapshotTime();
break;
}
case EventType::RM: {
assert (_rmEvent != NULL);
return _rmEvent->getRMEventTime();
break;
}
default: {
assert(false);
return lDateTime;
break;
}
}
return lDateTime;
}
// //////////////////////////////////////////////////////////////////////
void EventStruct::incrementEventTimeStamp() {
// The date-time is counted in milliseconds (1e-3 second). Hence,
// one thousand (1e3) of attempts correspond to 1 second.
// Increment the time stamp of one millisecond.
++_eventTimeStamp;
}
}
<commit_msg>[Dev] Added missing constructors for Event whose type is Break Point.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#if BOOST_VERSION >= 103900
#include <boost/make_shared.hpp>
#else // BOOST_VERSION >= 103900
#include <boost/shared_ptr.hpp>
#endif // BOOST_VERSION >= 103900
// StdAir
#include <stdair/basic/BasConst_General.hpp>
#include <stdair/basic/BasConst_Event.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/OptimisationNotificationStruct.hpp>
#include <stdair/bom/SnapshotStruct.hpp>
#include <stdair/bom/CancellationStruct.hpp>
#include <stdair/bom/RMEventStruct.hpp>
#include <stdair/bom/BreakPointStruct.hpp>
#include <stdair/bom/EventStruct.hpp>
namespace stdair {
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct()
: _eventType (EventType::BKG_REQ), _eventTimeStamp (0) {
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
BookingRequestPtr_T ioRequestPtr)
: _eventType (iEventType) {
//
assert (ioRequestPtr != NULL);
#if BOOST_VERSION >= 103900
_bookingRequest = boost::make_shared<BookingRequestStruct> (*ioRequestPtr);
#else // BOOST_VERSION >= 103900
_bookingRequest = ioRequestPtr;
#endif // BOOST_VERSION >= 103900
assert (_bookingRequest != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the booking request and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_bookingRequest->getRequestDateTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
CancellationPtr_T ioCancellationPtr)
: _eventType (iEventType) {
//
assert (ioCancellationPtr != NULL);
#if BOOST_VERSION >= 103900
_cancellation = boost::make_shared<CancellationStruct> (*ioCancellationPtr);
#else // BOOST_VERSION >= 103900
_cancellation = ioCancellationPtr;
#endif // BOOST_VERSION >= 103900
assert (_cancellation != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the cancellation and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_cancellation->getCancellationDateTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::
EventStruct (const EventType::EN_EventType& iEventType,
const DateTime_T& iDCPDate,
OptimisationNotificationPtr_T ioOptimisationNotificationPtr)
: _eventType (iEventType) {
//
assert (ioOptimisationNotificationPtr != NULL);
#if BOOST_VERSION >= 103900
_optimisationNotification =
boost::make_shared<OptimisationNotificationStruct> (*ioOptimisationNotificationPtr);
#else // BOOST_VERSION >= 103900
_optimisationNotification = ioOptimisationNotificationPtr;
#endif // BOOST_VERSION >= 103900
assert (_optimisationNotification != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the booking request and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration = iDCPDate - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
SnapshotPtr_T ioSnapshotPtr)
: _eventType (iEventType) {
//
assert (ioSnapshotPtr != NULL);
#if BOOST_VERSION >= 103900
_snapshot = boost::make_shared<SnapshotStruct> (*ioSnapshotPtr);
#else // BOOST_VERSION >= 103900
_snapshot = ioSnapshotPtr;
#endif // BOOST_VERSION >= 103900
assert (_snapshot != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the snapshot and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_snapshot->getSnapshotTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
RMEventPtr_T ioRMEventPtr)
: _eventType (iEventType) {
//
assert (ioRMEventPtr != NULL);
#if BOOST_VERSION >= 103900
_rmEvent = boost::make_shared<RMEventStruct> (*ioRMEventPtr);
#else // BOOST_VERSION >= 103900
_rmEvent = ioRMEventPtr;
#endif // BOOST_VERSION >= 103900
assert (_rmEvent != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the RM event and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_rmEvent->getRMEventTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventType::EN_EventType& iEventType,
BreakPointPtr_T ioBreakPointPtr)
: _eventType (iEventType) {
//
assert (ioBreakPointPtr != NULL);
#if BOOST_VERSION >= 103900
_breakPoint = boost::make_shared<BreakPointStruct> (*ioBreakPointPtr);
#else // BOOST_VERSION >= 103900
_breakPoint = ioBreakPointPtr;
#endif // BOOST_VERSION >= 103900
assert (_breakPoint != NULL);
/**
* Compute and store the number of milliseconds between the
* date-time of the RM event and DEFAULT_EVENT_OLDEST_DATETIME
* (as of Feb. 2011, that date is set to Jan. 1, 2010).
*/
const Duration_T lDuration =
_breakPoint->getBreakPointTime() - DEFAULT_EVENT_OLDEST_DATETIME;
_eventTimeStamp = lDuration.total_milliseconds();
}
// //////////////////////////////////////////////////////////////////////
EventStruct::EventStruct (const EventStruct& iEventStruct)
: _eventType (iEventStruct._eventType),
_eventTimeStamp (iEventStruct._eventTimeStamp) {
//
if (iEventStruct._bookingRequest != NULL) {
#if BOOST_VERSION >= 103900
_bookingRequest =
boost::make_shared<BookingRequestStruct>(*iEventStruct._bookingRequest);
#else // BOOST_VERSION >= 103900
_bookingRequest = iEventStruct._bookingRequest;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._cancellation != NULL) {
#if BOOST_VERSION >= 103900
_cancellation =
boost::make_shared<CancellationStruct>(*iEventStruct._cancellation);
#else // BOOST_VERSION >= 103900
_cancellation = iEventStruct._cancellation;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._optimisationNotification != NULL) {
#if BOOST_VERSION >= 103900
_optimisationNotification =
boost::make_shared<OptimisationNotificationStruct> (*iEventStruct._optimisationNotification);
#else // BOOST_VERSION >= 103900
_optimisationNotification = iEventStruct._optimisationNotification;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._snapshot != NULL) {
#if BOOST_VERSION >= 103900
_snapshot = boost::make_shared<SnapshotStruct> (*iEventStruct._snapshot);
#else // BOOST_VERSION >= 103900
_snapshot = iEventStruct._snapshot;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._rmEvent != NULL) {
#if BOOST_VERSION >= 103900
_rmEvent = boost::make_shared<RMEventStruct> (*iEventStruct._rmEvent);
#else // BOOST_VERSION >= 103900
_rmEvent = iEventStruct._rmEvent;
#endif // BOOST_VERSION >= 103900
}
//
if (iEventStruct._breakPoint != NULL) {
#if BOOST_VERSION >= 103900
_breakPoint = boost::make_shared<BreakPointStruct> (*iEventStruct._breakPoint);
#else // BOOST_VERSION >= 103900
_breakPoint = iEventStruct._breakPoint;
#endif // BOOST_VERSION >= 103900
}
}
// //////////////////////////////////////////////////////////////////////
EventStruct::~EventStruct() {
}
// //////////////////////////////////////////////////////////////////////
void EventStruct::fromStream (std::istream& ioIn) {
}
// //////////////////////////////////////////////////////////////////////
const std::string EventStruct::describe() const {
std::ostringstream oStr;
//
const Duration_T lEventDateTimeDelta =
boost::posix_time::milliseconds (_eventTimeStamp);
const DateTime_T lEventDateTime (DEFAULT_EVENT_OLDEST_DATETIME
+ lEventDateTimeDelta);
oStr << lEventDateTime;
//
switch (_eventType) {
case EventType::BKG_REQ: {
assert (_bookingRequest != NULL);
oStr << ", " << EventType::getLabel(_eventType)
<< ", " << _bookingRequest->describe();
break;
}
case EventType::CX: {
assert (_cancellation != NULL);
oStr << ", " << EventType::getLabel(_eventType)
<< ", " << _cancellation->describe();
break;
}
case EventType::OPT_NOT_4_FD: {
assert (_optimisationNotification != NULL);
oStr << ", " << EventType::getLabel(_eventType)
<< ", " << _optimisationNotification->describe();
break;
}
case EventType::SNAPSHOT: {
assert (_snapshot != NULL);
oStr << ", " << EventType::getLabel(_eventType)
<< ", " << _snapshot->describe();
break;
}
case EventType::RM: {
assert (_rmEvent != NULL);
oStr << ", " << EventType::getLabel(_eventType)
<< ", " << _rmEvent->describe();
break;
}
case EventType::BRK_PT: {
assert (_breakPoint != NULL);
oStr << ", " << EventType::getLabel(_eventType)
<< ", " << _breakPoint->describe();
break;
}
default: {
oStr << ", " << _eventType << " (not yet recognised)";
break;
}
}
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
const DateTime_T& EventStruct::getEventTime() const {
const DateTime_T& lDateTime (DEFAULT_EVENT_OLDEST_DATETIME);
//
switch (_eventType) {
case EventType::BKG_REQ: {
assert (_bookingRequest != NULL);
return _bookingRequest->getRequestDateTime();
break;
}
case EventType::CX: {
assert (_cancellation != NULL);
return _cancellation->getCancellationDateTime() ;
break;
}
case EventType::OPT_NOT_4_FD: {
assert (_optimisationNotification != NULL);
return _optimisationNotification->getNotificationDateTime();
break;
}
case EventType::SNAPSHOT: {
assert (_snapshot != NULL);
return _snapshot->getSnapshotTime();
break;
}
case EventType::RM: {
assert (_rmEvent != NULL);
return _rmEvent->getRMEventTime();
break;
}
case EventType::BRK_PT: {
assert (_breakPoint != NULL);
return _breakPoint->getBreakPointTime();
break;
}
default: {
assert(false);
return lDateTime;
break;
}
}
return lDateTime;
}
// //////////////////////////////////////////////////////////////////////
void EventStruct::incrementEventTimeStamp() {
// The date-time is counted in milliseconds (1e-3 second). Hence,
// one thousand (1e3) of attempts correspond to 1 second.
// Increment the time stamp of one millisecond.
++_eventTimeStamp;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_power_monitor.h"
#include <windows.h>
#include <wtsapi32.h>
#include "base/win/windows_types.h"
#include "base/win/wrapped_window_proc.h"
#include "ui/base/win/shell.h"
#include "ui/gfx/win/hwnd_util.h"
namespace electron {
namespace {
const wchar_t kPowerMonitorWindowClass[] = L"Electron_PowerMonitorHostWindow";
} // namespace
namespace api {
void PowerMonitor::InitPlatformSpecificMonitors() {
WNDCLASSEX window_class;
base::win::InitializeWindowClass(
kPowerMonitorWindowClass,
&base::win::WrappedWindowProc<PowerMonitor::WndProcStatic>, 0, 0, 0, NULL,
NULL, NULL, NULL, NULL, &window_class);
instance_ = window_class.hInstance;
atom_ = RegisterClassEx(&window_class);
// Create an offscreen window for receiving broadcast messages for the
// session lock and unlock events.
window_ = CreateWindow(MAKEINTATOM(atom_), 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0,
instance_, 0);
gfx::CheckWindowCreated(window_, ::GetLastError());
gfx::SetWindowUserData(window_, this);
// Tel windows we want to be notified with session events
WTSRegisterSessionNotification(window_, NOTIFY_FOR_THIS_SESSION);
}
LRESULT CALLBACK PowerMonitor::WndProcStatic(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
PowerMonitor* msg_wnd =
reinterpret_cast<PowerMonitor*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (msg_wnd)
return msg_wnd->WndProc(hwnd, message, wparam, lparam);
else
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
LRESULT CALLBACK PowerMonitor::WndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_WTSSESSION_CHANGE) {
bool should_treat_as_current_session = true;
DWORD current_session_id = 0;
if (!::ProcessIdToSessionId(::GetCurrentProcessId(), ¤t_session_id)) {
LOG(ERROR) << "ProcessIdToSessionId failed, assuming current session";
} else {
should_treat_as_current_session =
(static_cast<DWORD>(lparam) == current_session_id);
}
if (should_treat_as_current_session) {
if (wparam == WTS_SESSION_LOCK) {
Emit("lock-screen");
} else if (wparam == WTS_SESSION_UNLOCK) {
Emit("unlock-screen");
}
}
} else if (message == WM_POWERBROADCAST) {
if (wparam == PBT_APMRESUMEAUTOMATIC) {
Emit("resume");
} else if (wparam == PBT_APMSUSPEND) {
Emit("suspend");
}
}
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
} // namespace api
} // namespace electron
<commit_msg>fix: register for connected standby changes (#25076)<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_power_monitor.h"
#include <windows.h>
#include <wtsapi32.h>
#include "base/win/windows_types.h"
#include "base/win/windows_version.h"
#include "base/win/wrapped_window_proc.h"
#include "ui/base/win/shell.h"
#include "ui/gfx/win/hwnd_util.h"
namespace electron {
namespace {
const wchar_t kPowerMonitorWindowClass[] = L"Electron_PowerMonitorHostWindow";
} // namespace
namespace api {
void PowerMonitor::InitPlatformSpecificMonitors() {
WNDCLASSEX window_class;
base::win::InitializeWindowClass(
kPowerMonitorWindowClass,
&base::win::WrappedWindowProc<PowerMonitor::WndProcStatic>, 0, 0, 0, NULL,
NULL, NULL, NULL, NULL, &window_class);
instance_ = window_class.hInstance;
atom_ = RegisterClassEx(&window_class);
// Create an offscreen window for receiving broadcast messages for the
// session lock and unlock events.
window_ = CreateWindow(MAKEINTATOM(atom_), 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0,
instance_, 0);
gfx::CheckWindowCreated(window_, ::GetLastError());
gfx::SetWindowUserData(window_, this);
// Tel windows we want to be notified with session events
WTSRegisterSessionNotification(window_, NOTIFY_FOR_THIS_SESSION);
// For Windows 8 and later, a new "connected standy" mode has been added and
// we must explicitly register for its notifications.
if (base::win::GetVersion() >= base::win::Version::WIN8) {
RegisterSuspendResumeNotification(static_cast<HANDLE>(window_),
DEVICE_NOTIFY_WINDOW_HANDLE);
}
}
LRESULT CALLBACK PowerMonitor::WndProcStatic(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
PowerMonitor* msg_wnd =
reinterpret_cast<PowerMonitor*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (msg_wnd)
return msg_wnd->WndProc(hwnd, message, wparam, lparam);
else
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
LRESULT CALLBACK PowerMonitor::WndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_WTSSESSION_CHANGE) {
bool should_treat_as_current_session = true;
DWORD current_session_id = 0;
if (!::ProcessIdToSessionId(::GetCurrentProcessId(), ¤t_session_id)) {
LOG(ERROR) << "ProcessIdToSessionId failed, assuming current session";
} else {
should_treat_as_current_session =
(static_cast<DWORD>(lparam) == current_session_id);
}
if (should_treat_as_current_session) {
if (wparam == WTS_SESSION_LOCK) {
Emit("lock-screen");
} else if (wparam == WTS_SESSION_UNLOCK) {
Emit("unlock-screen");
}
}
} else if (message == WM_POWERBROADCAST) {
if (wparam == PBT_APMRESUMEAUTOMATIC) {
Emit("resume");
} else if (wparam == PBT_APMSUSPEND) {
Emit("suspend");
}
}
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
} // namespace api
} // namespace electron
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/pldm/extended/pldm_fru_to_ipz_mapping.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef PLDM_FRU_TO_IPZ_MAPPING__
#define PLDM_FRU_TO_IPZ_MAPPING__
/**
* @file pldm_fru_to_ipz_mapping.H
*
* @brief This header provides the constants needs to map IBM's OEM PLDM Fru
* Record type to the IPZ records. These are all based off of the
* PLDM FRU IPZ Keyword Mapping Doc
*/
namespace PLDM
{
// Currently these are the only VPD Records Hostboot Supports
// converting PLDM Fru Records to a IPZ VPD binary blob
// If more are added in the future be sure to update record_keyword_field_map
// with the appropriate PLDM Fru Record Field Type Numbers with IPZ Keywords
enum valid_records : uint32_t
{
VINI = 0x56494E49,
VSYS = 0x56535953,
LXR0 = 0x4C585230,
};
constexpr uint8_t RT_FIELD_TYPE = 2;
// Order must match PLDM FRU IPZ Keyword Mapping Doc
const uint16_t valid_vini_keywords[]
{ 0xFFFF, // invalid
0xFFFF, // invalid
0x5254, // RT
0x4233, // B3
0x4234, // B4
0x4237, // B7
0x4343, // CC
0x4345, // CE
0x4354, // CT
0x4452, // DR
0x4647, // FG
0x4657, // FN
0x4845, // HE
0x4857, // HW
0x4858, // HX
0x504E, // PN
0x534E, // SN
0x5453, // TS
0x565A // VZ
};
// Order must match PLDM FRU IPZ Keyword Mapping Doc
const uint16_t valid_vsys_keywords[]
{ 0xFFFF, // invalid
0xFFFF, // invalid
0x5254, // RT
0x4252, // BR
0x4452, // DR
0x4656, // FV
0x4944, // ID
0x4D4E, // MN
0x4E4E, // NN
0x5242, // RB
0x5247, // RG
0x5345, // SE
0x5347, // SG
0x5355, // SU
0x544D, // TM
0x544E, // TN
0x574E // WN
};
// Order must match PLDM FRU IPZ Keyword Mapping Doc
const uint16_t valid_lxr0_keywords[]
{ 0xFFFF, // invalid
0xFFFF, // invalid
0x5254, // RT
0x4C58, // LX
0x565A // VZ
};
}
#endif<commit_msg>Fix FN keyword ascii translation in PLDM Fru -> IPZ translation map<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/pldm/extended/pldm_fru_to_ipz_mapping.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef PLDM_FRU_TO_IPZ_MAPPING__
#define PLDM_FRU_TO_IPZ_MAPPING__
/**
* @file pldm_fru_to_ipz_mapping.H
*
* @brief This header provides the constants needs to map IBM's OEM PLDM Fru
* Record type to the IPZ records. These are all based off of the
* PLDM FRU IPZ Keyword Mapping Doc
*/
namespace PLDM
{
// Currently these are the only VPD Records Hostboot Supports
// converting PLDM Fru Records to a IPZ VPD binary blob
// If more are added in the future be sure to update record_keyword_field_map
// with the appropriate PLDM Fru Record Field Type Numbers with IPZ Keywords
enum valid_records : uint32_t
{
VINI = 0x56494E49,
VSYS = 0x56535953,
LXR0 = 0x4C585230,
};
constexpr uint8_t RT_FIELD_TYPE = 2;
// Order must match PLDM FRU IPZ Keyword Mapping Doc
const uint16_t valid_vini_keywords[]
{ 0xFFFF, // invalid
0xFFFF, // invalid
0x5254, // RT
0x4233, // B3
0x4234, // B4
0x4237, // B7
0x4343, // CC
0x4345, // CE
0x4354, // CT
0x4452, // DR
0x4647, // FG
0x464E, // FN
0x4845, // HE
0x4857, // HW
0x4858, // HX
0x504E, // PN
0x534E, // SN
0x5453, // TS
0x565A // VZ
};
// Order must match PLDM FRU IPZ Keyword Mapping Doc
const uint16_t valid_vsys_keywords[]
{ 0xFFFF, // invalid
0xFFFF, // invalid
0x5254, // RT
0x4252, // BR
0x4452, // DR
0x4656, // FV
0x4944, // ID
0x4D4E, // MN
0x4E4E, // NN
0x5242, // RB
0x5247, // RG
0x5345, // SE
0x5347, // SG
0x5355, // SU
0x544D, // TM
0x544E, // TN
0x574E // WN
};
// Order must match PLDM FRU IPZ Keyword Mapping Doc
const uint16_t valid_lxr0_keywords[]
{ 0xFFFF, // invalid
0xFFFF, // invalid
0x5254, // RT
0x4C58, // LX
0x565A // VZ
};
}
#endif<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <iostream>
#include <map>
#include <unordered_map>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
using sg14::fixed_point;
#include "RasterizerCommon.h"
#include "RaycastCommon.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "NativeBitmap.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
#include "LoadPNG.h"
#include <windows.h>
MSG Msg;
bool needsRedraw = true;
COLORREF paletteRef[256];
bool havePalette = false;
COLORREF transparencyRef;
long timeEllapsed = 0;
long uclock() {
timeEllapsed += 10;
return timeEllapsed;
}
namespace odb {
int readKeyboard(std::shared_ptr<CRenderer> renderer) {
needsRedraw = true;
while (renderer->mBufferedCommand != 13) {
needsRedraw = true;
renderer->handleSystemEvents();
}
renderer->mBufferedCommand = '.';
return 13;
}
bool peekKeyboard(std::shared_ptr<CRenderer> renderer) {
needsRedraw = true;
renderer->handleSystemEvents();
return renderer->mBufferedCommand == 13;
}
CRenderer::CRenderer(std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader) {
for (int r = 0; r < 256; r += 16) {
for (int g = 0; g < 256; g += 8) {
for (int b = 0; b < 256; b += 8) {
auto pixel = 0xFF000000 + (r << 16) + (g << 8) + (b);
auto paletteEntry = getPaletteEntry(pixel);
mPalette[paletteEntry] = pixel;
}
}
}
mFont = loadPNG("font.png", fileLoader);
}
LRESULT CALLBACK
WindProcedure(HWND
hWnd,
UINT Msg, WPARAM
wParam,
LPARAM lParam
) {
if (needsRedraw) {
InvalidateRect(hWnd,
nullptr, false);
needsRedraw = false;
}
HDC hDC, MemDCGame;
PAINTSTRUCT Ps;
switch (Msg) {
case
WM_CHAR:
switch (wParam) {
case 'a':
renderer->
mBufferedCommand = Knights::kPickItemCommand;
renderer->
mCached = false;
break;
case 's':
renderer->
mBufferedCommand = Knights::kCycleRightInventoryCommand;
renderer->
mCached = false;
break;
case 'z':
renderer->
mBufferedCommand = Knights::kStrafeLeftCommand;
renderer->
mCached = false;
break;
case 'x':
renderer->
mBufferedCommand = Knights::kStrafeRightCommand;
renderer->
mCached = false;
break;
case '1':
renderer->
mBufferedCommand = '1';
renderer->
mCached = false;
break;
case '2':
renderer->
mBufferedCommand = '2';
renderer->
mCached = false;
break;
case '3':
renderer->
mBufferedCommand = '3';
renderer->
mCached = false;
break;
}
needsRedraw = true;
break;
case
WM_KEYDOWN:
switch (wParam) {
case
VK_ESCAPE:
renderer
->
mBufferedCommand = Knights::kQuitGameCommand;
break;
case
VK_SPACE:
renderer
->
mBufferedCommand = Knights::kUseCurrentItemInInventoryCommand;
renderer->
mCached = false;
break;
case
VK_LEFT:
renderer
->
mBufferedCommand = Knights::kTurnPlayerLeftCommand;
renderer->
mCached = false;
break;
case
VK_RIGHT:
renderer
->
mBufferedCommand = Knights::kTurnPlayerRightCommand;
renderer->
mCached = false;
break;
case
VK_UP:
renderer
->
mBufferedCommand = Knights::kMovePlayerForwardCommand;
renderer->
mCached = false;
break;
case
VK_RETURN:
renderer
->
mBufferedCommand = 13;
break;
case
VK_DOWN:
renderer
->
mBufferedCommand = Knights::kMovePlayerBackwardCommand;
renderer->
mCached = false;
break;
}
needsRedraw = true;
break;
case
WM_DESTROY:
PostQuitMessage(WM_QUIT);
renderer
->
mBufferedCommand = Knights::kQuitGameCommand;
break;
case
WM_PAINT:
hDC = BeginPaint(hWnd, &Ps);
if (renderer != nullptr) {
uint8_t* bufferPtr = renderer->getBufferData();
auto palettePtr = &renderer->mPalette[0];
if ( !havePalette ) {
havePalette = true;
auto pixel = CRenderer::mTransparency;
auto r = (((pixel & 0x000000FF) )) - 0x38;
auto g = (((pixel & 0x0000FF00) >> 8)) - 0x18;
auto b = (((pixel & 0x00FF0000) >> 16)) - 0x10;
transparencyRef = RGB(r, g, b);
int c = 0;
for ( const auto& pixel : renderer->mPalette ) {
auto r = (((pixel & 0x000000FF) )) - 0x38;
auto g = (((pixel & 0x0000FF00) >> 8)) - 0x18;
auto b = (((pixel & 0x00FF0000) >> 16)) - 0x10;
paletteRef[c++] = transparencyRef;
}
}
RECT rect;
HBRUSH brush;
for (int c = 0;c < 200; ++c) {
uint8_t* line = &bufferPtr[ 320 * c ];
for (int d = 0;d < 320; ++d) {
uint8_t index = *line;
COLORREF ref = paletteRef[index];
if ( ref == transparencyRef ) {
auto pixel = palettePtr[index];
auto r = (((pixel & 0x000000FF) )) - 0x38;
auto g = (((pixel & 0x0000FF00) >> 8)) - 0x18;
auto b = (((pixel & 0x00FF0000) >> 16)) - 0x10;
ref = RGB(r, g, b);
paletteRef[index] = ref;
}
SetPixel( hDC, d, c, ref);
++line;
}
}
brush = CreateSolidBrush(RGB(0, 0, 0 ));
rect.left = 0;
rect.top = 200;
rect.right = 320;
rect.bottom = 240;
FillRect(Ps.hdc, &rect, brush);
DeleteObject(brush);
}
EndPaint(hWnd, &Ps);
break;
default:
return
DefWindowProc(hWnd, Msg, wParam, lParam);
}
return 0;
}
void CRenderer::sleep(long ms) {
}
void CRenderer::handleSystemEvents() {
if (GetMessage(&Msg, NULL, 0, 0)) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) {
if (x < 0 || x >= 256 || y < 0 || y >= 128) {
return;
}
mBuffer[(320 * y) + x] = pixel;
}
CRenderer::~CRenderer() {
mNativeTextures.clear();
}
void CRenderer::flip() {
needsRedraw = true;
}
void CRenderer::clear() {
}
}
<commit_msg>Use the correct timing function for Win32<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <iostream>
#include <map>
#include <unordered_map>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
using sg14::fixed_point;
#include "RasterizerCommon.h"
#include "RaycastCommon.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "NativeBitmap.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
#include "LoadPNG.h"
#include <windows.h>
MSG Msg;
bool needsRedraw = true;
COLORREF paletteRef[256];
bool havePalette = false;
COLORREF transparencyRef;
long uclock() {
return GetTickCount();
}
namespace odb {
int readKeyboard(std::shared_ptr<CRenderer> renderer) {
needsRedraw = true;
while (renderer->mBufferedCommand != 13) {
needsRedraw = true;
renderer->handleSystemEvents();
}
renderer->mBufferedCommand = '.';
return 13;
}
bool peekKeyboard(std::shared_ptr<CRenderer> renderer) {
needsRedraw = true;
renderer->handleSystemEvents();
return renderer->mBufferedCommand == 13;
}
CRenderer::CRenderer(std::shared_ptr<Knights::IFileLoaderDelegate> fileLoader) {
for (int r = 0; r < 256; r += 16) {
for (int g = 0; g < 256; g += 8) {
for (int b = 0; b < 256; b += 8) {
auto pixel = 0xFF000000 + (r << 16) + (g << 8) + (b);
auto paletteEntry = getPaletteEntry(pixel);
mPalette[paletteEntry] = pixel;
}
}
}
mFont = loadPNG("font.png", fileLoader);
}
LRESULT CALLBACK
WindProcedure(HWND
hWnd,
UINT Msg, WPARAM
wParam,
LPARAM lParam
) {
if (needsRedraw) {
InvalidateRect(hWnd,
nullptr, false);
needsRedraw = false;
}
HDC hDC, MemDCGame;
PAINTSTRUCT Ps;
switch (Msg) {
case
WM_CHAR:
switch (wParam) {
case 'a':
renderer->
mBufferedCommand = Knights::kPickItemCommand;
renderer->
mCached = false;
break;
case 's':
renderer->
mBufferedCommand = Knights::kCycleRightInventoryCommand;
renderer->
mCached = false;
break;
case 'z':
renderer->
mBufferedCommand = Knights::kStrafeLeftCommand;
renderer->
mCached = false;
break;
case 'x':
renderer->
mBufferedCommand = Knights::kStrafeRightCommand;
renderer->
mCached = false;
break;
case '1':
renderer->
mBufferedCommand = '1';
renderer->
mCached = false;
break;
case '2':
renderer->
mBufferedCommand = '2';
renderer->
mCached = false;
break;
case '3':
renderer->
mBufferedCommand = '3';
renderer->
mCached = false;
break;
}
needsRedraw = true;
break;
case
WM_KEYDOWN:
switch (wParam) {
case
VK_ESCAPE:
renderer
->
mBufferedCommand = Knights::kQuitGameCommand;
break;
case
VK_SPACE:
renderer
->
mBufferedCommand = Knights::kUseCurrentItemInInventoryCommand;
renderer->
mCached = false;
break;
case
VK_LEFT:
renderer
->
mBufferedCommand = Knights::kTurnPlayerLeftCommand;
renderer->
mCached = false;
break;
case
VK_RIGHT:
renderer
->
mBufferedCommand = Knights::kTurnPlayerRightCommand;
renderer->
mCached = false;
break;
case
VK_UP:
renderer
->
mBufferedCommand = Knights::kMovePlayerForwardCommand;
renderer->
mCached = false;
break;
case
VK_RETURN:
renderer
->
mBufferedCommand = 13;
break;
case
VK_DOWN:
renderer
->
mBufferedCommand = Knights::kMovePlayerBackwardCommand;
renderer->
mCached = false;
break;
}
needsRedraw = true;
break;
case
WM_DESTROY:
PostQuitMessage(WM_QUIT);
renderer
->
mBufferedCommand = Knights::kQuitGameCommand;
break;
case
WM_PAINT:
hDC = BeginPaint(hWnd, &Ps);
if (renderer != nullptr) {
uint8_t* bufferPtr = renderer->getBufferData();
auto palettePtr = &renderer->mPalette[0];
if ( !havePalette ) {
havePalette = true;
auto pixel = CRenderer::mTransparency;
auto r = (((pixel & 0x000000FF) )) - 0x38;
auto g = (((pixel & 0x0000FF00) >> 8)) - 0x18;
auto b = (((pixel & 0x00FF0000) >> 16)) - 0x10;
transparencyRef = RGB(r, g, b);
int c = 0;
for ( const auto& pixel : renderer->mPalette ) {
auto r = (((pixel & 0x000000FF) )) - 0x38;
auto g = (((pixel & 0x0000FF00) >> 8)) - 0x18;
auto b = (((pixel & 0x00FF0000) >> 16)) - 0x10;
paletteRef[c++] = transparencyRef;
}
}
RECT rect;
HBRUSH brush;
for (int c = 0;c < 200; ++c) {
uint8_t* line = &bufferPtr[ 320 * c ];
for (int d = 0;d < 320; ++d) {
uint8_t index = *line;
COLORREF ref = paletteRef[index];
if ( ref == transparencyRef ) {
auto pixel = palettePtr[index];
auto r = (((pixel & 0x000000FF) )) - 0x38;
auto g = (((pixel & 0x0000FF00) >> 8)) - 0x18;
auto b = (((pixel & 0x00FF0000) >> 16)) - 0x10;
ref = RGB(r, g, b);
paletteRef[index] = ref;
}
SetPixel( hDC, d, c, ref);
++line;
}
}
brush = CreateSolidBrush(RGB(0, 0, 0 ));
rect.left = 0;
rect.top = 200;
rect.right = 320;
rect.bottom = 240;
FillRect(Ps.hdc, &rect, brush);
DeleteObject(brush);
}
EndPaint(hWnd, &Ps);
break;
default:
return
DefWindowProc(hWnd, Msg, wParam, lParam);
}
return 0;
}
void CRenderer::sleep(long ms) {
}
void CRenderer::handleSystemEvents() {
if (GetMessage(&Msg, NULL, 0, 0)) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) {
if (x < 0 || x >= 256 || y < 0 || y >= 128) {
return;
}
mBuffer[(320 * y) + x] = pixel;
}
CRenderer::~CRenderer() {
mNativeTextures.clear();
}
void CRenderer::flip() {
needsRedraw = true;
}
void CRenderer::clear() {
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// 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 "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11TextureObject.h"
#include "platform/profiler.h"
#include "console/console.h"
#ifdef TORQUE_DEBUG
U32 GFXD3D11TextureObject::mTexCount = 0;
#endif
// GFXFormatR8G8B8 has now the same behaviour as GFXFormatR8G8B8X8.
// This is because 24 bit format are now deprecated by microsoft, for data alignment reason there's no changes beetween 24 and 32 bit formats.
// DirectX 10-11 both have 24 bit format no longer.
GFXD3D11TextureObject::GFXD3D11TextureObject( GFXDevice * d, GFXTextureProfile *profile) : GFXTextureObject( d, profile )
{
#ifdef D3D11_DEBUG_SPEW
mTexCount++;
Con::printf("+ texMake %d %x", mTexCount, this);
#endif
mD3DTexture = NULL;
mLocked = false;
mD3DSurface = NULL;
mLockedSubresource = 0;
mDSView = NULL;
mRTView = NULL;
mSRView = NULL;
}
GFXD3D11TextureObject::~GFXD3D11TextureObject()
{
kill();
#ifdef D3D11_DEBUG_SPEW
mTexCount--;
Con::printf("+ texkill %d %x", mTexCount, this);
#endif
}
GFXLockedRect *GFXD3D11TextureObject::lock(U32 mipLevel /*= 0*/, RectI *inRect /*= NULL*/)
{
AssertFatal( !mLocked, "GFXD3D11TextureObject::lock - The texture is already locked!" );
if( !mStagingTex ||
mStagingTex->getWidth() != getWidth() ||
mStagingTex->getHeight() != getHeight() )
{
mStagingTex.set( getWidth(), getHeight(), mFormat, &GFXSystemMemTextureProfile, avar("%s() - mLockTex (line %d)", __FUNCTION__, __LINE__) );
}
ID3D11DeviceContext* pContext = D3D11DEVICECONTEXT;
D3D11_MAPPED_SUBRESOURCE mapInfo;
U32 offset = 0;
mLockedSubresource = D3D11CalcSubresource(mipLevel, 0, getMipLevels());
GFXD3D11TextureObject* pD3DStagingTex = (GFXD3D11TextureObject*)&(*mStagingTex);
//map staging texture
HRESULT hr = pContext->Map(pD3DStagingTex->get2DTex(), mLockedSubresource, D3D11_MAP_READ, 0, &mapInfo);
if (FAILED(hr))
AssertFatal(false, "GFXD3D11TextureObject:lock - failed to map render target resource!");
const U32 width = mTextureSize.x >> mipLevel;
const U32 height = mTextureSize.y >> mipLevel;
//calculate locked box region and offset
if (inRect)
{
if ((inRect->point.x + inRect->extent.x > width) || (inRect->point.y + inRect->extent.y > height))
AssertFatal(false, "GFXD3D11TextureObject::lock - Rectangle too big!");
mLockBox.top = inRect->point.y;
mLockBox.left = inRect->point.x;
mLockBox.bottom = inRect->point.y + inRect->extent.y;
mLockBox.right = inRect->point.x + inRect->extent.x;
mLockBox.back = 1;
mLockBox.front = 0;
//calculate offset
offset = inRect->point.x * getFormatByteSize() + inRect->point.y * mapInfo.RowPitch;
}
else
{
mLockBox.top = 0;
mLockBox.left = 0;
mLockBox.bottom = height;
mLockBox.right = width;
mLockBox.back = 1;
mLockBox.front = 0;
}
mLocked = true;
mLockRect.pBits = static_cast<U8*>(mapInfo.pData) + offset;
mLockRect.Pitch = mapInfo.RowPitch;
return (GFXLockedRect*)&mLockRect;
}
void GFXD3D11TextureObject::unlock(U32 mipLevel)
{
AssertFatal( mLocked, "GFXD3D11TextureObject::unlock - Attempting to unlock a surface that has not been locked" );
//profile in the unlock function because all the heavy lifting is done here
PROFILE_START(GFXD3D11TextureObject_lockRT);
ID3D11DeviceContext* pContext = D3D11DEVICECONTEXT;
GFXD3D11TextureObject* pD3DStagingTex = (GFXD3D11TextureObject*)&(*mStagingTex);
ID3D11Texture2D *pStagingTex = pD3DStagingTex->get2DTex();
//unmap staging texture
pContext->Unmap(pStagingTex, mLockedSubresource);
//copy lock box region from the staging texture to our regular texture
pContext->CopySubresourceRegion(mD3DTexture, mLockedSubresource, mLockBox.left, mLockBox.top, 0, pStagingTex, mLockedSubresource, &mLockBox);
PROFILE_END();
mLockedSubresource = 0;
mLocked = false;
}
void GFXD3D11TextureObject::release()
{
SAFE_RELEASE(mSRView);
SAFE_RELEASE(mRTView);
SAFE_RELEASE(mDSView);
SAFE_RELEASE(mD3DTexture);
SAFE_RELEASE(mD3DSurface);
}
void GFXD3D11TextureObject::zombify()
{
// Managed textures are managed by D3D
AssertFatal(!mLocked, "GFXD3D11TextureObject::zombify - Cannot zombify a locked texture!");
if(isManaged)
return;
release();
}
void GFXD3D11TextureObject::resurrect()
{
// Managed textures are managed by D3D
if(isManaged)
return;
static_cast<GFXD3D11TextureManager*>(TEXMGR)->refreshTexture(this);
}
bool GFXD3D11TextureObject::copyToBmp(GBitmap* bmp)
{
if (!bmp)
return false;
// check format limitations
// at the moment we only support RGBA for the source (other 4 byte formats should
// be easy to add though)
AssertFatal(mFormat == GFXFormatR8G8B8A8 || mFormat == GFXFormatR8G8B8A8_LINEAR_FORCE || mFormat == GFXFormatR8G8B8A8_SRGB, "copyToBmp: invalid format");
if (mFormat != GFXFormatR8G8B8A8 && mFormat != GFXFormatR8G8B8A8_LINEAR_FORCE && mFormat != GFXFormatR8G8B8A8_SRGB)
return false;
PROFILE_START(GFXD3D11TextureObject_copyToBmp);
AssertFatal(bmp->getWidth() == getWidth(), "GFXD3D11TextureObject::copyToBmp - source/dest width does not match");
AssertFatal(bmp->getHeight() == getHeight(), "GFXD3D11TextureObject::copyToBmp - source/dest height does not match");
const U32 width = getWidth();
const U32 height = getHeight();
bmp->setHasTransparency(mHasTransparency);
// set some constants
const U32 sourceBytesPerPixel = 4;
U32 destBytesPerPixel = 0;
const GFXFormat fmt = bmp->getFormat();
if (fmt == GFXFormatR8G8B8A8 || fmt == GFXFormatR8G8B8A8_LINEAR_FORCE || fmt == GFXFormatR8G8B8A8_SRGB)
destBytesPerPixel = 4;
else if(bmp->getFormat() == GFXFormatR8G8B8)
destBytesPerPixel = 3;
else
// unsupported
AssertFatal(false, "GFXD3D11TextureObject::copyToBmp - unsupported bitmap format");
PROFILE_START(GFXD3D11TextureObject_copyToBmp_pixCopy);
//create temp staging texture
D3D11_TEXTURE2D_DESC desc;
static_cast<ID3D11Texture2D*>(mD3DTexture)->GetDesc(&desc);
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
desc.Usage = D3D11_USAGE_STAGING;
ID3D11Texture2D* pStagingTexture = NULL;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &pStagingTexture);
if (FAILED(hr))
{
Con::errorf("GFXD3D11TextureObject::copyToBmp - Failed to create staging texture");
return false;
}
//copy the classes texture to the staging texture
D3D11DEVICECONTEXT->CopyResource(pStagingTexture, mD3DTexture);
//map the staging resource
D3D11_MAPPED_SUBRESOURCE mappedRes;
hr = D3D11DEVICECONTEXT->Map(pStagingTexture, 0, D3D11_MAP_READ, 0, &mappedRes);
if (FAILED(hr))
{
//cleanup
SAFE_RELEASE(pStagingTexture);
Con::errorf("GFXD3D11TextureObject::copyToBmp - Failed to map staging texture");
return false;
}
// set pointers
const U8* srcPtr = (U8*)mappedRes.pData;
U8* destPtr = bmp->getWritableBits();
// we will want to skip over any D3D cache data in the source texture
const S32 sourceCacheSize = mappedRes.RowPitch - width * sourceBytesPerPixel;
AssertFatal(sourceCacheSize >= 0, "GFXD3D11TextureObject::copyToBmp - cache size is less than zero?");
// copy data into bitmap
for (U32 row = 0; row < height; ++row)
{
for (U32 col = 0; col < width; ++col)
{
destPtr[0] = srcPtr[2]; // red
destPtr[1] = srcPtr[1]; // green
destPtr[2] = srcPtr[0]; // blue
if (destBytesPerPixel == 4)
destPtr[3] = srcPtr[3]; // alpha
// go to next pixel in src
srcPtr += sourceBytesPerPixel;
// go to next pixel in dest
destPtr += destBytesPerPixel;
}
// skip past the cache data for this row (if any)
srcPtr += sourceCacheSize;
}
// assert if we stomped or underran memory
AssertFatal(U32(destPtr - bmp->getWritableBits()) == width * height * destBytesPerPixel, "GFXD3D11TextureObject::copyToBmp - memory error");
AssertFatal(U32(srcPtr - (U8*)mappedRes.pData) == height * mappedRes.RowPitch, "GFXD3D11TextureObject::copyToBmp - memory error");
D3D11DEVICECONTEXT->Unmap(pStagingTexture, 0);
SAFE_RELEASE(pStagingTexture);
PROFILE_END();
return true;
}
ID3D11ShaderResourceView* GFXD3D11TextureObject::getSRView()
{
return mSRView;
}
ID3D11RenderTargetView* GFXD3D11TextureObject::getRTView()
{
return mRTView;
}
ID3D11DepthStencilView* GFXD3D11TextureObject::getDSView()
{
return mDSView;
}
ID3D11ShaderResourceView** GFXD3D11TextureObject::getSRViewPtr()
{
return &mSRView;
}
ID3D11RenderTargetView** GFXD3D11TextureObject::getRTViewPtr()
{
return &mRTView;
}
ID3D11DepthStencilView** GFXD3D11TextureObject::getDSViewPtr()
{
return &mDSView;
}<commit_msg>alternative to #2268 : remove secondary profiling<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// 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 "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11TextureObject.h"
#include "platform/profiler.h"
#include "console/console.h"
#ifdef TORQUE_DEBUG
U32 GFXD3D11TextureObject::mTexCount = 0;
#endif
// GFXFormatR8G8B8 has now the same behaviour as GFXFormatR8G8B8X8.
// This is because 24 bit format are now deprecated by microsoft, for data alignment reason there's no changes beetween 24 and 32 bit formats.
// DirectX 10-11 both have 24 bit format no longer.
GFXD3D11TextureObject::GFXD3D11TextureObject( GFXDevice * d, GFXTextureProfile *profile) : GFXTextureObject( d, profile )
{
#ifdef D3D11_DEBUG_SPEW
mTexCount++;
Con::printf("+ texMake %d %x", mTexCount, this);
#endif
mD3DTexture = NULL;
mLocked = false;
mD3DSurface = NULL;
mLockedSubresource = 0;
mDSView = NULL;
mRTView = NULL;
mSRView = NULL;
}
GFXD3D11TextureObject::~GFXD3D11TextureObject()
{
kill();
#ifdef D3D11_DEBUG_SPEW
mTexCount--;
Con::printf("+ texkill %d %x", mTexCount, this);
#endif
}
GFXLockedRect *GFXD3D11TextureObject::lock(U32 mipLevel /*= 0*/, RectI *inRect /*= NULL*/)
{
AssertFatal( !mLocked, "GFXD3D11TextureObject::lock - The texture is already locked!" );
if( !mStagingTex ||
mStagingTex->getWidth() != getWidth() ||
mStagingTex->getHeight() != getHeight() )
{
mStagingTex.set( getWidth(), getHeight(), mFormat, &GFXSystemMemTextureProfile, avar("%s() - mLockTex (line %d)", __FUNCTION__, __LINE__) );
}
ID3D11DeviceContext* pContext = D3D11DEVICECONTEXT;
D3D11_MAPPED_SUBRESOURCE mapInfo;
U32 offset = 0;
mLockedSubresource = D3D11CalcSubresource(mipLevel, 0, getMipLevels());
GFXD3D11TextureObject* pD3DStagingTex = (GFXD3D11TextureObject*)&(*mStagingTex);
//map staging texture
HRESULT hr = pContext->Map(pD3DStagingTex->get2DTex(), mLockedSubresource, D3D11_MAP_READ, 0, &mapInfo);
if (FAILED(hr))
AssertFatal(false, "GFXD3D11TextureObject:lock - failed to map render target resource!");
const U32 width = mTextureSize.x >> mipLevel;
const U32 height = mTextureSize.y >> mipLevel;
//calculate locked box region and offset
if (inRect)
{
if ((inRect->point.x + inRect->extent.x > width) || (inRect->point.y + inRect->extent.y > height))
AssertFatal(false, "GFXD3D11TextureObject::lock - Rectangle too big!");
mLockBox.top = inRect->point.y;
mLockBox.left = inRect->point.x;
mLockBox.bottom = inRect->point.y + inRect->extent.y;
mLockBox.right = inRect->point.x + inRect->extent.x;
mLockBox.back = 1;
mLockBox.front = 0;
//calculate offset
offset = inRect->point.x * getFormatByteSize() + inRect->point.y * mapInfo.RowPitch;
}
else
{
mLockBox.top = 0;
mLockBox.left = 0;
mLockBox.bottom = height;
mLockBox.right = width;
mLockBox.back = 1;
mLockBox.front = 0;
}
mLocked = true;
mLockRect.pBits = static_cast<U8*>(mapInfo.pData) + offset;
mLockRect.Pitch = mapInfo.RowPitch;
return (GFXLockedRect*)&mLockRect;
}
void GFXD3D11TextureObject::unlock(U32 mipLevel)
{
AssertFatal( mLocked, "GFXD3D11TextureObject::unlock - Attempting to unlock a surface that has not been locked" );
//profile in the unlock function because all the heavy lifting is done here
PROFILE_START(GFXD3D11TextureObject_lockRT);
ID3D11DeviceContext* pContext = D3D11DEVICECONTEXT;
GFXD3D11TextureObject* pD3DStagingTex = (GFXD3D11TextureObject*)&(*mStagingTex);
ID3D11Texture2D *pStagingTex = pD3DStagingTex->get2DTex();
//unmap staging texture
pContext->Unmap(pStagingTex, mLockedSubresource);
//copy lock box region from the staging texture to our regular texture
pContext->CopySubresourceRegion(mD3DTexture, mLockedSubresource, mLockBox.left, mLockBox.top, 0, pStagingTex, mLockedSubresource, &mLockBox);
PROFILE_END();
mLockedSubresource = 0;
mLocked = false;
}
void GFXD3D11TextureObject::release()
{
SAFE_RELEASE(mSRView);
SAFE_RELEASE(mRTView);
SAFE_RELEASE(mDSView);
SAFE_RELEASE(mD3DTexture);
SAFE_RELEASE(mD3DSurface);
}
void GFXD3D11TextureObject::zombify()
{
// Managed textures are managed by D3D
AssertFatal(!mLocked, "GFXD3D11TextureObject::zombify - Cannot zombify a locked texture!");
if(isManaged)
return;
release();
}
void GFXD3D11TextureObject::resurrect()
{
// Managed textures are managed by D3D
if(isManaged)
return;
static_cast<GFXD3D11TextureManager*>(TEXMGR)->refreshTexture(this);
}
bool GFXD3D11TextureObject::copyToBmp(GBitmap* bmp)
{
if (!bmp)
return false;
// check format limitations
// at the moment we only support RGBA for the source (other 4 byte formats should
// be easy to add though)
AssertFatal(mFormat == GFXFormatR8G8B8A8 || mFormat == GFXFormatR8G8B8A8_LINEAR_FORCE || mFormat == GFXFormatR8G8B8A8_SRGB, "copyToBmp: invalid format");
if (mFormat != GFXFormatR8G8B8A8 && mFormat != GFXFormatR8G8B8A8_LINEAR_FORCE && mFormat != GFXFormatR8G8B8A8_SRGB)
return false;
PROFILE_START(GFXD3D11TextureObject_copyToBmp);
AssertFatal(bmp->getWidth() == getWidth(), "GFXD3D11TextureObject::copyToBmp - source/dest width does not match");
AssertFatal(bmp->getHeight() == getHeight(), "GFXD3D11TextureObject::copyToBmp - source/dest height does not match");
const U32 width = getWidth();
const U32 height = getHeight();
bmp->setHasTransparency(mHasTransparency);
// set some constants
const U32 sourceBytesPerPixel = 4;
U32 destBytesPerPixel = 0;
const GFXFormat fmt = bmp->getFormat();
if (fmt == GFXFormatR8G8B8A8 || fmt == GFXFormatR8G8B8A8_LINEAR_FORCE || fmt == GFXFormatR8G8B8A8_SRGB)
destBytesPerPixel = 4;
else if(bmp->getFormat() == GFXFormatR8G8B8)
destBytesPerPixel = 3;
else
// unsupported
AssertFatal(false, "GFXD3D11TextureObject::copyToBmp - unsupported bitmap format");
//create temp staging texture
D3D11_TEXTURE2D_DESC desc;
static_cast<ID3D11Texture2D*>(mD3DTexture)->GetDesc(&desc);
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
desc.Usage = D3D11_USAGE_STAGING;
ID3D11Texture2D* pStagingTexture = NULL;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &pStagingTexture);
if (FAILED(hr))
{
Con::errorf("GFXD3D11TextureObject::copyToBmp - Failed to create staging texture");
return false;
}
//copy the classes texture to the staging texture
D3D11DEVICECONTEXT->CopyResource(pStagingTexture, mD3DTexture);
//map the staging resource
D3D11_MAPPED_SUBRESOURCE mappedRes;
hr = D3D11DEVICECONTEXT->Map(pStagingTexture, 0, D3D11_MAP_READ, 0, &mappedRes);
if (FAILED(hr))
{
//cleanup
SAFE_RELEASE(pStagingTexture);
Con::errorf("GFXD3D11TextureObject::copyToBmp - Failed to map staging texture");
return false;
}
// set pointers
const U8* srcPtr = (U8*)mappedRes.pData;
U8* destPtr = bmp->getWritableBits();
// we will want to skip over any D3D cache data in the source texture
const S32 sourceCacheSize = mappedRes.RowPitch - width * sourceBytesPerPixel;
AssertFatal(sourceCacheSize >= 0, "GFXD3D11TextureObject::copyToBmp - cache size is less than zero?");
// copy data into bitmap
for (U32 row = 0; row < height; ++row)
{
for (U32 col = 0; col < width; ++col)
{
destPtr[0] = srcPtr[2]; // red
destPtr[1] = srcPtr[1]; // green
destPtr[2] = srcPtr[0]; // blue
if (destBytesPerPixel == 4)
destPtr[3] = srcPtr[3]; // alpha
// go to next pixel in src
srcPtr += sourceBytesPerPixel;
// go to next pixel in dest
destPtr += destBytesPerPixel;
}
// skip past the cache data for this row (if any)
srcPtr += sourceCacheSize;
}
// assert if we stomped or underran memory
AssertFatal(U32(destPtr - bmp->getWritableBits()) == width * height * destBytesPerPixel, "GFXD3D11TextureObject::copyToBmp - memory error");
AssertFatal(U32(srcPtr - (U8*)mappedRes.pData) == height * mappedRes.RowPitch, "GFXD3D11TextureObject::copyToBmp - memory error");
D3D11DEVICECONTEXT->Unmap(pStagingTexture, 0);
SAFE_RELEASE(pStagingTexture);
PROFILE_END();
return true;
}
ID3D11ShaderResourceView* GFXD3D11TextureObject::getSRView()
{
return mSRView;
}
ID3D11RenderTargetView* GFXD3D11TextureObject::getRTView()
{
return mRTView;
}
ID3D11DepthStencilView* GFXD3D11TextureObject::getDSView()
{
return mDSView;
}
ID3D11ShaderResourceView** GFXD3D11TextureObject::getSRViewPtr()
{
return &mSRView;
}
ID3D11RenderTargetView** GFXD3D11TextureObject::getRTViewPtr()
{
return &mRTView;
}
ID3D11DepthStencilView** GFXD3D11TextureObject::getDSViewPtr()
{
return &mDSView;
}<|endoftext|> |
<commit_before>//===--- Stmt.cpp - Statement AST Node Implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Stmt class and statement subclasses.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Stmt.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/Type.h"
using namespace clang;
static struct StmtClassNameTable {
const char *Name;
unsigned Counter;
unsigned Size;
} StmtClassInfo[Stmt::lastExprConstant+1];
static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
static bool Initialized = false;
if (Initialized)
return StmtClassInfo[E];
// Intialize the table on the first use.
Initialized = true;
#define STMT(CLASS, PARENT) \
StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
#include "clang/AST/StmtNodes.def"
return StmtClassInfo[E];
}
const char *Stmt::getStmtClassName() const {
return getStmtInfoTableEntry(sClass).Name;
}
void Stmt::DestroyChildren(ASTContext& C) {
for (child_iterator I = child_begin(), E = child_end(); I !=E; ++I)
if (Stmt* Child = *I) Child->Destroy(C);
}
void Stmt::Destroy(ASTContext& C) {
DestroyChildren(C);
// FIXME: Eventually all Stmts should be allocated with the allocator
// in ASTContext, just like with Decls.
// this->~Stmt();
delete this;
}
void DeclStmt::Destroy(ASTContext& C) {
DG.Destroy(C);
delete this;
}
void Stmt::PrintStats() {
// Ensure the table is primed.
getStmtInfoTableEntry(Stmt::NullStmtClass);
unsigned sum = 0;
fprintf(stderr, "*** Stmt/Expr Stats:\n");
for (int i = 0; i != Stmt::lastExprConstant+1; i++) {
if (StmtClassInfo[i].Name == 0) continue;
sum += StmtClassInfo[i].Counter;
}
fprintf(stderr, " %d stmts/exprs total.\n", sum);
sum = 0;
for (int i = 0; i != Stmt::lastExprConstant+1; i++) {
if (StmtClassInfo[i].Name == 0) continue;
fprintf(stderr, " %d %s, %d each (%d bytes)\n",
StmtClassInfo[i].Counter, StmtClassInfo[i].Name,
StmtClassInfo[i].Size,
StmtClassInfo[i].Counter*StmtClassInfo[i].Size);
sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
}
fprintf(stderr, "Total bytes = %d\n", sum);
}
void Stmt::addStmtClass(StmtClass s) {
++getStmtInfoTableEntry(s).Counter;
}
static bool StatSwitch = false;
bool Stmt::CollectingStats(bool enable) {
if (enable) StatSwitch = true;
return StatSwitch;
}
const char *LabelStmt::getName() const {
return getID()->getName();
}
// This is defined here to avoid polluting Stmt.h with importing Expr.h
SourceRange ReturnStmt::getSourceRange() const {
if (RetExpr)
return SourceRange(RetLoc, RetExpr->getLocEnd());
else
return SourceRange(RetLoc);
}
bool Stmt::hasImplicitControlFlow() const {
switch (sClass) {
default:
return false;
case CallExprClass:
case ConditionalOperatorClass:
case ChooseExprClass:
case StmtExprClass:
case DeclStmtClass:
return true;
case Stmt::BinaryOperatorClass: {
const BinaryOperator* B = cast<BinaryOperator>(this);
if (B->isLogicalOp() || B->getOpcode() == BinaryOperator::Comma)
return true;
else
return false;
}
}
}
const Expr* AsmStmt::getOutputExpr(unsigned i) const {
return cast<Expr>(Exprs[i]);
}
Expr* AsmStmt::getOutputExpr(unsigned i) {
return cast<Expr>(Exprs[i]);
}
Expr* AsmStmt::getInputExpr(unsigned i) {
return cast<Expr>(Exprs[i + NumOutputs]);
}
const Expr* AsmStmt::getInputExpr(unsigned i) const {
return cast<Expr>(Exprs[i + NumOutputs]);
}
//===----------------------------------------------------------------------===//
// Constructors
//===----------------------------------------------------------------------===//
AsmStmt::AsmStmt(SourceLocation asmloc, bool issimple, bool isvolatile,
unsigned numoutputs, unsigned numinputs,
std::string *names, StringLiteral **constraints,
Expr **exprs, StringLiteral *asmstr, unsigned numclobbers,
StringLiteral **clobbers, SourceLocation rparenloc)
: Stmt(AsmStmtClass), AsmLoc(asmloc), RParenLoc(rparenloc), AsmStr(asmstr)
, IsSimple(issimple), IsVolatile(isvolatile)
, NumOutputs(numoutputs), NumInputs(numinputs) {
for (unsigned i = 0, e = numinputs + numoutputs; i != e; i++) {
Names.push_back(names[i]);
Exprs.push_back(exprs[i]);
Constraints.push_back(constraints[i]);
}
for (unsigned i = 0; i != numclobbers; i++)
Clobbers.push_back(clobbers[i]);
}
ObjCForCollectionStmt::ObjCForCollectionStmt(Stmt *Elem, Expr *Collect,
Stmt *Body, SourceLocation FCL,
SourceLocation RPL)
: Stmt(ObjCForCollectionStmtClass) {
SubExprs[ELEM] = Elem;
SubExprs[COLLECTION] = reinterpret_cast<Stmt*>(Collect);
SubExprs[BODY] = Body;
ForLoc = FCL;
RParenLoc = RPL;
}
ObjCAtCatchStmt::ObjCAtCatchStmt(SourceLocation atCatchLoc,
SourceLocation rparenloc,
Stmt *catchVarStmtDecl, Stmt *atCatchStmt,
Stmt *atCatchList)
: Stmt(ObjCAtCatchStmtClass) {
SubExprs[SELECTOR] = catchVarStmtDecl;
SubExprs[BODY] = atCatchStmt;
SubExprs[NEXT_CATCH] = NULL;
if (atCatchList) {
ObjCAtCatchStmt *AtCatchList = static_cast<ObjCAtCatchStmt*>(atCatchList);
while (ObjCAtCatchStmt* NextCatch = AtCatchList->getNextCatchStmt())
AtCatchList = NextCatch;
AtCatchList->SubExprs[NEXT_CATCH] = this;
}
AtCatchLoc = atCatchLoc;
RParenLoc = rparenloc;
}
//===----------------------------------------------------------------------===//
// Child Iterators for iterating over subexpressions/substatements
//===----------------------------------------------------------------------===//
// DeclStmt
Stmt::child_iterator DeclStmt::child_begin() {
return StmtIterator(DG.begin(), DG.end());
}
Stmt::child_iterator DeclStmt::child_end() {
return StmtIterator(DG.end(), DG.end());
}
// NullStmt
Stmt::child_iterator NullStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator NullStmt::child_end() { return child_iterator(); }
// CompoundStmt
Stmt::child_iterator CompoundStmt::child_begin() { return &Body[0]; }
Stmt::child_iterator CompoundStmt::child_end() { return &Body[0]+Body.size(); }
// CaseStmt
Stmt::child_iterator CaseStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator CaseStmt::child_end() { return &SubExprs[END_EXPR]; }
// DefaultStmt
Stmt::child_iterator DefaultStmt::child_begin() { return &SubStmt; }
Stmt::child_iterator DefaultStmt::child_end() { return &SubStmt+1; }
// LabelStmt
Stmt::child_iterator LabelStmt::child_begin() { return &SubStmt; }
Stmt::child_iterator LabelStmt::child_end() { return &SubStmt+1; }
// IfStmt
Stmt::child_iterator IfStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator IfStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// SwitchStmt
Stmt::child_iterator SwitchStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator SwitchStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// WhileStmt
Stmt::child_iterator WhileStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator WhileStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// DoStmt
Stmt::child_iterator DoStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator DoStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// ForStmt
Stmt::child_iterator ForStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator ForStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// ObjCForCollectionStmt
Stmt::child_iterator ObjCForCollectionStmt::child_begin() {
return &SubExprs[0];
}
Stmt::child_iterator ObjCForCollectionStmt::child_end() {
return &SubExprs[0]+END_EXPR;
}
// GotoStmt
Stmt::child_iterator GotoStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator GotoStmt::child_end() { return child_iterator(); }
// IndirectGotoStmt
Expr* IndirectGotoStmt::getTarget() { return cast<Expr>(Target); }
const Expr* IndirectGotoStmt::getTarget() const { return cast<Expr>(Target); }
Stmt::child_iterator IndirectGotoStmt::child_begin() { return &Target; }
Stmt::child_iterator IndirectGotoStmt::child_end() { return &Target+1; }
// ContinueStmt
Stmt::child_iterator ContinueStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator ContinueStmt::child_end() { return child_iterator(); }
// BreakStmt
Stmt::child_iterator BreakStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator BreakStmt::child_end() { return child_iterator(); }
// ReturnStmt
const Expr* ReturnStmt::getRetValue() const {
return cast_or_null<Expr>(RetExpr);
}
Expr* ReturnStmt::getRetValue() {
return cast_or_null<Expr>(RetExpr);
}
Stmt::child_iterator ReturnStmt::child_begin() {
return &RetExpr;
}
Stmt::child_iterator ReturnStmt::child_end() {
return RetExpr ? &RetExpr+1 : &RetExpr;
}
// AsmStmt
Stmt::child_iterator AsmStmt::child_begin() {
return Exprs.empty() ? 0 : &Exprs[0];
}
Stmt::child_iterator AsmStmt::child_end() {
return Exprs.empty() ? 0 : &Exprs[0] + Exprs.size();
}
// ObjCAtCatchStmt
Stmt::child_iterator ObjCAtCatchStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator ObjCAtCatchStmt::child_end() {
return &SubExprs[0]+END_EXPR;
}
// ObjCAtFinallyStmt
Stmt::child_iterator ObjCAtFinallyStmt::child_begin() { return &AtFinallyStmt; }
Stmt::child_iterator ObjCAtFinallyStmt::child_end() { return &AtFinallyStmt+1; }
// ObjCAtTryStmt
Stmt::child_iterator ObjCAtTryStmt::child_begin() { return &SubStmts[0]; }
Stmt::child_iterator ObjCAtTryStmt::child_end() {
return &SubStmts[0]+END_EXPR;
}
// ObjCAtThrowStmt
Stmt::child_iterator ObjCAtThrowStmt::child_begin() {
return &Throw;
}
Stmt::child_iterator ObjCAtThrowStmt::child_end() {
return &Throw+1;
}
// ObjCAtSynchronizedStmt
Stmt::child_iterator ObjCAtSynchronizedStmt::child_begin() {
return &SubStmts[0];
}
Stmt::child_iterator ObjCAtSynchronizedStmt::child_end() {
return &SubStmts[0]+END_EXPR;
}
// CXXCatchStmt
Stmt::child_iterator CXXCatchStmt::child_begin() {
return &HandlerBlock;
}
Stmt::child_iterator CXXCatchStmt::child_end() {
return &HandlerBlock + 1;
}
QualType CXXCatchStmt::getCaughtType() {
if (ExceptionDecl)
return llvm::cast<VarDecl>(ExceptionDecl)->getType();
return QualType();
}
void CXXCatchStmt::Destroy(ASTContext& C) {
if (ExceptionDecl)
ExceptionDecl->Destroy(C);
Stmt::Destroy(C);
}
// CXXTryStmt
Stmt::child_iterator CXXTryStmt::child_begin() { return &Stmts[0]; }
Stmt::child_iterator CXXTryStmt::child_end() { return &Stmts[0]+Stmts.size(); }
CXXTryStmt::CXXTryStmt(SourceLocation tryLoc, Stmt *tryBlock,
Stmt **handlers, unsigned numHandlers)
: Stmt(CXXTryStmtClass), TryLoc(tryLoc) {
Stmts.push_back(tryBlock);
Stmts.insert(Stmts.end(), handlers, handlers + numHandlers);
}
<commit_msg>Don't advance the statement iterator after we've deallocated the statement<commit_after>//===--- Stmt.cpp - Statement AST Node Implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Stmt class and statement subclasses.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Stmt.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/Type.h"
using namespace clang;
static struct StmtClassNameTable {
const char *Name;
unsigned Counter;
unsigned Size;
} StmtClassInfo[Stmt::lastExprConstant+1];
static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
static bool Initialized = false;
if (Initialized)
return StmtClassInfo[E];
// Intialize the table on the first use.
Initialized = true;
#define STMT(CLASS, PARENT) \
StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
#include "clang/AST/StmtNodes.def"
return StmtClassInfo[E];
}
const char *Stmt::getStmtClassName() const {
return getStmtInfoTableEntry(sClass).Name;
}
void Stmt::DestroyChildren(ASTContext& C) {
for (child_iterator I = child_begin(), E = child_end(); I !=E; ) {
if (Stmt* Child = *I++) Child->Destroy(C);
}
}
void Stmt::Destroy(ASTContext& C) {
DestroyChildren(C);
// FIXME: Eventually all Stmts should be allocated with the allocator
// in ASTContext, just like with Decls.
// this->~Stmt();
delete this;
}
void DeclStmt::Destroy(ASTContext& C) {
DG.Destroy(C);
delete this;
}
void Stmt::PrintStats() {
// Ensure the table is primed.
getStmtInfoTableEntry(Stmt::NullStmtClass);
unsigned sum = 0;
fprintf(stderr, "*** Stmt/Expr Stats:\n");
for (int i = 0; i != Stmt::lastExprConstant+1; i++) {
if (StmtClassInfo[i].Name == 0) continue;
sum += StmtClassInfo[i].Counter;
}
fprintf(stderr, " %d stmts/exprs total.\n", sum);
sum = 0;
for (int i = 0; i != Stmt::lastExprConstant+1; i++) {
if (StmtClassInfo[i].Name == 0) continue;
fprintf(stderr, " %d %s, %d each (%d bytes)\n",
StmtClassInfo[i].Counter, StmtClassInfo[i].Name,
StmtClassInfo[i].Size,
StmtClassInfo[i].Counter*StmtClassInfo[i].Size);
sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
}
fprintf(stderr, "Total bytes = %d\n", sum);
}
void Stmt::addStmtClass(StmtClass s) {
++getStmtInfoTableEntry(s).Counter;
}
static bool StatSwitch = false;
bool Stmt::CollectingStats(bool enable) {
if (enable) StatSwitch = true;
return StatSwitch;
}
const char *LabelStmt::getName() const {
return getID()->getName();
}
// This is defined here to avoid polluting Stmt.h with importing Expr.h
SourceRange ReturnStmt::getSourceRange() const {
if (RetExpr)
return SourceRange(RetLoc, RetExpr->getLocEnd());
else
return SourceRange(RetLoc);
}
bool Stmt::hasImplicitControlFlow() const {
switch (sClass) {
default:
return false;
case CallExprClass:
case ConditionalOperatorClass:
case ChooseExprClass:
case StmtExprClass:
case DeclStmtClass:
return true;
case Stmt::BinaryOperatorClass: {
const BinaryOperator* B = cast<BinaryOperator>(this);
if (B->isLogicalOp() || B->getOpcode() == BinaryOperator::Comma)
return true;
else
return false;
}
}
}
const Expr* AsmStmt::getOutputExpr(unsigned i) const {
return cast<Expr>(Exprs[i]);
}
Expr* AsmStmt::getOutputExpr(unsigned i) {
return cast<Expr>(Exprs[i]);
}
Expr* AsmStmt::getInputExpr(unsigned i) {
return cast<Expr>(Exprs[i + NumOutputs]);
}
const Expr* AsmStmt::getInputExpr(unsigned i) const {
return cast<Expr>(Exprs[i + NumOutputs]);
}
//===----------------------------------------------------------------------===//
// Constructors
//===----------------------------------------------------------------------===//
AsmStmt::AsmStmt(SourceLocation asmloc, bool issimple, bool isvolatile,
unsigned numoutputs, unsigned numinputs,
std::string *names, StringLiteral **constraints,
Expr **exprs, StringLiteral *asmstr, unsigned numclobbers,
StringLiteral **clobbers, SourceLocation rparenloc)
: Stmt(AsmStmtClass), AsmLoc(asmloc), RParenLoc(rparenloc), AsmStr(asmstr)
, IsSimple(issimple), IsVolatile(isvolatile)
, NumOutputs(numoutputs), NumInputs(numinputs) {
for (unsigned i = 0, e = numinputs + numoutputs; i != e; i++) {
Names.push_back(names[i]);
Exprs.push_back(exprs[i]);
Constraints.push_back(constraints[i]);
}
for (unsigned i = 0; i != numclobbers; i++)
Clobbers.push_back(clobbers[i]);
}
ObjCForCollectionStmt::ObjCForCollectionStmt(Stmt *Elem, Expr *Collect,
Stmt *Body, SourceLocation FCL,
SourceLocation RPL)
: Stmt(ObjCForCollectionStmtClass) {
SubExprs[ELEM] = Elem;
SubExprs[COLLECTION] = reinterpret_cast<Stmt*>(Collect);
SubExprs[BODY] = Body;
ForLoc = FCL;
RParenLoc = RPL;
}
ObjCAtCatchStmt::ObjCAtCatchStmt(SourceLocation atCatchLoc,
SourceLocation rparenloc,
Stmt *catchVarStmtDecl, Stmt *atCatchStmt,
Stmt *atCatchList)
: Stmt(ObjCAtCatchStmtClass) {
SubExprs[SELECTOR] = catchVarStmtDecl;
SubExprs[BODY] = atCatchStmt;
SubExprs[NEXT_CATCH] = NULL;
if (atCatchList) {
ObjCAtCatchStmt *AtCatchList = static_cast<ObjCAtCatchStmt*>(atCatchList);
while (ObjCAtCatchStmt* NextCatch = AtCatchList->getNextCatchStmt())
AtCatchList = NextCatch;
AtCatchList->SubExprs[NEXT_CATCH] = this;
}
AtCatchLoc = atCatchLoc;
RParenLoc = rparenloc;
}
//===----------------------------------------------------------------------===//
// Child Iterators for iterating over subexpressions/substatements
//===----------------------------------------------------------------------===//
// DeclStmt
Stmt::child_iterator DeclStmt::child_begin() {
return StmtIterator(DG.begin(), DG.end());
}
Stmt::child_iterator DeclStmt::child_end() {
return StmtIterator(DG.end(), DG.end());
}
// NullStmt
Stmt::child_iterator NullStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator NullStmt::child_end() { return child_iterator(); }
// CompoundStmt
Stmt::child_iterator CompoundStmt::child_begin() { return &Body[0]; }
Stmt::child_iterator CompoundStmt::child_end() { return &Body[0]+Body.size(); }
// CaseStmt
Stmt::child_iterator CaseStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator CaseStmt::child_end() { return &SubExprs[END_EXPR]; }
// DefaultStmt
Stmt::child_iterator DefaultStmt::child_begin() { return &SubStmt; }
Stmt::child_iterator DefaultStmt::child_end() { return &SubStmt+1; }
// LabelStmt
Stmt::child_iterator LabelStmt::child_begin() { return &SubStmt; }
Stmt::child_iterator LabelStmt::child_end() { return &SubStmt+1; }
// IfStmt
Stmt::child_iterator IfStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator IfStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// SwitchStmt
Stmt::child_iterator SwitchStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator SwitchStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// WhileStmt
Stmt::child_iterator WhileStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator WhileStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// DoStmt
Stmt::child_iterator DoStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator DoStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// ForStmt
Stmt::child_iterator ForStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator ForStmt::child_end() { return &SubExprs[0]+END_EXPR; }
// ObjCForCollectionStmt
Stmt::child_iterator ObjCForCollectionStmt::child_begin() {
return &SubExprs[0];
}
Stmt::child_iterator ObjCForCollectionStmt::child_end() {
return &SubExprs[0]+END_EXPR;
}
// GotoStmt
Stmt::child_iterator GotoStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator GotoStmt::child_end() { return child_iterator(); }
// IndirectGotoStmt
Expr* IndirectGotoStmt::getTarget() { return cast<Expr>(Target); }
const Expr* IndirectGotoStmt::getTarget() const { return cast<Expr>(Target); }
Stmt::child_iterator IndirectGotoStmt::child_begin() { return &Target; }
Stmt::child_iterator IndirectGotoStmt::child_end() { return &Target+1; }
// ContinueStmt
Stmt::child_iterator ContinueStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator ContinueStmt::child_end() { return child_iterator(); }
// BreakStmt
Stmt::child_iterator BreakStmt::child_begin() { return child_iterator(); }
Stmt::child_iterator BreakStmt::child_end() { return child_iterator(); }
// ReturnStmt
const Expr* ReturnStmt::getRetValue() const {
return cast_or_null<Expr>(RetExpr);
}
Expr* ReturnStmt::getRetValue() {
return cast_or_null<Expr>(RetExpr);
}
Stmt::child_iterator ReturnStmt::child_begin() {
return &RetExpr;
}
Stmt::child_iterator ReturnStmt::child_end() {
return RetExpr ? &RetExpr+1 : &RetExpr;
}
// AsmStmt
Stmt::child_iterator AsmStmt::child_begin() {
return Exprs.empty() ? 0 : &Exprs[0];
}
Stmt::child_iterator AsmStmt::child_end() {
return Exprs.empty() ? 0 : &Exprs[0] + Exprs.size();
}
// ObjCAtCatchStmt
Stmt::child_iterator ObjCAtCatchStmt::child_begin() { return &SubExprs[0]; }
Stmt::child_iterator ObjCAtCatchStmt::child_end() {
return &SubExprs[0]+END_EXPR;
}
// ObjCAtFinallyStmt
Stmt::child_iterator ObjCAtFinallyStmt::child_begin() { return &AtFinallyStmt; }
Stmt::child_iterator ObjCAtFinallyStmt::child_end() { return &AtFinallyStmt+1; }
// ObjCAtTryStmt
Stmt::child_iterator ObjCAtTryStmt::child_begin() { return &SubStmts[0]; }
Stmt::child_iterator ObjCAtTryStmt::child_end() {
return &SubStmts[0]+END_EXPR;
}
// ObjCAtThrowStmt
Stmt::child_iterator ObjCAtThrowStmt::child_begin() {
return &Throw;
}
Stmt::child_iterator ObjCAtThrowStmt::child_end() {
return &Throw+1;
}
// ObjCAtSynchronizedStmt
Stmt::child_iterator ObjCAtSynchronizedStmt::child_begin() {
return &SubStmts[0];
}
Stmt::child_iterator ObjCAtSynchronizedStmt::child_end() {
return &SubStmts[0]+END_EXPR;
}
// CXXCatchStmt
Stmt::child_iterator CXXCatchStmt::child_begin() {
return &HandlerBlock;
}
Stmt::child_iterator CXXCatchStmt::child_end() {
return &HandlerBlock + 1;
}
QualType CXXCatchStmt::getCaughtType() {
if (ExceptionDecl)
return llvm::cast<VarDecl>(ExceptionDecl)->getType();
return QualType();
}
void CXXCatchStmt::Destroy(ASTContext& C) {
if (ExceptionDecl)
ExceptionDecl->Destroy(C);
Stmt::Destroy(C);
}
// CXXTryStmt
Stmt::child_iterator CXXTryStmt::child_begin() { return &Stmts[0]; }
Stmt::child_iterator CXXTryStmt::child_end() { return &Stmts[0]+Stmts.size(); }
CXXTryStmt::CXXTryStmt(SourceLocation tryLoc, Stmt *tryBlock,
Stmt **handlers, unsigned numHandlers)
: Stmt(CXXTryStmtClass), TryLoc(tryLoc) {
Stmts.push_back(tryBlock);
Stmts.insert(Stmts.end(), handlers, handlers + numHandlers);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {qb_RoadExtract.tif}
// OUTPUTS: {ExtractRoadOutput.png}
// 337 557 432 859 1.0 0.00005 1.0 0.39269 1.0 10.0 25.
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The easiest way to use the road extraction filter provided by OTB is to use the composite
// filter. If a modification in the pipeline is required to adapt to a particular situation,
// the step by step example, described in the next section can be adapted.
//
// This example demonstrates the use of the \doxygen{otb}{RoadExtractionFilter}.
// This filter is a composite filter achieving road extraction according to the algorithm
// adapted by E. Christophe and J. Inglada \cite{Christophe2007} from an original method
// proposed in \cite{Lacroix1998}.
//
// The first step toward the use of this filter is the inclusion of the proper header files.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbPolyLineParametricPathWithValue.h"
#include "otbRoadExtractionFilter.h"
#include "otbDrawPathListFilter.h"
// Software Guide : EndCodeSnippet
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbMath.h"
int main( int argc, char * argv[] )
{
if(argc != 14)
{
std::cerr << "Usage: "<< argv[0];
std:: cerr <<" inputFileName outputFileName firstPixelComponent secondPixelComponent ";
std::cerr <<"thirdPixelComponent fourthPixelComponent amplitudeThrehsold tolerance ";
std::cerr <<"angularThreshold firstMeanDistanceThreshold secondMeanDistanceThreshold ";
std::cerr<<"distanceThreshold"<<std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We choose to do
// all the computation in floating point precision and rescale the results
// between 0 and 255 in order to export PNG images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef double InputPixelType;
typedef unsigned char OutputPixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The images are defined using the pixel type and the dimension. Please note that
// the doxygen{otb}{RoadExtractionFilter} needs an \doxygen{otb}{VectorImage} as input
// to handle multispectral images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::VectorImage<InputPixelType,Dimension> InputVectorImageType;
typedef otb::Image<InputPixelType,Dimension> InputImageType;
typedef otb::Image<OutputPixelType,Dimension> OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We define the type of the polyline that the filter produces. We use the
// \doxygen{otb}{PolyLineParametricPathWithValue}, which allows the filter to produce
// a likehood value along with each polyline. The filter is able to produce
// \doxygen{itk}{PolyLineParametricPath} as well.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::PolyLineParametricPathWithValue<InputPixelType,Dimension> PathType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we can define the \doxygen{otb}{RoadExtractionFilter} that takes a multi-spectral
// image as input and produces a list of polylines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::RoadExtractionFilter<InputVectorImageType,PathType> RoadExtractionFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also define an \doxygen{otb}{DrawPathListFilter} to draw the output
// polylines on an image, taking their likehood values into account.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::DrawPathListFilter<InputImageType, PathType, InputImageType> DrawPathFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The intensity rescaling of the results will be carried out by the
// \code{itk::RescaleIntensityImageFilter} which is templated by the
// input and output image types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RescaleIntensityImageFilter< InputImageType,OutputImageType > RescalerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{ImageFileReader} class is also instantiated in order to read
// image data from a file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<InputVectorImageType> ReaderType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{ImageFileWriter} is instantiated in order to write the
// output image to a file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileWriter<OutputImageType> WriterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different filters composing our pipeline are created by invoking their
// \code{New()} methods, assigning the results to smart pointers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
RoadExtractionFilterType::Pointer roadExtractionFilter = RoadExtractionFilterType::New();
DrawPathFilterType::Pointer drawingFilter = DrawPathFilterType::New();
RescalerType::Pointer rescalingFilter = RescalerType::New();
WriterType::Pointer writer = WriterType::New();
// Software Guide : EndCodeSnippet
reader->SetFileName(argv[1]);
// Software Guide : BeginLatex
//
// The \doxygen{RoadExtractionFilter} needs to have a reference pixel
// corresponding to the color likely to represent a road. This is done
// by passing a pixel to the filter. Here we suppose that the input image
// has four spectral bands.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
InputVectorImageType::PixelType ReferencePixel;
ReferencePixel.SetSize(4);
ReferencePixel.SetElement(0,::atof(argv[3]));
ReferencePixel.SetElement(1,::atof(argv[4]));
ReferencePixel.SetElement(2,::atof(argv[5]));
ReferencePixel.SetElement(3,::atof(argv[6]));
roadExtractionFilter->SetReferencePixel(ReferencePixel);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We must also set the alpha parameter of the filter which allows us to tune the width of the roads
// we want to extract. Typical value is $1.0$ and should be working in most situations.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetAlpha(atof(argv[7]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// All other parameter should not influence the results too much in most situation and can
// be kept at a default value.
//
// The amplitude threshold parameter tunes the sensitivity of the vectorization step. A typical
// value is $5 \cdot 10^{-5}$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetAmplitudeThreshold(atof(argv[8]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The tolerance threshold tunes the sensitivity of the path simplification step.
// Typical value is $1.0$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetTolerance(atof(argv[9]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Roads are not likely to have sharp angle. Therefore we set the max angle parameter,
// as well as the link angular threshold. The value is typicaly $\frac{\Pi}{8}$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetMaxAngle(atof(argv[10]));
roadExtractionFilter->SetAngularThreshold(atof(argv[10]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The doxygen{RoadExtractionFilter} performs two odd path removing operations at different stage of
// its execution. The first mean distance threshold and the second mean distance threshold set their criterion
// for removal. Path are removed if their mean distance between nodes is to small, since such path coming
// from previous filters are likely to be tortuous. The first removal operation as a typical mean distance
// threshold parameter of $1.0$, and the second of $10.0$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetFirstMeanDistanceThreshold(atof(argv[11]));
roadExtractionFilter->SetSecondMeanDistanceThreshold(atof(argv[12]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \doxygen{RoadExtractionFilter} is able to link path whose ends are near
// according to an euclidean distance criterion. The threshold for this distance
// to link a path is the distance threshold parameter. A typical value is $25$.
//
// Software Guide : End Latex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetDistanceThreshold(atof(argv[13]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We will now create a black background image to draw the resulting polyline on.
// To achieve this we need to now the size of our input image. Therefore we trigger the
// \code{GenerateOutputInformation()} of the reader.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader->GenerateOutputInformation();
InputImageType::Pointer blackBackground = InputImageType::New();
blackBackground->SetRegions(reader->GetOutput()->GetLargestPossibleRegion());
blackBackground->Allocate();
blackBackground->FillBuffer(0);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We tell the \doxygen{DrawPathListFilter} to try to use the likehood value
// embedded within the polyline as a value for drawing this polyline if possible.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
drawingFilter->UseInternalPathValueOn();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \code{itk::RescaleIntensityImageFilter} needs to know which
// is the minimu and maximum values of the output generated
// image. Those can be chosen in a generic way by using the
// \code{NumericTraits} functions, since they are templated over
// the pixel type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
rescalingFilter->SetOutputMinimum( itk::NumericTraits< OutputPixelType >::min() );
rescalingFilter->SetOutputMaximum( itk::NumericTraits< OutputPixelType >::max() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now it is time for some pipeline wiring.
//
// Software Guide : EndLatex
writer->SetFileName(argv[2]);
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetInput(reader->GetOutput());
drawingFilter->SetInput(blackBackground);
drawingFilter->SetInputPath(roadExtractionFilter->GetOutput());
rescalingFilter->SetInput(drawingFilter->GetOutput());
writer->SetInput(rescalingFilter->GetOutput());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The update of the pipeline is triggered by the \code{Update()} method
// of the writing filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:ROADEXTRACTION_FILTER} shows the result of applying
// the road extraction filter to a fusionned Quickbird image.
// \begin{figure}
// \center
// \includegraphics[width=0.25\textwidth]{qb_ExtractRoad_pretty.eps}
// \includegraphics[width=0.25\textwidth]{ExtractRoadOutput.eps}
// \itkcaption[Road extraction filter application]{Result of applying
// the \doxygen{otb}{RoadExtractionFilter} to a fusionned Quickbird
// image. From left to right : original image, extracted road with their
// likehood values.}
// \label{fig:ROADEXTRACTION_FILTER}
// \end{figure}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<commit_msg>nomsg<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {qb_RoadExtract.tif}
// OUTPUTS: {ExtractRoadOutput.png}
// 337 557 432 859 1.0 0.00005 1.0 0.39269 1.0 10.0 25.
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The easiest way to use the road extraction filter provided by OTB is to use the composite
// filter. If a modification in the pipeline is required to adapt to a particular situation,
// the step by step example, described in the next section can be adapted.
//
// This example demonstrates the use of the \doxygen{otb}{RoadExtractionFilter}.
// This filter is a composite filter achieving road extraction according to the algorithm
// adapted by E. Christophe and J. Inglada \cite{Christophe2007} from an original method
// proposed in \cite{Lacroix1998}.
//
// The first step toward the use of this filter is the inclusion of the proper header files.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbPolyLineParametricPathWithValue.h"
#include "otbRoadExtractionFilter.h"
#include "otbDrawPathListFilter.h"
// Software Guide : EndCodeSnippet
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbMath.h"
int main( int argc, char * argv[] )
{
if(argc != 14)
{
std::cerr << "Usage: "<< argv[0];
std:: cerr <<" inputFileName outputFileName firstPixelComponent secondPixelComponent ";
std::cerr <<"thirdPixelComponent fourthPixelComponent amplitudeThrehsold tolerance ";
std::cerr <<"angularThreshold firstMeanDistanceThreshold secondMeanDistanceThreshold ";
std::cerr<<"distanceThreshold"<<std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We choose to do
// all the computation in floating point precision and rescale the results
// between 0 and 255 in order to export PNG images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef double InputPixelType;
typedef unsigned char OutputPixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The images are defined using the pixel type and the dimension. Please note that
// the doxygen{otb}{RoadExtractionFilter} needs an \doxygen{otb}{VectorImage} as input
// to handle multispectral images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::VectorImage<InputPixelType,Dimension> InputVectorImageType;
typedef otb::Image<InputPixelType,Dimension> InputImageType;
typedef otb::Image<OutputPixelType,Dimension> OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We define the type of the polyline that the filter produces. We use the
// \doxygen{otb}{PolyLineParametricPathWithValue}, which allows the filter to produce
// a likehood value along with each polyline. The filter is able to produce
// \doxygen{itk}{PolyLineParametricPath} as well.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::PolyLineParametricPathWithValue<InputPixelType,Dimension> PathType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we can define the \doxygen{otb}{RoadExtractionFilter} that takes a multi-spectral
// image as input and produces a list of polylines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::RoadExtractionFilter<InputVectorImageType,PathType> RoadExtractionFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also define an \doxygen{otb}{DrawPathListFilter} to draw the output
// polylines on an image, taking their likehood values into account.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::DrawPathListFilter<InputImageType, PathType, InputImageType> DrawPathFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The intensity rescaling of the results will be carried out by the
// \code{itk::RescaleIntensityImageFilter} which is templated by the
// input and output image types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RescaleIntensityImageFilter< InputImageType,OutputImageType > RescalerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{ImageFileReader} class is also instantiated in order to read
// image data from a file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<InputVectorImageType> ReaderType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{ImageFileWriter} is instantiated in order to write the
// output image to a file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileWriter<OutputImageType> WriterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different filters composing our pipeline are created by invoking their
// \code{New()} methods, assigning the results to smart pointers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
RoadExtractionFilterType::Pointer roadExtractionFilter = RoadExtractionFilterType::New();
DrawPathFilterType::Pointer drawingFilter = DrawPathFilterType::New();
RescalerType::Pointer rescalingFilter = RescalerType::New();
WriterType::Pointer writer = WriterType::New();
// Software Guide : EndCodeSnippet
reader->SetFileName(argv[1]);
// Software Guide : BeginLatex
//
// The \doxygen{RoadExtractionFilter} needs to have a reference pixel
// corresponding to the color likely to represent a road. This is done
// by passing a pixel to the filter. Here we suppose that the input image
// has four spectral bands.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
InputVectorImageType::PixelType ReferencePixel;
ReferencePixel.SetSize(4);
ReferencePixel.SetElement(0,::atof(argv[3]));
ReferencePixel.SetElement(1,::atof(argv[4]));
ReferencePixel.SetElement(2,::atof(argv[5]));
ReferencePixel.SetElement(3,::atof(argv[6]));
roadExtractionFilter->SetReferencePixel(ReferencePixel);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We must also set the alpha parameter of the filter which allows us to tune the width of the roads
// we want to extract. Typical value is $1.0$ and should be working in most situations.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetAlpha(atof(argv[7]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// All other parameter should not influence the results too much in most situation and can
// be kept at a default value.
//
// The amplitude threshold parameter tunes the sensitivity of the vectorization step. A typical
// value is $5 \cdot 10^{-5}$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetAmplitudeThreshold(atof(argv[8]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The tolerance threshold tunes the sensitivity of the path simplification step.
// Typical value is $1.0$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetTolerance(atof(argv[9]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Roads are not likely to have sharp angle. Therefore we set the max angle parameter,
// as well as the link angular threshold. The value is typicaly $\frac{\pi}{8}$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetMaxAngle(atof(argv[10]));
roadExtractionFilter->SetAngularThreshold(atof(argv[10]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The doxygen{RoadExtractionFilter} performs two odd path removing operations at different stage of
// its execution. The first mean distance threshold and the second mean distance threshold set their criterion
// for removal. Path are removed if their mean distance between nodes is to small, since such path coming
// from previous filters are likely to be tortuous. The first removal operation as a typical mean distance
// threshold parameter of $1.0$, and the second of $10.0$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetFirstMeanDistanceThreshold(atof(argv[11]));
roadExtractionFilter->SetSecondMeanDistanceThreshold(atof(argv[12]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \doxygen{RoadExtractionFilter} is able to link path whose ends are near
// according to an euclidean distance criterion. The threshold for this distance
// to link a path is the distance threshold parameter. A typical value is $25$.
//
// Software Guide : End Latex
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetDistanceThreshold(atof(argv[13]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We will now create a black background image to draw the resulting polyline on.
// To achieve this we need to now the size of our input image. Therefore we trigger the
// \code{GenerateOutputInformation()} of the reader.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader->GenerateOutputInformation();
InputImageType::Pointer blackBackground = InputImageType::New();
blackBackground->SetRegions(reader->GetOutput()->GetLargestPossibleRegion());
blackBackground->Allocate();
blackBackground->FillBuffer(0);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We tell the \doxygen{DrawPathListFilter} to try to use the likehood value
// embedded within the polyline as a value for drawing this polyline if possible.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
drawingFilter->UseInternalPathValueOn();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \code{itk::RescaleIntensityImageFilter} needs to know which
// is the minimu and maximum values of the output generated
// image. Those can be chosen in a generic way by using the
// \code{NumericTraits} functions, since they are templated over
// the pixel type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
rescalingFilter->SetOutputMinimum( itk::NumericTraits< OutputPixelType >::min() );
rescalingFilter->SetOutputMaximum( itk::NumericTraits< OutputPixelType >::max() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now it is time for some pipeline wiring.
//
// Software Guide : EndLatex
writer->SetFileName(argv[2]);
// Software Guide : BeginCodeSnippet
roadExtractionFilter->SetInput(reader->GetOutput());
drawingFilter->SetInput(blackBackground);
drawingFilter->SetInputPath(roadExtractionFilter->GetOutput());
rescalingFilter->SetInput(drawingFilter->GetOutput());
writer->SetInput(rescalingFilter->GetOutput());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The update of the pipeline is triggered by the \code{Update()} method
// of the writing filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:ROADEXTRACTION_FILTER} shows the result of applying
// the road extraction filter to a fusionned Quickbird image.
// \begin{figure}
// \center
// \includegraphics[width=0.25\textwidth]{qb_ExtractRoad_pretty.eps}
// \includegraphics[width=0.25\textwidth]{ExtractRoadOutput.eps}
// \itkcaption[Road extraction filter application]{Result of applying
// the \doxygen{otb}{RoadExtractionFilter} to a fusionned Quickbird
// image. From left to right : original image, extracted road with their
// likehood values.}
// \label{fig:ROADEXTRACTION_FILTER}
// \end{figure}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2011-2018 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_MEMORY_ALIGNED_DETAIL_ALIGNED_ALLOC_STD_HPP
#define INCLUDED_SROOK_MEMORY_ALIGNED_DETAIL_ALIGNED_ALLOC_STD_HPP
#include <srook/config.hpp>
#include <memory>
SROOK_NESTED_NAMESPACE(srook, memory, alignment) {
SROOK_INLINE_NAMESPACE(v1)
using std::aligned_alloc;
SROOK_FORCE_INLINE void aligned_free(void* pt) SROOK_NOEXCEPT_TRUE
{
std::free(pt);
}
SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(alignment, memory, srook)
#endif
<commit_msg>small fix<commit_after>// Copyright (C) 2011-2018 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_MEMORY_ALIGNED_DETAIL_ALIGNED_ALLOC_STD_HPP
#define INCLUDED_SROOK_MEMORY_ALIGNED_DETAIL_ALIGNED_ALLOC_STD_HPP
#include <srook/config.hpp>
#include <memory>
SROOK_NESTED_NAMESPACE(srook, memory, alignment) {
SROOK_INLINE_NAMESPACE(v1)
#if 0 && (SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS17_CONSTANT)
using std::aligned_alloc;
#else
using ::aligned_alloc;
#endif
SROOK_FORCE_INLINE void aligned_free(void* pt) SROOK_NOEXCEPT_TRUE
{
std::free(pt);
}
SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(alignment, memory, srook)
#endif
<|endoftext|> |
<commit_before>#include "DxfWriter.h"
#include "Core/StringUtils.h"
#include "IO/Log.h"
DxfWriter::DxfWriter(Context* context, String path) : Object(context)
{
}
bool DxfWriter::Save(String path)
{
FileSystem* fs = new FileSystem(GetContext());
//create the file
dest_ = new File(GetContext(), path, FILE_WRITE);
//double check
assert(dest_);
//create the log
GetContext()->RegisterSubsystem(new Log(GetContext()));
//oepn
WriteHeader();
//write the objects
WriteEntities();
//close
WriteLinePair(0, "EOF");
dest_->Close();
return false;
}
//writers
bool DxfWriter::WriteLinePair(int code, String value)
{
if (!dest_)
return false;
dest_->WriteLine(String(code));
dest_->WriteLine(value);
return true;
}
void DxfWriter::WriteHeader()
{
//opener
WriteLinePair(0, "SECTION");
WriteLinePair(2, "HEADER");
WriteLinePair(9, "$ACADVER");
WriteLinePair(1, "AC1018");
WriteLinePair(9, "$INSBASE");
WriteLinePair(10, String(0.0));
WriteLinePair(20, String(0.0));
WriteLinePair(30, String(0.0));
//closer
WriteLinePair(0, "ENDSEC");
}
void DxfWriter::WriteEntities()
{
//ENTITIES opener
WriteLinePair(0, "SECTION");
WriteLinePair(2, "ENTITIES");
//write meshes
for (int i = 0; i < meshes_.Size(); i++)
{
WriteMesh(i);
}
//write
for (int i = 0; i < polylines_.Size(); i++)
{
WritePolyline(i);
}
for (int i = 0; i < points_.Size(); i++)
{
WritePoint(i);
}
//ENTITIES closer
WriteLinePair(0, "ENDSEC");
}
void DxfWriter::WriteMesh(int id)
{
}
void DxfWriter::WritePolyline(int id)
{
}
void DxfWriter::WritePoint(int id)
{
if (id >= points_.Size())
return;
VariantMap pMap = points_[id].GetVariantMap();
//check that this is a point structure
if (pMap.Keys().Contains("000_TYPE")) {
if (pMap["000_TYPE"].GetString() == "POINT")
{
Vector3 v = pMap.Keys().Contains("Position") ? pMap["Position"].GetVector3() : Vector3::ZERO;
String layer = pMap.Keys().Contains("Layer") ? pMap["Layer"].GetString() : "Default";
//actually write
WriteLinePair(0, "POINT");
WriteLinePair(8, layer);
WriteLinePair(10, String(v.x_));
WriteLinePair(20, String(v.y_));
WriteLinePair(30, String(v.z_));
}
}
}
//setters
void DxfWriter::SetMesh(VariantMap mesh)
{
}
void DxfWriter::SetMesh(VariantVector meshes)
{
}
void DxfWriter::SetPolyline(VariantMap polyline)
{
}
void DxfWriter::SetPolyline(VariantVector polylines)
{
}
void DxfWriter::SetPoint(Vector3 point, String layer)
{
VariantMap pMap;
pMap["000_TYPE"] = "POINT";
pMap["Position"] = point;
pMap["Layer"] = layer;
points_.Push(pMap);
}
void DxfWriter::SetPoints(Vector<Vector3> points)
{
}<commit_msg>fixed merge<commit_after>#include "DxfWriter.h"
#include "Core/StringUtils.h"
#include "IO/Log.h"
DxfWriter::DxfWriter(Context* context) : Object(context)
{
}
bool DxfWriter::Save(String path)
{
FileSystem* fs = new FileSystem(GetContext());
//create the file
dest_ = new File(GetContext(), path, FILE_WRITE);
//double check
assert(dest_);
//create the log
GetContext()->RegisterSubsystem(new Log(GetContext()));
//oepn
WriteHeader();
//write the objects
WriteEntities();
//close
WriteLinePair(0, "EOF");
dest_->Close();
return false;
}
//writers
bool DxfWriter::WriteLinePair(int code, String value)
{
if (!dest_)
return false;
dest_->WriteLine(String(code));
dest_->WriteLine(value);
return true;
}
void DxfWriter::WriteHeader()
{
//opener
WriteLinePair(0, "SECTION");
WriteLinePair(2, "HEADER");
WriteLinePair(9, "$ACADVER");
WriteLinePair(1, "AC1018");
WriteLinePair(9, "$INSBASE");
WriteLinePair(10, String(0.0));
WriteLinePair(20, String(0.0));
WriteLinePair(30, String(0.0));
//closer
WriteLinePair(0, "ENDSEC");
}
void DxfWriter::WriteEntities()
{
//ENTITIES opener
WriteLinePair(0, "SECTION");
WriteLinePair(2, "ENTITIES");
//write meshes
for (int i = 0; i < meshes_.Size(); i++)
{
WriteMesh(i);
}
//write
for (int i = 0; i < polylines_.Size(); i++)
{
WritePolyline(i);
}
for (int i = 0; i < points_.Size(); i++)
{
WritePoint(i);
}
//ENTITIES closer
WriteLinePair(0, "ENDSEC");
}
void DxfWriter::WriteMesh(int id)
{
}
void DxfWriter::WritePolyline(int id)
{
}
void DxfWriter::WritePoint(int id)
{
if (id >= points_.Size())
return;
VariantMap pMap = points_[id].GetVariantMap();
//check that this is a point structure
if (pMap.Keys().Contains("000_TYPE")) {
if (pMap["000_TYPE"].GetString() == "POINT")
{
Vector3 v = pMap.Keys().Contains("Position") ? pMap["Position"].GetVector3() : Vector3::ZERO;
String layer = pMap.Keys().Contains("Layer") ? pMap["Layer"].GetString() : "Default";
//actually write
WriteLinePair(0, "POINT");
WriteLinePair(8, layer);
WriteLinePair(10, String(v.x_));
WriteLinePair(20, String(v.y_));
WriteLinePair(30, String(v.z_));
}
}
}
//setters
void DxfWriter::SetMesh(VariantMap mesh)
{
}
void DxfWriter::SetMesh(VariantVector meshes)
{
}
void DxfWriter::SetPolyline(VariantMap polyline)
{
}
void DxfWriter::SetPolyline(VariantVector polylines)
{
}
void DxfWriter::SetPoint(Vector3 point, String layer)
{
VariantMap pMap;
pMap["000_TYPE"] = "POINT";
pMap["Position"] = point;
pMap["Layer"] = layer;
points_.Push(pMap);
}
void DxfWriter::SetPoints(Vector<Vector3> points)
{
}<|endoftext|> |
<commit_before>/*
* stomp_planner.cpp
*
* Created on: Jan 22, 2013
* Author: kalakris
*/
#include <ros/ros.h>
#include <moveit/robot_state/conversions.h>
#include <stomp_moveit_interface/stomp_planner.h>
#include <stomp/stomp_utils.h>
#include <class_loader/class_loader.h>
namespace stomp_moveit_interface
{
const static double DEFAULT_CONTROL_COST_WEIGHT = 1;
const static int TERMINATION_ATTEMPTS = 200;
const double TERMINATION_DELAY = 0.1f;
StompPlanner::StompPlanner(const std::string& group,const moveit::core::RobotModelConstPtr& model):
PlanningContext("STOMP",group),
node_handle_("~"),
solving_(false),
stomp_()
{
trajectory_viz_pub_ = node_handle_.advertise<visualization_msgs::Marker>("stomp_trajectory", 20);
init(model);
}
StompPlanner::~StompPlanner()
{
}
void StompPlanner::init(const moveit::core::RobotModelConstPtr& model)
{
kinematic_model_ = model;
if(!getPlanningScene())
{
setPlanningScene(planning_scene::PlanningSceneConstPtr(new planning_scene::PlanningScene(model)));
}
// loading parameters
int max_rollouts;
XmlRpc::XmlRpcValue features_xml;
STOMP_VERIFY(node_handle_.getParam("features", features_xml));
STOMP_VERIFY(node_handle_.getParam("max_rollouts", max_rollouts));
// Stomp Optimization Task setup
stomp_task_.reset(new StompOptimizationTask(request_.group_name,
getPlanningScene()));
if(stomp_task_->initialize(max_rollouts) &&
stomp_task_->setFeaturesFromXml(features_xml))
{
stomp_task_->setControlCostWeight(DEFAULT_CONTROL_COST_WEIGHT);
stomp_task_->setTrajectoryVizPublisher(const_cast<ros::Publisher&>(trajectory_viz_pub_));
}
else
{
ROS_ERROR_STREAM("Stomp Optimization Task failed to initialize");
}
}
bool StompPlanner::solve(planning_interface::MotionPlanResponse &res)
{
ros::WallTime start_time = ros::WallTime::now();
planning_interface::MotionPlanDetailedResponse detailed_res;
bool success = solve(detailed_res);
// construct the compact response from the detailed one
res.trajectory_ = detailed_res.trajectory_.back();
ros::WallDuration wd = ros::WallTime::now() - start_time;
res.planning_time_ = ros::Duration(wd.sec, wd.nsec).toSec();
res.error_code_ = detailed_res.error_code_;
return success;
}
bool StompPlanner::solve(planning_interface::MotionPlanDetailedResponse &res)
{
// initializing response
res.description_.resize(1);
res.description_[0] = getDescription();
res.processing_time_.resize(1);
res.trajectory_.resize(1);
setSolving(true);
ros::WallTime start_time = ros::WallTime::now();
if(!stomp_task_->setMotionPlanRequest(planning_scene_, request_, res.error_code_))
{
ROS_ERROR("STOMP failed to set MotionPlanRequest ");
return false;
}
ros::Time start = ros::Time::now();
bool success = false;
stomp_.reset(new stomp::STOMP());
if(!stomp_->initialize(node_handle_, stomp_task_))
{
ROS_ERROR_STREAM("STOMP Optimizer initialization failed");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::FAILURE;
setSolving(false);
return success;
}
ROS_DEBUG_STREAM("STOMP planning started");
success = stomp_->runUntilValid();
if(success)
{
std::vector<Eigen::VectorXd> best_params;
double best_cost;
stomp_->getBestNoiselessParameters(best_params, best_cost);
trajectory_msgs::JointTrajectory trajectory;
if(stomp_task_->parametersToJointTrajectory(best_params, trajectory))
{
stomp_task_->publishResultsMarkers(best_params);
moveit::core::RobotState robot_state(planning_scene_->getRobotModel());
moveit::core::robotStateMsgToRobotState(request_.start_state,robot_state);
res.trajectory_.resize(1);
res.trajectory_[0]= robot_trajectory::RobotTrajectoryPtr(new robot_trajectory::RobotTrajectory(
kinematic_model_,request_.group_name));
res.trajectory_.back()->setRobotTrajectoryMsg( robot_state,trajectory);
ros::WallDuration wd = ros::WallTime::now() - start_time;
res.processing_time_[0] = ros::Duration(wd.sec, wd.nsec).toSec();
res.error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
ROS_INFO_STREAM("STOMP found a valid path after "<<res.processing_time_[0]<<" seconds");
}
else
{
res.error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
success = false;
ROS_ERROR_STREAM("STOMP returned an invalid motion plan");
}
}
else
{
ROS_ERROR("STOMP failed to find a collision-free plan");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
}
setSolving(false);
return success;
}
bool StompPlanner::canServiceRequest(const moveit_msgs::MotionPlanRequest &req) const
{
// check if planner is available
if (req.planner_id != "STOMP" && req.planner_id != "CHOMP")
{
ROS_ERROR("STOMP: Planner %s not available.", req.planner_id.c_str());
return false;
}
// check for single goal region
if (req.goal_constraints.size() != 1)
{
ROS_ERROR("STOMP: Can only handle a single goal region.");
return false;
}
// check that we have only joint constraints at the goal
if (req.goal_constraints[0].position_constraints.size() > 0
|| req.goal_constraints[0].orientation_constraints.size() > 0
|| req.goal_constraints[0].visibility_constraints.size() > 0
|| req.goal_constraints[0].joint_constraints.size() == 0)
{
ROS_ERROR("STOMP: Can only handle joint space goals.");
return false;
}
return true;
}
bool StompPlanner::terminate()
{
int num_attempts = TERMINATION_ATTEMPTS;
bool success = false;
ros::Duration delay(TERMINATION_DELAY);
if(stomp_)
{
stomp_->proceed(false);
for(unsigned int i = 0 ; i < num_attempts ; i++)
{
delay.sleep();
if(!getSolving())
{
success = true;
ROS_WARN("STOMP planner terminated");
break;
}
}
}
else
{
success = true;
ROS_WARN("STOMP planner terminated");
}
return success;
}
// thread save methods
bool StompPlanner::getSolving()
{
solving_mutex_.lock();
bool r = solving_;
solving_mutex_.unlock();
return r;
}
void StompPlanner::setSolving(bool solve)
{
solving_mutex_.lock();
solving_ = solve;
solving_mutex_.unlock();
}
void StompPlanner::clear()
{
stomp_.reset();
setSolving(false);
}
} /* namespace stomp_moveit_interface */
<commit_msg>reinstated the planning scene trajectory validation<commit_after>/*
* stomp_planner.cpp
*
* Created on: Jan 22, 2013
* Author: kalakris
*/
#include <ros/ros.h>
#include <moveit/robot_state/conversions.h>
#include <stomp_moveit_interface/stomp_planner.h>
#include <stomp/stomp_utils.h>
#include <class_loader/class_loader.h>
namespace stomp_moveit_interface
{
const static double DEFAULT_CONTROL_COST_WEIGHT = 1;
const static int TERMINATION_ATTEMPTS = 200;
const double TERMINATION_DELAY = 0.1f;
StompPlanner::StompPlanner(const std::string& group,const moveit::core::RobotModelConstPtr& model):
PlanningContext("STOMP",group),
node_handle_("~"),
solving_(false),
stomp_()
{
trajectory_viz_pub_ = node_handle_.advertise<visualization_msgs::Marker>("stomp_trajectory", 20);
init(model);
}
StompPlanner::~StompPlanner()
{
}
void StompPlanner::init(const moveit::core::RobotModelConstPtr& model)
{
kinematic_model_ = model;
if(!getPlanningScene())
{
setPlanningScene(planning_scene::PlanningSceneConstPtr(new planning_scene::PlanningScene(model)));
}
// loading parameters
int max_rollouts;
XmlRpc::XmlRpcValue features_xml;
STOMP_VERIFY(node_handle_.getParam("features", features_xml));
STOMP_VERIFY(node_handle_.getParam("max_rollouts", max_rollouts));
// Stomp Optimization Task setup
stomp_task_.reset(new StompOptimizationTask(request_.group_name,
getPlanningScene()));
if(stomp_task_->initialize(max_rollouts) &&
stomp_task_->setFeaturesFromXml(features_xml))
{
stomp_task_->setControlCostWeight(DEFAULT_CONTROL_COST_WEIGHT);
stomp_task_->setTrajectoryVizPublisher(const_cast<ros::Publisher&>(trajectory_viz_pub_));
}
else
{
ROS_ERROR_STREAM("Stomp Optimization Task failed to initialize");
}
}
bool StompPlanner::solve(planning_interface::MotionPlanResponse &res)
{
ros::WallTime start_time = ros::WallTime::now();
planning_interface::MotionPlanDetailedResponse detailed_res;
bool success = solve(detailed_res);
// construct the compact response from the detailed one
res.trajectory_ = detailed_res.trajectory_.back();
ros::WallDuration wd = ros::WallTime::now() - start_time;
res.planning_time_ = ros::Duration(wd.sec, wd.nsec).toSec();
res.error_code_ = detailed_res.error_code_;
return success;
}
bool StompPlanner::solve(planning_interface::MotionPlanDetailedResponse &res)
{
// initializing response
res.description_.resize(1);
res.description_[0] = getDescription();
res.processing_time_.resize(1);
res.trajectory_.resize(1);
setSolving(true);
ros::WallTime start_time = ros::WallTime::now();
if(!stomp_task_->setMotionPlanRequest(planning_scene_, request_, res.error_code_))
{
ROS_ERROR("STOMP failed to set MotionPlanRequest ");
return false;
}
ros::Time start = ros::Time::now();
bool success = false;
stomp_.reset(new stomp::STOMP());
if(!stomp_->initialize(node_handle_, stomp_task_))
{
ROS_ERROR_STREAM("STOMP Optimizer initialization failed");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::FAILURE;
setSolving(false);
return success;
}
ROS_DEBUG_STREAM("STOMP planning started");
success = stomp_->runUntilValid();
if(success)
{
std::vector<Eigen::VectorXd> best_params;
double best_cost;
stomp_->getBestNoiselessParameters(best_params, best_cost);
trajectory_msgs::JointTrajectory trajectory;
if(stomp_task_->parametersToJointTrajectory(best_params, trajectory))
{
stomp_task_->publishResultsMarkers(best_params);
moveit::core::RobotState robot_state(planning_scene_->getRobotModel());
moveit::core::robotStateMsgToRobotState(request_.start_state,robot_state);
res.trajectory_.resize(1);
res.trajectory_[0]= robot_trajectory::RobotTrajectoryPtr(new robot_trajectory::RobotTrajectory(
kinematic_model_,request_.group_name));
res.trajectory_.back()->setRobotTrajectoryMsg( robot_state,trajectory);
if(planning_scene_ && !planning_scene_->isPathValid(*res.trajectory_.back(),group_,true))
{
res.error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
success = false;
ROS_ERROR_STREAM("STOMP generated an invalid path");
}
else
{
ros::WallDuration wd = ros::WallTime::now() - start_time;
res.processing_time_[0] = ros::Duration(wd.sec, wd.nsec).toSec();
res.error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
ROS_INFO_STREAM("STOMP found a valid path after "<<res.processing_time_[0]<<" seconds");
}
}
else
{
res.error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
success = false;
ROS_ERROR_STREAM("STOMP returned an invalid motion plan");
}
}
else
{
ROS_ERROR("STOMP failed to find a collision-free plan");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
}
setSolving(false);
return success;
}
bool StompPlanner::canServiceRequest(const moveit_msgs::MotionPlanRequest &req) const
{
// check if planner is available
if (req.planner_id != "STOMP" && req.planner_id != "CHOMP")
{
ROS_ERROR("STOMP: Planner %s not available.", req.planner_id.c_str());
return false;
}
// check for single goal region
if (req.goal_constraints.size() != 1)
{
ROS_ERROR("STOMP: Can only handle a single goal region.");
return false;
}
// check that we have only joint constraints at the goal
if (req.goal_constraints[0].position_constraints.size() > 0
|| req.goal_constraints[0].orientation_constraints.size() > 0
|| req.goal_constraints[0].visibility_constraints.size() > 0
|| req.goal_constraints[0].joint_constraints.size() == 0)
{
ROS_ERROR("STOMP: Can only handle joint space goals.");
return false;
}
return true;
}
bool StompPlanner::terminate()
{
int num_attempts = TERMINATION_ATTEMPTS;
bool success = false;
ros::Duration delay(TERMINATION_DELAY);
if(stomp_)
{
stomp_->proceed(false);
for(unsigned int i = 0 ; i < num_attempts ; i++)
{
delay.sleep();
if(!getSolving())
{
success = true;
ROS_WARN("STOMP planner terminated");
break;
}
}
}
else
{
success = true;
ROS_WARN("STOMP planner terminated");
}
return success;
}
// thread save methods
bool StompPlanner::getSolving()
{
solving_mutex_.lock();
bool r = solving_;
solving_mutex_.unlock();
return r;
}
void StompPlanner::setSolving(bool solve)
{
solving_mutex_.lock();
solving_ = solve;
solving_mutex_.unlock();
}
void StompPlanner::clear()
{
stomp_.reset();
setSolving(false);
}
} /* namespace stomp_moveit_interface */
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmljs_engine.h"
#include "qmljs_objects.h"
#include "qv4ecmaobjects_p.h"
#include "qv4mm.h"
#include <QTime>
#include <QVector>
#include <QLinkedList>
#include <iostream>
#include <malloc.h>
using namespace QQmlJS::VM;
static const std::size_t CHUNK_SIZE = 65536;
struct MemoryManager::Data
{
bool enableGC;
bool gcBlocked;
bool scribble;
bool aggressiveGC;
ExecutionEngine *engine;
StringPool *stringPool;
// FIXME: this freeList will get out of hand if there is one allocation+deallocation of, say, 16M.
// TODO: turn the freeList into a fixed length array which can hold the most common sizes (e.g. up to 64K), then use a tree for anything afterwards.
// TODO: this requires that the interaction with the freeList is factored out first into separate methods.
QVector<MMObject *> freeList;
QLinkedList<QPair<char *, std::size_t> > heapChunks;
// statistics:
#ifdef DETAILED_MM_STATS
QVector<unsigned> allocSizeCounters;
#endif // DETAILED_MM_STATS
Data(bool enableGC)
: enableGC(enableGC)
, gcBlocked(false)
, engine(0)
, stringPool(0)
, freeList(0)
{
scribble = qgetenv("MM_NO_SCRIBBLE").isEmpty();
aggressiveGC = !qgetenv("MM_AGGRESSIVE_GC").isEmpty();
}
~Data()
{
for (QLinkedList<QPair<char *, std::size_t> >::iterator i = heapChunks.begin(), ei = heapChunks.end(); i != ei; ++i)
delete[] i->first;
}
};
MemoryManager::MemoryManager()
: m_d(new Data(true))
{
}
MemoryManager::MMObject *MemoryManager::alloc(std::size_t size)
{
if (m_d->aggressiveGC)
runGC();
#ifdef DETAILED_MM_STATS
willAllocate(size);
#endif // DETAILED_MM_STATS
size += align(sizeof(MMInfo));
assert(size >= 16);
assert(size % 16 == 0);
for (std::size_t s = size / 16, es = m_d->freeList.size(); s < es; ++s) {
if (MMObject *m = m_d->freeList.at(s)) {
m_d->freeList[s] = m->info.next;
if (s != size / 16) {
MMObject *tail = reinterpret_cast<MMObject *>(reinterpret_cast<char *>(m) + size);
assert(m->info.size == s * 16);
tail->info.inUse = 0;
tail->info.markBit = 0;
tail->info.size = m->info.size - size;
MMObject *&f = m_d->freeList[tail->info.size / 16];
tail->info.next = f;
f = tail;
m->info.size = size;
}
m->info.inUse = 1;
m->info.markBit = 0;
scribble(m, 0xaa);
// qDebug("alloc(%lu) -> %p", size, m);
return m;
}
}
if (!m_d->aggressiveGC)
if (runGC() >= size)
return alloc(size - sizeof(MMInfo));
std::size_t allocSize = std::max(size, CHUNK_SIZE);
char *ptr = (char*)memalign(16, allocSize);
m_d->heapChunks.append(qMakePair(ptr, allocSize));
// qDebug("Allocated new chunk of %lu bytes @ %p", allocSize, ptr);
if (allocSize > size) {
MMObject *m = reinterpret_cast<MMObject *>(ptr + size);
m->info.size = allocSize - size;
std::size_t off = m->info.size / 16;
if (((std::size_t) m_d->freeList.size()) <= off)
m_d->freeList.resize(off + 1);
MMObject *&f = m_d->freeList[off];
m->info.next = f;
f = m;
}
MMObject *m = reinterpret_cast<MMObject *>(ptr);
m->info.inUse = 1;
m->info.markBit = 0;
m->info.size = size;
scribble(m, 0xaa);
// qDebug("alloc(%lu) -> %p", size, ptr);
return m;
}
void MemoryManager::dealloc(MMObject *ptr)
{
if (!ptr)
return;
assert(ptr->info.size >= 16);
assert(ptr->info.size % 16 == 0);
// qDebug("dealloc %p (%lu)", ptr, ptr->info.size);
std::size_t off = ptr->info.size / 16;
if (((std::size_t) m_d->freeList.size()) <= off)
m_d->freeList.resize(off + 1);
MMObject *&f = m_d->freeList[off];
ptr->info.next = f;
ptr->info.inUse = 0;
ptr->info.markBit = 0;
ptr->info.needsManagedDestructorCall = 0;
f = ptr;
scribble(ptr, 0x55);
}
void MemoryManager::scribble(MemoryManager::MMObject *obj, int c) const
{
if (m_d->scribble)
::memset(&obj->data, c, obj->info.size - sizeof(MMInfo));
}
std::size_t MemoryManager::mark(const QVector<Object *> &objects)
{
std::size_t marks = 0;
QVector<Object *> kids;
kids.reserve(32);
foreach (Object *o, objects) {
if (!o)
continue;
MMObject *obj = toObject(o);
assert(obj->info.inUse);
if (obj->info.markBit == 0) {
obj->info.markBit = 1;
++marks;
static_cast<Managed *>(o)->getCollectables(kids);
marks += mark(kids);
kids.resize(0);
}
}
return marks;
}
std::size_t MemoryManager::sweep(std::size_t &largestFreedBlock)
{
std::size_t freedCount = 0;
for (QLinkedList<QPair<char *, std::size_t> >::iterator i = m_d->heapChunks.begin(), ei = m_d->heapChunks.end(); i != ei; ++i)
freedCount += sweep(i->first, i->second, largestFreedBlock);
return freedCount;
}
std::size_t MemoryManager::sweep(char *chunkStart, std::size_t chunkSize, std::size_t &largestFreedBlock)
{
// qDebug("chunkStart @ %p", chunkStart);
std::size_t freedCount = 0;
for (char *chunk = chunkStart, *chunkEnd = chunk + chunkSize; chunk < chunkEnd; ) {
MMObject *m = reinterpret_cast<MMObject *>(chunk);
// qDebug("chunk @ %p, size = %lu, in use: %s, mark bit: %s",
// chunk, m->info.size, (m->info.inUse ? "yes" : "no"), (m->info.markBit ? "true" : "false"));
assert((intptr_t) chunk % 16 == 0);
assert(m->info.size >= 16);
assert(m->info.size % 16 == 0);
chunk = chunk + m->info.size;
if (m->info.inUse) {
if (m->info.markBit) {
m->info.markBit = 0;
} else {
// qDebug("-- collecting it.");
if (m->info.needsManagedDestructorCall)
reinterpret_cast<VM::Managed *>(&m->data)->~Managed();
dealloc(m);
largestFreedBlock = std::max(largestFreedBlock, m->info.size);
++freedCount;
}
}
}
return freedCount;
}
bool MemoryManager::isGCBlocked() const
{
return m_d->gcBlocked;
}
void MemoryManager::setGCBlocked(bool blockGC)
{
m_d->gcBlocked = blockGC;
}
std::size_t MemoryManager::runGC()
{
if (!m_d->enableGC || m_d->gcBlocked) {
// qDebug() << "Not running GC.";
return 0;
}
// QTime t; t.start();
QVector<Object *> roots;
collectRoots(roots);
// std::cerr << "GC: found " << roots.size()
// << " roots in " << t.elapsed()
// << "ms" << std::endl;
// t.restart();
/*std::size_t marks =*/ mark(roots);
// std::cerr << "GC: marked " << marks
// << " objects in " << t.elapsed()
// << "ms" << std::endl;
// t.restart();
std::size_t freedCount = 0, largestFreedBlock = 0;
freedCount = sweep(largestFreedBlock);
// std::cerr << "GC: sweep freed " << freedCount
// << " objects in " << t.elapsed()
// << "ms" << std::endl;
return largestFreedBlock;
}
void MemoryManager::setEnableGC(bool enableGC)
{
m_d->enableGC = enableGC;
}
MemoryManager::~MemoryManager()
{
std::size_t dummy = 0;
sweep(dummy);
}
static inline void add(QVector<Object *> &values, const Value &v)
{
if (Object *o = v.asObject())
values.append(o);
}
void MemoryManager::setExecutionEngine(ExecutionEngine *engine)
{
m_d->engine = engine;
}
void MemoryManager::setStringPool(StringPool *stringPool)
{
m_d->stringPool = stringPool;
}
void MemoryManager::dumpStats() const
{
std::cerr << "=================" << std::endl;
std::cerr << "Allocation stats:" << std::endl;
#ifdef DETAILED_MM_STATS
std::cerr << "Requests for each chunk size:" << std::endl;
for (int i = 0; i < m_d->allocSizeCounters.size(); ++i) {
if (unsigned count = m_d->allocSizeCounters[i]) {
std::cerr << "\t" << (i << 4) << " bytes chunks: " << count << std::endl;
}
}
#endif // DETAILED_MM_STATS
}
ExecutionEngine *MemoryManager::engine() const
{
return m_d->engine;
}
#ifdef DETAILED_MM_STATS
void MemoryManager::willAllocate(std::size_t size)
{
unsigned alignedSize = (size + 15) >> 4;
QVector<unsigned> &counters = m_d->allocSizeCounters;
if ((unsigned) counters.size() < alignedSize + 1)
counters.resize(alignedSize + 1);
counters[alignedSize]++;
}
#endif // DETAILED_MM_STATS
void MemoryManager::collectRoots(QVector<VM::Object *> &roots) const
{
add(roots, m_d->engine->globalObject);
add(roots, m_d->engine->exception);
for (ExecutionContext *ctxt = engine()->current; ctxt; ctxt = ctxt->parent) {
add(roots, ctxt->thisObject);
if (ctxt->function)
roots.append(ctxt->function);
for (unsigned arg = 0, lastArg = ctxt->formalCount(); arg < lastArg; ++arg)
add(roots, ctxt->arguments[arg]);
for (unsigned local = 0, lastLocal = ctxt->variableCount(); local < lastLocal; ++local)
add(roots, ctxt->locals[local]);
if (ctxt->activation)
roots.append(ctxt->activation);
for (ExecutionContext::With *it = ctxt->withObject; it; it = it->next)
if (it->object)
roots.append(it->object);
}
collectRootsOnStack(roots);
}
MemoryManagerWithoutGC::~MemoryManagerWithoutGC()
{}
void MemoryManagerWithoutGC::collectRootsOnStack(QVector<VM::Object *> &roots) const
{
Q_UNUSED(roots);
}
<commit_msg>Fix new/free mismatch<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmljs_engine.h"
#include "qmljs_objects.h"
#include "qv4ecmaobjects_p.h"
#include "qv4mm.h"
#include <QTime>
#include <QVector>
#include <QLinkedList>
#include <iostream>
#include <malloc.h>
using namespace QQmlJS::VM;
static const std::size_t CHUNK_SIZE = 65536;
struct MemoryManager::Data
{
bool enableGC;
bool gcBlocked;
bool scribble;
bool aggressiveGC;
ExecutionEngine *engine;
StringPool *stringPool;
// FIXME: this freeList will get out of hand if there is one allocation+deallocation of, say, 16M.
// TODO: turn the freeList into a fixed length array which can hold the most common sizes (e.g. up to 64K), then use a tree for anything afterwards.
// TODO: this requires that the interaction with the freeList is factored out first into separate methods.
QVector<MMObject *> freeList;
QLinkedList<QPair<char *, std::size_t> > heapChunks;
// statistics:
#ifdef DETAILED_MM_STATS
QVector<unsigned> allocSizeCounters;
#endif // DETAILED_MM_STATS
Data(bool enableGC)
: enableGC(enableGC)
, gcBlocked(false)
, engine(0)
, stringPool(0)
, freeList(0)
{
scribble = qgetenv("MM_NO_SCRIBBLE").isEmpty();
aggressiveGC = !qgetenv("MM_AGGRESSIVE_GC").isEmpty();
}
~Data()
{
for (QLinkedList<QPair<char *, std::size_t> >::iterator i = heapChunks.begin(), ei = heapChunks.end(); i != ei; ++i)
free(i->first);
}
};
MemoryManager::MemoryManager()
: m_d(new Data(true))
{
}
MemoryManager::MMObject *MemoryManager::alloc(std::size_t size)
{
if (m_d->aggressiveGC)
runGC();
#ifdef DETAILED_MM_STATS
willAllocate(size);
#endif // DETAILED_MM_STATS
size += align(sizeof(MMInfo));
assert(size >= 16);
assert(size % 16 == 0);
for (std::size_t s = size / 16, es = m_d->freeList.size(); s < es; ++s) {
if (MMObject *m = m_d->freeList.at(s)) {
m_d->freeList[s] = m->info.next;
if (s != size / 16) {
MMObject *tail = reinterpret_cast<MMObject *>(reinterpret_cast<char *>(m) + size);
assert(m->info.size == s * 16);
tail->info.inUse = 0;
tail->info.markBit = 0;
tail->info.size = m->info.size - size;
MMObject *&f = m_d->freeList[tail->info.size / 16];
tail->info.next = f;
f = tail;
m->info.size = size;
}
m->info.inUse = 1;
m->info.markBit = 0;
scribble(m, 0xaa);
// qDebug("alloc(%lu) -> %p", size, m);
return m;
}
}
if (!m_d->aggressiveGC)
if (runGC() >= size)
return alloc(size - sizeof(MMInfo));
std::size_t allocSize = std::max(size, CHUNK_SIZE);
char *ptr = (char*)memalign(16, allocSize);
m_d->heapChunks.append(qMakePair(ptr, allocSize));
// qDebug("Allocated new chunk of %lu bytes @ %p", allocSize, ptr);
if (allocSize > size) {
MMObject *m = reinterpret_cast<MMObject *>(ptr + size);
m->info.size = allocSize - size;
std::size_t off = m->info.size / 16;
if (((std::size_t) m_d->freeList.size()) <= off)
m_d->freeList.resize(off + 1);
MMObject *&f = m_d->freeList[off];
m->info.next = f;
f = m;
}
MMObject *m = reinterpret_cast<MMObject *>(ptr);
m->info.inUse = 1;
m->info.markBit = 0;
m->info.size = size;
scribble(m, 0xaa);
// qDebug("alloc(%lu) -> %p", size, ptr);
return m;
}
void MemoryManager::dealloc(MMObject *ptr)
{
if (!ptr)
return;
assert(ptr->info.size >= 16);
assert(ptr->info.size % 16 == 0);
// qDebug("dealloc %p (%lu)", ptr, ptr->info.size);
std::size_t off = ptr->info.size / 16;
if (((std::size_t) m_d->freeList.size()) <= off)
m_d->freeList.resize(off + 1);
MMObject *&f = m_d->freeList[off];
ptr->info.next = f;
ptr->info.inUse = 0;
ptr->info.markBit = 0;
ptr->info.needsManagedDestructorCall = 0;
f = ptr;
scribble(ptr, 0x55);
}
void MemoryManager::scribble(MemoryManager::MMObject *obj, int c) const
{
if (m_d->scribble)
::memset(&obj->data, c, obj->info.size - sizeof(MMInfo));
}
std::size_t MemoryManager::mark(const QVector<Object *> &objects)
{
std::size_t marks = 0;
QVector<Object *> kids;
kids.reserve(32);
foreach (Object *o, objects) {
if (!o)
continue;
MMObject *obj = toObject(o);
assert(obj->info.inUse);
if (obj->info.markBit == 0) {
obj->info.markBit = 1;
++marks;
static_cast<Managed *>(o)->getCollectables(kids);
marks += mark(kids);
kids.resize(0);
}
}
return marks;
}
std::size_t MemoryManager::sweep(std::size_t &largestFreedBlock)
{
std::size_t freedCount = 0;
for (QLinkedList<QPair<char *, std::size_t> >::iterator i = m_d->heapChunks.begin(), ei = m_d->heapChunks.end(); i != ei; ++i)
freedCount += sweep(i->first, i->second, largestFreedBlock);
return freedCount;
}
std::size_t MemoryManager::sweep(char *chunkStart, std::size_t chunkSize, std::size_t &largestFreedBlock)
{
// qDebug("chunkStart @ %p", chunkStart);
std::size_t freedCount = 0;
for (char *chunk = chunkStart, *chunkEnd = chunk + chunkSize; chunk < chunkEnd; ) {
MMObject *m = reinterpret_cast<MMObject *>(chunk);
// qDebug("chunk @ %p, size = %lu, in use: %s, mark bit: %s",
// chunk, m->info.size, (m->info.inUse ? "yes" : "no"), (m->info.markBit ? "true" : "false"));
assert((intptr_t) chunk % 16 == 0);
assert(m->info.size >= 16);
assert(m->info.size % 16 == 0);
chunk = chunk + m->info.size;
if (m->info.inUse) {
if (m->info.markBit) {
m->info.markBit = 0;
} else {
// qDebug("-- collecting it.");
if (m->info.needsManagedDestructorCall)
reinterpret_cast<VM::Managed *>(&m->data)->~Managed();
dealloc(m);
largestFreedBlock = std::max(largestFreedBlock, m->info.size);
++freedCount;
}
}
}
return freedCount;
}
bool MemoryManager::isGCBlocked() const
{
return m_d->gcBlocked;
}
void MemoryManager::setGCBlocked(bool blockGC)
{
m_d->gcBlocked = blockGC;
}
std::size_t MemoryManager::runGC()
{
if (!m_d->enableGC || m_d->gcBlocked) {
// qDebug() << "Not running GC.";
return 0;
}
// QTime t; t.start();
QVector<Object *> roots;
collectRoots(roots);
// std::cerr << "GC: found " << roots.size()
// << " roots in " << t.elapsed()
// << "ms" << std::endl;
// t.restart();
/*std::size_t marks =*/ mark(roots);
// std::cerr << "GC: marked " << marks
// << " objects in " << t.elapsed()
// << "ms" << std::endl;
// t.restart();
std::size_t freedCount = 0, largestFreedBlock = 0;
freedCount = sweep(largestFreedBlock);
// std::cerr << "GC: sweep freed " << freedCount
// << " objects in " << t.elapsed()
// << "ms" << std::endl;
return largestFreedBlock;
}
void MemoryManager::setEnableGC(bool enableGC)
{
m_d->enableGC = enableGC;
}
MemoryManager::~MemoryManager()
{
std::size_t dummy = 0;
sweep(dummy);
}
static inline void add(QVector<Object *> &values, const Value &v)
{
if (Object *o = v.asObject())
values.append(o);
}
void MemoryManager::setExecutionEngine(ExecutionEngine *engine)
{
m_d->engine = engine;
}
void MemoryManager::setStringPool(StringPool *stringPool)
{
m_d->stringPool = stringPool;
}
void MemoryManager::dumpStats() const
{
std::cerr << "=================" << std::endl;
std::cerr << "Allocation stats:" << std::endl;
#ifdef DETAILED_MM_STATS
std::cerr << "Requests for each chunk size:" << std::endl;
for (int i = 0; i < m_d->allocSizeCounters.size(); ++i) {
if (unsigned count = m_d->allocSizeCounters[i]) {
std::cerr << "\t" << (i << 4) << " bytes chunks: " << count << std::endl;
}
}
#endif // DETAILED_MM_STATS
}
ExecutionEngine *MemoryManager::engine() const
{
return m_d->engine;
}
#ifdef DETAILED_MM_STATS
void MemoryManager::willAllocate(std::size_t size)
{
unsigned alignedSize = (size + 15) >> 4;
QVector<unsigned> &counters = m_d->allocSizeCounters;
if ((unsigned) counters.size() < alignedSize + 1)
counters.resize(alignedSize + 1);
counters[alignedSize]++;
}
#endif // DETAILED_MM_STATS
void MemoryManager::collectRoots(QVector<VM::Object *> &roots) const
{
add(roots, m_d->engine->globalObject);
add(roots, m_d->engine->exception);
for (ExecutionContext *ctxt = engine()->current; ctxt; ctxt = ctxt->parent) {
add(roots, ctxt->thisObject);
if (ctxt->function)
roots.append(ctxt->function);
for (unsigned arg = 0, lastArg = ctxt->formalCount(); arg < lastArg; ++arg)
add(roots, ctxt->arguments[arg]);
for (unsigned local = 0, lastLocal = ctxt->variableCount(); local < lastLocal; ++local)
add(roots, ctxt->locals[local]);
if (ctxt->activation)
roots.append(ctxt->activation);
for (ExecutionContext::With *it = ctxt->withObject; it; it = it->next)
if (it->object)
roots.append(it->object);
}
collectRootsOnStack(roots);
}
MemoryManagerWithoutGC::~MemoryManagerWithoutGC()
{}
void MemoryManagerWithoutGC::collectRootsOnStack(QVector<VM::Object *> &roots) const
{
Q_UNUSED(roots);
}
<|endoftext|> |
<commit_before>#include "qtfirebaseanalytics.h"
#include <QGuiApplication>
namespace analytics = ::firebase::analytics;
QtFirebaseAnalytics *QtFirebaseAnalytics::self = 0;
QtFirebaseAnalytics::QtFirebaseAnalytics(QObject* parent) : QObject(parent)
{
if(self == 0) {
self = this;
qDebug() << self << "::QtFirebaseAnalytics" << "singleton";
}
_ready = false;
_initializing = false;
if(qFirebase->ready())
init();
else {
connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseAnalytics::init);
qFirebase->requestInit();
}
}
QtFirebaseAnalytics::~QtFirebaseAnalytics()
{
if(_ready) {
qDebug() << self << "::~QtFirebaseAnalytics" << "shutting down";
analytics::Terminate();
_ready = false;
self = 0;
}
}
bool QtFirebaseAnalytics::checkInstance(const char *function)
{
bool b = (QtFirebaseAnalytics::self != 0);
if (!b)
qWarning("QtFirebaseAnalytics::%s: Please instantiate the QtFirebaseAnalytics object first", function);
return b;
}
void QtFirebaseAnalytics::setUserProperty(const QString &propertyName, const QString &propertyValue)
{
if(!_ready) {
qDebug() << this << "::setUserProperty native part not ready";
return;
}
qDebug() << this << "::setUserProperty" << propertyName << ":" << propertyValue;
analytics::SetUserProperty(propertyName.toLatin1().constData(), propertyValue.toLatin1().constData());
}
void QtFirebaseAnalytics::setCurrentScreen(const QString &screenName, const QString &screenClass)
{
if(!_ready) {
qDebug() << this << "::setCurrentScreen native part not ready";
return;
}
qDebug() << this << "::setCurrentScreen" << screenName << ":" << screenClass ;
analytics::SetCurrentScreen(screenName.toLatin1().constData(), screenName.toLatin1().constData());
}
void QtFirebaseAnalytics::logEvent(const QString &name)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging (no parameters)";
analytics::LogEvent(name.toUtf8().constData());
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QString ¶meterName, const QString ¶meterValue)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging string parameter" << parameterName << ":" << parameterValue;
analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue.toUtf8().constData());
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QString ¶meterName, const double parameterValue)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging double parameter" << parameterName << ":" << parameterValue;
analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue);
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QString ¶meterName, const int parameterValue)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging int parameter" << parameterName << ":" << parameterValue;
analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue);
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QVariantMap bundle)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
analytics::Parameter *parameters = new analytics::Parameter[bundle.size()];
QByteArrayList keys;
QByteArrayList strings;
QMapIterator<QString, QVariant> i(bundle);
int index = 0;
while (i.hasNext()) {
i.next();
keys.append(i.key().toLatin1());
QString eventKey = i.key();
QVariant variant = i.value();
if(variant.type() == QVariant::Type(QMetaType::Int)) {
parameters[index] = analytics::Parameter(keys.at(index).constData(), variant.toInt());
qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toInt();
} else if(variant.type() == QVariant::Type(QMetaType::Double)) {
parameters[index] = analytics::Parameter(keys.at(index).constData(),variant.toDouble());
qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toDouble();
} else if(variant.type() == QVariant::Type(QMetaType::QString)) {
strings.append(variant.toString().toLatin1());
parameters[index] = analytics::Parameter(keys.at(index).constData(), strings.at(strings.size()-1).constData());
qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << strings.at(strings.size()-1);
} else {
qWarning() << this << "::logEvent" << "bundle parameter" << eventKey << "has unsupported data type. Sending empty strings";
parameters[index] = analytics::Parameter("", "");
}
index++;
}
qDebug() << this << "::logEvent" << "logging" << "bundle" << name;
analytics::LogEvent(name.toUtf8().constData(), parameters, bundle.size());
delete[] parameters;
parameters = 0;
}
QVariantList QtFirebaseAnalytics::userProperties() const
{
return _userProperties;
}
void QtFirebaseAnalytics::setUserProperties(const QVariantList &userProperties)
{
if(!_ready) {
qDebug() << this << "::setUserProperties native part not ready";
return;
}
if (_userProperties != userProperties) {
_userProperties = userProperties;
if(_userProperties.size() > 25) {
}
unsigned index = 0;
for (QVariantList::iterator j = _userProperties.begin(); j != _userProperties.end(); j++)
{
if((*j).canConvert<QVariantMap>()) {
QVariantMap map = (*j).toMap();
if(!map.isEmpty()) {
if(map.first().canConvert<QString>()) {
QString key = map.firstKey();
QString value = map.first().toString();
setUserProperty(key,value);
}
}
} else {
qWarning() << this << "::setUserProperties" << "wrong entry in userProperties list at index" << index;
}
index++;
}
emit userPropertiesChanged();
}
}
QString QtFirebaseAnalytics::userId() const
{
return _userId;
}
void QtFirebaseAnalytics::setUserId(const QString &userId)
{
if(!_ready) {
qDebug() << this << "::setUserId native part not ready";
return;
}
QString aUserId = userId;
if(aUserId.isEmpty()) {
unsetUserId();
}
if(aUserId.length() > 36) {
aUserId = aUserId.left(36);
qWarning() << this << "::setUserId" << "ID longer than allowed 36 chars" << "TRUNCATED to" << aUserId;
}
if(_userId != aUserId) {
_userId = aUserId;
analytics::SetUserId(_userId.toLatin1().constData());
qDebug() << this << "::setUserId sat to" << _userId;
emit userIdChanged();
}
}
void QtFirebaseAnalytics::unsetUserId()
{
if(!_ready) {
qDebug() << this << "::unsetUserId native part not ready";
return;
}
if(!_userId.isEmpty()) {
_userId.clear();
analytics::SetUserId(NULL);
emit userIdChanged();
}
}
unsigned int QtFirebaseAnalytics::sessionTimeout() const
{
return _sessionTimeout;
}
void QtFirebaseAnalytics::setSessionTimeout(unsigned int sessionTimeout)
{
if(_sessionTimeout != sessionTimeout) {
_sessionTimeout = sessionTimeout;
emit sessionTimeoutChanged();
}
}
bool QtFirebaseAnalytics::ready()
{
return _ready;
}
void QtFirebaseAnalytics::setReady(bool ready)
{
if (_ready != ready) {
_ready = ready;
qDebug() << self << "::setReady" << ready;
emit readyChanged();
}
}
bool QtFirebaseAnalytics::enabled()
{
return _enabled;
}
void QtFirebaseAnalytics::setEnabled(bool enabled)
{
if(!_ready) {
qDebug() << this << "::setEnabled native part not ready";
return;
}
if (_enabled != enabled) {
analytics::SetAnalyticsCollectionEnabled(enabled);
_enabled = enabled;
qDebug() << self << "::setEnabled" << enabled;
emit enabledChanged();
}
}
unsigned int QtFirebaseAnalytics::minimumSessionDuration()
{
return _minimumSessionDuration;
}
void QtFirebaseAnalytics::setMinimumSessionDuration(unsigned int minimumSessionDuration)
{
if(!_ready) {
qDebug() << this << "::setMinimumSessionDuration native part not ready";
return;
}
if (_minimumSessionDuration != minimumSessionDuration) {
analytics::SetMinimumSessionDuration(minimumSessionDuration);
_minimumSessionDuration = minimumSessionDuration;
qDebug() << self << "::setMinimumSessionDuration" << minimumSessionDuration;
emit minimumSessionDurationChanged();
}
}
void QtFirebaseAnalytics::init()
{
if(!qFirebase->ready()) {
qDebug() << self << "::init" << "base not ready";
return;
}
if(!_ready && !_initializing) {
_initializing = true;
analytics::Initialize(*qFirebase->firebaseApp());
qDebug() << self << "::init" << "native initialized";
_initializing = false;
setReady(true);
}
}
<commit_msg>Fix issue #65<commit_after>#include "qtfirebaseanalytics.h"
#include <QGuiApplication>
namespace analytics = ::firebase::analytics;
QtFirebaseAnalytics *QtFirebaseAnalytics::self = 0;
QtFirebaseAnalytics::QtFirebaseAnalytics(QObject* parent) : QObject(parent)
{
if(self == 0) {
self = this;
qDebug() << self << "::QtFirebaseAnalytics" << "singleton";
}
_ready = false;
_initializing = false;
if(qFirebase->ready())
init();
else {
connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseAnalytics::init);
qFirebase->requestInit();
}
}
QtFirebaseAnalytics::~QtFirebaseAnalytics()
{
if(_ready) {
qDebug() << self << "::~QtFirebaseAnalytics" << "shutting down";
analytics::Terminate();
_ready = false;
self = 0;
}
}
bool QtFirebaseAnalytics::checkInstance(const char *function)
{
bool b = (QtFirebaseAnalytics::self != 0);
if (!b)
qWarning("QtFirebaseAnalytics::%s: Please instantiate the QtFirebaseAnalytics object first", function);
return b;
}
void QtFirebaseAnalytics::setUserProperty(const QString &propertyName, const QString &propertyValue)
{
if(!_ready) {
qDebug() << this << "::setUserProperty native part not ready";
return;
}
qDebug() << this << "::setUserProperty" << propertyName << ":" << propertyValue;
analytics::SetUserProperty(propertyName.toLatin1().constData(), propertyValue.toLatin1().constData());
}
void QtFirebaseAnalytics::setCurrentScreen(const QString &screenName, const QString &screenClass)
{
if(!_ready) {
qDebug() << this << "::setCurrentScreen native part not ready";
return;
}
qDebug() << this << "::setCurrentScreen" << screenName << ":" << screenClass ;
analytics::SetCurrentScreen(screenName.toLatin1().constData(), screenClass.toLatin1().constData());
}
void QtFirebaseAnalytics::logEvent(const QString &name)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging (no parameters)";
analytics::LogEvent(name.toUtf8().constData());
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QString ¶meterName, const QString ¶meterValue)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging string parameter" << parameterName << ":" << parameterValue;
analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue.toUtf8().constData());
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QString ¶meterName, const double parameterValue)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging double parameter" << parameterName << ":" << parameterValue;
analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue);
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QString ¶meterName, const int parameterValue)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
qDebug() << this << "::logEvent" << name << "logging int parameter" << parameterName << ":" << parameterValue;
analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue);
}
void QtFirebaseAnalytics::logEvent(const QString &name, const QVariantMap bundle)
{
if(!_ready) {
qDebug() << this << "::logEvent native part not ready";
return;
}
analytics::Parameter *parameters = new analytics::Parameter[bundle.size()];
QByteArrayList keys;
QByteArrayList strings;
QMapIterator<QString, QVariant> i(bundle);
int index = 0;
while (i.hasNext()) {
i.next();
keys.append(i.key().toLatin1());
QString eventKey = i.key();
QVariant variant = i.value();
if(variant.type() == QVariant::Type(QMetaType::Int)) {
parameters[index] = analytics::Parameter(keys.at(index).constData(), variant.toInt());
qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toInt();
} else if(variant.type() == QVariant::Type(QMetaType::Double)) {
parameters[index] = analytics::Parameter(keys.at(index).constData(),variant.toDouble());
qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toDouble();
} else if(variant.type() == QVariant::Type(QMetaType::QString)) {
strings.append(variant.toString().toLatin1());
parameters[index] = analytics::Parameter(keys.at(index).constData(), strings.at(strings.size()-1).constData());
qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << strings.at(strings.size()-1);
} else {
qWarning() << this << "::logEvent" << "bundle parameter" << eventKey << "has unsupported data type. Sending empty strings";
parameters[index] = analytics::Parameter("", "");
}
index++;
}
qDebug() << this << "::logEvent" << "logging" << "bundle" << name;
analytics::LogEvent(name.toUtf8().constData(), parameters, bundle.size());
delete[] parameters;
parameters = 0;
}
QVariantList QtFirebaseAnalytics::userProperties() const
{
return _userProperties;
}
void QtFirebaseAnalytics::setUserProperties(const QVariantList &userProperties)
{
if(!_ready) {
qDebug() << this << "::setUserProperties native part not ready";
return;
}
if (_userProperties != userProperties) {
_userProperties = userProperties;
if(_userProperties.size() > 25) {
}
unsigned index = 0;
for (QVariantList::iterator j = _userProperties.begin(); j != _userProperties.end(); j++)
{
if((*j).canConvert<QVariantMap>()) {
QVariantMap map = (*j).toMap();
if(!map.isEmpty()) {
if(map.first().canConvert<QString>()) {
QString key = map.firstKey();
QString value = map.first().toString();
setUserProperty(key,value);
}
}
} else {
qWarning() << this << "::setUserProperties" << "wrong entry in userProperties list at index" << index;
}
index++;
}
emit userPropertiesChanged();
}
}
QString QtFirebaseAnalytics::userId() const
{
return _userId;
}
void QtFirebaseAnalytics::setUserId(const QString &userId)
{
if(!_ready) {
qDebug() << this << "::setUserId native part not ready";
return;
}
QString aUserId = userId;
if(aUserId.isEmpty()) {
unsetUserId();
}
if(aUserId.length() > 36) {
aUserId = aUserId.left(36);
qWarning() << this << "::setUserId" << "ID longer than allowed 36 chars" << "TRUNCATED to" << aUserId;
}
if(_userId != aUserId) {
_userId = aUserId;
analytics::SetUserId(_userId.toLatin1().constData());
qDebug() << this << "::setUserId sat to" << _userId;
emit userIdChanged();
}
}
void QtFirebaseAnalytics::unsetUserId()
{
if(!_ready) {
qDebug() << this << "::unsetUserId native part not ready";
return;
}
if(!_userId.isEmpty()) {
_userId.clear();
analytics::SetUserId(NULL);
emit userIdChanged();
}
}
unsigned int QtFirebaseAnalytics::sessionTimeout() const
{
return _sessionTimeout;
}
void QtFirebaseAnalytics::setSessionTimeout(unsigned int sessionTimeout)
{
if(_sessionTimeout != sessionTimeout) {
_sessionTimeout = sessionTimeout;
emit sessionTimeoutChanged();
}
}
bool QtFirebaseAnalytics::ready()
{
return _ready;
}
void QtFirebaseAnalytics::setReady(bool ready)
{
if (_ready != ready) {
_ready = ready;
qDebug() << self << "::setReady" << ready;
emit readyChanged();
}
}
bool QtFirebaseAnalytics::enabled()
{
return _enabled;
}
void QtFirebaseAnalytics::setEnabled(bool enabled)
{
if(!_ready) {
qDebug() << this << "::setEnabled native part not ready";
return;
}
if (_enabled != enabled) {
analytics::SetAnalyticsCollectionEnabled(enabled);
_enabled = enabled;
qDebug() << self << "::setEnabled" << enabled;
emit enabledChanged();
}
}
unsigned int QtFirebaseAnalytics::minimumSessionDuration()
{
return _minimumSessionDuration;
}
void QtFirebaseAnalytics::setMinimumSessionDuration(unsigned int minimumSessionDuration)
{
if(!_ready) {
qDebug() << this << "::setMinimumSessionDuration native part not ready";
return;
}
if (_minimumSessionDuration != minimumSessionDuration) {
analytics::SetMinimumSessionDuration(minimumSessionDuration);
_minimumSessionDuration = minimumSessionDuration;
qDebug() << self << "::setMinimumSessionDuration" << minimumSessionDuration;
emit minimumSessionDurationChanged();
}
}
void QtFirebaseAnalytics::init()
{
if(!qFirebase->ready()) {
qDebug() << self << "::init" << "base not ready";
return;
}
if(!_ready && !_initializing) {
_initializing = true;
analytics::Initialize(*qFirebase->firebaseApp());
qDebug() << self << "::init" << "native initialized";
_initializing = false;
setReady(true);
}
}
<|endoftext|> |
<commit_before>/* Copyright 2013-present Barefoot Networks, 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.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/_assert.h>
#include <bm/bm_sim/logger.h>
#include <bm/bm_sim/options_parse.h>
#include <bm/PI/pi.h>
#include <PI/frontends/proto/device_mgr.h>
#include <PI/frontends/proto/logging.h>
#include <PI/proto/pi_server.h>
#include <PI/pi.h>
#include <PI/target/pi_imp.h>
#include <grpc++/grpc++.h>
#include <p4/bm/dataplane_interface.grpc.pb.h>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include "simple_switch.h"
#include "switch_runner.h"
#ifdef WITH_SYSREPO
#include "switch_sysrepo.h"
#endif // WITH_SYSREPO
namespace sswitch_grpc {
namespace {
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
using ServerReaderWriter = grpc::ServerReaderWriter<
p4::bm::PacketStreamResponse, p4::bm::PacketStreamRequest>;
class DataplaneInterfaceServiceImpl
: public p4::bm::DataplaneInterface::Service,
public bm::DevMgrIface {
public:
explicit DataplaneInterfaceServiceImpl(bm::device_id_t device_id)
: device_id(device_id) {
p_monitor = bm::PortMonitorIface::make_passive(device_id);
}
private:
using Lock = std::lock_guard<std::mutex>;
using Empty = google::protobuf::Empty;
Status PacketStream(ServerContext *context,
ServerReaderWriter *stream) override {
{
Lock lock(mutex);
if (!started)
return Status(StatusCode::UNAVAILABLE, "not ready");
if (active) {
return Status(StatusCode::RESOURCE_EXHAUSTED,
"only one client authorized at a time");
}
active = true;
this->context = context;
this->stream = stream;
}
p4::bm::PacketStreamRequest request;
while (this->stream->Read(&request)) {
if (request.device_id() != device_id) {
continue;
}
const auto &packet = request.packet();
if (packet.empty()) continue;
if (!pkt_handler) continue;
pkt_handler(request.port(), packet.data(), packet.size(), pkt_cookie);
}
auto &runner = sswitch_grpc::SimpleSwitchGrpcRunner::get_instance();
runner.block_until_all_packets_processed();
Lock lock(mutex);
active = false;
return Status::OK;
}
Status SetPortOperStatus(ServerContext *context,
const p4::bm::SetPortOperStatusRequest *request,
Empty *response) override {
(void) context;
(void) response;
Lock lock(mutex);
if (request->device_id() != device_id)
return Status(StatusCode::INVALID_ARGUMENT, "Invalid device id");
if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_DOWN)
ports_oper_status[request->port()] = false;
else if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_UP)
ports_oper_status[request->port()] = true;
else
return Status(StatusCode::INVALID_ARGUMENT, "Invalid oper status");
return Status::OK;
}
ReturnCode port_add_(const std::string &iface_name, port_t port_num,
const PortExtras &port_extras) override {
_BM_UNUSED(iface_name);
_BM_UNUSED(port_num);
_BM_UNUSED(port_extras);
return ReturnCode::SUCCESS;
}
ReturnCode port_remove_(port_t port_num) override {
_BM_UNUSED(port_num);
return ReturnCode::SUCCESS;
}
void transmit_fn_(int port_num, const char *buffer, int len) override {
p4::bm::PacketStreamResponse response;
response.set_device_id(device_id);
response.set_port(port_num);
response.set_packet(buffer, len);
Lock lock(mutex);
if (active) stream->Write(response);
}
void start_() override {
Lock lock(mutex);
started = true;
}
ReturnCode set_packet_handler_(const PacketHandler &handler, void *cookie)
override {
pkt_handler = handler;
pkt_cookie = cookie;
return ReturnCode::SUCCESS;
}
bool port_is_up_(port_t port) const override {
Lock lock(mutex);
auto status_it = ports_oper_status.find(port);
return (status_it == ports_oper_status.end()) ? true : status_it->second;
}
std::map<port_t, PortInfo> get_port_info_() const override {
return {};
}
bm::device_id_t device_id;
// protects the shared state (active) and prevents concurrent Write calls by
// different threads
mutable std::mutex mutex{};
bool started{false};
bool active{false};
ServerContext *context{nullptr};
ServerReaderWriter *stream{nullptr};
PacketHandler pkt_handler{};
void *pkt_cookie{nullptr};
std::unordered_map<port_t, bool> ports_oper_status{};
};
} // namespace
SimpleSwitchGrpcRunner::SimpleSwitchGrpcRunner(int max_port, bool enable_swap,
std::string grpc_server_addr,
int cpu_port,
std::string dp_grpc_server_addr)
: simple_switch(new SimpleSwitch(max_port, enable_swap)),
grpc_server_addr(grpc_server_addr), cpu_port(cpu_port),
dp_grpc_server_addr(dp_grpc_server_addr),
dp_grpc_server(nullptr) { }
int
SimpleSwitchGrpcRunner::init_and_start(const bm::OptionsParser &parser) {
std::unique_ptr<bm::DevMgrIface> my_dev_mgr = nullptr;
if (!dp_grpc_server_addr.empty()) {
auto service = new DataplaneInterfaceServiceImpl(parser.device_id);
grpc::ServerBuilder builder;
builder.SetSyncServerOption(
grpc::ServerBuilder::SyncServerOption::NUM_CQS, 1);
builder.SetSyncServerOption(
grpc::ServerBuilder::SyncServerOption::MIN_POLLERS, 1);
builder.SetSyncServerOption(
grpc::ServerBuilder::SyncServerOption::MAX_POLLERS, 1);
builder.AddListeningPort(dp_grpc_server_addr,
grpc::InsecureServerCredentials(),
&dp_grpc_server_port);
builder.RegisterService(service);
dp_grpc_server = builder.BuildAndStart();
my_dev_mgr.reset(service);
}
#ifdef WITH_SYSREPO
sysrepo_driver = std::unique_ptr<SysrepoDriver>(new SysrepoDriver(
parser.device_id, simple_switch.get()));
#endif // WITH_SYSREPO
// Even when using gNMI to manage ports, it is convenient to be able to use
// the --interface / -i command-line option. However we have to "intercept"
// the options before the call to DevMgr::port_add, otherwise we would try to
// add the ports twice (once when calling Switch::init_from_options_parser and
// once when we are notified by sysrepo of the YANG datastore change).
// We therefore save the interface list provided on the command-line and we
// call SysrepoDriver::add_iface at the end of this method after we start the
// sysrepo subscriber.
const bm::OptionsParser *parser_ptr;
#ifdef WITH_SYSREPO
auto new_parser = parser;
auto &interfaces = new_parser.ifaces;
auto saved_interfaces = interfaces;
interfaces.clear();
parser_ptr = &new_parser;
#else
parser_ptr = &parser;
#endif // WITH_SYSREPO
int status = simple_switch->init_from_options_parser(
*parser_ptr, nullptr, std::move(my_dev_mgr));
if (status != 0) return status;
// PortMonitor saves the CB by reference so we cannot use this code; it seems
// that at this stage we do not need the CB any way.
// using PortStatus = bm::DevMgrIface::PortStatus;
// auto port_cb = std::bind(&SimpleSwitchGrpcRunner::port_status_cb, this,
// std::placeholders::_1, std::placeholders::_2);
// simple_switch->register_status_cb(PortStatus::PORT_ADDED, port_cb);
// simple_switch->register_status_cb(PortStatus::PORT_REMOVED, port_cb);
// check if CPU port number is also used by --interface
// TODO(antonin): ports added dynamically?
if (cpu_port >= 0) {
if (parser.ifaces.find(cpu_port) != parser.ifaces.end()) {
bm::Logger::get()->error("Cpu port {} is used as a data port", cpu_port);
return 1;
}
}
if (cpu_port >= 0) {
auto transmit_fn = [this](int port_num, const char *buf, int len) {
if (port_num == cpu_port) {
BMLOG_DEBUG("Transmitting packet-in");
auto status = pi_packetin_receive(
simple_switch->get_device_id(), buf, static_cast<size_t>(len));
if (status != PI_STATUS_SUCCESS)
bm::Logger::get()->error("Error when transmitting packet-in");
} else {
simple_switch->transmit_fn(port_num, buf, len);
}
};
simple_switch->set_transmit_fn(transmit_fn);
}
bm::pi::register_switch(simple_switch.get(), cpu_port);
{
using pi::fe::proto::LogWriterIface;
using pi::fe::proto::LoggerConfig;
class P4RuntimeLogger : public LogWriterIface {
void write(Severity severity, const char *msg) override {
auto severity_map = [&severity]() {
namespace spdL = spdlog::level;
switch (severity) {
case Severity::TRACE : return spdL::trace;
case Severity::DEBUG: return spdL::debug;
case Severity::INFO: return spdL::info;
case Severity::WARN: return spdL::warn;
case Severity::ERROR: return spdL::err;
case Severity::CRITICAL: return spdL::critical;
}
return spdL::off;
};
// TODO(antonin): use a separate logger with a separate name
bm::Logger::get()->log(severity_map(), "[P4Runtime] {}", msg);
}
};
LoggerConfig::set_writer(std::make_shared<P4RuntimeLogger>());
}
using pi::fe::proto::DeviceMgr;
DeviceMgr::init(256);
PIGrpcServerRunAddr(grpc_server_addr.c_str());
#ifdef WITH_SYSREPO
if (!sysrepo_driver->start()) return 1;
for (const auto &p : saved_interfaces)
sysrepo_driver->add_iface(p.first, p.second);
#endif // WITH_SYSREPO
simple_switch->start_and_return();
return 0;
}
void
SimpleSwitchGrpcRunner::wait() {
PIGrpcServerWait();
}
void
SimpleSwitchGrpcRunner::shutdown() {
if (!dp_grpc_server_addr.empty()) dp_grpc_server->Shutdown();
PIGrpcServerShutdown();
}
void
SimpleSwitchGrpcRunner::mirroring_mapping_add(int mirror_id, int egress_port) {
simple_switch->mirroring_mapping_add(mirror_id, egress_port);
}
void
SimpleSwitchGrpcRunner::block_until_all_packets_processed() {
simple_switch->block_until_no_more_packets();
}
SimpleSwitchGrpcRunner::~SimpleSwitchGrpcRunner() {
PIGrpcServerCleanup();
}
void
SimpleSwitchGrpcRunner::port_status_cb(
bm::DevMgrIface::port_t port, const bm::DevMgrIface::PortStatus status) {
_BM_UNUSED(port);
_BM_UNUSED(status);
}
} // namespace sswitch_grpc
<commit_msg>Destroy DevMgr in SimpleSwitchGrpcRunner's destructor<commit_after>/* Copyright 2013-present Barefoot Networks, 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.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/_assert.h>
#include <bm/bm_sim/logger.h>
#include <bm/bm_sim/options_parse.h>
#include <bm/PI/pi.h>
#include <PI/frontends/proto/device_mgr.h>
#include <PI/frontends/proto/logging.h>
#include <PI/proto/pi_server.h>
#include <PI/pi.h>
#include <PI/target/pi_imp.h>
#include <grpc++/grpc++.h>
#include <p4/bm/dataplane_interface.grpc.pb.h>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include "simple_switch.h"
#include "switch_runner.h"
#ifdef WITH_SYSREPO
#include "switch_sysrepo.h"
#endif // WITH_SYSREPO
namespace sswitch_grpc {
using pi::fe::proto::DeviceMgr;
namespace {
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
using ServerReaderWriter = grpc::ServerReaderWriter<
p4::bm::PacketStreamResponse, p4::bm::PacketStreamRequest>;
class DataplaneInterfaceServiceImpl
: public p4::bm::DataplaneInterface::Service,
public bm::DevMgrIface {
public:
explicit DataplaneInterfaceServiceImpl(bm::device_id_t device_id)
: device_id(device_id) {
p_monitor = bm::PortMonitorIface::make_passive(device_id);
}
private:
using Lock = std::lock_guard<std::mutex>;
using Empty = google::protobuf::Empty;
Status PacketStream(ServerContext *context,
ServerReaderWriter *stream) override {
{
Lock lock(mutex);
if (!started)
return Status(StatusCode::UNAVAILABLE, "not ready");
if (active) {
return Status(StatusCode::RESOURCE_EXHAUSTED,
"only one client authorized at a time");
}
active = true;
this->context = context;
this->stream = stream;
}
p4::bm::PacketStreamRequest request;
while (this->stream->Read(&request)) {
if (request.device_id() != device_id) {
continue;
}
const auto &packet = request.packet();
if (packet.empty()) continue;
if (!pkt_handler) continue;
pkt_handler(request.port(), packet.data(), packet.size(), pkt_cookie);
}
auto &runner = sswitch_grpc::SimpleSwitchGrpcRunner::get_instance();
runner.block_until_all_packets_processed();
Lock lock(mutex);
active = false;
return Status::OK;
}
Status SetPortOperStatus(ServerContext *context,
const p4::bm::SetPortOperStatusRequest *request,
Empty *response) override {
(void) context;
(void) response;
Lock lock(mutex);
if (request->device_id() != device_id)
return Status(StatusCode::INVALID_ARGUMENT, "Invalid device id");
if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_DOWN)
ports_oper_status[request->port()] = false;
else if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_UP)
ports_oper_status[request->port()] = true;
else
return Status(StatusCode::INVALID_ARGUMENT, "Invalid oper status");
return Status::OK;
}
ReturnCode port_add_(const std::string &iface_name, port_t port_num,
const PortExtras &port_extras) override {
_BM_UNUSED(iface_name);
_BM_UNUSED(port_num);
_BM_UNUSED(port_extras);
return ReturnCode::SUCCESS;
}
ReturnCode port_remove_(port_t port_num) override {
_BM_UNUSED(port_num);
return ReturnCode::SUCCESS;
}
void transmit_fn_(int port_num, const char *buffer, int len) override {
p4::bm::PacketStreamResponse response;
response.set_device_id(device_id);
response.set_port(port_num);
response.set_packet(buffer, len);
Lock lock(mutex);
if (active) stream->Write(response);
}
void start_() override {
Lock lock(mutex);
started = true;
}
ReturnCode set_packet_handler_(const PacketHandler &handler, void *cookie)
override {
pkt_handler = handler;
pkt_cookie = cookie;
return ReturnCode::SUCCESS;
}
bool port_is_up_(port_t port) const override {
Lock lock(mutex);
auto status_it = ports_oper_status.find(port);
return (status_it == ports_oper_status.end()) ? true : status_it->second;
}
std::map<port_t, PortInfo> get_port_info_() const override {
return {};
}
bm::device_id_t device_id;
// protects the shared state (active) and prevents concurrent Write calls by
// different threads
mutable std::mutex mutex{};
bool started{false};
bool active{false};
ServerContext *context{nullptr};
ServerReaderWriter *stream{nullptr};
PacketHandler pkt_handler{};
void *pkt_cookie{nullptr};
std::unordered_map<port_t, bool> ports_oper_status{};
};
} // namespace
SimpleSwitchGrpcRunner::SimpleSwitchGrpcRunner(int max_port, bool enable_swap,
std::string grpc_server_addr,
int cpu_port,
std::string dp_grpc_server_addr)
: simple_switch(new SimpleSwitch(max_port, enable_swap)),
grpc_server_addr(grpc_server_addr), cpu_port(cpu_port),
dp_grpc_server_addr(dp_grpc_server_addr),
dp_grpc_server(nullptr) { }
int
SimpleSwitchGrpcRunner::init_and_start(const bm::OptionsParser &parser) {
std::unique_ptr<bm::DevMgrIface> my_dev_mgr = nullptr;
if (!dp_grpc_server_addr.empty()) {
auto service = new DataplaneInterfaceServiceImpl(parser.device_id);
grpc::ServerBuilder builder;
builder.SetSyncServerOption(
grpc::ServerBuilder::SyncServerOption::NUM_CQS, 1);
builder.SetSyncServerOption(
grpc::ServerBuilder::SyncServerOption::MIN_POLLERS, 1);
builder.SetSyncServerOption(
grpc::ServerBuilder::SyncServerOption::MAX_POLLERS, 1);
builder.AddListeningPort(dp_grpc_server_addr,
grpc::InsecureServerCredentials(),
&dp_grpc_server_port);
builder.RegisterService(service);
dp_grpc_server = builder.BuildAndStart();
my_dev_mgr.reset(service);
}
#ifdef WITH_SYSREPO
sysrepo_driver = std::unique_ptr<SysrepoDriver>(new SysrepoDriver(
parser.device_id, simple_switch.get()));
#endif // WITH_SYSREPO
// Even when using gNMI to manage ports, it is convenient to be able to use
// the --interface / -i command-line option. However we have to "intercept"
// the options before the call to DevMgr::port_add, otherwise we would try to
// add the ports twice (once when calling Switch::init_from_options_parser and
// once when we are notified by sysrepo of the YANG datastore change).
// We therefore save the interface list provided on the command-line and we
// call SysrepoDriver::add_iface at the end of this method after we start the
// sysrepo subscriber.
const bm::OptionsParser *parser_ptr;
#ifdef WITH_SYSREPO
auto new_parser = parser;
auto &interfaces = new_parser.ifaces;
auto saved_interfaces = interfaces;
interfaces.clear();
parser_ptr = &new_parser;
#else
parser_ptr = &parser;
#endif // WITH_SYSREPO
int status = simple_switch->init_from_options_parser(
*parser_ptr, nullptr, std::move(my_dev_mgr));
if (status != 0) return status;
// PortMonitor saves the CB by reference so we cannot use this code; it seems
// that at this stage we do not need the CB any way.
// using PortStatus = bm::DevMgrIface::PortStatus;
// auto port_cb = std::bind(&SimpleSwitchGrpcRunner::port_status_cb, this,
// std::placeholders::_1, std::placeholders::_2);
// simple_switch->register_status_cb(PortStatus::PORT_ADDED, port_cb);
// simple_switch->register_status_cb(PortStatus::PORT_REMOVED, port_cb);
// check if CPU port number is also used by --interface
// TODO(antonin): ports added dynamically?
if (cpu_port >= 0) {
if (parser.ifaces.find(cpu_port) != parser.ifaces.end()) {
bm::Logger::get()->error("Cpu port {} is used as a data port", cpu_port);
return 1;
}
}
if (cpu_port >= 0) {
auto transmit_fn = [this](int port_num, const char *buf, int len) {
if (port_num == cpu_port) {
BMLOG_DEBUG("Transmitting packet-in");
auto status = pi_packetin_receive(
simple_switch->get_device_id(), buf, static_cast<size_t>(len));
if (status != PI_STATUS_SUCCESS)
bm::Logger::get()->error("Error when transmitting packet-in");
} else {
simple_switch->transmit_fn(port_num, buf, len);
}
};
simple_switch->set_transmit_fn(transmit_fn);
}
bm::pi::register_switch(simple_switch.get(), cpu_port);
{
using pi::fe::proto::LogWriterIface;
using pi::fe::proto::LoggerConfig;
class P4RuntimeLogger : public LogWriterIface {
void write(Severity severity, const char *msg) override {
auto severity_map = [&severity]() {
namespace spdL = spdlog::level;
switch (severity) {
case Severity::TRACE : return spdL::trace;
case Severity::DEBUG: return spdL::debug;
case Severity::INFO: return spdL::info;
case Severity::WARN: return spdL::warn;
case Severity::ERROR: return spdL::err;
case Severity::CRITICAL: return spdL::critical;
}
return spdL::off;
};
// TODO(antonin): use a separate logger with a separate name
bm::Logger::get()->log(severity_map(), "[P4Runtime] {}", msg);
}
};
LoggerConfig::set_writer(std::make_shared<P4RuntimeLogger>());
}
DeviceMgr::init(256);
PIGrpcServerRunAddr(grpc_server_addr.c_str());
#ifdef WITH_SYSREPO
if (!sysrepo_driver->start()) return 1;
for (const auto &p : saved_interfaces)
sysrepo_driver->add_iface(p.first, p.second);
#endif // WITH_SYSREPO
simple_switch->start_and_return();
return 0;
}
void
SimpleSwitchGrpcRunner::wait() {
PIGrpcServerWait();
}
void
SimpleSwitchGrpcRunner::shutdown() {
if (!dp_grpc_server_addr.empty()) dp_grpc_server->Shutdown();
PIGrpcServerShutdown();
}
void
SimpleSwitchGrpcRunner::mirroring_mapping_add(int mirror_id, int egress_port) {
simple_switch->mirroring_mapping_add(mirror_id, egress_port);
}
void
SimpleSwitchGrpcRunner::block_until_all_packets_processed() {
simple_switch->block_until_no_more_packets();
}
SimpleSwitchGrpcRunner::~SimpleSwitchGrpcRunner() {
PIGrpcServerCleanup();
DeviceMgr::destroy();
}
void
SimpleSwitchGrpcRunner::port_status_cb(
bm::DevMgrIface::port_t port, const bm::DevMgrIface::PortStatus status) {
_BM_UNUSED(port);
_BM_UNUSED(status);
}
} // namespace sswitch_grpc
<|endoftext|> |
<commit_before>
/*
Stepper.cpp - - Stepper library for Wiring/Arduino - Version 0.4
Original library (0.1) by Tom Igoe.
Two-wire modifications (0.2) by Sebastian Gassner
Combination version (0.3) by Tom Igoe and David Mellis
Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley
Wave step mode (0.5) by Geoff Day
Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires
When wiring multiple stepper motors to a microcontroller,
you quickly run out of output pins, with each motor requiring 4 connections.
By making use of the fact that at any time two of the four motor
coils are the inverse of the other two, the number of
control connections can be reduced from 4 to 2.
A slightly modified circuit around a Darlington transistor array or an L293 H-bridge
connects to only 2 microcontroler pins, inverts the signals received,
and delivers the 4 (2 plus 2 inverted ones) output signals required
for driving a stepper motor.
The sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 1 0
2 0 1 1 0
3 0 1 0 1
4 1 0 0 1
The sequence of controls signals for 2 control wires is as follows
(columns C1 and C2 from above):
Step C0 C1
1 0 1
2 1 1
3 1 0
4 0 0
The circuits can be found at
http://www.arduino.cc/en/Tutorial/Stepper
The Wave step sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 0 0
2 0 0 1 0
3 0 1 0 0
4 0 0 0 1
Good for lower power operation where lower torque is ok.
*/
#include "application.h"
#include "Stepper.h"
/*
* two-wire constructor.
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
// When there are only 2 pins, set the other two to 0:
this->motor_pin_3 = 0;
this->motor_pin_4 = 0;
// pin_count is used by the stepMotor() method:
this->pin_count = 2;
}
/*
* constructor for four-pin version
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)
{
this->mode = 0; // full step mode = 0
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
this->motor_pin_3 = motor_pin_3;
this->motor_pin_4 = motor_pin_4;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
pinMode(this->motor_pin_3, OUTPUT);
pinMode(this->motor_pin_4, OUTPUT);
// pin_count is used by the stepMotor() method:
this->pin_count = 4;
}
/*
set stepper mode, full or wave currently. Wave mode for low power applications.
only applicable in 4 wire setups.
*/
void Stepper::setMode(int mode)
{
this->mode = mode;
}
/*
Sets the speed in revs per minute
*/
void Stepper::setSpeed(long whatSpeed)
{
this->step_delay = 60L * 1000L / this->number_of_steps / whatSpeed;
}
/*
Moves the motor steps_to_move steps. If the number is negative,
the motor moves in the reverse direction.
*/
void Stepper::step(int steps_to_move)
{
int steps_left = abs(steps_to_move); // how many steps to take
// determine direction based on whether steps_to_mode is + or -:
if (steps_to_move > 0) {this->direction = 1;}
if (steps_to_move < 0) {this->direction = 0;}
// decrement the number of steps, moving one step each time:
while(steps_left > 0) {
// move only if the appropriate delay has passed:
if (millis() - this->last_step_time >= this->step_delay) {
// get the timeStamp of when you stepped:
this->last_step_time = millis();
// increment or decrement the step number,
// depending on direction:
if (this->direction == 1) {
this->step_number++;
if (this->step_number == this->number_of_steps) {
this->step_number = 0;
}
}
else {
if (this->step_number == 0) {
this->step_number = this->number_of_steps;
}
this->step_number--;
}
// decrement the steps left:
steps_left--;
// step the motor to step number 0, 1, 2, or 3:
stepMotor(this->step_number % 4);
}
}
}
/*
* Moves the motor forward or backwards.
*/
void Stepper::stepMotor(int thisStep)
{
if (this->pin_count == 2) {
switch (thisStep) {
case 0: /* 01 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
break;
case 1: /* 11 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, HIGH);
break;
case 2: /* 10 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
break;
case 3: /* 00 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
break;
}
}
if (this->pin_count == 4) {
switch (thisStep) {
case 0: // 1010
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_3, LOW);
} else {
digitalWrite(motor_pin_3, HIGH);
}
digitalWrite(motor_pin_4, LOW);
break;
case 1: // 0110
digitalWrite(motor_pin_1, LOW);
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_2, LOW);
} else {
digitalWrite(motor_pin_2, HIGH);
}
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 2: //0101
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, LOW);
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_4, LOW);
} else {
digitalWrite(motor_pin_4, HIGH);
}
break;
case 3: //1001
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_1, LOW);
} else {
digitalWrite(motor_pin_1, HIGH);
}
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
}
}
}
/*
version() returns the version of the library:
*/
int Stepper::version(void)
{
return 5;
}
<commit_msg>Update Stepper.cpp<commit_after>
/*
Stepper.cpp - - Stepper library for Wiring/Arduino - Version 0.4
Original library (0.1) by Tom Igoe.
Two-wire modifications (0.2) by Sebastian Gassner
Combination version (0.3) by Tom Igoe and David Mellis
Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley
Wave step mode (0.5) by Geoff Day
Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires
When wiring multiple stepper motors to a microcontroller,
you quickly run out of output pins, with each motor requiring 4 connections.
By making use of the fact that at any time two of the four motor
coils are the inverse of the other two, the number of
control connections can be reduced from 4 to 2.
A slightly modified circuit around a Darlington transistor array or an L293 H-bridge
connects to only 2 microcontroler pins, inverts the signals received,
and delivers the 4 (2 plus 2 inverted ones) output signals required
for driving a stepper motor.
The sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 1 0
2 0 1 1 0
3 0 1 0 1
4 1 0 0 1
The sequence of controls signals for 2 control wires is as follows
(columns C1 and C2 from above):
Step C0 C1
1 0 1
2 1 1
3 1 0
4 0 0
The circuits can be found at
http://www.arduino.cc/en/Tutorial/Stepper
The Wave step sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 0 0
2 0 0 1 0
3 0 1 0 0
4 0 0 0 1
Good for lower power operation where lower torque is ok.
*/
#include "application.h"
#include "Stepper.h"
/*
* two-wire constructor.
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
// When there are only 2 pins, set the other two to 0:
this->motor_pin_3 = 0;
this->motor_pin_4 = 0;
// pin_count is used by the stepMotor() method:
this->pin_count = 2;
}
/*
* constructor for four-pin version
* Sets which wires should control the motor.
*/
Stepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)
{
this->sleep = 0; // default to 0 - no sleeping. 1 to sleep. All output drives to zero so no holding torque!
this->mode = 0; // full step mode = 0
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
this->motor_pin_3 = motor_pin_3;
this->motor_pin_4 = motor_pin_4;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
pinMode(this->motor_pin_3, OUTPUT);
pinMode(this->motor_pin_4, OUTPUT);
// pin_count is used by the stepMotor() method:
this->pin_count = 4;
}
/*
set to sleep mode for lower power consumption. Only valid in 4 wire mode.
Remember there's no holding torque!!!
*/
void setSleep(int sleep)
{
this->sleep = sleep;
}
/*
set stepper mode, full or wave currently. Wave mode for low power applications.
only applicable in 4 wire setups.
*/
void Stepper::setMode(int mode)
{
this->mode = mode;
}
/*
Sets the speed in revs per minute
*/
void Stepper::setSpeed(long whatSpeed)
{
this->step_delay = 60L * 1000L / this->number_of_steps / whatSpeed;
}
/*
Moves the motor steps_to_move steps. If the number is negative,
the motor moves in the reverse direction.
*/
void Stepper::step(int steps_to_move)
{
int steps_left = abs(steps_to_move); // how many steps to take
// determine direction based on whether steps_to_mode is + or -:
if (steps_to_move > 0) {this->direction = 1;}
if (steps_to_move < 0) {this->direction = 0;}
// decrement the number of steps, moving one step each time:
while(steps_left > 0) {
// move only if the appropriate delay has passed:
if (millis() - this->last_step_time >= this->step_delay) {
// get the timeStamp of when you stepped:
this->last_step_time = millis();
// increment or decrement the step number,
// depending on direction:
if (this->direction == 1) {
this->step_number++;
if (this->step_number == this->number_of_steps) {
this->step_number = 0;
}
}
else {
if (this->step_number == 0) {
this->step_number = this->number_of_steps;
}
this->step_number--;
}
// decrement the steps left:
steps_left--;
// step the motor to step number 0, 1, 2, or 3:
stepMotor(this->step_number % 4);
}
}
}
/*
* Moves the motor forward or backwards.
*/
void Stepper::stepMotor(int thisStep)
{
if (this->pin_count == 2) {
switch (thisStep) {
case 0: /* 01 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
break;
case 1: /* 11 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, HIGH);
break;
case 2: /* 10 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
break;
case 3: /* 00 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
break;
}
}
if (this->pin_count == 4) {
if (this->sleep == 1) {
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, LOW);
} else {
switch (thisStep) {
case 0: // 1010
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_3, LOW);
} else {
digitalWrite(motor_pin_3, HIGH);
}
digitalWrite(motor_pin_4, LOW);
break;
case 1: // 0110
digitalWrite(motor_pin_1, LOW);
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_2, LOW);
} else {
digitalWrite(motor_pin_2, HIGH);
}
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 2: //0101
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, LOW);
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_4, LOW);
} else {
digitalWrite(motor_pin_4, HIGH);
}
break;
case 3: //1001
// mode high for wave step
if (this->mode) {
digitalWrite(motor_pin_1, LOW);
} else {
digitalWrite(motor_pin_1, HIGH);
}
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
}
}
}
}
/*
version() returns the version of the library:
*/
int Stepper::version(void)
{
return 6;
}
<|endoftext|> |
<commit_before>#pragma once
#include <blobs-ipmid/blobs.hpp>
namespace blobs
{
/**
* Register only one firmware blob handler that will manage all sessions.
*/
class FirmwareBlobHandler : public GenericBlobInterface
{
public:
FirmwareBlobHandler() = default;
~FirmwareBlobHandler() = default;
FirmwareBlobHandler(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler& operator=(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler(FirmwareBlobHandler&&) = default;
FirmwareBlobHandler& operator=(FirmwareBlobHandler&&) = default;
bool canHandleBlob(const std::string& path) override;
std::vector<std::string> getBlobIds() override;
bool deleteBlob(const std::string& path) override;
bool stat(const std::string& path, struct BlobMeta* meta) override;
bool open(uint16_t session, uint16_t flags,
const std::string& path) override;
std::vector<uint8_t> read(uint16_t session, uint32_t offset,
uint32_t requestedSize) override;
bool write(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool writeMeta(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool commit(uint16_t session, const std::vector<uint8_t>& data) override;
bool close(uint16_t session) override;
bool stat(uint16_t session, struct BlobMeta* meta) override;
bool expire(uint16_t session) override;
};
} // namespace blobs
<commit_msg>add flags for update transport mechanisms<commit_after>#pragma once
#include <blobs-ipmid/blobs.hpp>
namespace blobs
{
enum class FirmwareUpdateFlags
{
bt = (1 << 8), /* Expect to send contents over IPMI BlockTransfer. */
p2a = (1 << 9), /* Expect to send contents over P2A bridge. */
lpc = (1 << 10), /* Expect to send contents over LPC bridge. */
};
/**
* Register only one firmware blob handler that will manage all sessions.
*/
class FirmwareBlobHandler : public GenericBlobInterface
{
public:
FirmwareBlobHandler() = default;
~FirmwareBlobHandler() = default;
FirmwareBlobHandler(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler& operator=(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler(FirmwareBlobHandler&&) = default;
FirmwareBlobHandler& operator=(FirmwareBlobHandler&&) = default;
bool canHandleBlob(const std::string& path) override;
std::vector<std::string> getBlobIds() override;
bool deleteBlob(const std::string& path) override;
bool stat(const std::string& path, struct BlobMeta* meta) override;
bool open(uint16_t session, uint16_t flags,
const std::string& path) override;
std::vector<uint8_t> read(uint16_t session, uint32_t offset,
uint32_t requestedSize) override;
bool write(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool writeMeta(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool commit(uint16_t session, const std::vector<uint8_t>& data) override;
bool close(uint16_t session) override;
bool stat(uint16_t session, struct BlobMeta* meta) override;
bool expire(uint16_t session) override;
};
} // namespace blobs
<|endoftext|> |
<commit_before>#pragma once
#include "data_handler.hpp"
#include "image_handler.hpp"
#include <blobs-ipmid/blobs.hpp>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace blobs
{
/**
* Representation of a session, includes how to read/write data.
*/
struct Session
{
/** Pointer to the correct Data handler interface. (nullptr on BT (or KCS))
*/
DataInterface* dataHandler;
/** Pointer to the correct image handler interface. (nullptr on hash
* blob_id) */
ImageHandlerInterface* imageHandler;
/** The flags used to open the session. */
std::uint16_t flags;
/** A sesion can be for an image (or tarball) or the hash. */
enum State
{
open = 0,
closed = 1,
};
/** The current state of this session. */
State state;
};
struct ExtChunkHdr
{
std::uint32_t length; /* Length of the data queued (little endian). */
} __attribute__((packed));
/**
* Register only one firmware blob handler that will manage all sessions.
*/
class FirmwareBlobHandler : public GenericBlobInterface
{
public:
enum UpdateFlags : std::uint16_t
{
ipmi = (1 << 8), /* Expect to send contents over IPMI BlockTransfer. */
p2a = (1 << 9), /* Expect to send contents over P2A bridge. */
lpc = (1 << 10), /* Expect to send contents over LPC bridge. */
};
/** The state of the firmware update process. */
enum UpdateState
{
/** The initial state. */
notYetStarted = 0,
/**
* The upload process has started, but verification has not started.
*/
uploadInProgress = 1,
/** The verification process has started, no more writes allowed. */
verificationStarted = 2,
/** The verification process has completed. */
verificationCompleted = 3,
};
/**
* Create a FirmwareBlobHandler.
*
* @param[in] firmwares - list of firmware blob_ids to support.
* @param[in] transports - list of transports to support.
*/
static std::unique_ptr<GenericBlobInterface> CreateFirmwareBlobHandler(
const std::vector<HandlerPack>& firmwares,
const std::vector<DataHandlerPack>& transports);
/**
* Create a FirmwareBlobHandler.
*
* @param[in] firmwares - list of firmware types and their handlers
* @param[in] blobs - list of blobs_ids to support
* @param[in] transports - list of transport types and their handlers
* @param[in] bitmask - bitmask of transports to support
*/
FirmwareBlobHandler(const std::vector<HandlerPack>& firmwares,
const std::vector<std::string>& blobs,
const std::vector<DataHandlerPack>& transports,
std::uint16_t bitmask) :
handlers(firmwares),
blobIDs(blobs), transports(transports), bitmask(bitmask), activeImage(),
activeHash(), lookup(), state(UpdateState::notYetStarted)
{
}
~FirmwareBlobHandler() = default;
FirmwareBlobHandler(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler& operator=(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler(FirmwareBlobHandler&&) = default;
FirmwareBlobHandler& operator=(FirmwareBlobHandler&&) = default;
bool canHandleBlob(const std::string& path) override;
std::vector<std::string> getBlobIds() override;
bool deleteBlob(const std::string& path) override;
bool stat(const std::string& path, struct BlobMeta* meta) override;
bool open(uint16_t session, uint16_t flags,
const std::string& path) override;
std::vector<uint8_t> read(uint16_t session, uint32_t offset,
uint32_t requestedSize) override;
bool write(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool writeMeta(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool commit(uint16_t session, const std::vector<uint8_t>& data) override;
bool close(uint16_t session) override;
bool stat(uint16_t session, struct BlobMeta* meta) override;
bool expire(uint16_t session) override;
static const std::string hashBlobID;
static const std::string activeImageBlobID;
static const std::string activeHashBlobID;
/** Allow grabbing the current state. */
UpdateState getCurrentState() const
{
return state;
};
private:
/** List of handlers by type. */
std::vector<HandlerPack> handlers;
/** Active list of blobIDs. */
std::vector<std::string> blobIDs;
/** List of handlers by transport type. */
std::vector<DataHandlerPack> transports;
/** The bits set indicate what transport mechanisms are supported. */
std::uint16_t bitmask;
/** Active image session. */
Session activeImage;
/** Active hash session. */
Session activeHash;
/** A quick method for looking up a session's mechanisms and details. */
std::map<std::uint16_t, Session*> lookup;
/** The firmware update state. */
UpdateState state;
/** Temporary variable to track whether a blob is open. */
bool fileOpen = false;
};
} // namespace blobs
<commit_msg>firmware: add verification response enum<commit_after>#pragma once
#include "data_handler.hpp"
#include "image_handler.hpp"
#include <blobs-ipmid/blobs.hpp>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace blobs
{
/**
* Representation of a session, includes how to read/write data.
*/
struct Session
{
/** Pointer to the correct Data handler interface. (nullptr on BT (or KCS))
*/
DataInterface* dataHandler;
/** Pointer to the correct image handler interface. (nullptr on hash
* blob_id) */
ImageHandlerInterface* imageHandler;
/** The flags used to open the session. */
std::uint16_t flags;
/** A sesion can be for an image (or tarball) or the hash. */
enum State
{
open = 0,
closed = 1,
};
/** The current state of this session. */
State state;
};
struct ExtChunkHdr
{
std::uint32_t length; /* Length of the data queued (little endian). */
} __attribute__((packed));
/**
* Register only one firmware blob handler that will manage all sessions.
*/
class FirmwareBlobHandler : public GenericBlobInterface
{
public:
enum UpdateFlags : std::uint16_t
{
ipmi = (1 << 8), /* Expect to send contents over IPMI BlockTransfer. */
p2a = (1 << 9), /* Expect to send contents over P2A bridge. */
lpc = (1 << 10), /* Expect to send contents over LPC bridge. */
};
/** The state of the firmware update process. */
enum UpdateState
{
/** The initial state. */
notYetStarted = 0,
/**
* The upload process has started, but verification has not started.
*/
uploadInProgress = 1,
/** The verification process has started, no more writes allowed. */
verificationStarted = 2,
/** The verification process has completed. */
verificationCompleted = 3,
};
/** The return values for verification. */
enum VerifyCheckResponses : std::uint8_t
{
running = 0,
success = 1,
failed = 2,
other = 3,
};
/**
* Create a FirmwareBlobHandler.
*
* @param[in] firmwares - list of firmware blob_ids to support.
* @param[in] transports - list of transports to support.
*/
static std::unique_ptr<GenericBlobInterface> CreateFirmwareBlobHandler(
const std::vector<HandlerPack>& firmwares,
const std::vector<DataHandlerPack>& transports);
/**
* Create a FirmwareBlobHandler.
*
* @param[in] firmwares - list of firmware types and their handlers
* @param[in] blobs - list of blobs_ids to support
* @param[in] transports - list of transport types and their handlers
* @param[in] bitmask - bitmask of transports to support
*/
FirmwareBlobHandler(const std::vector<HandlerPack>& firmwares,
const std::vector<std::string>& blobs,
const std::vector<DataHandlerPack>& transports,
std::uint16_t bitmask) :
handlers(firmwares),
blobIDs(blobs), transports(transports), bitmask(bitmask), activeImage(),
activeHash(), lookup(), state(UpdateState::notYetStarted)
{
}
~FirmwareBlobHandler() = default;
FirmwareBlobHandler(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler& operator=(const FirmwareBlobHandler&) = default;
FirmwareBlobHandler(FirmwareBlobHandler&&) = default;
FirmwareBlobHandler& operator=(FirmwareBlobHandler&&) = default;
bool canHandleBlob(const std::string& path) override;
std::vector<std::string> getBlobIds() override;
bool deleteBlob(const std::string& path) override;
bool stat(const std::string& path, struct BlobMeta* meta) override;
bool open(uint16_t session, uint16_t flags,
const std::string& path) override;
std::vector<uint8_t> read(uint16_t session, uint32_t offset,
uint32_t requestedSize) override;
bool write(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool writeMeta(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool commit(uint16_t session, const std::vector<uint8_t>& data) override;
bool close(uint16_t session) override;
bool stat(uint16_t session, struct BlobMeta* meta) override;
bool expire(uint16_t session) override;
static const std::string hashBlobID;
static const std::string activeImageBlobID;
static const std::string activeHashBlobID;
/** Allow grabbing the current state. */
UpdateState getCurrentState() const
{
return state;
};
private:
/** List of handlers by type. */
std::vector<HandlerPack> handlers;
/** Active list of blobIDs. */
std::vector<std::string> blobIDs;
/** List of handlers by transport type. */
std::vector<DataHandlerPack> transports;
/** The bits set indicate what transport mechanisms are supported. */
std::uint16_t bitmask;
/** Active image session. */
Session activeImage;
/** Active hash session. */
Session activeHash;
/** A quick method for looking up a session's mechanisms and details. */
std::map<std::uint16_t, Session*> lookup;
/** The firmware update state. */
UpdateState state;
/** Temporary variable to track whether a blob is open. */
bool fileOpen = false;
};
} // namespace blobs
<|endoftext|> |
<commit_before>/*
* Open Chinese Convert
*
* Copyright 2010-2020 Carbo Kuo <byvoid@byvoid.com>
*
* 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 <algorithm>
#include <cassert>
#include <cstring>
#include "BinaryDict.hpp"
#include "Lexicon.hpp"
using namespace opencc;
size_t BinaryDict::KeyMaxLength() const {
size_t maxLength = 0;
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
maxLength = (std::max)(maxLength, entry->KeyLength());
}
return maxLength;
}
void BinaryDict::SerializeToFile(FILE* fp) const {
std::string keyBuf, valueBuf;
std::vector<size_t> keyOffsets, valueOffsets;
size_t keyTotalLength = 0, valueTotalLength = 0;
ConstructBuffer(keyBuf, keyOffsets, keyTotalLength, valueBuf, valueOffsets,
valueTotalLength);
// Number of items
size_t numItems = lexicon->Length();
fwrite(&numItems, sizeof(size_t), 1, fp);
// Data
fwrite(&keyTotalLength, sizeof(size_t), 1, fp);
fwrite(keyBuf.c_str(), sizeof(char), keyTotalLength, fp);
fwrite(&valueTotalLength, sizeof(size_t), 1, fp);
fwrite(valueBuf.c_str(), sizeof(char), valueTotalLength, fp);
size_t keyCursor = 0, valueCursor = 0;
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
// Number of values
size_t numValues = entry->NumValues();
fwrite(&numValues, sizeof(size_t), 1, fp);
// Key offset
size_t keyOffset = keyOffsets[keyCursor++];
fwrite(&keyOffset, sizeof(size_t), 1, fp);
// Values offset
for (size_t i = 0; i < numValues; i++) {
size_t valueOffset = valueOffsets[valueCursor++];
fwrite(&valueOffset, sizeof(size_t), 1, fp);
}
}
assert(keyCursor == numItems);
}
BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) {
BinaryDictPtr dict(new BinaryDict(LexiconPtr(new Lexicon)));
// Number of items
size_t numItems;
size_t unitsRead = fread(&numItems, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (numItems)");
}
// Keys
size_t keyTotalLength;
unitsRead = fread(&keyTotalLength, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyTotalLength)");
}
dict->keyBuffer.resize(keyTotalLength);
unitsRead = fread(const_cast<char*>(dict->keyBuffer.c_str()), sizeof(char),
keyTotalLength, fp);
if (unitsRead != keyTotalLength) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyBuffer)");
}
// Values
size_t valueTotalLength;
unitsRead = fread(&valueTotalLength, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueTotalLength)");
}
dict->valueBuffer.resize(valueTotalLength);
unitsRead = fread(const_cast<char*>(dict->valueBuffer.c_str()), sizeof(char),
valueTotalLength, fp);
if (unitsRead != valueTotalLength) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueBuffer)");
}
// Offsets
for (size_t i = 0; i < numItems; i++) {
// Number of values
size_t numValues;
unitsRead = fread(&numValues, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (numValues)");
}
// Key offset
size_t keyOffset;
unitsRead = fread(&keyOffset, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyOffset)");
}
std::string key = dict->keyBuffer.c_str() + keyOffset;
// Value offset
std::vector<std::string> values;
for (size_t j = 0; j < numValues; j++) {
size_t valueOffset;
unitsRead = fread(&valueOffset, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueOffset)");
}
const char* value = dict->valueBuffer.c_str() + valueOffset;
values.push_back(value);
}
DictEntry* entry = DictEntryFactory::New(key, values);
dict->lexicon->Add(entry);
}
return dict;
}
void BinaryDict::ConstructBuffer(std::string& keyBuf,
std::vector<size_t>& keyOffset,
size_t& keyTotalLength, std::string& valueBuf,
std::vector<size_t>& valueOffset,
size_t& valueTotalLength) const {
keyTotalLength = 0;
valueTotalLength = 0;
// Calculate total length
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
keyTotalLength += entry->KeyLength() + 1;
assert(entry->NumValues() != 0);
if (entry->NumValues() == 1) {
const auto* svEntry =
static_cast<const SingleValueDictEntry*>(entry.get());
valueTotalLength += svEntry->Value().length() + 1;
} else {
const auto* mvEntry =
static_cast<const MultiValueDictEntry*>(entry.get());
for (const auto& value : mvEntry->Values()) {
valueTotalLength += value.length() + 1;
}
}
}
// Write keys and values to buffers
keyBuf.resize(keyTotalLength, '\0');
valueBuf.resize(valueTotalLength, '\0');
char* pKeyBuffer = const_cast<char*>(keyBuf.c_str());
char* pValueBuffer = const_cast<char*>(valueBuf.c_str());
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
strcpy(pKeyBuffer, entry->Key().c_str());
keyOffset.push_back(pKeyBuffer - keyBuf.c_str());
pKeyBuffer += entry->KeyLength() + 1;
if (entry->NumValues() == 1) {
const auto* svEntry =
static_cast<const SingleValueDictEntry*>(entry.get());
strcpy(pValueBuffer, svEntry->Value().c_str());
valueOffset.push_back(pValueBuffer - valueBuf.c_str());
pValueBuffer += svEntry->Value().length() + 1;
} else {
const auto* mvEntry =
static_cast<const MultiValueDictEntry*>(entry.get());
for (const auto& value : mvEntry->Values()) {
strcpy(pValueBuffer, value.c_str());
valueOffset.push_back(pValueBuffer - valueBuf.c_str());
pValueBuffer += value.length() + 1;
}
}
}
assert(keyBuf.c_str() + keyTotalLength == pKeyBuffer);
assert(valueBuf.c_str() + valueTotalLength == pValueBuffer);
}
<commit_msg>Check offset bounds in BinaryDict::NewFromFile method<commit_after>/*
* Open Chinese Convert
*
* Copyright 2010-2020 Carbo Kuo <byvoid@byvoid.com>
*
* 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 <algorithm>
#include <cassert>
#include <cstring>
#include "BinaryDict.hpp"
#include "Lexicon.hpp"
using namespace opencc;
size_t BinaryDict::KeyMaxLength() const {
size_t maxLength = 0;
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
maxLength = (std::max)(maxLength, entry->KeyLength());
}
return maxLength;
}
void BinaryDict::SerializeToFile(FILE* fp) const {
std::string keyBuf, valueBuf;
std::vector<size_t> keyOffsets, valueOffsets;
size_t keyTotalLength = 0, valueTotalLength = 0;
ConstructBuffer(keyBuf, keyOffsets, keyTotalLength, valueBuf, valueOffsets,
valueTotalLength);
// Number of items
size_t numItems = lexicon->Length();
fwrite(&numItems, sizeof(size_t), 1, fp);
// Data
fwrite(&keyTotalLength, sizeof(size_t), 1, fp);
fwrite(keyBuf.c_str(), sizeof(char), keyTotalLength, fp);
fwrite(&valueTotalLength, sizeof(size_t), 1, fp);
fwrite(valueBuf.c_str(), sizeof(char), valueTotalLength, fp);
size_t keyCursor = 0, valueCursor = 0;
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
// Number of values
size_t numValues = entry->NumValues();
fwrite(&numValues, sizeof(size_t), 1, fp);
// Key offset
size_t keyOffset = keyOffsets[keyCursor++];
fwrite(&keyOffset, sizeof(size_t), 1, fp);
// Values offset
for (size_t i = 0; i < numValues; i++) {
size_t valueOffset = valueOffsets[valueCursor++];
fwrite(&valueOffset, sizeof(size_t), 1, fp);
}
}
assert(keyCursor == numItems);
}
BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) {
size_t offsetBound, savedOffset;
savedOffset = ftell(fp);
fseek(fp, 0L, SEEK_END);
offsetBound = ftell(fp) - savedOffset;
fseek(fp, savedOffset, SEEK_SET);
BinaryDictPtr dict(new BinaryDict(LexiconPtr(new Lexicon)));
// Number of items
size_t numItems;
size_t unitsRead = fread(&numItems, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (numItems)");
}
// Keys
size_t keyTotalLength;
unitsRead = fread(&keyTotalLength, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyTotalLength)");
}
dict->keyBuffer.resize(keyTotalLength);
unitsRead = fread(const_cast<char*>(dict->keyBuffer.c_str()), sizeof(char),
keyTotalLength, fp);
if (unitsRead != keyTotalLength) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyBuffer)");
}
// Values
size_t valueTotalLength;
unitsRead = fread(&valueTotalLength, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueTotalLength)");
}
dict->valueBuffer.resize(valueTotalLength);
unitsRead = fread(const_cast<char*>(dict->valueBuffer.c_str()), sizeof(char),
valueTotalLength, fp);
if (unitsRead != valueTotalLength) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueBuffer)");
}
// Offsets
for (size_t i = 0; i < numItems; i++) {
// Number of values
size_t numValues;
unitsRead = fread(&numValues, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
throw InvalidFormat("Invalid OpenCC binary dictionary (numValues)");
}
// Key offset
size_t keyOffset;
unitsRead = fread(&keyOffset, sizeof(size_t), 1, fp);
if (unitsRead != 1 || keyOffset >= offsetBound) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyOffset)");
}
std::string key = dict->keyBuffer.c_str() + keyOffset;
// Value offset
std::vector<std::string> values;
for (size_t j = 0; j < numValues; j++) {
size_t valueOffset;
unitsRead = fread(&valueOffset, sizeof(size_t), 1, fp);
if (unitsRead != 1 || valueOffset >= offsetBound) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueOffset)");
}
const char* value = dict->valueBuffer.c_str() + valueOffset;
values.push_back(value);
}
DictEntry* entry = DictEntryFactory::New(key, values);
dict->lexicon->Add(entry);
}
return dict;
}
void BinaryDict::ConstructBuffer(std::string& keyBuf,
std::vector<size_t>& keyOffset,
size_t& keyTotalLength, std::string& valueBuf,
std::vector<size_t>& valueOffset,
size_t& valueTotalLength) const {
keyTotalLength = 0;
valueTotalLength = 0;
// Calculate total length
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
keyTotalLength += entry->KeyLength() + 1;
assert(entry->NumValues() != 0);
if (entry->NumValues() == 1) {
const auto* svEntry =
static_cast<const SingleValueDictEntry*>(entry.get());
valueTotalLength += svEntry->Value().length() + 1;
} else {
const auto* mvEntry =
static_cast<const MultiValueDictEntry*>(entry.get());
for (const auto& value : mvEntry->Values()) {
valueTotalLength += value.length() + 1;
}
}
}
// Write keys and values to buffers
keyBuf.resize(keyTotalLength, '\0');
valueBuf.resize(valueTotalLength, '\0');
char* pKeyBuffer = const_cast<char*>(keyBuf.c_str());
char* pValueBuffer = const_cast<char*>(valueBuf.c_str());
for (const std::unique_ptr<DictEntry>& entry : *lexicon) {
strcpy(pKeyBuffer, entry->Key().c_str());
keyOffset.push_back(pKeyBuffer - keyBuf.c_str());
pKeyBuffer += entry->KeyLength() + 1;
if (entry->NumValues() == 1) {
const auto* svEntry =
static_cast<const SingleValueDictEntry*>(entry.get());
strcpy(pValueBuffer, svEntry->Value().c_str());
valueOffset.push_back(pValueBuffer - valueBuf.c_str());
pValueBuffer += svEntry->Value().length() + 1;
} else {
const auto* mvEntry =
static_cast<const MultiValueDictEntry*>(entry.get());
for (const auto& value : mvEntry->Values()) {
strcpy(pValueBuffer, value.c_str());
valueOffset.push_back(pValueBuffer - valueBuf.c_str());
pValueBuffer += value.length() + 1;
}
}
}
assert(keyBuf.c_str() + keyTotalLength == pKeyBuffer);
assert(valueBuf.c_str() + valueTotalLength == pValueBuffer);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2019-2022 Diligent Graphics LLC
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "RenderStateNotation/interface/RenderStateNotationParser.h"
#include <cstddef>
namespace Diligent
{
namespace
{
#ifdef __GNUC__
// Disable GCC warnings like this one:
// warning: offsetof within non-standard-layout type ‘Diligent::{anonymous}::DeviceObjectAttribs is conditionally-supported [-Winvalid-offsetof]
# pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif
#define CHECK_BASE_STRUCT_ALIGNMENT(StructName) \
struct StructName##Test : StructName \
{ \
Uint8 AlignmentTest; \
}; \
static_assert(offsetof(StructName##Test, AlignmentTest) == sizeof(StructName), "Using " #StructName " as a base class may result in misalignment")
CHECK_BASE_STRUCT_ALIGNMENT(PipelineStateNotation);
} // namespace
} // namespace Diligent
<commit_msg>Updated BaseStructAlignmentTest.cpp<commit_after>/*
* Copyright 2019-2022 Diligent Graphics LLC
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "../../../DiligentCore/Primitives/interface/CheckBaseStructAlignment.hpp"
#include "RenderStateNotation/interface/RenderStateNotationParser.h"
namespace Diligent
{
namespace
{
CHECK_BASE_STRUCT_ALIGNMENT(PipelineStateNotation);
} // namespace
} // namespace Diligent
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2015 Marcus Johansson <mcodev31@gmail.com>
This source code is released under the New BSD License, (the "License").
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 "symmetryscene.h"
#include <avogadro/qtgui/molecule.h>
#include <avogadro/qtgui/rwmolecule.h>
#include <avogadro/core/array.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <avogadro/rendering/cylindergeometry.h>
#include <avogadro/rendering/geometrynode.h>
#include <avogadro/rendering/groupnode.h>
#include <avogadro/rendering/spheregeometry.h>
#include <QtCore/QDebug>
#include <QVector3D>
using namespace Avogadro;
namespace Avogadro {
namespace QtPlugins {
using Rendering::GeometryNode;
using Rendering::GroupNode;
using Rendering::SphereGeometry;
using Rendering::CylinderGeometry;
SymmetryScene::SymmetryScene(QObject* p)
: QtGui::ScenePlugin(p), m_enabled(true)
{
}
SymmetryScene::~SymmetryScene()
{
}
void SymmetryScene::process(const Core::Molecule& coreMolecule,
Rendering::GroupNode& node)
{
const QtGui::Molecule* molecule =
dynamic_cast<const QtGui::Molecule*>(&coreMolecule);
if (!molecule)
return;
QVariant origo = molecule->property("SymmetryOrigo");
QVariant radius = molecule->property("SymmetryRadius");
QVariant inversion = molecule->property("SymmetryInversion");
QVariant properRotation =
molecule->property("SymmetryProperRotationVariantList");
QVariant improperRotation =
molecule->property("SymmetryImproperRotationVariantList");
QVariant reflection = molecule->property("SymmetryReflectionVariantList");
if (!origo.isValid() || !radius.isValid()) {
return;
}
QVector3D qorigo = origo.value<QVector3D>();
Vector3f forigo = Vector3f(qorigo.x(), qorigo.y(), qorigo.z());
float fradius = radius.toFloat();
GeometryNode* geometry = new GeometryNode;
node.addChild(geometry);
SphereGeometry* spheres = new SphereGeometry;
spheres->identifier().molecule = reinterpret_cast<const void*>(&molecule);
spheres->identifier().type = Rendering::AtomType;
geometry->addDrawable(spheres);
CylinderGeometry* cylinders = new CylinderGeometry;
cylinders->identifier().molecule = &molecule;
cylinders->identifier().type = Rendering::BondType;
geometry->addDrawable(cylinders);
if (inversion.isValid()) {
Vector3ub color(0, 0, 255);
QVector3D qvec = inversion.value<QVector3D>();
Vector3f fvec = Vector3f(qvec.x(), qvec.y(), qvec.z());
spheres->addSphere(fvec, color, 0.3f);
}
if (properRotation.isValid()) {
Vector3ub color(255, 0, 0);
QVariantList properRotationVariantList = properRotation.toList();
foreach (QVariant qv, properRotationVariantList) {
QVector3D qvec = qv.value<QVector3D>();
Vector3f fvec = Vector3f(qvec.x(), qvec.y(), qvec.z());
cylinders->addCylinder(forigo, forigo + 1.1 * fradius * fvec, 0.05f,
color);
}
}
if (improperRotation.isValid()) {
QVariantList improperRotationVariantList = improperRotation.toList();
}
if (reflection.isValid()) {
Vector3ub color(255, 255, 0);
QVariantList reflectionVariantList = reflection.toList();
foreach (QVariant qv, reflectionVariantList) {
QVector3D qvec = qv.value<QVector3D>();
Vector3f fvec = Vector3f(qvec.x(), qvec.y(), qvec.z());
cylinders->addCylinder(forigo - fvec * 0.025f, forigo + fvec * 0.025f,
fradius, color);
}
}
}
void SymmetryScene::processEditable(const QtGui::RWMolecule& molecule,
Rendering::GroupNode& node)
{
process(molecule.molecule(), node);
}
bool SymmetryScene::isEnabled() const
{
return m_enabled;
}
void SymmetryScene::setEnabled(bool enable)
{
m_enabled = enable;
}
}
}
<commit_msg>Render mirror planes as translucent discs<commit_after>/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2015 Marcus Johansson <mcodev31@gmail.com>
This source code is released under the New BSD License, (the "License").
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 "symmetryscene.h"
#include <avogadro/qtgui/molecule.h>
#include <avogadro/qtgui/rwmolecule.h>
#include <avogadro/core/array.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <avogadro/rendering/cylindergeometry.h>
#include <avogadro/rendering/geometrynode.h>
#include <avogadro/rendering/groupnode.h>
#include <avogadro/rendering/meshgeometry.h>
#include <avogadro/rendering/spheregeometry.h>
#include <QtCore/QDebug>
#include <QVector3D>
using namespace Avogadro;
namespace Avogadro {
namespace QtPlugins {
using Core::Array;
using Rendering::CylinderGeometry;
using Rendering::GeometryNode;
using Rendering::GroupNode;
using Rendering::MeshGeometry;
using Rendering::SphereGeometry;
namespace {
// Convenience arc sector drawable:
class ArcSector : public MeshGeometry
{
public:
ArcSector() {}
~ArcSector() override {}
/**
* Define the sector.
* @param origin Center of the circle from which the arc is cut.
* @param startEdge A vector defining an leading edge of the sector. The
* direction is used to fix the sector's rotation about the origin, and the
* length defines the radius of the sector.
* @param normal The normal direction to the plane of the sector.
* @param degreesCCW The extent of the sector, measured counter-clockwise from
* startEdge in degrees.
* @param resolutionDeg The radial width of each triangle used in the sector
* approximation in degrees. This will be adjusted to fit an integral number
* of triangles in the sector. Smaller triangles (better approximations) are
* chosen if adjustment is needed.
*/
void setArcSector(const Vector3f& origin, const Vector3f& startEdge,
const Vector3f& normal, float degreesCCW,
float resolutionDeg);
};
void ArcSector::setArcSector(const Vector3f& origin, const Vector3f& startEdge,
const Vector3f& normal, float degreesCCW,
float resolutionDeg)
{
// Prepare rotation, calculate sizes
const unsigned int numTriangles =
static_cast<unsigned int>(std::fabs(std::ceil(degreesCCW / resolutionDeg)));
const size_t numVerts = static_cast<size_t>(numTriangles + 2);
const float stepAngleRads =
(degreesCCW / static_cast<float>(numTriangles)) * DEG_TO_RAD_F;
const Eigen::AngleAxisf rot(stepAngleRads, normal);
// Generate normal array
Array<Vector3f> norms(numVerts, normal);
// Generate vertices
Array<Vector3f> verts(numVerts);
Array<Vector3f>::iterator vertsInserter(verts.begin());
Array<Vector3f>::iterator vertsEnd(verts.end());
Vector3f radial = startEdge;
*(vertsInserter++) = origin;
*(vertsInserter++) = origin + radial;
while (vertsInserter != vertsEnd)
*(vertsInserter++) = origin + (radial = rot * radial);
// Generate indices
Array<unsigned int> indices(numTriangles * 3);
Array<unsigned int>::iterator indexInserter(indices.begin());
Array<unsigned int>::iterator indexEnd(indices.end());
for (unsigned int i = 1; indexInserter != indexEnd; ++i) {
*(indexInserter++) = 0;
*(indexInserter++) = i;
*(indexInserter++) = i + 1;
}
clear();
addVertices(verts, norms);
addTriangles(indices);
}
}
SymmetryScene::SymmetryScene(QObject* p)
: QtGui::ScenePlugin(p), m_enabled(true)
{
}
SymmetryScene::~SymmetryScene()
{
}
void SymmetryScene::process(const Core::Molecule& coreMolecule,
Rendering::GroupNode& node)
{
const QtGui::Molecule* molecule =
dynamic_cast<const QtGui::Molecule*>(&coreMolecule);
if (!molecule)
return;
QVariant origo = molecule->property("SymmetryOrigo");
QVariant radius = molecule->property("SymmetryRadius");
QVariant inversion = molecule->property("SymmetryInversion");
QVariant properRotation =
molecule->property("SymmetryProperRotationVariantList");
QVariant improperRotation =
molecule->property("SymmetryImproperRotationVariantList");
QVariant reflection = molecule->property("SymmetryReflectionVariantList");
if (!origo.isValid() || !radius.isValid()) {
return;
}
QVector3D qorigo = origo.value<QVector3D>();
Vector3f forigo = Vector3f(qorigo.x(), qorigo.y(), qorigo.z());
float fradius = radius.toFloat();
GeometryNode* geometry = new GeometryNode;
node.addChild(geometry);
SphereGeometry* spheres = new SphereGeometry;
spheres->identifier().molecule = reinterpret_cast<const void*>(&molecule);
spheres->identifier().type = Rendering::AtomType;
geometry->addDrawable(spheres);
CylinderGeometry* cylinders = new CylinderGeometry;
cylinders->identifier().molecule = &molecule;
cylinders->identifier().type = Rendering::BondType;
geometry->addDrawable(cylinders);
if (inversion.isValid()) {
Vector3ub color(0, 0, 255);
QVector3D qvec = inversion.value<QVector3D>();
Vector3f fvec = Vector3f(qvec.x(), qvec.y(), qvec.z());
spheres->addSphere(fvec, color, 0.3f);
}
if (properRotation.isValid()) {
Vector3ub color(255, 0, 0);
QVariantList properRotationVariantList = properRotation.toList();
foreach (QVariant qv, properRotationVariantList) {
QVector3D qvec = qv.value<QVector3D>();
Vector3f fvec = Vector3f(qvec.x(), qvec.y(), qvec.z());
cylinders->addCylinder(forigo, forigo + 1.1 * fradius * fvec, 0.05f,
color);
}
}
if (improperRotation.isValid()) {
QVariantList improperRotationVariantList = improperRotation.toList();
}
if (reflection.isValid()) {
Vector3ub color(255, 255, 0);
QVariantList reflectionVariantList = reflection.toList();
foreach (QVariant qv, reflectionVariantList) {
QVector3D qvec = qv.value<QVector3D>();
// normal to the mirror plane
Vector3f vecNormal = Vector3f(qvec.x(), qvec.y(), qvec.z());
// get an arbitrary vector in the plane, scaled by fradius
Vector3f vecPlane;
if (qvec.z() < qvec.x())
vecPlane = Vector3f(-qvec.y(), qvec.x(), 0);
else
vecPlane = Vector3f(0, -qvec.z(), qvec.y());
vecPlane = vecPlane.normalized() * fradius;
ArcSector* sect = new ArcSector;
geometry->addDrawable(sect);
sect->setColor(Vector3ub(color));
sect->setOpacity(127); // 50%
sect->setRenderPass(Rendering::TranslucentPass);
sect->setArcSector(forigo, vecPlane, vecNormal, 360.0f, 5.f);
// cylinders->addCylinder(forigo - fvec * 0.025f, forigo + fvec * 0.025f,
// fradius, color);
}
}
}
void SymmetryScene::processEditable(const QtGui::RWMolecule& molecule,
Rendering::GroupNode& node)
{
process(molecule.molecule(), node);
}
bool SymmetryScene::isEnabled() const
{
return m_enabled;
}
void SymmetryScene::setEnabled(bool enable)
{
m_enabled = enable;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Wraps dumb protocol buffer paymentRequest
// with some extra methods
//
#include "paymentrequestplus.h"
#include <stdexcept>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QDateTime>
#include <QDebug>
#include <QSslCertificate>
using namespace std;
class SSLVerifyError : public std::runtime_error
{
public:
SSLVerifyError(std::string err) : std::runtime_error(err) { }
};
bool PaymentRequestPlus::parse(const QByteArray& data)
{
bool parseOK = paymentRequest.ParseFromArray(data.data(), data.size());
if (!parseOK) {
qWarning() << "PaymentRequestPlus::parse : Error parsing payment request";
return false;
}
if (paymentRequest.payment_details_version() > 1) {
qWarning() << "PaymentRequestPlus::parse : Received up-version payment details, version=" << paymentRequest.payment_details_version();
return false;
}
parseOK = details.ParseFromString(paymentRequest.serialized_payment_details());
if (!parseOK)
{
qWarning() << "PaymentRequestPlus::parse : Error parsing payment details";
paymentRequest.Clear();
return false;
}
return true;
}
bool PaymentRequestPlus::SerializeToString(string* output) const
{
return paymentRequest.SerializeToString(output);
}
bool PaymentRequestPlus::IsInitialized() const
{
return paymentRequest.IsInitialized();
}
QString PaymentRequestPlus::getPKIType() const
{
if (!IsInitialized()) return QString("none");
return QString::fromStdString(paymentRequest.pki_type());
}
bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) const
{
merchant.clear();
if (!IsInitialized())
return false;
// One day we'll support more PKI types, but just
// x509 for now:
const EVP_MD* digestAlgorithm = NULL;
if (paymentRequest.pki_type() == "x509+sha256") {
digestAlgorithm = EVP_sha256();
}
else if (paymentRequest.pki_type() == "x509+sha1") {
digestAlgorithm = EVP_sha1();
}
else if (paymentRequest.pki_type() == "none") {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: pki_type == none";
return false;
}
else {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: unknown pki_type " << QString::fromStdString(paymentRequest.pki_type());
return false;
}
payments::X509Certificates certChain;
if (!certChain.ParseFromString(paymentRequest.pki_data())) {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: error parsing pki_data";
return false;
}
std::vector<X509*> certs;
const QDateTime currentTime = QDateTime::currentDateTime();
for (int i = 0; i < certChain.certificate_size(); i++) {
QByteArray certData(certChain.certificate(i).data(), certChain.certificate(i).size());
QSslCertificate qCert(certData, QSsl::Der);
if (currentTime < qCert.effectiveDate() || currentTime > qCert.expiryDate()) {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: certificate expired or not yet active: " << qCert;
return false;
}
#if QT_VERSION >= 0x050000
if (qCert.isBlacklisted()) {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: certificate blacklisted: " << qCert;
return false;
}
#endif
const unsigned char *data = (const unsigned char *)certChain.certificate(i).data();
X509 *cert = d2i_X509(NULL, &data, certChain.certificate(i).size());
if (cert)
certs.push_back(cert);
}
if (certs.empty()) {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: empty certificate chain";
return false;
}
// The first cert is the signing cert, the rest are untrusted certs that chain
// to a valid root authority. OpenSSL needs them separately.
STACK_OF(X509) *chain = sk_X509_new_null();
for (int i = certs.size()-1; i > 0; i--) {
sk_X509_push(chain, certs[i]);
}
X509 *signing_cert = certs[0];
// Now create a "store context", which is a single use object for checking,
// load the signing cert into it and verify.
X509_STORE_CTX *store_ctx = X509_STORE_CTX_new();
if (!store_ctx) {
qWarning() << "PaymentRequestPlus::getMerchant : Payment request: error creating X509_STORE_CTX";
return false;
}
char *website = NULL;
bool fResult = true;
try
{
if (!X509_STORE_CTX_init(store_ctx, certStore, signing_cert, chain))
{
int error = X509_STORE_CTX_get_error(store_ctx);
throw SSLVerifyError(X509_verify_cert_error_string(error));
}
// Now do the verification!
int result = X509_verify_cert(store_ctx);
if (result != 1) {
int error = X509_STORE_CTX_get_error(store_ctx);
throw SSLVerifyError(X509_verify_cert_error_string(error));
}
X509_NAME *certname = X509_get_subject_name(signing_cert);
// Valid cert; check signature:
payments::PaymentRequest rcopy(paymentRequest); // Copy
rcopy.set_signature(std::string(""));
std::string data_to_verify; // Everything but the signature
rcopy.SerializeToString(&data_to_verify);
EVP_MD_CTX ctx;
EVP_PKEY *pubkey = X509_get_pubkey(signing_cert);
EVP_MD_CTX_init(&ctx);
if (!EVP_VerifyInit_ex(&ctx, digestAlgorithm, NULL) ||
!EVP_VerifyUpdate(&ctx, data_to_verify.data(), data_to_verify.size()) ||
!EVP_VerifyFinal(&ctx, (const unsigned char*)paymentRequest.signature().data(), paymentRequest.signature().size(), pubkey)) {
throw SSLVerifyError("Bad signature, invalid PaymentRequest.");
}
// OpenSSL API for getting human printable strings from certs is baroque.
int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0);
website = new char[textlen + 1];
if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) {
merchant = website;
}
else {
throw SSLVerifyError("Bad certificate, missing common name.");
}
// TODO: detect EV certificates and set merchant = business name instead of unfriendly NID_commonName ?
}
catch (SSLVerifyError& err)
{
fResult = false;
qWarning() << "PaymentRequestPlus::getMerchant : SSL error: " << err.what();
}
if (website)
delete[] website;
X509_STORE_CTX_free(store_ctx);
for (unsigned int i = 0; i < certs.size(); i++)
X509_free(certs[i]);
return fResult;
}
QList<std::pair<CScript,CAmount> > PaymentRequestPlus::getPayTo() const
{
QList<std::pair<CScript,CAmount> > result;
for (int i = 0; i < details.outputs_size(); i++)
{
const unsigned char* scriptStr = (const unsigned char*)details.outputs(i).script().data();
CScript s(scriptStr, scriptStr+details.outputs(i).script().size());
result.append(make_pair(s, details.outputs(i).amount()));
}
return result;
}
<commit_msg>Delete paymentrequestplus.cpp<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <qt/receivecoinsdialog.h>
#include <qt/forms/ui_receivecoinsdialog.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/walletmodel.h>
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(0),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(QIcon(":/icons/remove"));
ui->receiveButton->setIcon(QIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(QIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(QIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
}
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
OutputType address_type;
if (ui->useBech32->isChecked()) {
address_type = OUTPUT_TYPE_BECH32;
} else {
address_type = model->getDefaultAddressType();
if (address_type == OUTPUT_TYPE_BECH32) {
address_type = OUTPUT_TYPE_P2SH_SEGWIT;
}
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
<commit_msg>GUI: Allow generating Bech32 addresses with a legacy-address default<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <qt/receivecoinsdialog.h>
#include <qt/forms/ui_receivecoinsdialog.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/walletmodel.h>
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(0),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(QIcon(":/icons/remove"));
ui->receiveButton->setIcon(QIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(QIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(QIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
}
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
OutputType address_type;
if (ui->useBech32->isChecked()) {
address_type = OutputType::BECH32;
} else {
address_type = model->wallet().getDefaultAddressType();
if (address_type == OutputType::BECH32) {
address_type = OutputType::P2SH_SEGWIT;
}
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
clear();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return)
{
// press return -> submit form
if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())
{
event->ignore();
on_receiveButton_clicked();
return;
}
}
this->QDialog::keyPressEvent(event);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include <QColor>
#include <QPainter>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget* parent) : QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &TrafficGraphWidget::updateRates);
}
void TrafficGraphWidget::setClientModel(ClientModel* model)
{
clientModel = model;
if (model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath& path, QQueue<float>& samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if (sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for (int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
if (fMax <= 0.0f) return;
QColor axisCol(Qt::gray);
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
const QString units = tr("KB/s");
const float yMarginText = 2.0;
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax - yMarginText, QString("%1 %2").arg(val).arg(units));
for (float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if (fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax - yMarginText, QString("%1 %2").arg(val).arg(units));
int count = 1;
for (float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if (count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if (!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if (!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if (!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while (vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while (vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
Q_FOREACH (float f, vSamplesIn) {
if (f > tmax) tmax = f;
}
Q_FOREACH (float f, vSamplesOut) {
if (f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if (clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
<commit_msg>[GUI] Add missing QPainterPath include<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include <QColor>
#include <QPainter>
#include <QPainterPath>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget* parent) : QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &TrafficGraphWidget::updateRates);
}
void TrafficGraphWidget::setClientModel(ClientModel* model)
{
clientModel = model;
if (model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath& path, QQueue<float>& samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if (sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for (int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
if (fMax <= 0.0f) return;
QColor axisCol(Qt::gray);
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
const QString units = tr("KB/s");
const float yMarginText = 2.0;
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax - yMarginText, QString("%1 %2").arg(val).arg(units));
for (float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if (fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax - yMarginText, QString("%1 %2").arg(val).arg(units));
int count = 1;
for (float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if (count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if (!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if (!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if (!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while (vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while (vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
Q_FOREACH (float f, vSamplesIn) {
if (f > tmax) tmax = f;
}
Q_FOREACH (float f, vSamplesOut) {
if (f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if (clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "FedReplicaManager.h"
#include "ReplicaThread.h"
#include "Nebula.h"
#include "Client.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const char * FedReplicaManager::table = "fed_logdb";
const char * FedReplicaManager::db_names = "log_index, sqlcmd";
const char * FedReplicaManager::db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"fed_logdb (log_index INTEGER PRIMARY KEY, sqlcmd MEDIUMTEXT)";
const time_t FedReplicaManager::xmlrpc_timeout_ms = 10000;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
FedReplicaManager::FedReplicaManager(time_t _t, time_t _p, SqlDB * d,
unsigned int l): ReplicaManager(), timer_period(_t), purge_period(_p),
last_index(-1), logdb(d), log_retention(l)
{
pthread_mutex_init(&mutex, 0);
am.addListener(this);
get_last_index(last_index);
};
/* -------------------------------------------------------------------------- */
FedReplicaManager::~FedReplicaManager()
{
Nebula& nd = Nebula::instance();
std::map<int, ZoneServers *>::iterator it;
for ( it = zones.begin() ; it != zones.end() ; ++it )
{
delete it->second;
}
zones.clear();
if ( nd.is_federation_master() )
{
stop_replica_threads();
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::replicate(const std::string& sql)
{
pthread_mutex_lock(&mutex);
if ( insert_log_record(last_index+1, sql) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
last_index++;
pthread_mutex_unlock(&mutex);
ReplicaManager::replicate();
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::apply_log_record(int index, const std::string& sql)
{
int rc;
pthread_mutex_lock(&mutex);
if ( (unsigned int) index != last_index + 1 )
{
rc = last_index;
pthread_mutex_unlock(&mutex);
return rc;
}
std::ostringstream oss;
char * sql_db = logdb->escape_str(sql.c_str());
if ( sql_db == 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
oss << "BEGIN;\n"
<< "REPLACE INTO " << table << " ("<< db_names <<") VALUES "
<< "(" << last_index + 1 << ",'" << sql_db << "');\n"
<< sql << ";\n"
<< "END;";
if ( logdb->exec_wr(oss) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
last_index++;
pthread_mutex_unlock(&mutex);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * frm_loop(void *arg)
{
FedReplicaManager * fedrm;
if ( arg == 0 )
{
return 0;
}
fedrm = static_cast<FedReplicaManager *>(arg);
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger started.");
fedrm->am.loop(fedrm->timer_period);
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::start()
{
int rc;
pthread_attr_t pattr;
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
NebulaLog::log("FRM",Log::INFO,"Starting Federation Replica Manager...");
rc = pthread_create(&frm_thread, &pattr, frm_loop,(void *) this);
return rc;
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::finalize_action(const ActionRequest& ar)
{
NebulaLog::log("FRM", Log::INFO, "Federation Replica Manager...");
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::update_zones(std::vector<int>& zone_ids)
{
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
vector<int>::iterator it;
int zone_id = nd.get_zone_id();
if ( zpool->list_zones(zone_ids) != 0 )
{
return;
}
pthread_mutex_lock(&mutex);
zones.clear();
for (it = zone_ids.begin() ; it != zone_ids.end(); )
{
if ( *it == zone_id )
{
it = zone_ids.erase(it);
}
else
{
Zone * zone = zpool->get(*it, true);
if ( zone == 0 )
{
it = zone_ids.erase(it);
}
else
{
std::string zedp;
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
ZoneServers * zs = new ZoneServers(*it, last_index, zedp);
zones.insert(make_pair(*it, zs));
++it;
}
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::add_zone(int zone_id)
{
std::ostringstream oss;
std::string zedp;
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
Zone * zone = zpool->get(zone_id, true);
if ( zone == 0 )
{
return;
}
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
pthread_mutex_lock(&mutex);
ZoneServers * zs = new ZoneServers(zone_id, last_index, zedp);
zones.insert(make_pair(zone_id, zs));
oss << "Starting federation replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
add_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::delete_zone(int zone_id)
{
std::ostringstream oss;
std::map<int, ZoneServers *>::iterator it;
pthread_mutex_lock(&mutex);
it = zones.find(zone_id);
if ( it == zones.end() )
{
return;
}
delete it->second;
zones.erase(it);
oss << "Stopping replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
delete_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ReplicaThread * FedReplicaManager::thread_factory(int zone_id)
{
return new FedReplicaThread(zone_id);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::timer_action(const ActionRequest& ar)
{
static int mark_tics = 0;
static int purge_tics = 0;
mark_tics++;
purge_tics++;
// Thread heartbeat
if ( (mark_tics * timer_period) >= 600 )
{
NebulaLog::log("FRM",Log::INFO,"--Mark--");
mark_tics = 0;
}
// Database housekeeping
if ( (purge_tics * timer_period) >= purge_period )
{
Nebula& nd = Nebula::instance();
RaftManager * raftm = nd.get_raftm();
if ( raftm->is_leader() || raftm->is_solo() )
{
NebulaLog::log("FRM", Log::INFO, "Purging federated log");
std::ostringstream oss;
pthread_mutex_lock(&mutex);
if ( last_index > log_retention )
{
unsigned int delete_index = last_index - log_retention;
// keep the last "log_retention" records
oss << "DELETE FROM fed_logdb WHERE log_index >= 0 AND "
<< "log_index < " << delete_index;
logdb->exec_wr(oss);
}
pthread_mutex_unlock(&mutex);
}
purge_tics = 0;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_next_record(int zone_id, int& index,
std::string& sql, std::string& zedp)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return -1;
}
index = it->second->next;
zedp = it->second->endpoint;
int rc = get_log_record(index, sql);
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_log_record(int index, std::string& sql)
{
ostringstream oss;
single_cb<std::string> cb;
oss << "SELECT sqlcmd FROM fed_logdb WHERE log_index = " << index;
cb.set_callback(&sql);
int rc = logdb->exec_rd(oss, &cb);
cb.unset_callback();
return rc;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::insert_log_record(int index, const std::string& sql)
{
std::ostringstream oss;
char * sql_db = logdb->escape_str(sql.c_str());
if ( sql_db == 0 )
{
return -1;
}
oss << "REPLACE INTO " << table << " ("<< db_names <<") VALUES "
<< "(" << index << ",'" << sql_db << "')";
return logdb->exec_wr(oss);
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_last_index(unsigned int& index) const
{
ostringstream oss;
single_cb<unsigned int> cb;
oss << "SELECT MAX(log_index) FROM fed_logdb";
cb.set_callback(&index);
int rc = logdb->exec_rd(oss, &cb);
cb.unset_callback();
return rc;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::bootstrap(SqlDB *_db)
{
int rc;
std::ostringstream oss(db_bootstrap);
rc = _db->exec_local_wr(oss);
oss.str("");
oss << "REPLACE INTO " << table << " ("<< db_names <<") VALUES (-1,-1)";
rc += _db->exec_local_wr(oss);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_success(int zone_id)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return;
}
ZoneServers * zs = it->second;
zs->next++;
if ( last_index >= zs->next )
{
ReplicaManager::replicate(zone_id);
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_failure(int zone_id, int last_zone)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it != zones.end() )
{
ZoneServers * zs = it->second;
if ( last_zone >= 0 )
{
zs->next = last_zone + 1;
}
if ( last_index >= zs->next )
{
ReplicaManager::replicate(zone_id);
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::xmlrpc_replicate_log(int zone_id, bool& success,
int& last, std::string& error)
{
static const std::string replica_method = "one.zone.fedreplicate";
int index;
std::string sql, secret, zedp;
int xml_rc = 0;
if ( get_next_record(zone_id, index, sql, zedp) != 0 )
{
error = "Failed to load federation log record";
return -1;
}
// -------------------------------------------------------------------------
// Get parameters to call append entries on follower
// -------------------------------------------------------------------------
if ( Client::read_oneauth(secret, error) == -1 )
{
return -1;
}
xmlrpc_c::value result;
xmlrpc_c::paramList replica_params;
replica_params.add(xmlrpc_c::value_string(secret));
replica_params.add(xmlrpc_c::value_int(index));
replica_params.add(xmlrpc_c::value_string(sql));
// -------------------------------------------------------------------------
// Do the XML-RPC call
// -------------------------------------------------------------------------
xml_rc = Client::client()->call(zedp, replica_method, replica_params,
xmlrpc_timeout_ms, &result, error);
if ( xml_rc == 0 )
{
vector<xmlrpc_c::value> values;
values = xmlrpc_c::value_array(result).vectorValueValue();
success = xmlrpc_c::value_boolean(values[0]);
if ( success ) //values[2] = error code (string)
{
last = xmlrpc_c::value_int(values[1]);
}
else
{
error = xmlrpc_c::value_string(values[1]);
last = xmlrpc_c::value_int(values[3]);
}
}
else
{
std::ostringstream ess;
ess << "Error replicating log entry " << index << " on zone "
<< zone_id << " (" << zedp << "): " << error;
NebulaLog::log("FRM", Log::ERROR, error);
error = ess.str();
}
return xml_rc;
}
<commit_msg>F #4809: Compress federated log<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "FedReplicaManager.h"
#include "ReplicaThread.h"
#include "Nebula.h"
#include "Client.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const char * FedReplicaManager::table = "fed_logdb";
const char * FedReplicaManager::db_names = "log_index, sqlcmd";
const char * FedReplicaManager::db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"fed_logdb (log_index INTEGER PRIMARY KEY, sqlcmd MEDIUMTEXT)";
const time_t FedReplicaManager::xmlrpc_timeout_ms = 10000;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
FedReplicaManager::FedReplicaManager(time_t _t, time_t _p, SqlDB * d,
unsigned int l): ReplicaManager(), timer_period(_t), purge_period(_p),
last_index(-1), logdb(d), log_retention(l)
{
pthread_mutex_init(&mutex, 0);
am.addListener(this);
get_last_index(last_index);
};
/* -------------------------------------------------------------------------- */
FedReplicaManager::~FedReplicaManager()
{
Nebula& nd = Nebula::instance();
std::map<int, ZoneServers *>::iterator it;
for ( it = zones.begin() ; it != zones.end() ; ++it )
{
delete it->second;
}
zones.clear();
if ( nd.is_federation_master() )
{
stop_replica_threads();
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::replicate(const std::string& sql)
{
pthread_mutex_lock(&mutex);
if ( insert_log_record(last_index+1, sql) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
last_index++;
pthread_mutex_unlock(&mutex);
ReplicaManager::replicate();
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::apply_log_record(int index, const std::string& sql)
{
int rc;
pthread_mutex_lock(&mutex);
if ( (unsigned int) index != last_index + 1 )
{
rc = last_index;
pthread_mutex_unlock(&mutex);
return rc;
}
std::ostringstream oss;
std::string * zsql = one_util::zlib_compress(sql, true);
if ( zsql == 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
char * sql_db = logdb->escape_str(zsql->c_str());
delete zsql;
if ( sql_db == 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
oss << "BEGIN;\n"
<< "REPLACE INTO " << table << " ("<< db_names <<") VALUES "
<< "(" << last_index + 1 << ",'" << sql_db << "');\n"
<< sql << ";\n"
<< "END;";
if ( logdb->exec_wr(oss) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
last_index++;
pthread_mutex_unlock(&mutex);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * frm_loop(void *arg)
{
FedReplicaManager * fedrm;
if ( arg == 0 )
{
return 0;
}
fedrm = static_cast<FedReplicaManager *>(arg);
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger started.");
fedrm->am.loop(fedrm->timer_period);
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::start()
{
int rc;
pthread_attr_t pattr;
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
NebulaLog::log("FRM",Log::INFO,"Starting Federation Replica Manager...");
rc = pthread_create(&frm_thread, &pattr, frm_loop,(void *) this);
return rc;
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::finalize_action(const ActionRequest& ar)
{
NebulaLog::log("FRM", Log::INFO, "Federation Replica Manager...");
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::update_zones(std::vector<int>& zone_ids)
{
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
vector<int>::iterator it;
int zone_id = nd.get_zone_id();
if ( zpool->list_zones(zone_ids) != 0 )
{
return;
}
pthread_mutex_lock(&mutex);
zones.clear();
for (it = zone_ids.begin() ; it != zone_ids.end(); )
{
if ( *it == zone_id )
{
it = zone_ids.erase(it);
}
else
{
Zone * zone = zpool->get(*it, true);
if ( zone == 0 )
{
it = zone_ids.erase(it);
}
else
{
std::string zedp;
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
ZoneServers * zs = new ZoneServers(*it, last_index, zedp);
zones.insert(make_pair(*it, zs));
++it;
}
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::add_zone(int zone_id)
{
std::ostringstream oss;
std::string zedp;
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
Zone * zone = zpool->get(zone_id, true);
if ( zone == 0 )
{
return;
}
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
pthread_mutex_lock(&mutex);
ZoneServers * zs = new ZoneServers(zone_id, last_index, zedp);
zones.insert(make_pair(zone_id, zs));
oss << "Starting federation replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
add_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::delete_zone(int zone_id)
{
std::ostringstream oss;
std::map<int, ZoneServers *>::iterator it;
pthread_mutex_lock(&mutex);
it = zones.find(zone_id);
if ( it == zones.end() )
{
return;
}
delete it->second;
zones.erase(it);
oss << "Stopping replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
delete_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ReplicaThread * FedReplicaManager::thread_factory(int zone_id)
{
return new FedReplicaThread(zone_id);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::timer_action(const ActionRequest& ar)
{
static int mark_tics = 0;
static int purge_tics = 0;
mark_tics++;
purge_tics++;
// Thread heartbeat
if ( (mark_tics * timer_period) >= 600 )
{
NebulaLog::log("FRM",Log::INFO,"--Mark--");
mark_tics = 0;
}
// Database housekeeping
if ( (purge_tics * timer_period) >= purge_period )
{
Nebula& nd = Nebula::instance();
RaftManager * raftm = nd.get_raftm();
if ( raftm->is_leader() || raftm->is_solo() )
{
NebulaLog::log("FRM", Log::INFO, "Purging federated log");
std::ostringstream oss;
pthread_mutex_lock(&mutex);
if ( last_index > log_retention )
{
unsigned int delete_index = last_index - log_retention;
// keep the last "log_retention" records
oss << "DELETE FROM fed_logdb WHERE log_index >= 0 AND "
<< "log_index < " << delete_index;
logdb->exec_wr(oss);
}
pthread_mutex_unlock(&mutex);
}
purge_tics = 0;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_next_record(int zone_id, int& index,
std::string& sql, std::string& zedp)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return -1;
}
index = it->second->next;
zedp = it->second->endpoint;
int rc = get_log_record(index, sql);
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_log_record(int index, std::string& sql)
{
std::string zsql;
ostringstream oss;
single_cb<std::string> cb;
oss << "SELECT sqlcmd FROM fed_logdb WHERE log_index = " << index;
cb.set_callback(&zsql);
int rc = logdb->exec_rd(oss, &cb);
cb.unset_callback();
std::string * _sql = one_util::zlib_decompress(zsql, true);
if ( _sql == 0 )
{
return -1;
}
sql = *_sql;
delete _sql;
return rc;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::insert_log_record(int index, const std::string& sql)
{
std::ostringstream oss;
std::string * zsql = one_util::zlib_compress(sql, true);
if ( zsql == 0 )
{
return -1;
}
char * sql_db = logdb->escape_str(zsql->c_str());
delete zsql;
if ( sql_db == 0 )
{
return -1;
}
oss << "REPLACE INTO " << table << " ("<< db_names <<") VALUES "
<< "(" << index << ",'" << sql_db << "')";
return logdb->exec_wr(oss);
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_last_index(unsigned int& index) const
{
ostringstream oss;
single_cb<unsigned int> cb;
oss << "SELECT MAX(log_index) FROM fed_logdb";
cb.set_callback(&index);
int rc = logdb->exec_rd(oss, &cb);
cb.unset_callback();
return rc;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::bootstrap(SqlDB *_db)
{
int rc;
std::ostringstream oss(db_bootstrap);
rc = _db->exec_local_wr(oss);
oss.str("");
oss << "REPLACE INTO " << table << " ("<< db_names <<") VALUES (-1,-1)";
rc += _db->exec_local_wr(oss);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_success(int zone_id)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return;
}
ZoneServers * zs = it->second;
zs->next++;
if ( last_index >= zs->next )
{
ReplicaManager::replicate(zone_id);
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_failure(int zone_id, int last_zone)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it != zones.end() )
{
ZoneServers * zs = it->second;
if ( last_zone >= 0 )
{
zs->next = last_zone + 1;
}
if ( last_index >= zs->next )
{
ReplicaManager::replicate(zone_id);
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::xmlrpc_replicate_log(int zone_id, bool& success,
int& last, std::string& error)
{
static const std::string replica_method = "one.zone.fedreplicate";
int index;
std::string sql, secret, zedp;
int xml_rc = 0;
if ( get_next_record(zone_id, index, sql, zedp) != 0 )
{
error = "Failed to load federation log record";
return -1;
}
// -------------------------------------------------------------------------
// Get parameters to call append entries on follower
// -------------------------------------------------------------------------
if ( Client::read_oneauth(secret, error) == -1 )
{
return -1;
}
xmlrpc_c::value result;
xmlrpc_c::paramList replica_params;
replica_params.add(xmlrpc_c::value_string(secret));
replica_params.add(xmlrpc_c::value_int(index));
replica_params.add(xmlrpc_c::value_string(sql));
// -------------------------------------------------------------------------
// Do the XML-RPC call
// -------------------------------------------------------------------------
xml_rc = Client::client()->call(zedp, replica_method, replica_params,
xmlrpc_timeout_ms, &result, error);
if ( xml_rc == 0 )
{
vector<xmlrpc_c::value> values;
values = xmlrpc_c::value_array(result).vectorValueValue();
success = xmlrpc_c::value_boolean(values[0]);
if ( success ) //values[2] = error code (string)
{
last = xmlrpc_c::value_int(values[1]);
}
else
{
error = xmlrpc_c::value_string(values[1]);
last = xmlrpc_c::value_int(values[3]);
}
}
else
{
std::ostringstream ess;
ess << "Error replicating log entry " << index << " on zone "
<< zone_id << " (" << zedp << "): " << error;
NebulaLog::log("FRM", Log::ERROR, error);
error = ess.str();
}
return xml_rc;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2011 Neevarp Yhtroom
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 <fstream>
#include "Logger.h"
#include "ConfigFile.h"
using std::ifstream;
using std::map;
namespace lepcpplib {
const int kConfigFileMaxLineLength = 256;
ConfigFile::ConfigFile(const String& filename)
: filename_(filename)
{
}
ConfigFile::~ConfigFile()
{
}
bool ConfigFile::Load()
{
bool result = false;
if (filename_ != "") {
ifstream file(filename_.toCharArray());
char buffer[kConfigFileMaxLineLength];
//LOG_D("Processing config file: %s\n", filename_.toCharArray());
while ((!file.eof()) && (!file.fail())) {
file.getline(buffer, sizeof(buffer));
if (file.gcount()) {
String line(buffer);
int q = line.indexOf('=');
if (q != -1)
{
String key = line.substring(0, q - 1);
String value = line.substring(q + 1);
keyvalues_[key] = value;
}
}
}
}
result = true;
//LOG_D("Done processing config file: %s\n", filename_.toCharArray());
return result;
}
bool ConfigFile::ValueOf(const String& key, String& value)
{
bool result = false;
map<String, String>::iterator it = keyvalues_.find(key);
if (it != keyvalues_.end()) {
value = it->second;
result = true;
}
return result;
}
} // namespace lepcpplib
<commit_msg>Use string tokenizer functionality instead of re-implementing partly here.<commit_after>/*
Copyright (c) 2011 Neevarp Yhtroom
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 <fstream>
#include <vector>
#include "Logger.h"
#include "ConfigFile.h"
using std::ifstream;
using std::map;
using std::vector;
namespace lepcpplib {
const int kConfigFileMaxLineLength = 256;
ConfigFile::ConfigFile(const String& filename)
: filename_(filename)
{
}
ConfigFile::~ConfigFile()
{
}
bool ConfigFile::Load()
{
bool result = false;
if (filename_ != "") {
ifstream file(filename_.toCharArray());
char buffer[kConfigFileMaxLineLength];
result = file.good();
while ((!file.eof()) && (!file.fail())) {
file.getline(buffer, sizeof(buffer));
if (file.gcount()) {
String line(buffer);
vector<String> key_value;
line.tokenize('=', key_value);
if (key_value.size() >= 2)
{
keyvalues_[key_value[0]] = key_value[1];
result &= true;
}
else {
result &= false;
}
}
}
}
return result;
}
bool ConfigFile::ValueOf(const String& key, String& value)
{
bool result = false;
map<String, String>::iterator it = keyvalues_.find(key);
if (it != keyvalues_.end()) {
value = it->second;
result = true;
}
return result;
}
} // namespace lepcpplib
<|endoftext|> |
<commit_before>#include "ut_atom.h"
#include "ut_population.h"
#include "ut_objective_function.h"
#include "gtest/gtest.h"
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>unit tests for revolution::Version<commit_after>#include "ut_atom.h"
#include "ut_population.h"
#include "ut_objective_function.h"
#include "ut_version.h"
#include "gtest/gtest.h"
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* dir_access_windows.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#if defined(WINDOWS_ENABLED)
#include "dir_access_windows.h"
#include "core/os/memory.h"
#include "core/print_string.h"
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
/*
[03:57] <reduz> yessopie, so i don't havemak to rely on unicows
[03:58] <yessopie> reduz- yeah, all of the functions fail, and then you can call GetLastError () which will return 120
[03:58] <drumstick> CategoryApl, hehe, what? :)
[03:59] <CategoryApl> didn't Verona lead to some trouble
[03:59] <yessopie> 120 = ERROR_CALL_NOT_IMPLEMENTED
[03:59] <yessopie> (you can use that constant if you include winerr.h)
[03:59] <CategoryApl> well answer with winning a compo
[04:02] <yessopie> if ( SetCurrentDirectoryW ( L"." ) == FALSE && GetLastError () == ERROR_CALL_NOT_IMPLEMENTED ) { use ANSI }
*/
struct DirAccessWindowsPrivate {
HANDLE h; //handle for findfirstfile
WIN32_FIND_DATA f;
WIN32_FIND_DATAW fu; //unicode version
};
// CreateFolderAsync
Error DirAccessWindows::list_dir_begin() {
_cisdir = false;
_cishidden = false;
list_dir_end();
p->h = FindFirstFileExW((current_dir + "\\*").c_str(), FindExInfoStandard, &p->fu, FindExSearchNameMatch, NULL, 0);
return (p->h == INVALID_HANDLE_VALUE) ? ERR_CANT_OPEN : OK;
}
String DirAccessWindows::get_next() {
if (p->h == INVALID_HANDLE_VALUE)
return "";
_cisdir = (p->fu.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
_cishidden = (p->fu.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
String name = p->fu.cFileName;
if (FindNextFileW(p->h, &p->fu) == 0) {
FindClose(p->h);
p->h = INVALID_HANDLE_VALUE;
}
return name;
}
bool DirAccessWindows::current_is_dir() const {
return _cisdir;
}
bool DirAccessWindows::current_is_hidden() const {
return _cishidden;
}
void DirAccessWindows::list_dir_end() {
if (p->h != INVALID_HANDLE_VALUE) {
FindClose(p->h);
p->h = INVALID_HANDLE_VALUE;
}
}
int DirAccessWindows::get_drive_count() {
return drive_count;
}
String DirAccessWindows::get_drive(int p_drive) {
if (p_drive < 0 || p_drive >= drive_count)
return "";
return String::chr(drives[p_drive]) + ":";
}
Error DirAccessWindows::change_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
p_dir = fix_path(p_dir);
wchar_t real_current_dir_name[2048];
GetCurrentDirectoryW(2048, real_current_dir_name);
String prev_dir = real_current_dir_name;
SetCurrentDirectoryW(current_dir.c_str());
bool worked = (SetCurrentDirectoryW(p_dir.c_str()) != 0);
String base = _get_root_path();
if (base != "") {
GetCurrentDirectoryW(2048, real_current_dir_name);
String new_dir;
new_dir = String(real_current_dir_name).replace("\\", "/");
if (!new_dir.begins_with(base)) {
worked = false;
}
}
if (worked) {
GetCurrentDirectoryW(2048, real_current_dir_name);
current_dir = real_current_dir_name; // TODO, utf8 parser
current_dir = current_dir.replace("\\", "/");
} //else {
SetCurrentDirectoryW(prev_dir.c_str());
//}
return worked ? OK : ERR_INVALID_PARAMETER;
}
Error DirAccessWindows::make_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
p_dir = fix_path(p_dir);
if (p_dir.is_rel_path())
p_dir = current_dir.plus_file(p_dir);
p_dir = p_dir.replace("/", "\\");
bool success;
int err;
p_dir = "\\\\?\\" + p_dir; //done according to
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx
success = CreateDirectoryW(p_dir.c_str(), NULL);
err = GetLastError();
if (success) {
return OK;
};
if (err == ERROR_ALREADY_EXISTS || err == ERROR_ACCESS_DENIED) {
return ERR_ALREADY_EXISTS;
};
return ERR_CANT_CREATE;
}
String DirAccessWindows::get_current_dir() {
String base = _get_root_path();
if (base != "") {
String bd = current_dir.replace("\\", "/").replace_first(base, "");
if (bd.begins_with("/"))
return _get_root_string() + bd.substr(1, bd.length());
else
return _get_root_string() + bd;
} else {
}
return current_dir;
}
String DirAccessWindows::get_current_dir_without_drive() {
String dir = get_current_dir();
int p = current_dir.find(":");
return p != -1 ? dir.right(p + 1) : dir;
}
bool DirAccessWindows::file_exists(String p_file) {
GLOBAL_LOCK_FUNCTION
if (!p_file.is_abs_path())
p_file = get_current_dir().plus_file(p_file);
p_file = fix_path(p_file);
//p_file.replace("/","\\");
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_file.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return false;
return !(fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
bool DirAccessWindows::dir_exists(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
p_dir = get_current_dir().plus_file(p_dir);
p_dir = fix_path(p_dir);
//p_dir.replace("/","\\");
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_dir.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return false;
return (fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
Error DirAccessWindows::rename(String p_path, String p_new_path) {
if (p_path.is_rel_path())
p_path = get_current_dir().plus_file(p_path);
p_path = fix_path(p_path);
if (p_new_path.is_rel_path())
p_new_path = get_current_dir().plus_file(p_new_path);
p_new_path = fix_path(p_new_path);
// If we're only changing file name case we need to do a little juggling
if (p_path.to_lower() == p_new_path.to_lower()) {
WCHAR tmpfile[MAX_PATH];
if (!GetTempFileNameW(fix_path(get_current_dir()).c_str(), NULL, 0, tmpfile)) {
return FAILED;
}
if (!::ReplaceFileW(tmpfile, p_path.c_str(), NULL, 0, NULL, NULL)) {
DeleteFileW(tmpfile);
return FAILED;
}
return ::_wrename(tmpfile, p_new_path.c_str()) == 0 ? OK : FAILED;
} else {
if (file_exists(p_new_path)) {
if (remove(p_new_path) != OK) {
return FAILED;
}
}
return ::_wrename(p_path.c_str(), p_new_path.c_str()) == 0 ? OK : FAILED;
}
}
Error DirAccessWindows::remove(String p_path) {
if (p_path.is_rel_path())
p_path = get_current_dir().plus_file(p_path);
p_path = fix_path(p_path);
printf("erasing %s\n", p_path.utf8().get_data());
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
//DWORD fileAttr = GetFileAttributesExW(p_path.c_str(), GetFileExInfoStandard, &fileInfo);
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_path.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return FAILED;
if ((fileAttr & FILE_ATTRIBUTE_DIRECTORY))
return ::_wrmdir(p_path.c_str()) == 0 ? OK : FAILED;
else
return ::_wunlink(p_path.c_str()) == 0 ? OK : FAILED;
}
/*
FileType DirAccessWindows::get_file_type(const String& p_file) const {
wchar_t real_current_dir_name[2048];
GetCurrentDirectoryW(2048,real_current_dir_name);
String prev_dir=real_current_dir_name;
bool worked SetCurrentDirectoryW(current_dir.c_str());
DWORD attr;
if (worked) {
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
attr = GetFileAttributesExW(p_file.c_str(), GetFileExInfoStandard, &fileInfo);
}
SetCurrentDirectoryW(prev_dir.c_str());
if (!worked)
return FILE_TYPE_NONE;
return (attr&FILE_ATTRIBUTE_DIRECTORY)?FILE_TYPE_
}
*/
size_t DirAccessWindows::get_space_left() {
uint64_t bytes = 0;
if (!GetDiskFreeSpaceEx(NULL, (PULARGE_INTEGER)&bytes, NULL, NULL))
return 0;
//this is either 0 or a value in bytes.
return (size_t)bytes;
}
String DirAccessWindows::get_filesystem_type() const {
String path = fix_path(const_cast<DirAccessWindows *>(this)->get_current_dir());
int unit_end = path.find(":");
ERR_FAIL_COND_V(unit_end == -1, String());
String unit = path.substr(0, unit_end + 1) + "\\";
WCHAR szVolumeName[100];
WCHAR szFileSystemName[10];
DWORD dwSerialNumber = 0;
DWORD dwMaxFileNameLength = 0;
DWORD dwFileSystemFlags = 0;
if (::GetVolumeInformationW(unit.c_str(),
szVolumeName,
sizeof(szVolumeName),
&dwSerialNumber,
&dwMaxFileNameLength,
&dwFileSystemFlags,
szFileSystemName,
sizeof(szFileSystemName)) == TRUE) {
return String(szFileSystemName);
}
ERR_FAIL_V("");
}
DirAccessWindows::DirAccessWindows() {
p = memnew(DirAccessWindowsPrivate);
p->h = INVALID_HANDLE_VALUE;
current_dir = ".";
drive_count = 0;
#ifdef UWP_ENABLED
Windows::Storage::StorageFolder ^ install_folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
change_dir(install_folder->Path->Data());
#else
DWORD mask = GetLogicalDrives();
for (int i = 0; i < MAX_DRIVES; i++) {
if (mask & (1 << i)) { //DRIVE EXISTS
drives[drive_count] = 'A' + i;
drive_count++;
}
}
change_dir(".");
#endif
}
DirAccessWindows::~DirAccessWindows() {
memdelete(p);
}
#endif //windows DirAccess support
<commit_msg>Fix res:// trimmed to s:// on Windows<commit_after>/*************************************************************************/
/* dir_access_windows.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#if defined(WINDOWS_ENABLED)
#include "dir_access_windows.h"
#include "core/os/memory.h"
#include "core/print_string.h"
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
/*
[03:57] <reduz> yessopie, so i don't havemak to rely on unicows
[03:58] <yessopie> reduz- yeah, all of the functions fail, and then you can call GetLastError () which will return 120
[03:58] <drumstick> CategoryApl, hehe, what? :)
[03:59] <CategoryApl> didn't Verona lead to some trouble
[03:59] <yessopie> 120 = ERROR_CALL_NOT_IMPLEMENTED
[03:59] <yessopie> (you can use that constant if you include winerr.h)
[03:59] <CategoryApl> well answer with winning a compo
[04:02] <yessopie> if ( SetCurrentDirectoryW ( L"." ) == FALSE && GetLastError () == ERROR_CALL_NOT_IMPLEMENTED ) { use ANSI }
*/
struct DirAccessWindowsPrivate {
HANDLE h; //handle for findfirstfile
WIN32_FIND_DATA f;
WIN32_FIND_DATAW fu; //unicode version
};
// CreateFolderAsync
Error DirAccessWindows::list_dir_begin() {
_cisdir = false;
_cishidden = false;
list_dir_end();
p->h = FindFirstFileExW((current_dir + "\\*").c_str(), FindExInfoStandard, &p->fu, FindExSearchNameMatch, NULL, 0);
return (p->h == INVALID_HANDLE_VALUE) ? ERR_CANT_OPEN : OK;
}
String DirAccessWindows::get_next() {
if (p->h == INVALID_HANDLE_VALUE)
return "";
_cisdir = (p->fu.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
_cishidden = (p->fu.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
String name = p->fu.cFileName;
if (FindNextFileW(p->h, &p->fu) == 0) {
FindClose(p->h);
p->h = INVALID_HANDLE_VALUE;
}
return name;
}
bool DirAccessWindows::current_is_dir() const {
return _cisdir;
}
bool DirAccessWindows::current_is_hidden() const {
return _cishidden;
}
void DirAccessWindows::list_dir_end() {
if (p->h != INVALID_HANDLE_VALUE) {
FindClose(p->h);
p->h = INVALID_HANDLE_VALUE;
}
}
int DirAccessWindows::get_drive_count() {
return drive_count;
}
String DirAccessWindows::get_drive(int p_drive) {
if (p_drive < 0 || p_drive >= drive_count)
return "";
return String::chr(drives[p_drive]) + ":";
}
Error DirAccessWindows::change_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
p_dir = fix_path(p_dir);
wchar_t real_current_dir_name[2048];
GetCurrentDirectoryW(2048, real_current_dir_name);
String prev_dir = real_current_dir_name;
SetCurrentDirectoryW(current_dir.c_str());
bool worked = (SetCurrentDirectoryW(p_dir.c_str()) != 0);
String base = _get_root_path();
if (base != "") {
GetCurrentDirectoryW(2048, real_current_dir_name);
String new_dir;
new_dir = String(real_current_dir_name).replace("\\", "/");
if (!new_dir.begins_with(base)) {
worked = false;
}
}
if (worked) {
GetCurrentDirectoryW(2048, real_current_dir_name);
current_dir = real_current_dir_name; // TODO, utf8 parser
current_dir = current_dir.replace("\\", "/");
} //else {
SetCurrentDirectoryW(prev_dir.c_str());
//}
return worked ? OK : ERR_INVALID_PARAMETER;
}
Error DirAccessWindows::make_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
p_dir = fix_path(p_dir);
if (p_dir.is_rel_path())
p_dir = current_dir.plus_file(p_dir);
p_dir = p_dir.replace("/", "\\");
bool success;
int err;
p_dir = "\\\\?\\" + p_dir; //done according to
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx
success = CreateDirectoryW(p_dir.c_str(), NULL);
err = GetLastError();
if (success) {
return OK;
};
if (err == ERROR_ALREADY_EXISTS || err == ERROR_ACCESS_DENIED) {
return ERR_ALREADY_EXISTS;
};
return ERR_CANT_CREATE;
}
String DirAccessWindows::get_current_dir() {
String base = _get_root_path();
if (base != "") {
String bd = current_dir.replace("\\", "/").replace_first(base, "");
if (bd.begins_with("/"))
return _get_root_string() + bd.substr(1, bd.length());
else
return _get_root_string() + bd;
} else {
}
return current_dir;
}
String DirAccessWindows::get_current_dir_without_drive() {
String dir = get_current_dir();
if (_get_root_string() == "") {
int p = current_dir.find(":");
if (p != -1) {
dir = dir.right(p + 1);
}
}
return dir;
}
bool DirAccessWindows::file_exists(String p_file) {
GLOBAL_LOCK_FUNCTION
if (!p_file.is_abs_path())
p_file = get_current_dir().plus_file(p_file);
p_file = fix_path(p_file);
//p_file.replace("/","\\");
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_file.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return false;
return !(fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
bool DirAccessWindows::dir_exists(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
p_dir = get_current_dir().plus_file(p_dir);
p_dir = fix_path(p_dir);
//p_dir.replace("/","\\");
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_dir.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return false;
return (fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
Error DirAccessWindows::rename(String p_path, String p_new_path) {
if (p_path.is_rel_path())
p_path = get_current_dir().plus_file(p_path);
p_path = fix_path(p_path);
if (p_new_path.is_rel_path())
p_new_path = get_current_dir().plus_file(p_new_path);
p_new_path = fix_path(p_new_path);
// If we're only changing file name case we need to do a little juggling
if (p_path.to_lower() == p_new_path.to_lower()) {
WCHAR tmpfile[MAX_PATH];
if (!GetTempFileNameW(fix_path(get_current_dir()).c_str(), NULL, 0, tmpfile)) {
return FAILED;
}
if (!::ReplaceFileW(tmpfile, p_path.c_str(), NULL, 0, NULL, NULL)) {
DeleteFileW(tmpfile);
return FAILED;
}
return ::_wrename(tmpfile, p_new_path.c_str()) == 0 ? OK : FAILED;
} else {
if (file_exists(p_new_path)) {
if (remove(p_new_path) != OK) {
return FAILED;
}
}
return ::_wrename(p_path.c_str(), p_new_path.c_str()) == 0 ? OK : FAILED;
}
}
Error DirAccessWindows::remove(String p_path) {
if (p_path.is_rel_path())
p_path = get_current_dir().plus_file(p_path);
p_path = fix_path(p_path);
printf("erasing %s\n", p_path.utf8().get_data());
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
//DWORD fileAttr = GetFileAttributesExW(p_path.c_str(), GetFileExInfoStandard, &fileInfo);
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_path.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return FAILED;
if ((fileAttr & FILE_ATTRIBUTE_DIRECTORY))
return ::_wrmdir(p_path.c_str()) == 0 ? OK : FAILED;
else
return ::_wunlink(p_path.c_str()) == 0 ? OK : FAILED;
}
/*
FileType DirAccessWindows::get_file_type(const String& p_file) const {
wchar_t real_current_dir_name[2048];
GetCurrentDirectoryW(2048,real_current_dir_name);
String prev_dir=real_current_dir_name;
bool worked SetCurrentDirectoryW(current_dir.c_str());
DWORD attr;
if (worked) {
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
attr = GetFileAttributesExW(p_file.c_str(), GetFileExInfoStandard, &fileInfo);
}
SetCurrentDirectoryW(prev_dir.c_str());
if (!worked)
return FILE_TYPE_NONE;
return (attr&FILE_ATTRIBUTE_DIRECTORY)?FILE_TYPE_
}
*/
size_t DirAccessWindows::get_space_left() {
uint64_t bytes = 0;
if (!GetDiskFreeSpaceEx(NULL, (PULARGE_INTEGER)&bytes, NULL, NULL))
return 0;
//this is either 0 or a value in bytes.
return (size_t)bytes;
}
String DirAccessWindows::get_filesystem_type() const {
String path = fix_path(const_cast<DirAccessWindows *>(this)->get_current_dir());
int unit_end = path.find(":");
ERR_FAIL_COND_V(unit_end == -1, String());
String unit = path.substr(0, unit_end + 1) + "\\";
WCHAR szVolumeName[100];
WCHAR szFileSystemName[10];
DWORD dwSerialNumber = 0;
DWORD dwMaxFileNameLength = 0;
DWORD dwFileSystemFlags = 0;
if (::GetVolumeInformationW(unit.c_str(),
szVolumeName,
sizeof(szVolumeName),
&dwSerialNumber,
&dwMaxFileNameLength,
&dwFileSystemFlags,
szFileSystemName,
sizeof(szFileSystemName)) == TRUE) {
return String(szFileSystemName);
}
ERR_FAIL_V("");
}
DirAccessWindows::DirAccessWindows() {
p = memnew(DirAccessWindowsPrivate);
p->h = INVALID_HANDLE_VALUE;
current_dir = ".";
drive_count = 0;
#ifdef UWP_ENABLED
Windows::Storage::StorageFolder ^ install_folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
change_dir(install_folder->Path->Data());
#else
DWORD mask = GetLogicalDrives();
for (int i = 0; i < MAX_DRIVES; i++) {
if (mask & (1 << i)) { //DRIVE EXISTS
drives[drive_count] = 'A' + i;
drive_count++;
}
}
change_dir(".");
#endif
}
DirAccessWindows::~DirAccessWindows() {
memdelete(p);
}
#endif //windows DirAccess support
<|endoftext|> |
<commit_before>/***********************************************************************
filename: ShaderParameterBindings.cpp
created: 18th July 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 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 "CEGUI/ShaderParameterBindings.h"
#include "CEGUI/System.h"
#include "glm/glm.hpp"
namespace CEGUI
{
//----------------------------------------------------------------------------//
ShaderParameterBindings::ShaderParameterBindings()
{
}
//----------------------------------------------------------------------------//
ShaderParameterBindings::~ShaderParameterBindings()
{
while (!d_shaderParameterBindings.empty())
{
ShaderParameterBindingsMap::iterator current = d_shaderParameterBindings.begin();
delete current->second;
d_shaderParameterBindings.erase(current);
}
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::removeParameter(const std::string& parameterName)
{
ShaderParameterBindingsMap::iterator found_iterator = d_shaderParameterBindings.find(parameterName);
if (found_iterator != d_shaderParameterBindings.end())
{
delete found_iterator->second;
d_shaderParameterBindings.erase(found_iterator);
}
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::setParameter(const std::string& parameterName, ShaderParameter* shaderParameter)
{
std::map<std::string, ShaderParameter*>::iterator iter = d_shaderParameterBindings.find(parameterName);
if(iter != d_shaderParameterBindings.end())
{
delete iter->second;
iter->second = shaderParameter;
}
else
{
std::pair<std::string, ShaderParameter*> shader_params_pair(parameterName, shaderParameter);
d_shaderParameterBindings.insert(shader_params_pair);
}
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::setParameter(const std::string& parameterName, const glm::mat4& matrix)
{
ShaderParameterMatrix* shaderParameterMatrix = new ShaderParameterMatrix(matrix);
setParameter(parameterName, shaderParameterMatrix);
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::setParameter(const std::string& parameterName, const CEGUI::Texture* texture)
{
ShaderParameterTexture* shaderParameterTexture = new ShaderParameterTexture(texture);
setParameter(parameterName, shaderParameterTexture);
}
//----------------------------------------------------------------------------//
const ShaderParameterBindings::ShaderParameterBindingsMap& ShaderParameterBindings::getShaderParameterBindings()
{
return d_shaderParameterBindings;
}
//----------------------------------------------------------------------------//
}
<commit_msg>MOD: Fixing ShaderParameter deletion performance<commit_after>/***********************************************************************
filename: ShaderParameterBindings.cpp
created: 18th July 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 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 "CEGUI/ShaderParameterBindings.h"
#include "CEGUI/System.h"
#include "glm/glm.hpp"
namespace CEGUI
{
//----------------------------------------------------------------------------//
ShaderParameterBindings::ShaderParameterBindings()
{
}
//----------------------------------------------------------------------------//
ShaderParameterBindings::~ShaderParameterBindings()
{
ShaderParameterBindings::ShaderParameterBindingsMap::iterator iter = d_shaderParameterBindings.begin();
ShaderParameterBindings::ShaderParameterBindingsMap::iterator end = d_shaderParameterBindings.end();
while (iter != end)
{
delete iter->second;
}
d_shaderParameterBindings.clear();
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::removeParameter(const std::string& parameterName)
{
ShaderParameterBindingsMap::iterator found_iterator = d_shaderParameterBindings.find(parameterName);
if (found_iterator != d_shaderParameterBindings.end())
{
delete found_iterator->second;
d_shaderParameterBindings.erase(found_iterator);
}
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::setParameter(const std::string& parameterName, ShaderParameter* shaderParameter)
{
std::map<std::string, ShaderParameter*>::iterator found_iterator = d_shaderParameterBindings.find(parameterName);
if(found_iterator != d_shaderParameterBindings.end())
{
delete found_iterator->second;
found_iterator->second = shaderParameter;
}
else
{
std::pair<std::string, ShaderParameter*> shader_params_pair(parameterName, shaderParameter);
d_shaderParameterBindings.insert(shader_params_pair);
}
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::setParameter(const std::string& parameterName, const glm::mat4& matrix)
{
ShaderParameterMatrix* shaderParameterMatrix = new ShaderParameterMatrix(matrix);
setParameter(parameterName, shaderParameterMatrix);
}
//----------------------------------------------------------------------------//
void ShaderParameterBindings::setParameter(const std::string& parameterName, const CEGUI::Texture* texture)
{
ShaderParameterTexture* shaderParameterTexture = new ShaderParameterTexture(texture);
setParameter(parameterName, shaderParameterTexture);
}
//----------------------------------------------------------------------------//
const ShaderParameterBindings::ShaderParameterBindingsMap& ShaderParameterBindings::getShaderParameterBindings()
{
return d_shaderParameterBindings;
}
//----------------------------------------------------------------------------//
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: mcnttfactory.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: tra $ $Date: 2001-02-13 13:04:11 $
*
* 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): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _MCNTTFACTORY_HXX_
#include "mcnttfactory.hxx"
#endif
#ifndef _MCNTTYPE_HXX_
#include "mcnttype.hxx"
#endif
//------------------------------------------------------------------------
// defines
//------------------------------------------------------------------------
#define MIMECONTENTTYPEFACTORY_IMPL_NAME "com.sun.star.datatransfer.MimeCntTypeFactory"
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::datatransfer;
//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------
namespace
{
Sequence< OUString > SAL_CALL MimeContentTypeFactory_getSupportedServiceNames( )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.MimeContentTypeFactory");
return aRet;
}
}
//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------
CMimeContentTypeFactory::CMimeContentTypeFactory( const Reference< XMultiServiceFactory >& rSrvMgr ) :
m_SrvMgr( rSrvMgr )
{
}
//------------------------------------------------------------------------
// createMimeContentType
//------------------------------------------------------------------------
Reference< XMimeContentType > CMimeContentTypeFactory::createMimeContentType( const OUString& aContentType )
throw( IllegalArgumentException, RuntimeException )
{
MutexGuard aGuard( m_aMutex );
return Reference< XMimeContentType >( new CMimeContentType( aContentType ) );
}
// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------
OUString SAL_CALL CMimeContentTypeFactory::getImplementationName( )
throw( RuntimeException )
{
return OUString::createFromAscii( MIMECONTENTTYPEFACTORY_IMPL_NAME );
}
// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------
sal_Bool SAL_CALL CMimeContentTypeFactory::supportsService( const OUString& ServiceName )
throw( RuntimeException )
{
Sequence < OUString > SupportedServicesNames = MimeContentTypeFactory_getSupportedServiceNames();
for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
return sal_True;
return sal_False;
}
// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------
Sequence< OUString > SAL_CALL CMimeContentTypeFactory::getSupportedServiceNames( )
throw( RuntimeException )
{
return MimeContentTypeFactory_getSupportedServiceNames( );
}<commit_msg>INTEGRATION: CWS rt02 (1.2.102); FILE MERGED 2003/10/01 12:05:55 rt 1.2.102.1: #i19697# No newline at end of file<commit_after>/*************************************************************************
*
* $RCSfile: mcnttfactory.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-10-06 14:35:57 $
*
* 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): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _MCNTTFACTORY_HXX_
#include "mcnttfactory.hxx"
#endif
#ifndef _MCNTTYPE_HXX_
#include "mcnttype.hxx"
#endif
//------------------------------------------------------------------------
// defines
//------------------------------------------------------------------------
#define MIMECONTENTTYPEFACTORY_IMPL_NAME "com.sun.star.datatransfer.MimeCntTypeFactory"
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::datatransfer;
//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------
namespace
{
Sequence< OUString > SAL_CALL MimeContentTypeFactory_getSupportedServiceNames( )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.MimeContentTypeFactory");
return aRet;
}
}
//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------
CMimeContentTypeFactory::CMimeContentTypeFactory( const Reference< XMultiServiceFactory >& rSrvMgr ) :
m_SrvMgr( rSrvMgr )
{
}
//------------------------------------------------------------------------
// createMimeContentType
//------------------------------------------------------------------------
Reference< XMimeContentType > CMimeContentTypeFactory::createMimeContentType( const OUString& aContentType )
throw( IllegalArgumentException, RuntimeException )
{
MutexGuard aGuard( m_aMutex );
return Reference< XMimeContentType >( new CMimeContentType( aContentType ) );
}
// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------
OUString SAL_CALL CMimeContentTypeFactory::getImplementationName( )
throw( RuntimeException )
{
return OUString::createFromAscii( MIMECONTENTTYPEFACTORY_IMPL_NAME );
}
// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------
sal_Bool SAL_CALL CMimeContentTypeFactory::supportsService( const OUString& ServiceName )
throw( RuntimeException )
{
Sequence < OUString > SupportedServicesNames = MimeContentTypeFactory_getSupportedServiceNames();
for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
return sal_True;
return sal_False;
}
// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------
Sequence< OUString > SAL_CALL CMimeContentTypeFactory::getSupportedServiceNames( )
throw( RuntimeException )
{
return MimeContentTypeFactory_getSupportedServiceNames( );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: formstrings.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2003-03-25 16:03:54 $
*
* 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 EXPRESS 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 _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_
#define _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_
#ifndef _EXTENSIONS_FORMSCTRLR_STRINGDEFINE_HXX_
#include "stringdefine.hxx"
#endif
//............................................................................
namespace pcr
{
//............................................................................
// properties
PCR_CONSTASCII_STRING( PROPERTY_CLASSID, "ClassId" );
PCR_CONSTASCII_STRING( PROPERTY_CONTROLLABEL, "LabelControl");
PCR_CONSTASCII_STRING( PROPERTY_LABEL, "Label");
PCR_CONSTASCII_STRING( PROPERTY_TABINDEX, "TabIndex");
PCR_CONSTASCII_STRING( PROPERTY_TAG, "Tag");
PCR_CONSTASCII_STRING( PROPERTY_NAME, "Name");
PCR_CONSTASCII_STRING( PROPERTY_VALUE, "Value");
PCR_CONSTASCII_STRING( PROPERTY_TEXT, "Text");
PCR_CONSTASCII_STRING( PROPERTY_NAVIGATION, "NavigationBarMode");
PCR_CONSTASCII_STRING( PROPERTY_CYCLE, "Cycle");
PCR_CONSTASCII_STRING( PROPERTY_CONTROLSOURCE, "DataField");
PCR_CONSTASCII_STRING( PROPERTY_ENABLED, "Enabled");
PCR_CONSTASCII_STRING( PROPERTY_READONLY, "ReadOnly");
PCR_CONSTASCII_STRING( PROPERTY_ISREADONLY, "IsReadOnly");
PCR_CONSTASCII_STRING( PROPERTY_FILTER_CRITERIA, "Filter");
PCR_CONSTASCII_STRING( PROPERTY_WIDTH, "Width");
PCR_CONSTASCII_STRING( PROPERTY_MULTILINE, "MultiLine");
PCR_CONSTASCII_STRING( PROPERTY_TARGET_URL, "TargetURL");
PCR_CONSTASCII_STRING( PROPERTY_TARGET_FRAME, "TargetFrame");
PCR_CONSTASCII_STRING( PROPERTY_MAXTEXTLEN, "MaxTextLen");
PCR_CONSTASCII_STRING( PROPERTY_EDITMASK, "EditMask");
PCR_CONSTASCII_STRING( PROPERTY_SPIN, "Spin");
PCR_CONSTASCII_STRING( PROPERTY_TRISTATE, "TriState");
PCR_CONSTASCII_STRING( PROPERTY_HIDDEN_VALUE, "HiddenValue");
PCR_CONSTASCII_STRING( PROPERTY_BUTTONTYPE, "ButtonType");
PCR_CONSTASCII_STRING( PROPERTY_STRINGITEMLIST, "StringItemList");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_TEXT, "DefaultText");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULTCHECKED, "DefaultState");
PCR_CONSTASCII_STRING( PROPERTY_FORMATKEY, "FormatKey");
PCR_CONSTASCII_STRING( PROPERTY_FORMATSSUPPLIER, "FormatsSupplier");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_ACTION, "SubmitAction");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_TARGET, "SubmitTarget");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_METHOD, "SubmitMethod");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_ENCODING, "SubmitEncoding");
PCR_CONSTASCII_STRING( PROPERTY_IMAGE_URL, "ImageURL");
PCR_CONSTASCII_STRING( PROPERTY_EMPTY_IS_NULL, "ConvertEmptyToNull");
PCR_CONSTASCII_STRING( PROPERTY_LISTSOURCETYPE, "ListSourceType");
PCR_CONSTASCII_STRING( PROPERTY_LISTSOURCE, "ListSource");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_SELECT_SEQ, "DefaultSelection");
PCR_CONSTASCII_STRING( PROPERTY_MULTISELECTION, "MultiSelection");
PCR_CONSTASCII_STRING( PROPERTY_ALIGN, "Align");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_DATE, "DefaultDate");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_TIME, "DefaultTime");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_VALUE, "DefaultValue");
PCR_CONSTASCII_STRING( PROPERTY_DECIMAL_ACCURACY, "DecimalAccuracy");
PCR_CONSTASCII_STRING( PROPERTY_REFVALUE, "RefValue");
PCR_CONSTASCII_STRING( PROPERTY_VALUEMIN, "ValueMin");
PCR_CONSTASCII_STRING( PROPERTY_VALUEMAX, "ValueMax");
PCR_CONSTASCII_STRING( PROPERTY_STRICTFORMAT, "StrictFormat");
PCR_CONSTASCII_STRING( PROPERTY_ALLOWADDITIONS, "AllowInserts");
PCR_CONSTASCII_STRING( PROPERTY_ALLOWEDITS, "AllowUpdates");
PCR_CONSTASCII_STRING( PROPERTY_ALLOWDELETIONS, "AllowDeletes");
PCR_CONSTASCII_STRING( PROPERTY_MASTERFIELDS, "MasterFields");
PCR_CONSTASCII_STRING( PROPERTY_LITERALMASK, "LiteralMask");
PCR_CONSTASCII_STRING( PROPERTY_VALUESTEP, "ValueStep");
PCR_CONSTASCII_STRING( PROPERTY_SHOWTHOUSANDSEP, "ShowThousandsSeparator");
PCR_CONSTASCII_STRING( PROPERTY_CURRENCYSYMBOL, "CurrencySymbol");
PCR_CONSTASCII_STRING( PROPERTY_DATEFORMAT, "DateFormat");
PCR_CONSTASCII_STRING( PROPERTY_DATEMIN, "DateMin");
PCR_CONSTASCII_STRING( PROPERTY_DATEMAX, "DateMax");
PCR_CONSTASCII_STRING( PROPERTY_TIMEFORMAT, "TimeFormat");
PCR_CONSTASCII_STRING( PROPERTY_TIMEMIN, "TimeMin");
PCR_CONSTASCII_STRING( PROPERTY_TIMEMAX, "TimeMax");
PCR_CONSTASCII_STRING( PROPERTY_LINECOUNT, "LineCount");
PCR_CONSTASCII_STRING( PROPERTY_BOUNDCOLUMN, "BoundColumn");
PCR_CONSTASCII_STRING( PROPERTY_BACKGROUNDCOLOR, "BackgroundColor");
PCR_CONSTASCII_STRING( PROPERTY_FILLCOLOR, "FillColor");
PCR_CONSTASCII_STRING( PROPERTY_TEXTCOLOR, "TextColor");
PCR_CONSTASCII_STRING( PROPERTY_LINECOLOR, "LineColor");
PCR_CONSTASCII_STRING( PROPERTY_BORDER, "Border");
PCR_CONSTASCII_STRING( PROPERTY_DROPDOWN, "Dropdown");
PCR_CONSTASCII_STRING( PROPERTY_MULTI, "Multi");
PCR_CONSTASCII_STRING( PROPERTY_HSCROLL, "HScroll");
PCR_CONSTASCII_STRING( PROPERTY_VSCROLL, "VScroll");
PCR_CONSTASCII_STRING( PROPERTY_TABSTOP, "Tabstop");
PCR_CONSTASCII_STRING( PROPERTY_AUTOCOMPLETE, "Autocomplete");
PCR_CONSTASCII_STRING( PROPERTY_HARDLINEBREAKS, "HardLineBreaks");
PCR_CONSTASCII_STRING( PROPERTY_PRINTABLE, "Printable");
PCR_CONSTASCII_STRING( PROPERTY_ECHO_CHAR, "EchoChar");
PCR_CONSTASCII_STRING( PROPERTY_ROWHEIGHT, "RowHeight");
PCR_CONSTASCII_STRING( PROPERTY_HELPTEXT, "HelpText");
PCR_CONSTASCII_STRING( PROPERTY_FONT_NAME, "FontName");
PCR_CONSTASCII_STRING( PROPERTY_FONT_STYLENAME, "FontStyleName");
PCR_CONSTASCII_STRING( PROPERTY_FONT_FAMILY, "FontFamily");
PCR_CONSTASCII_STRING( PROPERTY_FONT_CHARSET, "FontCharset");
PCR_CONSTASCII_STRING( PROPERTY_FONT_HEIGHT, "FontHeight");
PCR_CONSTASCII_STRING( PROPERTY_FONT_WEIGHT, "FontWeight");
PCR_CONSTASCII_STRING( PROPERTY_FONT_SLANT, "FontSlant");
PCR_CONSTASCII_STRING( PROPERTY_FONT_UNDERLINE, "FontUnderline");
PCR_CONSTASCII_STRING( PROPERTY_FONT_STRIKEOUT, "FontStrikeout");
PCR_CONSTASCII_STRING( PROPERTY_FONT_RELIEF, "FontRelief");
PCR_CONSTASCII_STRING( PROPERTY_FONT_EMPHASIS_MARK, "FontEmphasisMark");
PCR_CONSTASCII_STRING( PROPERTY_TEXTLINECOLOR, "TextLineColor");
PCR_CONSTASCII_STRING( PROPERTY_HELPURL, "HelpURL");
PCR_CONSTASCII_STRING( PROPERTY_RECORDMARKER, "HasRecordMarker");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_DEFAULT, "EffectiveDefault");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_MIN, "EffectiveMin");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_MAX, "EffectiveMax");
PCR_CONSTASCII_STRING( PROPERTY_FILTERPROPOSAL, "UseFilterValueProposal");
PCR_CONSTASCII_STRING( PROPERTY_CURRSYM_POSITION, "PrependCurrencySymbol");
PCR_CONSTASCII_STRING( PROPERTY_COMMAND, "Command");
PCR_CONSTASCII_STRING( PROPERTY_COMMANDTYPE, "CommandType");
PCR_CONSTASCII_STRING( PROPERTY_INSERTONLY, "IgnoreResult");
PCR_CONSTASCII_STRING( PROPERTY_ESCAPE_PROCESSING, "EscapeProcessing");
PCR_CONSTASCII_STRING( PROPERTY_TITLE, "Title");
PCR_CONSTASCII_STRING( PROPERTY_SORT, "Order");
PCR_CONSTASCII_STRING( PROPERTY_DATASOURCE, "DataSourceName");
PCR_CONSTASCII_STRING( PROPERTY_DETAILFIELDS, "DetailFields");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULTBUTTON, "DefaultButton");
PCR_CONSTASCII_STRING( PROPERTY_LISTINDEX, "ListIndex");
PCR_CONSTASCII_STRING( PROPERTY_HEIGHT, "Height");
PCR_CONSTASCII_STRING( PROPERTY_HASNAVIGATION, "HasNavigationBar");
PCR_CONSTASCII_STRING( PROPERTY_POSITIONX, "PositionX");
PCR_CONSTASCII_STRING( PROPERTY_POSITIONY, "PositionY");
PCR_CONSTASCII_STRING( PROPERTY_STEP, "Step");
PCR_CONSTASCII_STRING( PROPERTY_WORDLINEMODE, "FontWordLineMode");
PCR_CONSTASCII_STRING( PROPERTY_PROGRESSVALUE, "ProgressValue");
PCR_CONSTASCII_STRING( PROPERTY_PROGRESSVALUE_MIN, "ProgressValueMin");
PCR_CONSTASCII_STRING( PROPERTY_PROGRESSVALUE_MAX, "ProgressValueMax");
PCR_CONSTASCII_STRING( PROPERTY_SCROLLVALUE, "ScrollValue");
PCR_CONSTASCII_STRING( PROPERTY_SCROLLVALUE_MAX, "ScrollValueMax");
PCR_CONSTASCII_STRING( PROPERTY_LINEINCREMENT, "LineIncrement");
PCR_CONSTASCII_STRING( PROPERTY_BLOCKINCREMENT, "BlockIncrement");
PCR_CONSTASCII_STRING( PROPERTY_VISIBLESIZE, "VisibleSize");
PCR_CONSTASCII_STRING( PROPERTY_ORIENTATION, "Orientation");
PCR_CONSTASCII_STRING( PROPERTY_IMAGEALIGN, "ImageAlign");
PCR_CONSTASCII_STRING( PROPERTY_ACTIVE_CONNECTION, "ActiveConnection");
PCR_CONSTASCII_STRING( PROPERTY_DATE, "Date");
PCR_CONSTASCII_STRING( PROPERTY_STATE, "State");
PCR_CONSTASCII_STRING( PROPERTY_TIME, "Time");
PCR_CONSTASCII_STRING( PROPERTY_SCALEIMAGE, "ScaleImage");
PCR_CONSTASCII_STRING( PROPERTY_PUSHBUTTONTYPE, "PushButtonType");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_VALUE, "EffectiveValue");
// services
PCR_CONSTASCII_STRING( SERVICE_COMPONENT_GROUPBOX, "com.sun.star.form.component.GroupBox");
PCR_CONSTASCII_STRING( SERVICE_COMPONENT_FIXEDTEXT, "com.sun.star.form.component.FixedText");
PCR_CONSTASCII_STRING( SERVICE_COMPONENT_FORMATTEDFIELD,"com.sun.star.form.component.FormattedField");
PCR_CONSTASCII_STRING( SERVICE_DATABASE_CONTEXT, "com.sun.star.sdb.DatabaseContext");
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_
<commit_msg>INTEGRATION: CWS formcelllinkage (1.16.94); FILE MERGED 2003/10/01 09:17:55 fs 1.16.94.1: #i18994# merging the changes from the CWS fs002<commit_after>/*************************************************************************
*
* $RCSfile: formstrings.hxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2003-10-21 09:06:12 $
*
* 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 EXPRESS 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 _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_
#define _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_
#ifndef _EXTENSIONS_FORMSCTRLR_STRINGDEFINE_HXX_
#include "stringdefine.hxx"
#endif
//............................................................................
namespace pcr
{
//............................................................................
// properties
PCR_CONSTASCII_STRING( PROPERTY_CLASSID, "ClassId" );
PCR_CONSTASCII_STRING( PROPERTY_CONTROLLABEL, "LabelControl");
PCR_CONSTASCII_STRING( PROPERTY_LABEL, "Label");
PCR_CONSTASCII_STRING( PROPERTY_TABINDEX, "TabIndex");
PCR_CONSTASCII_STRING( PROPERTY_TAG, "Tag");
PCR_CONSTASCII_STRING( PROPERTY_NAME, "Name");
PCR_CONSTASCII_STRING( PROPERTY_VALUE, "Value");
PCR_CONSTASCII_STRING( PROPERTY_TEXT, "Text");
PCR_CONSTASCII_STRING( PROPERTY_NAVIGATION, "NavigationBarMode");
PCR_CONSTASCII_STRING( PROPERTY_CYCLE, "Cycle");
PCR_CONSTASCII_STRING( PROPERTY_CONTROLSOURCE, "DataField");
PCR_CONSTASCII_STRING( PROPERTY_ENABLED, "Enabled");
PCR_CONSTASCII_STRING( PROPERTY_READONLY, "ReadOnly");
PCR_CONSTASCII_STRING( PROPERTY_ISREADONLY, "IsReadOnly");
PCR_CONSTASCII_STRING( PROPERTY_FILTER_CRITERIA, "Filter");
PCR_CONSTASCII_STRING( PROPERTY_WIDTH, "Width");
PCR_CONSTASCII_STRING( PROPERTY_MULTILINE, "MultiLine");
PCR_CONSTASCII_STRING( PROPERTY_TARGET_URL, "TargetURL");
PCR_CONSTASCII_STRING( PROPERTY_TARGET_FRAME, "TargetFrame");
PCR_CONSTASCII_STRING( PROPERTY_MAXTEXTLEN, "MaxTextLen");
PCR_CONSTASCII_STRING( PROPERTY_EDITMASK, "EditMask");
PCR_CONSTASCII_STRING( PROPERTY_SPIN, "Spin");
PCR_CONSTASCII_STRING( PROPERTY_TRISTATE, "TriState");
PCR_CONSTASCII_STRING( PROPERTY_HIDDEN_VALUE, "HiddenValue");
PCR_CONSTASCII_STRING( PROPERTY_BUTTONTYPE, "ButtonType");
PCR_CONSTASCII_STRING( PROPERTY_STRINGITEMLIST, "StringItemList");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_TEXT, "DefaultText");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULTCHECKED, "DefaultState");
PCR_CONSTASCII_STRING( PROPERTY_FORMATKEY, "FormatKey");
PCR_CONSTASCII_STRING( PROPERTY_FORMATSSUPPLIER, "FormatsSupplier");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_ACTION, "SubmitAction");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_TARGET, "SubmitTarget");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_METHOD, "SubmitMethod");
PCR_CONSTASCII_STRING( PROPERTY_SUBMIT_ENCODING, "SubmitEncoding");
PCR_CONSTASCII_STRING( PROPERTY_IMAGE_URL, "ImageURL");
PCR_CONSTASCII_STRING( PROPERTY_EMPTY_IS_NULL, "ConvertEmptyToNull");
PCR_CONSTASCII_STRING( PROPERTY_LISTSOURCETYPE, "ListSourceType");
PCR_CONSTASCII_STRING( PROPERTY_LISTSOURCE, "ListSource");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_SELECT_SEQ, "DefaultSelection");
PCR_CONSTASCII_STRING( PROPERTY_MULTISELECTION, "MultiSelection");
PCR_CONSTASCII_STRING( PROPERTY_ALIGN, "Align");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_DATE, "DefaultDate");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_TIME, "DefaultTime");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULT_VALUE, "DefaultValue");
PCR_CONSTASCII_STRING( PROPERTY_DECIMAL_ACCURACY, "DecimalAccuracy");
PCR_CONSTASCII_STRING( PROPERTY_REFVALUE, "RefValue");
PCR_CONSTASCII_STRING( PROPERTY_VALUEMIN, "ValueMin");
PCR_CONSTASCII_STRING( PROPERTY_VALUEMAX, "ValueMax");
PCR_CONSTASCII_STRING( PROPERTY_STRICTFORMAT, "StrictFormat");
PCR_CONSTASCII_STRING( PROPERTY_ALLOWADDITIONS, "AllowInserts");
PCR_CONSTASCII_STRING( PROPERTY_ALLOWEDITS, "AllowUpdates");
PCR_CONSTASCII_STRING( PROPERTY_ALLOWDELETIONS, "AllowDeletes");
PCR_CONSTASCII_STRING( PROPERTY_MASTERFIELDS, "MasterFields");
PCR_CONSTASCII_STRING( PROPERTY_LITERALMASK, "LiteralMask");
PCR_CONSTASCII_STRING( PROPERTY_VALUESTEP, "ValueStep");
PCR_CONSTASCII_STRING( PROPERTY_SHOWTHOUSANDSEP, "ShowThousandsSeparator");
PCR_CONSTASCII_STRING( PROPERTY_CURRENCYSYMBOL, "CurrencySymbol");
PCR_CONSTASCII_STRING( PROPERTY_DATEFORMAT, "DateFormat");
PCR_CONSTASCII_STRING( PROPERTY_DATEMIN, "DateMin");
PCR_CONSTASCII_STRING( PROPERTY_DATEMAX, "DateMax");
PCR_CONSTASCII_STRING( PROPERTY_TIMEFORMAT, "TimeFormat");
PCR_CONSTASCII_STRING( PROPERTY_TIMEMIN, "TimeMin");
PCR_CONSTASCII_STRING( PROPERTY_TIMEMAX, "TimeMax");
PCR_CONSTASCII_STRING( PROPERTY_LINECOUNT, "LineCount");
PCR_CONSTASCII_STRING( PROPERTY_BOUNDCOLUMN, "BoundColumn");
PCR_CONSTASCII_STRING( PROPERTY_BACKGROUNDCOLOR, "BackgroundColor");
PCR_CONSTASCII_STRING( PROPERTY_FILLCOLOR, "FillColor");
PCR_CONSTASCII_STRING( PROPERTY_TEXTCOLOR, "TextColor");
PCR_CONSTASCII_STRING( PROPERTY_LINECOLOR, "LineColor");
PCR_CONSTASCII_STRING( PROPERTY_BORDER, "Border");
PCR_CONSTASCII_STRING( PROPERTY_DROPDOWN, "Dropdown");
PCR_CONSTASCII_STRING( PROPERTY_MULTI, "Multi");
PCR_CONSTASCII_STRING( PROPERTY_HSCROLL, "HScroll");
PCR_CONSTASCII_STRING( PROPERTY_VSCROLL, "VScroll");
PCR_CONSTASCII_STRING( PROPERTY_TABSTOP, "Tabstop");
PCR_CONSTASCII_STRING( PROPERTY_AUTOCOMPLETE, "Autocomplete");
PCR_CONSTASCII_STRING( PROPERTY_HARDLINEBREAKS, "HardLineBreaks");
PCR_CONSTASCII_STRING( PROPERTY_PRINTABLE, "Printable");
PCR_CONSTASCII_STRING( PROPERTY_ECHO_CHAR, "EchoChar");
PCR_CONSTASCII_STRING( PROPERTY_ROWHEIGHT, "RowHeight");
PCR_CONSTASCII_STRING( PROPERTY_HELPTEXT, "HelpText");
PCR_CONSTASCII_STRING( PROPERTY_FONT_NAME, "FontName");
PCR_CONSTASCII_STRING( PROPERTY_FONT_STYLENAME, "FontStyleName");
PCR_CONSTASCII_STRING( PROPERTY_FONT_FAMILY, "FontFamily");
PCR_CONSTASCII_STRING( PROPERTY_FONT_CHARSET, "FontCharset");
PCR_CONSTASCII_STRING( PROPERTY_FONT_HEIGHT, "FontHeight");
PCR_CONSTASCII_STRING( PROPERTY_FONT_WEIGHT, "FontWeight");
PCR_CONSTASCII_STRING( PROPERTY_FONT_SLANT, "FontSlant");
PCR_CONSTASCII_STRING( PROPERTY_FONT_UNDERLINE, "FontUnderline");
PCR_CONSTASCII_STRING( PROPERTY_FONT_STRIKEOUT, "FontStrikeout");
PCR_CONSTASCII_STRING( PROPERTY_FONT_RELIEF, "FontRelief");
PCR_CONSTASCII_STRING( PROPERTY_FONT_EMPHASIS_MARK, "FontEmphasisMark");
PCR_CONSTASCII_STRING( PROPERTY_TEXTLINECOLOR, "TextLineColor");
PCR_CONSTASCII_STRING( PROPERTY_HELPURL, "HelpURL");
PCR_CONSTASCII_STRING( PROPERTY_RECORDMARKER, "HasRecordMarker");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_DEFAULT, "EffectiveDefault");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_MIN, "EffectiveMin");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_MAX, "EffectiveMax");
PCR_CONSTASCII_STRING( PROPERTY_FILTERPROPOSAL, "UseFilterValueProposal");
PCR_CONSTASCII_STRING( PROPERTY_CURRSYM_POSITION, "PrependCurrencySymbol");
PCR_CONSTASCII_STRING( PROPERTY_COMMAND, "Command");
PCR_CONSTASCII_STRING( PROPERTY_COMMANDTYPE, "CommandType");
PCR_CONSTASCII_STRING( PROPERTY_INSERTONLY, "IgnoreResult");
PCR_CONSTASCII_STRING( PROPERTY_ESCAPE_PROCESSING, "EscapeProcessing");
PCR_CONSTASCII_STRING( PROPERTY_TITLE, "Title");
PCR_CONSTASCII_STRING( PROPERTY_SORT, "Order");
PCR_CONSTASCII_STRING( PROPERTY_DATASOURCE, "DataSourceName");
PCR_CONSTASCII_STRING( PROPERTY_DETAILFIELDS, "DetailFields");
PCR_CONSTASCII_STRING( PROPERTY_DEFAULTBUTTON, "DefaultButton");
PCR_CONSTASCII_STRING( PROPERTY_LISTINDEX, "ListIndex");
PCR_CONSTASCII_STRING( PROPERTY_HEIGHT, "Height");
PCR_CONSTASCII_STRING( PROPERTY_HASNAVIGATION, "HasNavigationBar");
PCR_CONSTASCII_STRING( PROPERTY_POSITIONX, "PositionX");
PCR_CONSTASCII_STRING( PROPERTY_POSITIONY, "PositionY");
PCR_CONSTASCII_STRING( PROPERTY_STEP, "Step");
PCR_CONSTASCII_STRING( PROPERTY_WORDLINEMODE, "FontWordLineMode");
PCR_CONSTASCII_STRING( PROPERTY_PROGRESSVALUE, "ProgressValue");
PCR_CONSTASCII_STRING( PROPERTY_PROGRESSVALUE_MIN, "ProgressValueMin");
PCR_CONSTASCII_STRING( PROPERTY_PROGRESSVALUE_MAX, "ProgressValueMax");
PCR_CONSTASCII_STRING( PROPERTY_SCROLLVALUE, "ScrollValue");
PCR_CONSTASCII_STRING( PROPERTY_SCROLLVALUE_MAX, "ScrollValueMax");
PCR_CONSTASCII_STRING( PROPERTY_LINEINCREMENT, "LineIncrement");
PCR_CONSTASCII_STRING( PROPERTY_BLOCKINCREMENT, "BlockIncrement");
PCR_CONSTASCII_STRING( PROPERTY_VISIBLESIZE, "VisibleSize");
PCR_CONSTASCII_STRING( PROPERTY_ORIENTATION, "Orientation");
PCR_CONSTASCII_STRING( PROPERTY_IMAGEALIGN, "ImageAlign");
PCR_CONSTASCII_STRING( PROPERTY_ACTIVE_CONNECTION, "ActiveConnection");
PCR_CONSTASCII_STRING( PROPERTY_DATE, "Date");
PCR_CONSTASCII_STRING( PROPERTY_STATE, "State");
PCR_CONSTASCII_STRING( PROPERTY_TIME, "Time");
PCR_CONSTASCII_STRING( PROPERTY_SCALEIMAGE, "ScaleImage");
PCR_CONSTASCII_STRING( PROPERTY_PUSHBUTTONTYPE, "PushButtonType");
PCR_CONSTASCII_STRING( PROPERTY_EFFECTIVE_VALUE, "EffectiveValue");
PCR_CONSTASCII_STRING( PROPERTY_BOUND_CELL, "BoundCell");
PCR_CONSTASCII_STRING( PROPERTY_LIST_CELL_RANGE, "CellRange");
PCR_CONSTASCII_STRING( PROPERTY_ADDRESS, "Address");
PCR_CONSTASCII_STRING( PROPERTY_REFERENCE_SHEET, "ReferenceSheet");
PCR_CONSTASCII_STRING( PROPERTY_UI_REPRESENTATION, "UserInterfaceRepresentation");
// "virtual" properties (not to be used with real property sets)
PCR_CONSTASCII_STRING( PROPERTY_CELL_EXCHANGE_TYPE, "ExchangeSelectionIndex");
// services
PCR_CONSTASCII_STRING( SERVICE_COMPONENT_GROUPBOX, "com.sun.star.form.component.GroupBox");
PCR_CONSTASCII_STRING( SERVICE_COMPONENT_FIXEDTEXT, "com.sun.star.form.component.FixedText");
PCR_CONSTASCII_STRING( SERVICE_COMPONENT_FORMATTEDFIELD,"com.sun.star.form.component.FormattedField");
PCR_CONSTASCII_STRING( SERVICE_DATABASE_CONTEXT, "com.sun.star.sdb.DatabaseContext");
PCR_CONSTASCII_STRING( SERVICE_SPREADSHEET_DOCUMENT, "com.sun.star.sheet.SpreadsheetDocument");
PCR_CONSTASCII_STRING( SERVICE_SHEET_CELL_BINDING, "drafts.com.sun.star.table.CellValueBinding");
PCR_CONSTASCII_STRING( SERVICE_SHEET_CELL_INT_BINDING, "drafts.com.sun.star.table.ListPositionCellBinding");
PCR_CONSTASCII_STRING( SERVICE_SHEET_CELLRANGE_LISTSOURCE, "drafts.com.sun.star.table.CellRangeListSource");
PCR_CONSTASCII_STRING( SERVICE_ADDRESS_CONVERSION, "com.sun.star.table.CellAddressConversion");
PCR_CONSTASCII_STRING( SERVICE_RANGEADDRESS_CONVERSION, "com.sun.star.table.CellRangeAddressConversion");
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_
<|endoftext|> |
<commit_before>/** \brief Convert WiBiLex/WiRelex Database entries to MARC 21 Records
* \author Johannes Riedl
*
* \copyright 2022 Universitätsbibliothek Tübingen. All rights reserved.
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include "DbConnection.h"
#include "FileUtil.h"
#include "HtmlUtil.h"
#include "IniFile.h"
#include "MARC.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "UBTools.h"
#include "util.h"
namespace {
using ConversionFunctor = std::function<void(const std::string, const char, MARC::Record * const, const std::string)>;
enum BIBWISS_TYPES { WIBILEX, WIRELEX };
const char SEPARATOR_CHAR('|');
const std::map<int, std::string> BIBWISS_TYPE_TO_STRING{ { BIBWISS_TYPES::WIRELEX, "WiReLex" }, { BIBWISS_TYPES::WIBILEX, "WiBiLex" } };
const std::string GetStringForBibWissType(enum BIBWISS_TYPES type) {
const auto type_pair(BIBWISS_TYPE_TO_STRING.find(type));
if (type_pair == BIBWISS_TYPE_TO_STRING.end())
LOG_ERROR("Invalid type \"" + std::to_string(type) + "\"");
return type_pair->second;
}
struct DbFieldToMARCMapping {
const std::string db_field_name_;
const std::string marc_tag_;
const char subfield_code_;
std::function<void(MARC::Record * const, const std::string)> extraction_function_;
DbFieldToMARCMapping(const std::string &db_field_name, const std::string marc_tag, const char subfield_code,
ConversionFunctor extraction_function)
: db_field_name_(db_field_name), marc_tag_(marc_tag), subfield_code_(subfield_code),
extraction_function_(std::bind(extraction_function, marc_tag, subfield_code, std::placeholders::_1, std::placeholders::_2)) { }
};
const auto DbFieldToMarcMappingComparator = [](const DbFieldToMARCMapping &lhs, const DbFieldToMARCMapping &rhs) {
return lhs.db_field_name_ < rhs.db_field_name_;
};
using DbFieldToMARCMappingMultiset = std::multiset<DbFieldToMARCMapping, decltype(DbFieldToMarcMappingComparator)>;
MARC::Record *CreateNewRecord(const std::string &bibwiss_id, const BIBWISS_TYPES type) {
std::ostringstream formatted_number;
formatted_number << std::setfill('0') << std::setw(8) << std::atoi(bibwiss_id.c_str());
const std::string prefix(type == BIBWISS_TYPES::WIRELEX ? "BRE" : "BBI");
const std::string ppn(prefix + formatted_number.str());
return new MARC::Record(MARC::Record::TypeOfRecord::LANGUAGE_MATERIAL, MARC::Record::BibliographicLevel::UNDEFINED, ppn);
}
[[noreturn]] void Usage() {
::Usage("db_inifile map_file marc_output");
}
void InsertField(const std::string &tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
if (data.length())
record->insertField(tag, subfield_code, data);
}
void InsertCreationField(const std::string &tag, const char, MARC::Record * const record, const std::string &data) {
if (data.length()) {
static ThreadSafeRegexMatcher date_matcher("((\\d{4})-\\d{2}-\\d{2})");
if (const auto &match_result = date_matcher.match(data)) {
if (match_result[1] == "0000-00-00")
record->insertField(tag, "000101s2000 x ||||| 00| ||ger c");
else
record->insertField(
tag, StringUtil::Filter(match_result[1], "-").substr(2) + "s" + match_result[2] + " xx ||||| 00| ||ger c");
return;
} else
LOG_ERROR("Invalid date format \"" + data + "\"");
}
// Fallback with dummy data
record->insertField(tag, "000101s2000 xx ||||| 00| ||ger c");
}
void InsertAuthors(const std::string, const char, MARC::Record * const record, const std::string &data) {
if (data.length()) {
std::vector<std::string> authors;
std::string author, further_parts;
std::string data_to_split(data);
while (StringUtil::SplitOnString(data_to_split, " and ", &author, &further_parts)) {
authors.emplace_back(author);
data_to_split = further_parts;
}
authors.emplace_back(data_to_split);
record->insertField("100", { { 'a', authors[0] }, { '4', "aut" }, { 'e', "VerfasserIn" } });
for (auto further_author = authors.begin() + 1; further_author != authors.end(); ++further_author)
record->insertField("700", { { 'a', *further_author }, { '4', "aut" }, { 'e', "VerfasserIn" } });
}
}
void InsertOrForceSubfield(const std::string &tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
if (data.length()) {
if (not record->hasTag(tag)) {
InsertField(tag, subfield_code, record, data);
return;
}
for (auto &field : record->getTagRange(tag)) {
// FIXME: Do not necessarily replace
field.insertOrReplaceSubfield(subfield_code, data);
}
}
}
void InsertEditors(const std::string, const char, MARC::Record * const record, const std::string &data) {
if (data.length()) {
std::vector<std::string> editors;
std::string editor, further_parts;
std::string data_to_split(data);
while (StringUtil::SplitOnString(data_to_split, " and ", &editor, &further_parts)) {
editors.emplace_back(editor);
data_to_split = further_parts;
}
for (const auto &further_editor : editors)
record->insertField("700", { { 'a', further_editor }, { '4', "edt" }, { 'e', "HerausgeberIn" } });
}
}
void InsertStripped(const std::string tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
if (data.length()) {
std::string field_content;
if (data.length() > MARC::Record::MAX_VARIABLE_FIELD_DATA_LENGTH - MARC::Record::TAG_LENGTH)
field_content = StringUtil::Truncate(MARC::Record::MAX_VARIABLE_FIELD_DATA_LENGTH - MARC::Record::TAG_LENGTH - 4, data) + "...";
else
field_content = data;
record->insertField(tag, { { subfield_code, field_content } });
}
}
void InsertStrippedRemoveHTML(const std::string tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
InsertStripped(tag, subfield_code, record, HtmlUtil::StripHtmlTags(data));
}
void ConvertArticles(DbConnection * const db_connection, const DbFieldToMARCMappingMultiset &dbfield_to_marc_mappings,
MARC::Writer * const marc_writer) {
static unsigned ppn_index(0);
for (const auto bibwiss_type : { BIBWISS_TYPES::WIBILEX, BIBWISS_TYPES::WIRELEX }) {
const std::string bibwiss_query("SELECT * FROM articles where encyclopedia_id"
" IN (SELECT id FROM encyclopedias WHERE name='"
+ GetStringForBibWissType(bibwiss_type) + "')"
" ORDER BY name ASC");
db_connection->queryOrDie(bibwiss_query);
DbResultSet result_set(db_connection->getLastResultSet());
while (const auto row = result_set.getNextRow()) {
MARC::Record * const new_record(CreateNewRecord(std::to_string(++ppn_index), bibwiss_type));
for (auto dbfield_to_marc_mapping(dbfield_to_marc_mappings.begin()); dbfield_to_marc_mapping != dbfield_to_marc_mappings.end();
++dbfield_to_marc_mapping)
{
dbfield_to_marc_mapping->extraction_function_(new_record, row[dbfield_to_marc_mapping->db_field_name_]);
}
// Dummy entries
new_record->insertField("005", TimeUtil::GetCurrentDateAndTime("%Y%m%d%H%M%S") + ".0");
marc_writer->write(*new_record);
delete new_record;
}
ppn_index = 0;
}
}
const std::map<std::string, ConversionFunctor> name_to_functor_map{ { "InsertField", InsertField },
{ "InsertCreationField", InsertCreationField },
{ "InsertAuthors", InsertAuthors },
{ "InsertOrForceSubfield", InsertOrForceSubfield },
{ "InsertEditors", InsertEditors },
{ "InsertStripped", InsertStripped },
{ "InsertStrippedRemoveHTML", InsertStrippedRemoveHTML } };
ConversionFunctor GetConversionFunctor(const std::string &functor_name) {
if (not name_to_functor_map.contains(functor_name))
LOG_ERROR("Unknown functor " + functor_name);
return name_to_functor_map.find(functor_name)->second;
}
void ExtractTagAndSubfield(const std::string combined, std::string *tag, char *subfield_code) {
bool is_no_subfield_tag(StringUtil::StartsWith(combined, "00"));
if (combined.length() != 4 and not is_no_subfield_tag)
LOG_ERROR("Invalid Tag and Subfield format " + combined);
*tag = combined.substr(0, 3);
*subfield_code = is_no_subfield_tag ? ' ' : combined[3];
}
void CreateDbFieldToMarcMappings(File * const map_file, DbFieldToMARCMappingMultiset * const dbfield_to_marc_mappings) {
unsigned linenum(0);
while (not map_file->eof()) {
++linenum;
std::string line;
map_file->getline(&line);
StringUtil::Trim(&line);
std::vector<std::string> mapping;
StringUtil::SplitThenTrim(line, SEPARATOR_CHAR, " \t", &mapping);
if (unlikely(mapping.size() < 2 and line.back() != SEPARATOR_CHAR)) {
LOG_WARNING("Invalid line format in line " + std::to_string(linenum));
continue;
}
static ThreadSafeRegexMatcher tag_subfield_and_functorname("(?i)([a-z0-9]{3,4})\\s+\\((\\p{L}+)\\)\\s*");
const std::vector<std::string> extraction_rules(mapping.begin() + 1, mapping.end());
for (const auto &extraction_rule : extraction_rules) {
std::string tag;
char subfield_code;
ConversionFunctor conversion_functor;
if (const auto match_result = tag_subfield_and_functorname.match(extraction_rule)) {
ExtractTagAndSubfield(match_result[1], &tag, &subfield_code);
conversion_functor = GetConversionFunctor(match_result[2]);
} else if (extraction_rule.length() >= 3 && extraction_rule.length() <= 4) {
ExtractTagAndSubfield(extraction_rule, &tag, &subfield_code);
conversion_functor = GetConversionFunctor("InsertField");
} else
LOG_ERROR("Invalid extraction rule: " + extraction_rule);
dbfield_to_marc_mappings->emplace(DbFieldToMARCMapping(mapping[0], tag, subfield_code, conversion_functor));
}
}
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
Usage();
const std::string ini_file_path(argv[1]);
const std::string map_file_path(argv[2]);
const std::string marc_output_path(argv[3]);
DbConnection db_connection(DbConnection::PostgresFactory(IniFile(ini_file_path)));
std::unique_ptr<File> map_file(FileUtil::OpenInputFileOrDie(map_file_path));
const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_path));
DbFieldToMARCMappingMultiset dbfield_to_marc_mappings(DbFieldToMarcMappingComparator);
CreateDbFieldToMarcMappings(map_file.get(), &dbfield_to_marc_mappings);
ConvertArticles(&db_connection, dbfield_to_marc_mappings, marc_writer.get());
return EXIT_SUCCESS;
}
<commit_msg>Add dictionary entry identifier and superior work information<commit_after>/** \brief Convert WiBiLex/WiRelex Database entries to MARC 21 Records
* \author Johannes Riedl
*
* \copyright 2022 Universitätsbibliothek Tübingen. All rights reserved.
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include "DbConnection.h"
#include "FileUtil.h"
#include "HtmlUtil.h"
#include "IniFile.h"
#include "MARC.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "UBTools.h"
#include "util.h"
namespace {
using ConversionFunctor = std::function<void(const std::string, const char, MARC::Record * const, const std::string)>;
enum BIBWISS_TYPES { WIBILEX, WIRELEX };
const char SEPARATOR_CHAR('|');
const std::map<int, std::string> BIBWISS_TYPE_TO_STRING{ { BIBWISS_TYPES::WIRELEX, "WiReLex" }, { BIBWISS_TYPES::WIBILEX, "WiBiLex" } };
const std::string GetStringForBibWissType(enum BIBWISS_TYPES type) {
const auto type_pair(BIBWISS_TYPE_TO_STRING.find(type));
if (type_pair == BIBWISS_TYPE_TO_STRING.end())
LOG_ERROR("Invalid type \"" + std::to_string(type) + "\"");
return type_pair->second;
}
struct DbFieldToMARCMapping {
const std::string db_field_name_;
const std::string marc_tag_;
const char subfield_code_;
std::function<void(MARC::Record * const, const std::string)> extraction_function_;
DbFieldToMARCMapping(const std::string &db_field_name, const std::string marc_tag, const char subfield_code,
ConversionFunctor extraction_function)
: db_field_name_(db_field_name), marc_tag_(marc_tag), subfield_code_(subfield_code),
extraction_function_(std::bind(extraction_function, marc_tag, subfield_code, std::placeholders::_1, std::placeholders::_2)) { }
};
const auto DbFieldToMarcMappingComparator = [](const DbFieldToMARCMapping &lhs, const DbFieldToMARCMapping &rhs) {
return lhs.db_field_name_ < rhs.db_field_name_;
};
using DbFieldToMARCMappingMultiset = std::multiset<DbFieldToMARCMapping, decltype(DbFieldToMarcMappingComparator)>;
MARC::Record *CreateNewRecord(const std::string &bibwiss_id, const BIBWISS_TYPES type) {
std::ostringstream formatted_number;
formatted_number << std::setfill('0') << std::setw(8) << std::atoi(bibwiss_id.c_str());
const std::string prefix(type == BIBWISS_TYPES::WIRELEX ? "BRE" : "BBI");
const std::string ppn(prefix + formatted_number.str());
return new MARC::Record(MARC::Record::TypeOfRecord::LANGUAGE_MATERIAL, MARC::Record::BibliographicLevel::UNDEFINED, ppn);
}
[[noreturn]] void Usage() {
::Usage("db_inifile map_file marc_output");
}
void InsertField(const std::string &tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
if (data.length())
record->insertField(tag, subfield_code, data);
}
void InsertCreationField(const std::string &tag, const char, MARC::Record * const record, const std::string &data) {
if (data.length()) {
static ThreadSafeRegexMatcher date_matcher("((\\d{4})-\\d{2}-\\d{2})");
if (const auto &match_result = date_matcher.match(data)) {
if (match_result[1] == "0000-00-00")
record->insertField(tag, "000101s2000 x ||||| 00| ||ger c");
else
record->insertField(
tag, StringUtil::Filter(match_result[1], "-").substr(2) + "s" + match_result[2] + " xx ||||| 00| ||ger c");
return;
} else
LOG_ERROR("Invalid date format \"" + data + "\"");
}
// Fallback with dummy data
record->insertField(tag, "000101s2000 xx ||||| 00| ||ger c");
}
void InsertAuthors(const std::string, const char, MARC::Record * const record, const std::string &data) {
if (data.length()) {
std::vector<std::string> authors;
std::string author, further_parts;
std::string data_to_split(data);
while (StringUtil::SplitOnString(data_to_split, " and ", &author, &further_parts)) {
authors.emplace_back(author);
data_to_split = further_parts;
}
authors.emplace_back(data_to_split);
record->insertField("100", { { 'a', authors[0] }, { '4', "aut" }, { 'e', "VerfasserIn" } });
for (auto further_author = authors.begin() + 1; further_author != authors.end(); ++further_author)
record->insertField("700", { { 'a', *further_author }, { '4', "aut" }, { 'e', "VerfasserIn" } });
}
}
void InsertOrForceSubfield(const std::string &tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
if (data.length()) {
if (not record->hasTag(tag)) {
InsertField(tag, subfield_code, record, data);
return;
}
for (auto &field : record->getTagRange(tag)) {
// FIXME: Do not necessarily replace
field.insertOrReplaceSubfield(subfield_code, data);
}
}
}
void InsertEditors(const std::string, const char, MARC::Record * const record, const std::string &data) {
if (data.length()) {
std::vector<std::string> editors;
std::string editor, further_parts;
std::string data_to_split(data);
while (StringUtil::SplitOnString(data_to_split, " and ", &editor, &further_parts)) {
editors.emplace_back(editor);
data_to_split = further_parts;
}
for (const auto &further_editor : editors)
record->insertField("700", { { 'a', further_editor }, { '4', "edt" }, { 'e', "HerausgeberIn" } });
}
}
void InsertStripped(const std::string tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
if (data.length()) {
std::string field_content;
if (data.length() > MARC::Record::MAX_VARIABLE_FIELD_DATA_LENGTH - MARC::Record::TAG_LENGTH)
field_content = StringUtil::Truncate(MARC::Record::MAX_VARIABLE_FIELD_DATA_LENGTH - MARC::Record::TAG_LENGTH - 4, data) + "...";
else
field_content = data;
record->insertField(tag, { { subfield_code, field_content } });
}
}
void InsertStrippedRemoveHTML(const std::string tag, const char subfield_code, MARC::Record * const record, const std::string &data) {
InsertStripped(tag, subfield_code, record, HtmlUtil::StripHtmlTags(data));
}
MARC::Subfields GetSuperiorWorkDescription(enum BIBWISS_TYPES type) {
switch (type) {
case BIBWISS_TYPES::WIBILEX:
return MARC::Subfields({ { 'i', "Enhalten in" },
{ 't', "Das wissenschaftliche Bibellexikon im Internet" },
{ 'd', "Stuttgart : Deutsche Bibelgesellschaft, 2004" },
{ 'g', "JAHRYYY" },
{ 'h', "Online-Ressource" },
{ 'w', "(DE-627)896670716" },
{ 'w', "(DE-600)2903948-4" },
{ 'w', "(DE-576)49274064X" } });
case BIBWISS_TYPES::WIRELEX:
return MARC::Subfields({ { 'i', "Enhalten in" },
{ 't', "WiReLex - das wissenschaftlich-religionspädagogische Lexikon im Internet " },
{ 'd', "Stuttgart : Deutsche Bibelgesellschaft, 2015" },
{ 'g', "JAHRXXXX" },
{ 'h', "Online-Ressource" },
{ 'w', "(DE627)896670740" },
{ 'w', "(DE600)2903951-4" },
{ 'w', "(DE576)492740909" } });
default:
LOG_ERROR("Invalid BibWiss type: " + std::to_string(type));
}
}
void ConvertArticles(DbConnection * const db_connection, const DbFieldToMARCMappingMultiset &dbfield_to_marc_mappings,
MARC::Writer * const marc_writer) {
static unsigned ppn_index(0);
for (const auto bibwiss_type : { BIBWISS_TYPES::WIBILEX, BIBWISS_TYPES::WIRELEX }) {
const std::string bibwiss_query("SELECT * FROM articles where encyclopedia_id"
" IN (SELECT id FROM encyclopedias WHERE name='"
+ GetStringForBibWissType(bibwiss_type) + "')"
" ORDER BY name ASC");
db_connection->queryOrDie(bibwiss_query);
DbResultSet result_set(db_connection->getLastResultSet());
while (const auto row = result_set.getNextRow()) {
MARC::Record * const new_record(CreateNewRecord(std::to_string(++ppn_index), bibwiss_type));
for (auto dbfield_to_marc_mapping(dbfield_to_marc_mappings.begin()); dbfield_to_marc_mapping != dbfield_to_marc_mappings.end();
++dbfield_to_marc_mapping)
{
dbfield_to_marc_mapping->extraction_function_(new_record, row[dbfield_to_marc_mapping->db_field_name_]);
}
// Dummy entries
new_record->insertField("005", TimeUtil::GetCurrentDateAndTime("%Y%m%d%H%M%S") + ".0");
// Make sure we are a dictionary entry/article
new_record->insertField("935", { { 'c', "uwlx" } });
new_record->insertField("773", GetSuperiorWorkDescription(bibwiss_type));
marc_writer->write(*new_record);
delete new_record;
}
ppn_index = 0;
}
}
const std::map<std::string, ConversionFunctor> name_to_functor_map{ { "InsertField", InsertField },
{ "InsertCreationField", InsertCreationField },
{ "InsertAuthors", InsertAuthors },
{ "InsertOrForceSubfield", InsertOrForceSubfield },
{ "InsertEditors", InsertEditors },
{ "InsertStripped", InsertStripped },
{ "InsertStrippedRemoveHTML", InsertStrippedRemoveHTML } };
ConversionFunctor GetConversionFunctor(const std::string &functor_name) {
if (not name_to_functor_map.contains(functor_name))
LOG_ERROR("Unknown functor " + functor_name);
return name_to_functor_map.find(functor_name)->second;
}
void ExtractTagAndSubfield(const std::string combined, std::string *tag, char *subfield_code) {
bool is_no_subfield_tag(StringUtil::StartsWith(combined, "00"));
if (combined.length() != 4 and not is_no_subfield_tag)
LOG_ERROR("Invalid Tag and Subfield format " + combined);
*tag = combined.substr(0, 3);
*subfield_code = is_no_subfield_tag ? ' ' : combined[3];
}
void CreateDbFieldToMarcMappings(File * const map_file, DbFieldToMARCMappingMultiset * const dbfield_to_marc_mappings) {
unsigned linenum(0);
while (not map_file->eof()) {
++linenum;
std::string line;
map_file->getline(&line);
StringUtil::Trim(&line);
std::vector<std::string> mapping;
StringUtil::SplitThenTrim(line, SEPARATOR_CHAR, " \t", &mapping);
if (unlikely(mapping.size() < 2 and line.back() != SEPARATOR_CHAR)) {
LOG_WARNING("Invalid line format in line " + std::to_string(linenum));
continue;
}
static ThreadSafeRegexMatcher tag_subfield_and_functorname("(?i)([a-z0-9]{3,4})\\s+\\((\\p{L}+)\\)\\s*");
const std::vector<std::string> extraction_rules(mapping.begin() + 1, mapping.end());
for (const auto &extraction_rule : extraction_rules) {
std::string tag;
char subfield_code;
ConversionFunctor conversion_functor;
if (const auto match_result = tag_subfield_and_functorname.match(extraction_rule)) {
ExtractTagAndSubfield(match_result[1], &tag, &subfield_code);
conversion_functor = GetConversionFunctor(match_result[2]);
} else if (extraction_rule.length() >= 3 && extraction_rule.length() <= 4) {
ExtractTagAndSubfield(extraction_rule, &tag, &subfield_code);
conversion_functor = GetConversionFunctor("InsertField");
} else
LOG_ERROR("Invalid extraction rule: " + extraction_rule);
dbfield_to_marc_mappings->emplace(DbFieldToMARCMapping(mapping[0], tag, subfield_code, conversion_functor));
}
}
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
Usage();
const std::string ini_file_path(argv[1]);
const std::string map_file_path(argv[2]);
const std::string marc_output_path(argv[3]);
DbConnection db_connection(DbConnection::PostgresFactory(IniFile(ini_file_path)));
std::unique_ptr<File> map_file(FileUtil::OpenInputFileOrDie(map_file_path));
const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_path));
DbFieldToMARCMappingMultiset dbfield_to_marc_mappings(DbFieldToMarcMappingComparator);
CreateDbFieldToMarcMappings(map_file.get(), &dbfield_to_marc_mappings);
ConvertArticles(&db_connection, dbfield_to_marc_mappings, marc_writer.get());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: usercontrol.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2007-05-10 10:50:39 $
*
* 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_extensions.hxx"
#ifndef _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_
#include "usercontrol.hxx"
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_INSPECTION_PROPERTYCONTROLTYPE_HPP_
#include <com/sun/star/inspection/PropertyControlType.hpp>
#endif
#ifndef _COM_SUN_STAR_INSPECTION_PROPERTYCONTROLTYPE_HPP_
#include <com/sun/star/inspection/PropertyControlType.hpp>
#endif
/** === end UNO includes === **/
#ifndef _NUMUNO_HXX
#include <svtools/numuno.hxx>
#endif
#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _ZFORMAT_HXX
#include <svtools/zformat.hxx>
#endif
//............................................................................
namespace pcr
{
//............................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Type;
using ::com::sun::star::beans::IllegalTypeException;
using ::com::sun::star::uno::RuntimeException;
/** === end UNO using === **/
namespace PropertyControlType = ::com::sun::star::inspection::PropertyControlType;
//==================================================================
// NumberFormatSampleField
//==================================================================
//------------------------------------------------------------------
long NumberFormatSampleField::PreNotify( NotifyEvent& rNEvt )
{
// want to handle two keys myself : Del/Backspace should empty the window (setting my prop to "standard" this way)
if (EVENT_KEYINPUT == rNEvt.GetType())
{
sal_uInt16 nKey = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();
if ((KEY_DELETE == nKey) || (KEY_BACKSPACE == nKey))
{
SetText( String() );
if ( m_pHelper )
m_pHelper->ModifiedHdl( this );
return 1;
}
}
return BaseClass::PreNotify( rNEvt );
}
//------------------------------------------------------------------
void NumberFormatSampleField::SetFormatSupplier( const SvNumberFormatsSupplierObj* pSupplier )
{
if ( pSupplier )
{
TreatAsNumber( sal_True );
SvNumberFormatter* pFormatter = pSupplier->GetNumberFormatter();
SetFormatter( pFormatter, sal_True );
SetValue( 1234.56789 );
}
else
{
TreatAsNumber( sal_False );
SetFormatter( NULL, sal_True );
SetText( String() );
}
}
//==================================================================
// OFormatSampleControl
//==================================================================
//------------------------------------------------------------------
OFormatSampleControl::OFormatSampleControl( Window* pParent, WinBits nWinStyle )
:OFormatSampleControl_Base( PropertyControlType::Unknown, pParent, nWinStyle )
{
}
//------------------------------------------------------------------
void SAL_CALL OFormatSampleControl::setValue( const Any& _rValue ) throw (IllegalTypeException, RuntimeException)
{
sal_Int32 nFormatKey = 0;
if ( _rValue >>= nFormatKey )
{
// else set the new format key, the text will be reformatted
getTypedControlWindow()->SetValue( 1234.56789 );
getTypedControlWindow()->SetFormatKey( nFormatKey );
}
else
getTypedControlWindow()->SetText( String() );
}
//------------------------------------------------------------------
Any SAL_CALL OFormatSampleControl::getValue() throw (RuntimeException)
{
Any aPropValue;
if ( getTypedControlWindow()->GetText().Len() )
aPropValue <<= (sal_Int32)getTypedControlWindow()->GetFormatKey();
return aPropValue;
}
//------------------------------------------------------------------
Type SAL_CALL OFormatSampleControl::getValueType() throw (RuntimeException)
{
return ::getCppuType( static_cast< sal_Int32* >( NULL ) );
}
//==================================================================
// class OFormattedNumericControl
//==================================================================
DBG_NAME(OFormattedNumericControl);
//------------------------------------------------------------------
OFormattedNumericControl::OFormattedNumericControl( Window* pParent, WinBits nWinStyle )
:OFormattedNumericControl_Base( PropertyControlType::Unknown, pParent, nWinStyle )
{
DBG_CTOR(OFormattedNumericControl,NULL);
getTypedControlWindow()->TreatAsNumber(sal_True);
m_nLastDecimalDigits = getTypedControlWindow()->GetDecimalDigits();
}
//------------------------------------------------------------------
OFormattedNumericControl::~OFormattedNumericControl()
{
DBG_DTOR(OFormattedNumericControl,NULL);
}
//------------------------------------------------------------------
void SAL_CALL OFormattedNumericControl::setValue( const Any& _rValue ) throw (IllegalTypeException, RuntimeException)
{
double nValue( 0 );
if ( _rValue >>= nValue )
getTypedControlWindow()->SetValue( nValue );
else
getTypedControlWindow()->SetText(String());
}
//------------------------------------------------------------------
Any SAL_CALL OFormattedNumericControl::getValue() throw (RuntimeException)
{
Any aPropValue;
if ( getTypedControlWindow()->GetText().Len() )
aPropValue <<= (double)getTypedControlWindow()->GetValue();
return aPropValue;
}
//------------------------------------------------------------------
Type SAL_CALL OFormattedNumericControl::getValueType() throw (RuntimeException)
{
return ::getCppuType( static_cast< double* >( NULL ) );
}
//------------------------------------------------------------------
void OFormattedNumericControl::SetFormatDescription(const FormatDescription& rDesc)
{
sal_Bool bFallback = sal_True;
if (rDesc.pSupplier)
{
getTypedControlWindow()->TreatAsNumber(sal_True);
SvNumberFormatter* pFormatter = rDesc.pSupplier->GetNumberFormatter();
if (pFormatter != getTypedControlWindow()->GetFormatter())
getTypedControlWindow()->SetFormatter(pFormatter, sal_True);
getTypedControlWindow()->SetFormatKey(rDesc.nKey);
const SvNumberformat* pEntry = getTypedControlWindow()->GetFormatter()->GetEntry(getTypedControlWindow()->GetFormatKey());
DBG_ASSERT( pEntry, "OFormattedNumericControl::SetFormatDescription: invalid format key!" );
if ( pEntry )
{
switch (pEntry->GetType() & ~NUMBERFORMAT_DEFINED)
{
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_FRACTION:
case NUMBERFORMAT_PERCENT:
m_nLastDecimalDigits = getTypedControlWindow()->GetDecimalDigits();
break;
case NUMBERFORMAT_DATETIME:
case NUMBERFORMAT_DATE:
case NUMBERFORMAT_TIME:
m_nLastDecimalDigits = 7;
break;
default:
m_nLastDecimalDigits = 0;
break;
}
bFallback = sal_False;
}
}
if ( bFallback )
{
getTypedControlWindow()->TreatAsNumber(sal_False);
getTypedControlWindow()->SetFormatter(NULL, sal_True);
getTypedControlWindow()->SetText(String());
m_nLastDecimalDigits = 0;
}
}
//========================================================================
//= OFileUrlControl
//========================================================================
//------------------------------------------------------------------
OFileUrlControl::OFileUrlControl( Window* pParent, WinBits nWinStyle )
:OFileUrlControl_Base( PropertyControlType::Unknown, pParent, nWinStyle | WB_DROPDOWN )
{
getTypedControlWindow()->SetDropDownLineCount( 10 );
}
//------------------------------------------------------------------
OFileUrlControl::~OFileUrlControl()
{
}
//------------------------------------------------------------------
void SAL_CALL OFileUrlControl::setValue( const Any& _rValue ) throw (IllegalTypeException, RuntimeException)
{
::rtl::OUString sURL;
if ( _rValue >>= sURL )
getTypedControlWindow()->DisplayURL( sURL );
else
getTypedControlWindow()->SetText( String() );
}
//------------------------------------------------------------------
Any SAL_CALL OFileUrlControl::getValue() throw (RuntimeException)
{
Any aPropValue;
if ( getTypedControlWindow()->GetText().Len() )
aPropValue <<= (::rtl::OUString)getTypedControlWindow()->GetURL();
return aPropValue;
}
//------------------------------------------------------------------
Type SAL_CALL OFileUrlControl::getValueType() throw (RuntimeException)
{
return ::getCppuType( static_cast< ::rtl::OUString* >( NULL ) );
}
//========================================================================
//= OTimeDurationControl
//========================================================================
//------------------------------------------------------------------
OTimeDurationControl::OTimeDurationControl( ::Window* pParent, WinBits nWinStyle )
:ONumericControl( pParent, nWinStyle )
{
getTypedControlWindow()->SetUnit( FUNIT_CUSTOM );
getTypedControlWindow()->SetCustomUnitText( String::CreateFromAscii( " ms" ) );
getTypedControlWindow()->SetCustomConvertHdl( LINK( this, OTimeDurationControl, OnCustomConvert ) );
}
//------------------------------------------------------------------
OTimeDurationControl::~OTimeDurationControl()
{
}
//------------------------------------------------------------------
::sal_Int16 SAL_CALL OTimeDurationControl::getControlType() throw (::com::sun::star::uno::RuntimeException)
{
// don't use the base class'es method, it would claim we're a standard control, which
// we in fact aren't
return PropertyControlType::Unknown;
}
//------------------------------------------------------------------
IMPL_LINK( OTimeDurationControl, OnCustomConvert, MetricField*, /*pField*/ )
{
long nMultiplier = 1;
if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "ms" ) )
nMultiplier = 1;
if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "s" ) )
nMultiplier = 1000;
else if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "m" ) )
nMultiplier = 1000 * 60;
else if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "h" ) )
nMultiplier = 1000 * 60 * 60;
getTypedControlWindow()->SetValue( getTypedControlWindow()->GetLastValue() * nMultiplier );
return 0L;
}
//............................................................................
} // namespace pcr
//............................................................................
<commit_msg>INTEGRATION: CWS reportdesign01 (1.10.82); FILE MERGED 2007/10/16 10:56:29 oj 1.10.82.1: #i78403# use current date or time as preview value for the format dialog and string<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: usercontrol.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: ihi $ $Date: 2007-11-20 19:53:00 $
*
* 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_extensions.hxx"
#ifndef _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_
#include "usercontrol.hxx"
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_INSPECTION_PROPERTYCONTROLTYPE_HPP_
#include <com/sun/star/inspection/PropertyControlType.hpp>
#endif
#ifndef _COM_SUN_STAR_INSPECTION_PROPERTYCONTROLTYPE_HPP_
#include <com/sun/star/inspection/PropertyControlType.hpp>
#endif
/** === end UNO includes === **/
#ifndef _NUMUNO_HXX
#include <svtools/numuno.hxx>
#endif
#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _ZFORMAT_HXX
#include <svtools/zformat.hxx>
#endif
#include <connectivity/dbconversion.hxx>
#include <com/sun/star/util/Time.hpp>
//............................................................................
namespace pcr
{
//............................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Type;
using ::com::sun::star::beans::IllegalTypeException;
using ::com::sun::star::uno::RuntimeException;
/** === end UNO using === **/
namespace PropertyControlType = ::com::sun::star::inspection::PropertyControlType;
//==================================================================
// NumberFormatSampleField
//==================================================================
//------------------------------------------------------------------
long NumberFormatSampleField::PreNotify( NotifyEvent& rNEvt )
{
// want to handle two keys myself : Del/Backspace should empty the window (setting my prop to "standard" this way)
if (EVENT_KEYINPUT == rNEvt.GetType())
{
sal_uInt16 nKey = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();
if ((KEY_DELETE == nKey) || (KEY_BACKSPACE == nKey))
{
SetText( String() );
if ( m_pHelper )
m_pHelper->ModifiedHdl( this );
return 1;
}
}
return BaseClass::PreNotify( rNEvt );
}
//------------------------------------------------------------------
void NumberFormatSampleField::SetFormatSupplier( const SvNumberFormatsSupplierObj* pSupplier )
{
if ( pSupplier )
{
TreatAsNumber( sal_True );
SvNumberFormatter* pFormatter = pSupplier->GetNumberFormatter();
SetFormatter( pFormatter, sal_True );
SetValue( 1234.56789 );
}
else
{
TreatAsNumber( sal_False );
SetFormatter( NULL, sal_True );
SetText( String() );
}
}
//==================================================================
// OFormatSampleControl
//==================================================================
//------------------------------------------------------------------
OFormatSampleControl::OFormatSampleControl( Window* pParent, WinBits nWinStyle )
:OFormatSampleControl_Base( PropertyControlType::Unknown, pParent, nWinStyle )
{
}
//------------------------------------------------------------------
void SAL_CALL OFormatSampleControl::setValue( const Any& _rValue ) throw (IllegalTypeException, RuntimeException)
{
sal_Int32 nFormatKey = 0;
if ( _rValue >>= nFormatKey )
{
// else set the new format key, the text will be reformatted
getTypedControlWindow()->SetFormatKey( nFormatKey );
SvNumberFormatter* pNF = getTypedControlWindow()->GetFormatter();
getTypedControlWindow()->SetValue( getPreviewValue(pNF,getTypedControlWindow()->GetFormatKey()) );
}
else
getTypedControlWindow()->SetText( String() );
}
//------------------------------------------------------------------
double OFormatSampleControl::getPreviewValue(SvNumberFormatter* _pNF,sal_Int32 _nFormatKey)
{
const SvNumberformat* pEntry = _pNF->GetEntry(_nFormatKey);
DBG_ASSERT( pEntry, "OFormattedNumericControl::SetFormatDescription: invalid format key!" );
double nValue = 1234.56789;
if ( pEntry )
{
switch (pEntry->GetType() & ~NUMBERFORMAT_DEFINED)
{
case NUMBERFORMAT_DATE:
{
Date aCurrentDate;
static ::com::sun::star::util::Date STANDARD_DB_DATE(30,12,1899);
nValue = ::dbtools::DBTypeConversion::toDouble(::dbtools::DBTypeConversion::toDate(static_cast<sal_Int32>(aCurrentDate.GetDate())),STANDARD_DB_DATE);
}
break;
case NUMBERFORMAT_TIME:
case NUMBERFORMAT_DATETIME:
{
Time aCurrentTime;
nValue = ::dbtools::DBTypeConversion::toDouble(::dbtools::DBTypeConversion::toTime(aCurrentTime.GetTime()));
}
break;
default:
break;
}
}
return nValue;
}
//------------------------------------------------------------------
Any SAL_CALL OFormatSampleControl::getValue() throw (RuntimeException)
{
Any aPropValue;
if ( getTypedControlWindow()->GetText().Len() )
aPropValue <<= (sal_Int32)getTypedControlWindow()->GetFormatKey();
return aPropValue;
}
//------------------------------------------------------------------
Type SAL_CALL OFormatSampleControl::getValueType() throw (RuntimeException)
{
return ::getCppuType( static_cast< sal_Int32* >( NULL ) );
}
//==================================================================
// class OFormattedNumericControl
//==================================================================
DBG_NAME(OFormattedNumericControl);
//------------------------------------------------------------------
OFormattedNumericControl::OFormattedNumericControl( Window* pParent, WinBits nWinStyle )
:OFormattedNumericControl_Base( PropertyControlType::Unknown, pParent, nWinStyle )
{
DBG_CTOR(OFormattedNumericControl,NULL);
getTypedControlWindow()->TreatAsNumber(sal_True);
m_nLastDecimalDigits = getTypedControlWindow()->GetDecimalDigits();
}
//------------------------------------------------------------------
OFormattedNumericControl::~OFormattedNumericControl()
{
DBG_DTOR(OFormattedNumericControl,NULL);
}
//------------------------------------------------------------------
void SAL_CALL OFormattedNumericControl::setValue( const Any& _rValue ) throw (IllegalTypeException, RuntimeException)
{
double nValue( 0 );
if ( _rValue >>= nValue )
getTypedControlWindow()->SetValue( nValue );
else
getTypedControlWindow()->SetText(String());
}
//------------------------------------------------------------------
Any SAL_CALL OFormattedNumericControl::getValue() throw (RuntimeException)
{
Any aPropValue;
if ( getTypedControlWindow()->GetText().Len() )
aPropValue <<= (double)getTypedControlWindow()->GetValue();
return aPropValue;
}
//------------------------------------------------------------------
Type SAL_CALL OFormattedNumericControl::getValueType() throw (RuntimeException)
{
return ::getCppuType( static_cast< double* >( NULL ) );
}
//------------------------------------------------------------------
void OFormattedNumericControl::SetFormatDescription(const FormatDescription& rDesc)
{
sal_Bool bFallback = sal_True;
if (rDesc.pSupplier)
{
getTypedControlWindow()->TreatAsNumber(sal_True);
SvNumberFormatter* pFormatter = rDesc.pSupplier->GetNumberFormatter();
if (pFormatter != getTypedControlWindow()->GetFormatter())
getTypedControlWindow()->SetFormatter(pFormatter, sal_True);
getTypedControlWindow()->SetFormatKey(rDesc.nKey);
const SvNumberformat* pEntry = getTypedControlWindow()->GetFormatter()->GetEntry(getTypedControlWindow()->GetFormatKey());
DBG_ASSERT( pEntry, "OFormattedNumericControl::SetFormatDescription: invalid format key!" );
if ( pEntry )
{
switch (pEntry->GetType() & ~NUMBERFORMAT_DEFINED)
{
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_FRACTION:
case NUMBERFORMAT_PERCENT:
m_nLastDecimalDigits = getTypedControlWindow()->GetDecimalDigits();
break;
case NUMBERFORMAT_DATETIME:
case NUMBERFORMAT_DATE:
case NUMBERFORMAT_TIME:
m_nLastDecimalDigits = 7;
break;
default:
m_nLastDecimalDigits = 0;
break;
}
bFallback = sal_False;
}
}
if ( bFallback )
{
getTypedControlWindow()->TreatAsNumber(sal_False);
getTypedControlWindow()->SetFormatter(NULL, sal_True);
getTypedControlWindow()->SetText(String());
m_nLastDecimalDigits = 0;
}
}
//========================================================================
//= OFileUrlControl
//========================================================================
//------------------------------------------------------------------
OFileUrlControl::OFileUrlControl( Window* pParent, WinBits nWinStyle )
:OFileUrlControl_Base( PropertyControlType::Unknown, pParent, nWinStyle | WB_DROPDOWN )
{
getTypedControlWindow()->SetDropDownLineCount( 10 );
}
//------------------------------------------------------------------
OFileUrlControl::~OFileUrlControl()
{
}
//------------------------------------------------------------------
void SAL_CALL OFileUrlControl::setValue( const Any& _rValue ) throw (IllegalTypeException, RuntimeException)
{
::rtl::OUString sURL;
if ( _rValue >>= sURL )
getTypedControlWindow()->DisplayURL( sURL );
else
getTypedControlWindow()->SetText( String() );
}
//------------------------------------------------------------------
Any SAL_CALL OFileUrlControl::getValue() throw (RuntimeException)
{
Any aPropValue;
if ( getTypedControlWindow()->GetText().Len() )
aPropValue <<= (::rtl::OUString)getTypedControlWindow()->GetURL();
return aPropValue;
}
//------------------------------------------------------------------
Type SAL_CALL OFileUrlControl::getValueType() throw (RuntimeException)
{
return ::getCppuType( static_cast< ::rtl::OUString* >( NULL ) );
}
//========================================================================
//= OTimeDurationControl
//========================================================================
//------------------------------------------------------------------
OTimeDurationControl::OTimeDurationControl( ::Window* pParent, WinBits nWinStyle )
:ONumericControl( pParent, nWinStyle )
{
getTypedControlWindow()->SetUnit( FUNIT_CUSTOM );
getTypedControlWindow()->SetCustomUnitText( String::CreateFromAscii( " ms" ) );
getTypedControlWindow()->SetCustomConvertHdl( LINK( this, OTimeDurationControl, OnCustomConvert ) );
}
//------------------------------------------------------------------
OTimeDurationControl::~OTimeDurationControl()
{
}
//------------------------------------------------------------------
::sal_Int16 SAL_CALL OTimeDurationControl::getControlType() throw (::com::sun::star::uno::RuntimeException)
{
// don't use the base class'es method, it would claim we're a standard control, which
// we in fact aren't
return PropertyControlType::Unknown;
}
//------------------------------------------------------------------
IMPL_LINK( OTimeDurationControl, OnCustomConvert, MetricField*, /*pField*/ )
{
long nMultiplier = 1;
if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "ms" ) )
nMultiplier = 1;
if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "s" ) )
nMultiplier = 1000;
else if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "m" ) )
nMultiplier = 1000 * 60;
else if ( getTypedControlWindow()->GetCurUnitText().EqualsIgnoreCaseAscii( "h" ) )
nMultiplier = 1000 * 60 * 60;
getTypedControlWindow()->SetValue( getTypedControlWindow()->GetLastValue() * nMultiplier );
return 0L;
}
//............................................................................
} // namespace pcr
//............................................................................
<|endoftext|> |
<commit_before>/*
* FileSystem.cpp
*
* Created on: Jun 20, 2014
* Author: Pimenta
*/
// this
#include "FileSystem.hpp"
using namespace std;
using namespace helpers;
map<string, FileSystem::Folder> FileSystem::folders;
void FileSystem::init() {
folders.clear();
folders["root"];
}
bool FileSystem::parseName(const string& name) {
static set<char> allowedChars;
static StaticInitializer staticInitializar([&]() {
for (char c = '0'; c <= '9'; c++)
allowedChars.insert(c);
for (char c = 'a'; c <= 'z'; c++)
allowedChars.insert(c);
for (char c = 'A'; c <= 'Z'; c++)
allowedChars.insert(c);
allowedChars.insert('_');
allowedChars.insert('-');
allowedChars.insert('+');
allowedChars.insert('.');
});
if (!name.size())
return false;
for (int i = 0; i < int(name.size()); i++) {
if (allowedChars.find(name[i]) != allowedChars.end())
return false;
}
return true;
}
bool FileSystem::parsePath(const string& path) {
if (!path.size())
return false;
list<string> atoms = explode(path, '/');
string tmp;
auto it = atoms.begin();
for (int i = 0; i < int(atoms.size()) - 1; i++) {
if (!parseName(*it))
return false;
tmp += (*it);
tmp += '/';
it++;
}
if (it != atoms.end()) {
if (!parseName(*it))
return false;
tmp += (*it);
}
return tmp == path;
}
bool FileSystem::createFolder(const string& fullPath) {
if (!parsePath(fullPath)) // if the path is invalid
return false;
if (folders.find(fullPath) != folders.end()) // if the folder already exists
return false;
pair<string, string> divided = divide(fullPath, '/');
auto motherFolder = folders.find(divided.first);
if (motherFolder == folders.end()) // if the mother folder doesn't exist
return false;
motherFolder->second.subfolders.insert(fullPath);
folders[fullPath];
return true;
}
FileSystem::Folder* FileSystem::retrieveFolder(const string& fullPath) {
auto folder = folders.find(fullPath);
if (folder == folders.end())
return nullptr;
return &folder->second;
}
bool FileSystem::updateFolder(const string& fullPath, const string& newPath) {
//TODO
return false;
}
bool FileSystem::deleteFolder(const string& fullPath) {
//TODO
return false;
}
FileSystem::File* FileSystem::retrieveFile(const string& fullPath) {
int i;
for (i = fullPath.size() - 1; i >= 0 && fullPath[i] != '/'; i--);
auto folder = folders.find(fullPath.substr(0, i));
if (folder == folders.end())
return nullptr;
auto& files = folder->second.files;
auto file = files.find(fullPath.substr(i + 1, fullPath.size()));
if (file == folder->second.files.end())
return nullptr;
return &file->second;
}
int FileSystem::getTotalFiles() {
int total = 0;
for (auto& kv : folders)
total += kv.second.files.size();
return total;
}
int FileSystem::getTotalSize() {
int total = 0;
for (auto& kv1 : folders) {
for (auto& kv2 : kv1.second.files)
total += kv2.second.size;
}
return total;
}
ByteQueue FileSystem::readFile(FILE* fp) {
fseek(fp, 0, SEEK_END);
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET);
ByteQueue data(size);
fread(data.ptr(), size, 1, fp);
return data;
}
<commit_msg>Adding comment<commit_after>/*
* FileSystem.cpp
*
* Created on: Jun 20, 2014
* Author: Pimenta
*/
// this
#include "FileSystem.hpp"
using namespace std;
using namespace helpers;
map<string, FileSystem::Folder> FileSystem::folders;
void FileSystem::init() {
folders.clear();
folders["root"];
}
bool FileSystem::parseName(const string& name) {
static set<char> allowedChars;
static StaticInitializer staticInitializar([&]() {
for (char c = '0'; c <= '9'; c++)
allowedChars.insert(c);
for (char c = 'a'; c <= 'z'; c++)
allowedChars.insert(c);
for (char c = 'A'; c <= 'Z'; c++)
allowedChars.insert(c);
allowedChars.insert('_');
allowedChars.insert('-');
allowedChars.insert('+');
allowedChars.insert('.');
});
if (!name.size())
return false;
for (int i = 0; i < int(name.size()); i++) {
if (allowedChars.find(name[i]) != allowedChars.end())
return false;
}
return true;
}
bool FileSystem::parsePath(const string& path) {
if (!path.size())
return false;
list<string> atoms = explode(path, '/');
string tmp;
auto it = atoms.begin();
for (int i = 0; i < int(atoms.size()) - 1; i++) {
if (!parseName(*it))
return false;
tmp += (*it);
tmp += '/';
it++;
}
if (it != atoms.end()) {
if (!parseName(*it))
return false;
tmp += (*it);
}
return tmp == path;
}
bool FileSystem::createFolder(const string& fullPath) {//FIXME sync
if (!parsePath(fullPath)) // if the path is invalid
return false;
if (folders.find(fullPath) != folders.end()) // if the folder already exists
return false;
pair<string, string> divided = divide(fullPath, '/');
auto motherFolder = folders.find(divided.first);
if (motherFolder == folders.end()) // if the mother folder doesn't exist
return false;
motherFolder->second.subfolders.insert(fullPath);
folders[fullPath];
return true;
}
FileSystem::Folder* FileSystem::retrieveFolder(const string& fullPath) {
auto folder = folders.find(fullPath);
if (folder == folders.end())
return nullptr;
return &folder->second;
}
bool FileSystem::updateFolder(const string& fullPath, const string& newPath) {
//TODO
return false;
}
bool FileSystem::deleteFolder(const string& fullPath) {
//TODO
return false;
}
FileSystem::File* FileSystem::retrieveFile(const string& fullPath) {
int i;
for (i = fullPath.size() - 1; i >= 0 && fullPath[i] != '/'; i--);
auto folder = folders.find(fullPath.substr(0, i));
if (folder == folders.end())
return nullptr;
auto& files = folder->second.files;
auto file = files.find(fullPath.substr(i + 1, fullPath.size()));
if (file == folder->second.files.end())
return nullptr;
return &file->second;
}
int FileSystem::getTotalFiles() {
int total = 0;
for (auto& kv : folders)
total += kv.second.files.size();
return total;
}
int FileSystem::getTotalSize() {
int total = 0;
for (auto& kv1 : folders) {
for (auto& kv2 : kv1.second.files)
total += kv2.second.size;
}
return total;
}
ByteQueue FileSystem::readFile(FILE* fp) {
fseek(fp, 0, SEEK_END);
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET);
ByteQueue data(size);
fread(data.ptr(), size, 1, fp);
return data;
}
<|endoftext|> |
<commit_before>#include "FileSystem.hpp"
#include "File.hpp"
#include <iostream>
#include <cmath>
using namespace std;
FileSystem::FileSystem() {
root = new Directory("/");
mMemblockDevice = MemBlockDevice(250, 512);
freeBlockNumbers = vector<bool>(mMemblockDevice.size(), true);
}
FileSystem::~FileSystem() {
delete root;
}
void FileSystem::format() {
mMemblockDevice.reset();
freeBlockNumbers = vector<bool>(mMemblockDevice.size(), true);
delete root;
root = new Directory("/");
}
void FileSystem::ls(const std::string &path) const {
Directory* directory = root->getDirectory(path);
if (directory == nullptr) {
cout << "Directory does not exist." << endl;
return;
}
directory->ls();
}
void FileSystem::create(const std::string &filePath) {
if (fileOrDirectoryExists(filePath)) {
cout << "File or directory already exists.";
return;
}
cout << "Enter file contents: \n";
string fileContent;
getline(cin, fileContent);
int requiredBlocks = ceil(fileContent.length() / (float)mMemblockDevice.getBlockLength());
vector<int> freeBlock = freeBlocks();
if (requiredBlocks > freeBlock.size()) {
cout << "Not enough free blocks to save string." << endl;
return;
}
Directory* directory = root->getDirectory(directoryPart(filePath));
File* file = directory->createFile(filePart(filePath));
appendToFile(file, fileContent);
}
void FileSystem::mkdir(const string &path) {
if (filePart(path).empty()) {
cout << "Wrong syntax." << endl;
return;
}
Directory* directory = root->getDirectory(directoryPart(path));
if (directory == nullptr) {
cout << "Directory " << directoryPart(path) << " does not exist." << endl;
return;
}
if (fileOrDirectoryExists(path)) {
cout << "File or directory with that name already exists." << endl;
return;
}
directory->createDirectory(filePart(path));
cout << "Directory created." << endl;
}
void FileSystem::cat(const std::string &fileName) const {
Directory* directory = root->getDirectory(directoryPart(fileName));
if (directory == nullptr) {
cout << "File does not exist." << endl;
return;
}
File* file = directory->getFile(filePart(fileName));
if (file == nullptr) {
cout << "File does not exist." << endl;
return;
} else if (!file->getReadPermission()) {
cout << "File is read protected." << endl;
return;
}
cout << fileToString(fileName) << endl;
}
void FileSystem::save(const std::string &saveFile) const {
ofstream file;
int nrOfBlocks = mMemblockDevice.size();
int nrOfElements = mMemblockDevice.getBlockLength();
char* buffer = new char[nrOfElements];
file.open(saveFile, ios::out|ios::binary);
for (int i = 0; i < nrOfBlocks; i++) {
for (int j = 0; j < nrOfElements; j++) {
buffer[j] = mMemblockDevice.readBlock(i)[j];
}
file.write(buffer, nrOfElements);
}
delete[] buffer;
root->save(file);
file.close();
}
void FileSystem::load(const std::string &saveFile) {
format();
ifstream file;
int nrOfBlocks = mMemblockDevice.size();
int nrOfElements = mMemblockDevice.getBlockLength();
char* buffer = new char[nrOfElements];
file.open(saveFile, ios::in | ios::binary);
for (int i = 0; i < nrOfBlocks; i++) {
file.read(buffer, nrOfElements);
mMemblockDevice.writeBlock(i, buffer);
}
delete[] buffer;
root->load(file);
file.close();
}
void FileSystem::rm(const std::string &path) {
if (!fileExists(path))
return;
Directory* directory = root->getDirectory(directoryPart(path));
File* file = directory->getFile(filePart(path));
if (!file->getWritePermission()) {
cout << "File is write protected." << endl;
return;
}
for (int i = 0; i < file->getBlockNumbers().size(); i++)
freeBlockNumbers[file->getBlockNumbers()[i]] = true;
delete file;
directory->rm(filePart(path));
}
void FileSystem::copy(const std::string &source, const std::string &dest) {
if (!fileExists(source)) {
cout << "Can't copy file, file does not exist." << endl;
return;
}
if (fileOrDirectoryExists(dest)) {
cout << "Can't copy file, destination already exists." << endl;
}
Directory* directory = root->getDirectory(directoryPart(source));
File* sourceFile = directory->getFile(filePart(source));
if (!sourceFile->getReadPermission()) {
cout << "File is read protected." << endl;
return;
}
Directory* destinationDirectory = root->getDirectory(directoryPart(dest));
if (destinationDirectory == nullptr) {
cout << "Destination directory does not exist." << endl;
return;
}
File* destinationFile = destinationDirectory->createFile(filePart(dest));
string contents = fileToString(source);
appendToFile(destinationFile, contents);
}
void FileSystem::append(const std::string &source, const std::string &destination) {
if (fileExists(destination) && fileExists(source)) {
Directory* destinationDirectory = root->getDirectory(directoryPart(destination));
Directory* sourceDirectory = root->getDirectory(directoryPart(source));
File* destinationFile = destinationDirectory->getFile(filePart(destination));
File* sourceFile = sourceDirectory->getFile(filePart(source));
if (sourceFile->getReadPermission() && destinationFile->getWritePermission()) {
string appendString = fileToString(source);
cout << appendString << " will be added." << endl;
appendToFile(destinationFile, appendString);
} else {
cout << "Files did not have proper read/write permission." << endl;
}
} else {
cout << "File(s) were not found." << endl;
}
}
void FileSystem::rename(const string &source, const string &newName) {
if (newName.empty()) {
cout << "New name can't be empty." << endl;
return;
}
if (!fileExists(source)) {
cout << "Can't rename file, source does not exist." << endl;
return;
}
if (fileOrDirectoryExists(newName)) {
cout << "Destination already exists." << endl;
return;
}
Directory* sourceDirectory = root->getDirectory(directoryPart(source));
Directory* destinationDirectory = root->getDirectory(directoryPart(newName));
if (destinationDirectory == nullptr) {
cout << "Destination directory does not exist." << endl;
return;
}
File* file = sourceDirectory->getFile(filePart(source));
if (!file->getWritePermission()) {
cout << "File is write protected." << endl;
return;
}
sourceDirectory->rm(filePart(source));
file->rename(newName);
destinationDirectory->addFile(file);
}
void FileSystem::chmod(const std::string &path, int permission) {
Directory* directory = root->getDirectory(directoryPart(path));
if (directory == nullptr) {
cout << "File does not exist." << endl;
return;
}
File* file = directory->getFile(filePart(path));
if (file == nullptr) {
cout << "File does not exist." << endl;
return;
}
if (permission > 4 || permission < 0){
cout << "Invalid permission level. Valid permission levels:\n";
cout << "0 = NONE.\n";
cout << "1 = READ only.\n";
cout << "2 = WRITE only.\n";
cout << "3 = READ and WRITE permission.\n";
return;
}
file->setPermission(File::Permission(permission));
}
bool FileSystem::directoryExists(const string &path) {
return root->getDirectory(path) != nullptr;
}
string FileSystem::fileToString(const std::string &path) const {
Directory* directory = root->getDirectory(directoryPart(path));
File* file = directory->getFile(filePart(path));
vector<int> tempNrs = file->getBlockNumbers();
string contents;
int bufferPos = 0;
// Read blocks and print characters until there is no more characters left or we have read a whole block (and should start to read a new block).
for (int i = 0; i < tempNrs.size(); i++){
while ((bufferPos < (mMemblockDevice.getBlockLength())) && (mMemblockDevice.readBlock(tempNrs[i])[bufferPos] != '\0')){
contents += mMemblockDevice.readBlock(tempNrs[i])[bufferPos];
bufferPos++;
}
bufferPos = 0;
}
return contents;
}
void FileSystem::appendToFile(File* file, string contents) {
vector<int> freeBlock = freeBlocks();
vector<int> usedBlockNumbers;
int bufferPos = 0; // Keeps track of where we are in the buffer
int freeBlockPos = 0; // Keeps track of what free block number we are using
int requiredBlocks = 0; // Keeps track of how many blocks we may need to allocate
char* buffer = new char[mMemblockDevice.getBlockLength()]; // Stores what we want to write to the block
if (file->getBlockNumbers().size() > 0) {
//The file we are appending to is not a new file.
//Recalculate file length
int tempLength = file->getLength() + contents.length();
//Calculate how many new blocks we need, if any.
requiredBlocks = ceil(tempLength / (float)mMemblockDevice.getBlockLength()) - file->getBlockNumbers().size();
if (requiredBlocks > freeBlock.size()) {
cout << "Not enough free blocks.\n";
return;
}
file->setLength(tempLength);
// Null out buffer.
for (int i = 0; i < mMemblockDevice.getBlockLength(); i++)
buffer[i] = '\0';
// Read the last block of the file into the buffer.
char c;
while ((bufferPos < ((float)mMemblockDevice.getBlockLength())) && ((c = mMemblockDevice.readBlock(file->getBlockNumbers().back())[bufferPos]) != '\0')) {
buffer[bufferPos] = c;
bufferPos++;
}
usedBlockNumbers = file->getBlockNumbers();
usedBlockNumbers.pop_back();
// Insert the files last block number at the start of freeBlock,
// indicating that if we need a new block then we should write the buffer
// to the files last block.
freeBlock.insert(freeBlock.begin(), file->getBlockNumbers().back());
if (bufferPos == (mMemblockDevice.getBlockLength())) { // If pos is greater than block length, we need to write to next block.
mMemblockDevice.writeBlock(freeBlock[freeBlockPos], buffer);
freeBlockNumbers[freeBlock[freeBlockPos]] = false;
usedBlockNumbers.push_back(freeBlock[freeBlockPos]);
bufferPos = 0;
freeBlockPos++;
}
} else {
requiredBlocks = ceil(contents.length() / (float)mMemblockDevice.getBlockLength());
file->setLength(contents.length());
for (int i = 0; i < mMemblockDevice.getBlockLength(); i++)
buffer[i] = '\0';
bufferPos = 0;
}
for (int j = 0; j < contents.length(); j++) {
buffer[bufferPos] = contents[j];
bufferPos++;
if (j == (contents.length()-1)) { // If we have reached the end of the string and should write the contents to block.
mMemblockDevice.writeBlock(freeBlock[freeBlockPos], buffer);
freeBlockNumbers[freeBlock[freeBlockPos]] = false;
usedBlockNumbers.push_back(freeBlock[freeBlockPos]);
} else if (bufferPos == (mMemblockDevice.getBlockLength())) { // If pos is greater than block length, we need to write to next block.
mMemblockDevice.writeBlock(freeBlock[freeBlockPos], buffer);
freeBlockNumbers[freeBlock[freeBlockPos]] = false;
usedBlockNumbers.push_back(freeBlock[freeBlockPos]);
for (int i = 0; i < mMemblockDevice.getBlockLength(); i++)
buffer[i] = '\0';
bufferPos = 0;
freeBlockPos++;
}
}
delete[] buffer;
freeBlocks();
file->setBlockNumbers(usedBlockNumbers);
}
vector<int> FileSystem::freeBlocks() const{
vector<int> blockList;
for (int i = 0; i < freeBlockNumbers.size(); i++){
if (freeBlockNumbers[i] == true)
blockList.push_back(i);
}
return blockList;
}
bool FileSystem::fileOrDirectoryExists(const string &path) const {
Directory* directory = root->getDirectory(directoryPart(path));
if (directory->getDirectory(filePart(path)) != nullptr) {
cout << "Directory with that name already exists." << endl;
return true;
}
if (directory->getFile(filePart(path)) != nullptr) {
cout << "File with same name already exists." << endl;
return true;
}
return false;
}
bool FileSystem::fileExists(const string &path) const {
Directory* directory = root->getDirectory(directoryPart(path));
if (directory == nullptr)
return false;
return (directory->getFile(filePart(path)) != nullptr);
}
string FileSystem::directoryPart(const string &path) {
size_t pos = path.find_last_of('/');
if (pos == string::npos)
return "";
return path.substr(0, pos);
}
string FileSystem::filePart(const string &path) {
size_t pos = path.find_last_of('/');
if (pos == string::npos)
return path;
if (path.length() < pos + 2)
return "";
return path.substr(pos + 1);
}
<commit_msg>now formats disk when FileSystem is created<commit_after>#include "FileSystem.hpp"
#include "File.hpp"
#include <iostream>
#include <cmath>
using namespace std;
FileSystem::FileSystem() {
root = new Directory("/");
mMemblockDevice = MemBlockDevice(250, 512);
format();
}
FileSystem::~FileSystem() {
delete root;
}
void FileSystem::format() {
mMemblockDevice.reset();
freeBlockNumbers = vector<bool>(mMemblockDevice.size(), true);
delete root;
root = new Directory("/");
}
void FileSystem::ls(const std::string &path) const {
Directory* directory = root->getDirectory(path);
if (directory == nullptr) {
cout << "Directory does not exist." << endl;
return;
}
directory->ls();
}
void FileSystem::create(const std::string &filePath) {
if (fileOrDirectoryExists(filePath)) {
cout << "File or directory already exists.";
return;
}
cout << "Enter file contents: \n";
string fileContent;
getline(cin, fileContent);
int requiredBlocks = ceil(fileContent.length() / (float)mMemblockDevice.getBlockLength());
vector<int> freeBlock = freeBlocks();
if (requiredBlocks > freeBlock.size()) {
cout << "Not enough free blocks to save string." << endl;
return;
}
Directory* directory = root->getDirectory(directoryPart(filePath));
File* file = directory->createFile(filePart(filePath));
appendToFile(file, fileContent);
}
void FileSystem::mkdir(const string &path) {
if (filePart(path).empty()) {
cout << "Wrong syntax." << endl;
return;
}
Directory* directory = root->getDirectory(directoryPart(path));
if (directory == nullptr) {
cout << "Directory " << directoryPart(path) << " does not exist." << endl;
return;
}
if (fileOrDirectoryExists(path)) {
cout << "File or directory with that name already exists." << endl;
return;
}
directory->createDirectory(filePart(path));
cout << "Directory created." << endl;
}
void FileSystem::cat(const std::string &fileName) const {
Directory* directory = root->getDirectory(directoryPart(fileName));
if (directory == nullptr) {
cout << "File does not exist." << endl;
return;
}
File* file = directory->getFile(filePart(fileName));
if (file == nullptr) {
cout << "File does not exist." << endl;
return;
} else if (!file->getReadPermission()) {
cout << "File is read protected." << endl;
return;
}
cout << fileToString(fileName) << endl;
}
void FileSystem::save(const std::string &saveFile) const {
ofstream file;
int nrOfBlocks = mMemblockDevice.size();
int nrOfElements = mMemblockDevice.getBlockLength();
char* buffer = new char[nrOfElements];
file.open(saveFile, ios::out|ios::binary);
for (int i = 0; i < nrOfBlocks; i++) {
for (int j = 0; j < nrOfElements; j++) {
buffer[j] = mMemblockDevice.readBlock(i)[j];
}
file.write(buffer, nrOfElements);
}
delete[] buffer;
root->save(file);
file.close();
}
void FileSystem::load(const std::string &saveFile) {
format();
ifstream file;
int nrOfBlocks = mMemblockDevice.size();
int nrOfElements = mMemblockDevice.getBlockLength();
char* buffer = new char[nrOfElements];
file.open(saveFile, ios::in | ios::binary);
for (int i = 0; i < nrOfBlocks; i++) {
file.read(buffer, nrOfElements);
mMemblockDevice.writeBlock(i, buffer);
}
delete[] buffer;
root->load(file);
file.close();
}
void FileSystem::rm(const std::string &path) {
if (!fileExists(path))
return;
Directory* directory = root->getDirectory(directoryPart(path));
File* file = directory->getFile(filePart(path));
if (!file->getWritePermission()) {
cout << "File is write protected." << endl;
return;
}
for (int i = 0; i < file->getBlockNumbers().size(); i++)
freeBlockNumbers[file->getBlockNumbers()[i]] = true;
delete file;
directory->rm(filePart(path));
}
void FileSystem::copy(const std::string &source, const std::string &dest) {
if (!fileExists(source)) {
cout << "Can't copy file, file does not exist." << endl;
return;
}
if (fileOrDirectoryExists(dest)) {
cout << "Can't copy file, destination already exists." << endl;
}
Directory* directory = root->getDirectory(directoryPart(source));
File* sourceFile = directory->getFile(filePart(source));
if (!sourceFile->getReadPermission()) {
cout << "File is read protected." << endl;
return;
}
Directory* destinationDirectory = root->getDirectory(directoryPart(dest));
if (destinationDirectory == nullptr) {
cout << "Destination directory does not exist." << endl;
return;
}
File* destinationFile = destinationDirectory->createFile(filePart(dest));
string contents = fileToString(source);
appendToFile(destinationFile, contents);
}
void FileSystem::append(const std::string &source, const std::string &destination) {
if (fileExists(destination) && fileExists(source)) {
Directory* destinationDirectory = root->getDirectory(directoryPart(destination));
Directory* sourceDirectory = root->getDirectory(directoryPart(source));
File* destinationFile = destinationDirectory->getFile(filePart(destination));
File* sourceFile = sourceDirectory->getFile(filePart(source));
if (sourceFile->getReadPermission() && destinationFile->getWritePermission()) {
string appendString = fileToString(source);
appendToFile(destinationFile, appendString);
} else {
cout << "Files did not have proper read/write permission." << endl;
}
} else {
cout << "File(s) were not found." << endl;
}
}
void FileSystem::rename(const string &source, const string &newName) {
if (newName.empty()) {
cout << "New name can't be empty." << endl;
return;
}
if (!fileExists(source)) {
cout << "Can't rename file, source does not exist." << endl;
return;
}
if (fileOrDirectoryExists(newName)) {
cout << "Destination already exists." << endl;
return;
}
Directory* sourceDirectory = root->getDirectory(directoryPart(source));
Directory* destinationDirectory = root->getDirectory(directoryPart(newName));
if (destinationDirectory == nullptr) {
cout << "Destination directory does not exist." << endl;
return;
}
File* file = sourceDirectory->getFile(filePart(source));
if (!file->getWritePermission()) {
cout << "File is write protected." << endl;
return;
}
sourceDirectory->rm(filePart(source));
file->rename(newName);
destinationDirectory->addFile(file);
}
void FileSystem::chmod(const std::string &path, int permission) {
Directory* directory = root->getDirectory(directoryPart(path));
if (directory == nullptr) {
cout << "File does not exist." << endl;
return;
}
File* file = directory->getFile(filePart(path));
if (file == nullptr) {
cout << "File does not exist." << endl;
return;
}
if (permission > 4 || permission < 0){
cout << "Invalid permission level. Valid permission levels:\n";
cout << "0 = NONE.\n";
cout << "1 = READ only.\n";
cout << "2 = WRITE only.\n";
cout << "3 = READ and WRITE permission.\n";
return;
}
file->setPermission(File::Permission(permission));
}
bool FileSystem::directoryExists(const string &path) {
return root->getDirectory(path) != nullptr;
}
string FileSystem::fileToString(const std::string &path) const {
Directory* directory = root->getDirectory(directoryPart(path));
File* file = directory->getFile(filePart(path));
vector<int> tempNrs = file->getBlockNumbers();
string contents;
int bufferPos = 0;
// Read blocks and print characters until there is no more characters left or we have read a whole block (and should start to read a new block).
for (int i = 0; i < tempNrs.size(); i++){
while ((bufferPos < (mMemblockDevice.getBlockLength())) && (mMemblockDevice.readBlock(tempNrs[i])[bufferPos] != '\0')){
contents += mMemblockDevice.readBlock(tempNrs[i])[bufferPos];
bufferPos++;
}
bufferPos = 0;
}
return contents;
}
void FileSystem::appendToFile(File* file, string contents) {
vector<int> freeBlock = freeBlocks();
vector<int> usedBlockNumbers;
int bufferPos = 0; // Keeps track of where we are in the buffer
int freeBlockPos = 0; // Keeps track of what free block number we are using
int requiredBlocks = 0; // Keeps track of how many blocks we may need to allocate
char* buffer = new char[mMemblockDevice.getBlockLength()]; // Stores what we want to write to the block
if (file->getBlockNumbers().size() > 0) {
//The file we are appending to is not a new file.
//Recalculate file length
int tempLength = file->getLength() + contents.length();
//Calculate how many new blocks we need, if any.
requiredBlocks = ceil(tempLength / (float)mMemblockDevice.getBlockLength()) - file->getBlockNumbers().size();
if (requiredBlocks > freeBlock.size()) {
cout << "Not enough free blocks.\n";
return;
}
file->setLength(tempLength);
// Null out buffer.
for (int i = 0; i < mMemblockDevice.getBlockLength(); i++)
buffer[i] = '\0';
// Read the last block of the file into the buffer.
char c;
while ((bufferPos < ((float)mMemblockDevice.getBlockLength())) && ((c = mMemblockDevice.readBlock(file->getBlockNumbers().back())[bufferPos]) != '\0')) {
buffer[bufferPos] = c;
bufferPos++;
}
usedBlockNumbers = file->getBlockNumbers();
usedBlockNumbers.pop_back();
// Insert the files last block number at the start of freeBlock,
// indicating that if we need a new block then we should write the buffer
// to the files last block.
freeBlock.insert(freeBlock.begin(), file->getBlockNumbers().back());
if (bufferPos == (mMemblockDevice.getBlockLength())) { // If pos is greater than block length, we need to write to next block.
mMemblockDevice.writeBlock(freeBlock[freeBlockPos], buffer);
freeBlockNumbers[freeBlock[freeBlockPos]] = false;
usedBlockNumbers.push_back(freeBlock[freeBlockPos]);
bufferPos = 0;
freeBlockPos++;
}
} else {
requiredBlocks = ceil(contents.length() / (float)mMemblockDevice.getBlockLength());
file->setLength(contents.length());
for (int i = 0; i < mMemblockDevice.getBlockLength(); i++)
buffer[i] = '\0';
bufferPos = 0;
}
for (int j = 0; j < contents.length(); j++) {
buffer[bufferPos] = contents[j];
bufferPos++;
if (j == (contents.length()-1)) { // If we have reached the end of the string and should write the contents to block.
mMemblockDevice.writeBlock(freeBlock[freeBlockPos], buffer);
freeBlockNumbers[freeBlock[freeBlockPos]] = false;
usedBlockNumbers.push_back(freeBlock[freeBlockPos]);
} else if (bufferPos == (mMemblockDevice.getBlockLength())) { // If pos is greater than block length, we need to write to next block.
mMemblockDevice.writeBlock(freeBlock[freeBlockPos], buffer);
freeBlockNumbers[freeBlock[freeBlockPos]] = false;
usedBlockNumbers.push_back(freeBlock[freeBlockPos]);
for (int i = 0; i < mMemblockDevice.getBlockLength(); i++)
buffer[i] = '\0';
bufferPos = 0;
freeBlockPos++;
}
}
delete[] buffer;
freeBlocks();
file->setBlockNumbers(usedBlockNumbers);
}
vector<int> FileSystem::freeBlocks() const{
vector<int> blockList;
for (int i = 0; i < freeBlockNumbers.size(); i++){
if (freeBlockNumbers[i] == true)
blockList.push_back(i);
}
return blockList;
}
bool FileSystem::fileOrDirectoryExists(const string &path) const {
Directory* directory = root->getDirectory(directoryPart(path));
if (directory->getDirectory(filePart(path)) != nullptr) {
cout << "Directory with that name already exists." << endl;
return true;
}
if (directory->getFile(filePart(path)) != nullptr) {
cout << "File with same name already exists." << endl;
return true;
}
return false;
}
bool FileSystem::fileExists(const string &path) const {
Directory* directory = root->getDirectory(directoryPart(path));
if (directory == nullptr)
return false;
return (directory->getFile(filePart(path)) != nullptr);
}
string FileSystem::directoryPart(const string &path) {
size_t pos = path.find_last_of('/');
if (pos == string::npos)
return "";
return path.substr(0, pos);
}
string FileSystem::filePart(const string &path) {
size_t pos = path.find_last_of('/');
if (pos == string::npos)
return path;
if (path.length() < pos + 2)
return "";
return path.substr(pos + 1);
}
<|endoftext|> |
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "GException.hxx"
#include "HttpMessageResponse.hxx"
#include "http_quark.h"
#include "util/Exception.hxx"
void
SetGError(GError **error_r, const std::exception &e)
{
g_set_error_literal(error_r, exception_quark(), 0,
GetFullMessage(e).c_str());
}
GError *
ToGError(const std::exception &e)
{
return g_error_new_literal(exception_quark(), 0,
GetFullMessage(e).c_str());
}
GError *
ToGError(std::exception_ptr ep)
{
try {
FindRetrowNested<HttpMessageResponse>(ep);
} catch (const HttpMessageResponse &e) {
return g_error_new_literal(http_response_quark(), e.GetStatus(),
GetFullMessage(ep).c_str());
}
return g_error_new_literal(exception_quark(), 0,
GetFullMessage(ep).c_str());
}
<commit_msg>GException: call GetFullMessage() only once<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "GException.hxx"
#include "HttpMessageResponse.hxx"
#include "http_quark.h"
#include "util/Exception.hxx"
void
SetGError(GError **error_r, const std::exception &e)
{
g_set_error_literal(error_r, exception_quark(), 0,
GetFullMessage(e).c_str());
}
GError *
ToGError(const std::exception &e)
{
return g_error_new_literal(exception_quark(), 0,
GetFullMessage(e).c_str());
}
GError *
ToGError(std::exception_ptr ep)
{
const auto msg = GetFullMessage(ep);
try {
FindRetrowNested<HttpMessageResponse>(ep);
} catch (const HttpMessageResponse &e) {
return g_error_new_literal(http_response_quark(), e.GetStatus(),
msg.c_str());
}
return g_error_new_literal(exception_quark(), 0, msg.c_str());
}
<|endoftext|> |
<commit_before>#include "details/compiler/compiler.h"
#include "details/compiler/compdb.h"
#include "details/program/program.h"
#include "details/reporting/report.h"
#include "details/errors/errors.h"
#include "details/pass/a-src2ast/ast-from-source.h"
#include "details/pass/b-ast-normalize/normalize.h"
#include "details/pass/c-ast2ir/source-ast-to-ir.h"
#include "details/pass/d-object-map/attach.h"
#include "details/semantic/atom-factory.h"
#include "details/intrinsic/std.core.h"
#include "details/compiler/report.h"
#include "libnanyc-config.h"
#include "libnanyc-traces.h"
#include "libnanyc-version.h"
#include "embed-nsl.hxx" // generated
#include <yuni/io/file.h>
#include <libnanyc.h>
#include <utility>
#include <memory>
#include <unordered_map>
namespace ny {
namespace compiler {
namespace {
constexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;
void bugReportInfo(ny::Logs::Report& report) {
auto e = report.info("nanyc {c++/bootstrap}") << " v" << LIBNANYC_VERSION_STR;
if (yuni::debugmode)
e << " {debug}";
e.message.section = "comp";
}
Logs::Report buildGenerateReport(void* ptr, Logs::Level level) {
return (*((ny::Logs::Report*) ptr)).fromErrLevel(level);
}
void copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {
if (opts.filename.len != 0) {
if (unlikely(opts.filename.len > memoryHardlimit))
throw "input filename bigger than internal limit";
yuni::IO::Canonicalize(source.storageFilename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});
source.filename = source.storageFilename;
}
if (opts.content.len != 0) {
if (unlikely(opts.content.len > memoryHardlimit))
throw "input source content bigger than internal limit";
source.storageContent.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));
source.content = source.storageContent;
}
}
Atom& findEntrypointAtom(Atom& root, const AnyString& entrypoint) {
Atom* atom = nullptr;
root.eachChild(entrypoint, [&](Atom & child) -> bool {
if (unlikely(atom != nullptr))
throw "': multiple entry points found";
atom = &child;
return true;
});
if (unlikely(!atom))
throw "()': function not found";
if (unlikely(not atom->isFunction() or atom->isClassMember()))
throw "': the atom is not a function";
return *atom;
}
bool instanciate(ny::compiler::Compdb& compdb, ny::Logs::Report& report, AnyString entrypoint) {
using ParameterList = decltype(ny::semantic::FuncOverloadMatch::result.params);
try {
auto& atom = findEntrypointAtom(compdb.cdeftable.atoms.root, entrypoint);
atom.funcinfo.raisedErrors.noleaks.enabled = true;
ParameterList params;
ParameterList tmplparams;
ClassdefTableView cdeftblView{compdb.cdeftable};
ny::semantic::Settings settings(atom, cdeftblView, compdb, params, tmplparams);
bool instanciated = ny::semantic::instanciateAtom(settings);
report.appendEntry(settings.report);
if (config::traces::atomTable)
compdb.cdeftable.atoms.root.printTree(compdb.cdeftable);
if (likely(instanciated)) {
compdb.entrypoint.atomid = atom.atomid;
compdb.entrypoint.instanceid = settings.instanceid;
return not report.hasErrors();
}
}
catch (const char* e) {
report.error() << "failed to instanciate '" << entrypoint << e;
}
compdb.entrypoint.atomid = (uint32_t) -1;
compdb.entrypoint.instanceid = (uint32_t) -1;
return false;
}
struct CompilerQueue final {
ny::compiler::Compdb& compdb;
ny::Logs::Report report;
std::vector<yuni::String> collectionSearchPaths;
std::unordered_set<yuni::String> collectionsLoaded;
CompilerQueue(ny::compiler::Compdb& compdb)
: compdb(compdb)
, report(compdb.messages) {
collectionSearchPaths.reserve(4);
collectionSearchPaths.emplace_back(ny::config::collectionSystemPath);
}
static void usesCollection(void* userdata, const AnyString& name) {
auto& queue = *(reinterpret_cast<CompilerQueue*>(userdata));
if (queue.collectionsLoaded.count(name) != 0)
return;
queue.collectionsLoaded.insert(name);
yuni::String filename;
yuni::String content;
for (auto& searchpath: queue.collectionSearchPaths) {
filename = searchpath;
filename << '/' << name << "/nanyc.collection";
if (yuni::IO::errNone != yuni::IO::File::LoadFromFile(content, filename))
continue;
if (unlikely(queue.compdb.opts.verbose == nytrue))
info() << "uses " << name << " -> " << searchpath << '/' << name;
content.words("\n", [&](AnyString line) -> bool {
if (not line.empty()) {
if (unlikely(line[0] == 'u' and line.startsWith("uses "))) {
line.consume(5);
if (not line.empty())
usesCollection(userdata, line);
}
else {
queue.compdb.sources.emplace_back();
auto& source = queue.compdb.sources.back();
source.storageFilename = searchpath;
source.storageFilename << '/' << name << '/' << line;
source.filename = source.storageFilename;
}
}
return true;
});
return;
}
auto err = (error() << "collection '" << name << "' not found");
for (auto& searchpath: queue.collectionSearchPaths)
err.hint() << "from path '" << searchpath << "'";
}
bool compileSource(ny::compiler::Source& source) {
if (unlikely(compdb.opts.verbose == nytrue))
info() << "compile " << source.filename;
auto subreport = report.subgroup();
subreport.data().origins.location.filename = source.filename;
subreport.data().origins.location.target.clear();
bool compiled = true;
compiled &= makeASTFromSource(source);
compiled &= passDuplicateAndNormalizeAST(source, subreport, &usesCollection, this);
compiled &= passTransformASTToIR(source, subreport, compdb.opts);
compiled = compiled and attach(compdb, source);
return compiled;
}
bool importSourceAndCompile(ny::compiler::Source& source, const nysource_opts_t& opts) {
copySourceOpts(source, opts);
return compileSource(source);
}
};
std::unique_ptr<ny::Program> compile(ny::compiler::Compdb& compdb) {
CompilerQueue queue(compdb);
auto& report = queue.report;
Logs::Handler errorHandler{&report, &buildGenerateReport};
try {
if (unlikely(compdb.opts.verbose == nytrue))
bugReportInfo(report);
uint32_t scount = compdb.opts.sources.count;
if (unlikely(scount == 0))
throw "no input source code";
if (config::importNSL)
ny::intrinsic::import::all(compdb.intrinsics);
if (config::importNSL)
scount += corefilesCount;
auto& sources = compdb.sources;
sources.resize(scount);
bool compiled = true;
uint32_t offset = 0;
if (config::importNSL) {
registerNSLCoreFiles(sources, offset, [&](ny::compiler::Source& source) {
compiled &= queue.compileSource(source);
});
}
if (unlikely(compdb.opts.with_nsl_unittests == nytrue))
queue.usesCollection(&queue, "nsl.selftest");
for (uint32_t i = 0; i != compdb.opts.sources.count; ++i) {
auto& source = sources[offset + i];
compiled &= queue.importSourceAndCompile(source, compdb.opts.sources.items[i]);
}
for (uint32_t i = offset + compdb.opts.sources.count; i < sources.size(); ++i) {
auto& source = sources[i];
compiled &= queue.compileSource(source);
}
if (unlikely(compdb.opts.verbose == nytrue))
report.info() << "building... ";
compiled = compiled
and likely(compdb.opts.on_unittest == nullptr)
and compdb.cdeftable.atoms.fetchAndIndexCoreObjects() // indexing bool, u32, f64...
and ny::semantic::resolveStrictParameterTypes(compdb, compdb.cdeftable.atoms.root); // typedef
if (config::traces::preAtomTable)
compdb.cdeftable.atoms.root.printTree(ClassdefTableView{compdb.cdeftable});
if (unlikely(not compiled))
return nullptr;
auto& entrypoint = compdb.opts.entrypoint;
if (unlikely(entrypoint.len == 0))
return nullptr;
bool epinst = instanciate(compdb, report, AnyString(entrypoint.c_str, static_cast<uint32_t>(entrypoint.len)));
if (config::traces::raisedErrorSummary)
ny::compiler::report::raisedErrorsForAllAtoms(compdb, report);
if (unlikely(not epinst))
return nullptr;
return std::make_unique<ny::Program>();
}
catch (const std::bad_alloc&) {
report.ice() << "not enough memory when compiling";
}
catch (const std::exception& e) {
report.ice() << "exception: " << e.what();
}
catch (const char* e) {
report.error() << e;
}
catch (...) {
report.ice() << "uncaught exception when compiling";
}
return nullptr;
}
void pleaseReport(nycompile_opts_t& opts, std::unique_ptr<ny::compiler::Compdb>& compdb) {
auto* rp = reinterpret_cast<const nyreport_t*>(&compdb->messages);
if (opts.on_report)
opts.on_report(opts.userdata, rp);
else
nyreport_print_stdout(rp);
}
} // namespace
nyprogram_t* compile(nycompile_opts_t& opts) {
try {
if (opts.on_build_start)
opts.userdata = opts.on_build_start(opts.userdata);
auto compdb = std::make_unique<Compdb>(opts);
auto program = compile(*compdb);
if (opts.on_build_stop)
opts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));
if (not compdb->messages.entries.empty())
pleaseReport(opts, compdb);
if (unlikely(!program))
return nullptr;
program->compdb = std::move(compdb);
return ny::Program::pointer(program.release());
}
catch (...) {
}
if (opts.on_build_stop)
opts.on_build_stop(opts.userdata, nyfalse);
return nullptr;
}
} // namespace compiler
} // namespace ny
<commit_msg>nanyc: use more appropriate hard limits for filename and content size<commit_after>#include "details/compiler/compiler.h"
#include "details/compiler/compdb.h"
#include "details/program/program.h"
#include "details/reporting/report.h"
#include "details/errors/errors.h"
#include "details/pass/a-src2ast/ast-from-source.h"
#include "details/pass/b-ast-normalize/normalize.h"
#include "details/pass/c-ast2ir/source-ast-to-ir.h"
#include "details/pass/d-object-map/attach.h"
#include "details/semantic/atom-factory.h"
#include "details/intrinsic/std.core.h"
#include "details/compiler/report.h"
#include "libnanyc-config.h"
#include "libnanyc-traces.h"
#include "libnanyc-version.h"
#include "embed-nsl.hxx" // generated
#include <yuni/io/file.h>
#include <libnanyc.h>
#include <utility>
#include <memory>
#include <unordered_map>
namespace ny {
namespace compiler {
namespace {
void bugReportInfo(ny::Logs::Report& report) {
auto e = report.info("nanyc {c++/bootstrap}") << " v" << LIBNANYC_VERSION_STR;
if (yuni::debugmode)
e << " {debug}";
e.message.section = "comp";
}
Logs::Report buildGenerateReport(void* ptr, Logs::Level level) {
return (*((ny::Logs::Report*) ptr)).fromErrLevel(level);
}
void copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {
if (opts.filename.len != 0) {
if (unlikely(opts.filename.len > 64 * 1024))
throw "input filename bigger than internal limit";
yuni::IO::Canonicalize(source.storageFilename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});
source.filename = source.storageFilename;
}
if (opts.content.len != 0) {
if (unlikely(opts.content.len > 64 * 1024 * 1024))
throw "input source content bigger than internal limit";
source.storageContent.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));
source.content = source.storageContent;
}
}
Atom& findEntrypointAtom(Atom& root, const AnyString& entrypoint) {
Atom* atom = nullptr;
root.eachChild(entrypoint, [&](Atom & child) -> bool {
if (unlikely(atom != nullptr))
throw "': multiple entry points found";
atom = &child;
return true;
});
if (unlikely(!atom))
throw "()': function not found";
if (unlikely(not atom->isFunction() or atom->isClassMember()))
throw "': the atom is not a function";
return *atom;
}
bool instanciate(ny::compiler::Compdb& compdb, ny::Logs::Report& report, AnyString entrypoint) {
using ParameterList = decltype(ny::semantic::FuncOverloadMatch::result.params);
try {
auto& atom = findEntrypointAtom(compdb.cdeftable.atoms.root, entrypoint);
atom.funcinfo.raisedErrors.noleaks.enabled = true;
ParameterList params;
ParameterList tmplparams;
ClassdefTableView cdeftblView{compdb.cdeftable};
ny::semantic::Settings settings(atom, cdeftblView, compdb, params, tmplparams);
bool instanciated = ny::semantic::instanciateAtom(settings);
report.appendEntry(settings.report);
if (config::traces::atomTable)
compdb.cdeftable.atoms.root.printTree(compdb.cdeftable);
if (likely(instanciated)) {
compdb.entrypoint.atomid = atom.atomid;
compdb.entrypoint.instanceid = settings.instanceid;
return not report.hasErrors();
}
}
catch (const char* e) {
report.error() << "failed to instanciate '" << entrypoint << e;
}
compdb.entrypoint.atomid = (uint32_t) -1;
compdb.entrypoint.instanceid = (uint32_t) -1;
return false;
}
struct CompilerQueue final {
ny::compiler::Compdb& compdb;
ny::Logs::Report report;
std::vector<yuni::String> collectionSearchPaths;
std::unordered_set<yuni::String> collectionsLoaded;
CompilerQueue(ny::compiler::Compdb& compdb)
: compdb(compdb)
, report(compdb.messages) {
collectionSearchPaths.reserve(4);
collectionSearchPaths.emplace_back(ny::config::collectionSystemPath);
}
static void usesCollection(void* userdata, const AnyString& name) {
auto& queue = *(reinterpret_cast<CompilerQueue*>(userdata));
if (queue.collectionsLoaded.count(name) != 0)
return;
queue.collectionsLoaded.insert(name);
yuni::String filename;
yuni::String content;
for (auto& searchpath: queue.collectionSearchPaths) {
filename = searchpath;
filename << '/' << name << "/nanyc.collection";
if (yuni::IO::errNone != yuni::IO::File::LoadFromFile(content, filename))
continue;
if (unlikely(queue.compdb.opts.verbose == nytrue))
info() << "uses " << name << " -> " << searchpath << '/' << name;
content.words("\n", [&](AnyString line) -> bool {
if (not line.empty()) {
if (unlikely(line[0] == 'u' and line.startsWith("uses "))) {
line.consume(5);
if (not line.empty())
usesCollection(userdata, line);
}
else {
queue.compdb.sources.emplace_back();
auto& source = queue.compdb.sources.back();
source.storageFilename = searchpath;
source.storageFilename << '/' << name << '/' << line;
source.filename = source.storageFilename;
}
}
return true;
});
return;
}
auto err = (error() << "collection '" << name << "' not found");
for (auto& searchpath: queue.collectionSearchPaths)
err.hint() << "from path '" << searchpath << "'";
}
bool compileSource(ny::compiler::Source& source) {
if (unlikely(compdb.opts.verbose == nytrue))
info() << "compile " << source.filename;
auto subreport = report.subgroup();
subreport.data().origins.location.filename = source.filename;
subreport.data().origins.location.target.clear();
bool compiled = true;
compiled &= makeASTFromSource(source);
compiled &= passDuplicateAndNormalizeAST(source, subreport, &usesCollection, this);
compiled &= passTransformASTToIR(source, subreport, compdb.opts);
compiled = compiled and attach(compdb, source);
return compiled;
}
bool importSourceAndCompile(ny::compiler::Source& source, const nysource_opts_t& opts) {
copySourceOpts(source, opts);
return compileSource(source);
}
};
std::unique_ptr<ny::Program> compile(ny::compiler::Compdb& compdb) {
CompilerQueue queue(compdb);
auto& report = queue.report;
Logs::Handler errorHandler{&report, &buildGenerateReport};
try {
if (unlikely(compdb.opts.verbose == nytrue))
bugReportInfo(report);
uint32_t scount = compdb.opts.sources.count;
if (unlikely(scount == 0))
throw "no input source code";
if (config::importNSL)
ny::intrinsic::import::all(compdb.intrinsics);
if (config::importNSL)
scount += corefilesCount;
auto& sources = compdb.sources;
sources.resize(scount);
bool compiled = true;
uint32_t offset = 0;
if (config::importNSL) {
registerNSLCoreFiles(sources, offset, [&](ny::compiler::Source& source) {
compiled &= queue.compileSource(source);
});
}
if (unlikely(compdb.opts.with_nsl_unittests == nytrue))
queue.usesCollection(&queue, "nsl.selftest");
for (uint32_t i = 0; i != compdb.opts.sources.count; ++i) {
auto& source = sources[offset + i];
compiled &= queue.importSourceAndCompile(source, compdb.opts.sources.items[i]);
}
for (uint32_t i = offset + compdb.opts.sources.count; i < sources.size(); ++i) {
auto& source = sources[i];
compiled &= queue.compileSource(source);
}
if (unlikely(compdb.opts.verbose == nytrue))
report.info() << "building... ";
compiled = compiled
and likely(compdb.opts.on_unittest == nullptr)
and compdb.cdeftable.atoms.fetchAndIndexCoreObjects() // indexing bool, u32, f64...
and ny::semantic::resolveStrictParameterTypes(compdb, compdb.cdeftable.atoms.root); // typedef
if (config::traces::preAtomTable)
compdb.cdeftable.atoms.root.printTree(ClassdefTableView{compdb.cdeftable});
if (unlikely(not compiled))
return nullptr;
auto& entrypoint = compdb.opts.entrypoint;
if (unlikely(entrypoint.len == 0))
return nullptr;
bool epinst = instanciate(compdb, report, AnyString(entrypoint.c_str, static_cast<uint32_t>(entrypoint.len)));
if (config::traces::raisedErrorSummary)
ny::compiler::report::raisedErrorsForAllAtoms(compdb, report);
if (unlikely(not epinst))
return nullptr;
return std::make_unique<ny::Program>();
}
catch (const std::bad_alloc&) {
report.ice() << "not enough memory when compiling";
}
catch (const std::exception& e) {
report.ice() << "exception: " << e.what();
}
catch (const char* e) {
report.error() << e;
}
catch (...) {
report.ice() << "uncaught exception when compiling";
}
return nullptr;
}
void pleaseReport(nycompile_opts_t& opts, std::unique_ptr<ny::compiler::Compdb>& compdb) {
auto* rp = reinterpret_cast<const nyreport_t*>(&compdb->messages);
if (opts.on_report)
opts.on_report(opts.userdata, rp);
else
nyreport_print_stdout(rp);
}
} // namespace
nyprogram_t* compile(nycompile_opts_t& opts) {
try {
if (opts.on_build_start)
opts.userdata = opts.on_build_start(opts.userdata);
auto compdb = std::make_unique<Compdb>(opts);
auto program = compile(*compdb);
if (opts.on_build_stop)
opts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));
if (not compdb->messages.entries.empty())
pleaseReport(opts, compdb);
if (unlikely(!program))
return nullptr;
program->compdb = std::move(compdb);
return ny::Program::pointer(program.release());
}
catch (...) {
}
if (opts.on_build_stop)
opts.on_build_stop(opts.userdata, nyfalse);
return nullptr;
}
} // namespace compiler
} // namespace ny
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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 the Willow Garage 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.
*********************************************************************/
/* Author: Wim Meeussen */
#include <map>
#include <string>
#include <vector>
#include <utility>
#include "kdl/frames_io.hpp"
#include "geometry_msgs/msg/transform_stamped.hpp"
#include "robot_state_publisher/robot_state_publisher.h"
namespace robot_state_publisher
{
inline
KDL::Frame transformToKDL(const geometry_msgs::msg::TransformStamped & t)
{
return KDL::Frame(KDL::Rotation::Quaternion(t.transform.rotation.x, t.transform.rotation.y,
t.transform.rotation.z, t.transform.rotation.w),
KDL::Vector(t.transform.translation.x, t.transform.translation.y,
t.transform.translation.z));
}
inline
geometry_msgs::msg::TransformStamped kdlToTransform(const KDL::Frame & k)
{
geometry_msgs::msg::TransformStamped t;
t.transform.translation.x = k.p.x();
t.transform.translation.y = k.p.y();
t.transform.translation.z = k.p.z();
k.M.GetQuaternion(t.transform.rotation.x, t.transform.rotation.y, t.transform.rotation.z,
t.transform.rotation.w);
return t;
}
RobotStatePublisher::RobotStatePublisher(
rclcpp::Node::SharedPtr node_handle,
const KDL::Tree & tree,
const urdf::Model & model,
const std::string & model_xml)
: model_(model),
tf_broadcaster_(node_handle),
static_tf_broadcaster_(node_handle),
description_published_(false),
clock_(node_handle->get_clock())
{
// walk the tree and add segments to segments_
addChildren(tree.getRootSegment());
model_xml_.data = model_xml;
node_handle->declare_parameter("robot_description", model_xml);
description_pub_ = node_handle->create_publisher<std_msgs::msg::String>(
"robot_description",
// Transient local is similar to latching in ROS 1.
rclcpp::QoS(1).transient_local());
}
// add children to correct maps
void RobotStatePublisher::addChildren(const KDL::SegmentMap::const_iterator segment)
{
auto root = GetTreeElementSegment(segment->second).getName();
auto children = GetTreeElementChildren(segment->second);
for (unsigned int i = 0; i < children.size(); i++) {
const KDL::Segment & child = GetTreeElementSegment(children[i]->second);
SegmentPair s(GetTreeElementSegment(children[i]->second), root, child.getName());
if (child.getJoint().getType() == KDL::Joint::None) {
if (model_.getJoint(child.getJoint().getName()) &&
model_.getJoint(child.getJoint().getName())->type == urdf::Joint::FLOATING)
{
fprintf(stderr,
"Floating joint. Not adding segment from %s to %s.\n",
root.c_str(), child.getName().c_str());
} else {
segments_fixed_.insert(make_pair(child.getJoint().getName(), s));
fprintf(stderr, "Adding fixed segment from %s to %s\n", root.c_str(),
child.getName().c_str());
}
} else {
segments_.insert(make_pair(child.getJoint().getName(), s));
fprintf(stderr, "Adding moving segment from %s to %s\n", root.c_str(),
child.getName().c_str());
}
addChildren(children[i]);
}
}
// publish moving transforms
void RobotStatePublisher::publishTransforms(
const std::map<std::string, double> & joint_positions,
const builtin_interfaces::msg::Time & time,
const std::string & tf_prefix)
{
// fprintf(stderr, "Publishing transforms for moving joints\n");
std::vector<geometry_msgs::msg::TransformStamped> tf_transforms;
// loop over all joints
for (auto jnt = joint_positions.begin(); jnt != joint_positions.end(); ++jnt) {
auto seg = segments_.find(jnt->first);
if (seg != segments_.end()) {
geometry_msgs::msg::TransformStamped tf_transform =
kdlToTransform(seg->second.segment.pose(jnt->second));
tf_transform.header.stamp = time;
tf_transform.header.frame_id = tf_prefix + "/" + seg->second.root;
tf_transform.child_frame_id = tf_prefix + "/" + seg->second.tip;
tf_transforms.push_back(tf_transform);
}
}
tf_broadcaster_.sendTransform(tf_transforms);
// Publish the robot description, as necessary
if (!description_published_) {
description_pub_->publish(model_xml_);
description_published_ = true;
}
}
// publish fixed transforms
void RobotStatePublisher::publishFixedTransforms(const std::string & tf_prefix, bool use_tf_static)
{
// fprintf(stderr, "Publishing transforms for fixed joints\n");
std::vector<geometry_msgs::msg::TransformStamped> tf_transforms;
geometry_msgs::msg::TransformStamped tf_transform;
// loop over all fixed segments
for (auto seg = segments_fixed_.begin(); seg != segments_fixed_.end(); seg++) {
geometry_msgs::msg::TransformStamped tf_transform = kdlToTransform(seg->second.segment.pose(0));
rclcpp::Time now = clock_->now();
if (!use_tf_static) {
now = now + rclcpp::Duration(std::chrono::milliseconds(500)); // 0.5sec in NS
}
tf_transform.header.stamp = now;
tf_transform.header.frame_id = tf_prefix + "/" + seg->second.root;
tf_transform.child_frame_id = tf_prefix + "/" + seg->second.tip;
tf_transforms.push_back(tf_transform);
}
if (use_tf_static) {
static_tf_broadcaster_.sendTransform(tf_transforms);
} else {
tf_broadcaster_.sendTransform(tf_transforms);
}
}
} // namespace robot_state_publisher
<commit_msg>Publish URDF string on startup. Don't wait until /joint_states is received. This allows unit testts and other programs that want to use the URDF (without parsing it themselves) but might not be hooked up to a live robot/simulation, or even know what joints exist before getting this URDF string.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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 the Willow Garage 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.
*********************************************************************/
/* Author: Wim Meeussen */
#include <map>
#include <string>
#include <vector>
#include <utility>
#include "kdl/frames_io.hpp"
#include "geometry_msgs/msg/transform_stamped.hpp"
#include "robot_state_publisher/robot_state_publisher.h"
namespace robot_state_publisher
{
inline
KDL::Frame transformToKDL(const geometry_msgs::msg::TransformStamped & t)
{
return KDL::Frame(KDL::Rotation::Quaternion(t.transform.rotation.x, t.transform.rotation.y,
t.transform.rotation.z, t.transform.rotation.w),
KDL::Vector(t.transform.translation.x, t.transform.translation.y,
t.transform.translation.z));
}
inline
geometry_msgs::msg::TransformStamped kdlToTransform(const KDL::Frame & k)
{
geometry_msgs::msg::TransformStamped t;
t.transform.translation.x = k.p.x();
t.transform.translation.y = k.p.y();
t.transform.translation.z = k.p.z();
k.M.GetQuaternion(t.transform.rotation.x, t.transform.rotation.y, t.transform.rotation.z,
t.transform.rotation.w);
return t;
}
RobotStatePublisher::RobotStatePublisher(
rclcpp::Node::SharedPtr node_handle,
const KDL::Tree & tree,
const urdf::Model & model,
const std::string & model_xml)
: model_(model),
tf_broadcaster_(node_handle),
static_tf_broadcaster_(node_handle),
description_published_(false),
clock_(node_handle->get_clock())
{
// walk the tree and add segments to segments_
addChildren(tree.getRootSegment());
model_xml_.data = model_xml;
node_handle->declare_parameter("robot_description", model_xml);
description_pub_ = node_handle->create_publisher<std_msgs::msg::String>(
"robot_description",
// Transient local is similar to latching in ROS 1.
rclcpp::QoS(1).transient_local());
// Publish the robot description, as necessary
if (!description_published_) {
description_pub_->publish(model_xml_);
description_published_ = true;
}
}
// add children to correct maps
void RobotStatePublisher::addChildren(const KDL::SegmentMap::const_iterator segment)
{
auto root = GetTreeElementSegment(segment->second).getName();
auto children = GetTreeElementChildren(segment->second);
for (unsigned int i = 0; i < children.size(); i++) {
const KDL::Segment & child = GetTreeElementSegment(children[i]->second);
SegmentPair s(GetTreeElementSegment(children[i]->second), root, child.getName());
if (child.getJoint().getType() == KDL::Joint::None) {
if (model_.getJoint(child.getJoint().getName()) &&
model_.getJoint(child.getJoint().getName())->type == urdf::Joint::FLOATING)
{
fprintf(stderr,
"Floating joint. Not adding segment from %s to %s.\n",
root.c_str(), child.getName().c_str());
} else {
segments_fixed_.insert(make_pair(child.getJoint().getName(), s));
fprintf(stderr, "Adding fixed segment from %s to %s\n", root.c_str(),
child.getName().c_str());
}
} else {
segments_.insert(make_pair(child.getJoint().getName(), s));
fprintf(stderr, "Adding moving segment from %s to %s\n", root.c_str(),
child.getName().c_str());
}
addChildren(children[i]);
}
}
// publish moving transforms
void RobotStatePublisher::publishTransforms(
const std::map<std::string, double> & joint_positions,
const builtin_interfaces::msg::Time & time,
const std::string & tf_prefix)
{
// fprintf(stderr, "Publishing transforms for moving joints\n");
std::vector<geometry_msgs::msg::TransformStamped> tf_transforms;
// loop over all joints
for (auto jnt = joint_positions.begin(); jnt != joint_positions.end(); ++jnt) {
auto seg = segments_.find(jnt->first);
if (seg != segments_.end()) {
geometry_msgs::msg::TransformStamped tf_transform =
kdlToTransform(seg->second.segment.pose(jnt->second));
tf_transform.header.stamp = time;
tf_transform.header.frame_id = tf_prefix + "/" + seg->second.root;
tf_transform.child_frame_id = tf_prefix + "/" + seg->second.tip;
tf_transforms.push_back(tf_transform);
}
}
tf_broadcaster_.sendTransform(tf_transforms);
}
// publish fixed transforms
void RobotStatePublisher::publishFixedTransforms(const std::string & tf_prefix, bool use_tf_static)
{
// fprintf(stderr, "Publishing transforms for fixed joints\n");
std::vector<geometry_msgs::msg::TransformStamped> tf_transforms;
geometry_msgs::msg::TransformStamped tf_transform;
// loop over all fixed segments
for (auto seg = segments_fixed_.begin(); seg != segments_fixed_.end(); seg++) {
geometry_msgs::msg::TransformStamped tf_transform = kdlToTransform(seg->second.segment.pose(0));
rclcpp::Time now = clock_->now();
if (!use_tf_static) {
now = now + rclcpp::Duration(std::chrono::milliseconds(500)); // 0.5sec in NS
}
tf_transform.header.stamp = now;
tf_transform.header.frame_id = tf_prefix + "/" + seg->second.root;
tf_transform.child_frame_id = tf_prefix + "/" + seg->second.tip;
tf_transforms.push_back(tf_transform);
}
if (use_tf_static) {
static_tf_broadcaster_.sendTransform(tf_transforms);
} else {
tf_broadcaster_.sendTransform(tf_transforms);
}
}
} // namespace robot_state_publisher
<|endoftext|> |
<commit_before>// Copyright (c) 2012, Steinwurf ApS
// 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 Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp"
#include "error.hpp"
#include <fstream>
#include <cassert>
namespace sak
{
file_input_stream::file_input_stream()
: m_filesize(0)
{
}
file_input_stream::file_input_stream(const std::string& filename)
: m_filesize(0)
{
open(filename);
}
void file_input_stream::open(const std::string& filename)
{
assert(!m_file.is_open());
boost::system::error_code ec;
open(filename, ec);
// If an error throw
std::cout << "before throw" << std::endl;
error::throw_error(ec);
}
void file_input_stream::open(const std::string& filename,
boost::system::error_code& ec)
{
assert(!m_file.is_open());
m_file.open(filename.c_str(),
std::ios::in | std::ios::binary);
if (!m_file.is_open())
{
ec = error::make_error_code(error::failed_open_file);
return;
}
m_file.seekg(0, std::ios::end);
assert(m_file);
// We cannot use the read_position function here due to a
// problem on the iOS platform described in the read_position
// function.
auto pos = m_file.tellg();
assert(pos >= 0);
m_filesize = (uint32_t) pos;
m_file.seekg(0, std::ios::beg);
assert(m_file);
}
void file_input_stream::seek(uint32_t pos)
{
assert(m_file.is_open());
m_file.seekg(pos, std::ios::beg);
assert(m_file);
}
uint32_t file_input_stream::read_position()
{
assert(m_file.is_open());
// Work around for problem on iOS where tellg returned -1 when
// reading the last byte. However the EOF flag was correctly
// set. So here we check for EOF if true we set the
// read_position = m_file_size
if(m_file.eof())
{
return m_filesize;
}
else
{
std::streamoff pos = m_file.tellg();
assert(pos >= 0);
return static_cast<uint32_t>(pos);
}
}
void file_input_stream::read(uint8_t* buffer, uint32_t bytes)
{
assert(m_file.is_open());
m_file.read(reinterpret_cast<char*>(buffer), bytes);
assert(bytes == static_cast<uint32_t>(m_file.gcount()));
}
uint32_t file_input_stream::bytes_available()
{
assert(m_file.is_open());
uint32_t pos = read_position();
assert(pos <= m_filesize);
return m_filesize - pos;
}
uint32_t file_input_stream::size()
{
assert(m_file.is_open());
return m_filesize;
}
}
<commit_msg>Trying to throw without boost<commit_after>// Copyright (c) 2012, Steinwurf ApS
// 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 Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp"
#include "error.hpp"
#include <fstream>
#include <cassert>
namespace sak
{
file_input_stream::file_input_stream()
: m_filesize(0)
{
}
file_input_stream::file_input_stream(const std::string& filename)
: m_filesize(0)
{
open(filename);
}
void file_input_stream::open(const std::string& filename)
{
assert(!m_file.is_open());
boost::system::error_code ec;
open(filename, ec);
// If an error throw
std::cout << "before throw" << std::endl;
if(ec)
{
boost::system::system_error e(ec);
std::cout << "right before throw" << std::endl;
throw ec;
}
// error::throw_error(ec);
}
void file_input_stream::open(const std::string& filename,
boost::system::error_code& ec)
{
assert(!m_file.is_open());
m_file.open(filename.c_str(),
std::ios::in | std::ios::binary);
if (!m_file.is_open())
{
ec = error::make_error_code(error::failed_open_file);
return;
}
m_file.seekg(0, std::ios::end);
assert(m_file);
// We cannot use the read_position function here due to a
// problem on the iOS platform described in the read_position
// function.
auto pos = m_file.tellg();
assert(pos >= 0);
m_filesize = (uint32_t) pos;
m_file.seekg(0, std::ios::beg);
assert(m_file);
}
void file_input_stream::seek(uint32_t pos)
{
assert(m_file.is_open());
m_file.seekg(pos, std::ios::beg);
assert(m_file);
}
uint32_t file_input_stream::read_position()
{
assert(m_file.is_open());
// Work around for problem on iOS where tellg returned -1 when
// reading the last byte. However the EOF flag was correctly
// set. So here we check for EOF if true we set the
// read_position = m_file_size
if(m_file.eof())
{
return m_filesize;
}
else
{
std::streamoff pos = m_file.tellg();
assert(pos >= 0);
return static_cast<uint32_t>(pos);
}
}
void file_input_stream::read(uint8_t* buffer, uint32_t bytes)
{
assert(m_file.is_open());
m_file.read(reinterpret_cast<char*>(buffer), bytes);
assert(bytes == static_cast<uint32_t>(m_file.gcount()));
}
uint32_t file_input_stream::bytes_available()
{
assert(m_file.is_open());
uint32_t pos = read_position();
assert(pos <= m_filesize);
return m_filesize - pos;
}
uint32_t file_input_stream::size()
{
assert(m_file.is_open());
return m_filesize;
}
}
<|endoftext|> |
<commit_before>#include "GameWindow.h"
GameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()
{
/****Central widget****/
GameModeWidget * m_gameModeWidget;
AngleStatusWidget * m_currentAngle;
FirePowerWidget * m_currentPower;
this->setCentralWidget(m_game.getView());
/****Bottom Widget (Information about player)****/
QWidget* bottomWidget = new QWidget;
QDockWidget* informationPanel = new QDockWidget;
informationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
informationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);
GameBottomLayout *bottomLayout = new GameBottomLayout;
m_gameModeWidget = new GameModeWidget;
bottomLayout->addWidget(m_gameModeWidget);
//This should be an object with custom paint method to make it interesting
m_currentAngle = new AngleStatusWidget;
m_currentAngle->setAngle(0);
//This will be an object with custom paint method to make it interesting
m_currentPower = new FirePowerWidget;
m_currentPower->setPower(50);
bottomLayout->addStretch();
bottomLayout->addWidget(m_currentAngle);
bottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);
bottomLayout->addWidget(m_currentPower);
bottomWidget->setLayout(bottomLayout);
informationPanel->setWidget(bottomWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);
connect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);
connect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);
connect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);
connect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);
/****Menus****/
m_menuBar = new QMenuBar;
m_menuFile = new QMenu("Fichier");
m_actionQuit = new QAction("Quitter", this);
m_actionNewGame = new QAction("New game", this);
connect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);
m_menuFile->addAction(m_actionNewGame);
m_menuFile->addSeparator();
m_menuFile->addAction(m_actionQuit);
m_menuBar->addMenu(m_menuFile);
this->setMenuBar(m_menuBar);
this->setWindowTitle("Scorch");
this->setStatusBar(new QStatusBar);
setFocusPolicy(Qt::TabFocus);
connect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);
/****Connect Game****/
connect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);
connect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);
connect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);
connect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);
}
GameWindow::~GameWindow()
{
}
void GameWindow::displayStatusMessage(QString message)
{
statusBar()->showMessage(message);
}
void GameWindow::playerChanged(Player p_player)
{
emit changePlayer(p_player);
}
void GameWindow::stateChanged(State p_state)
{
emit changeState(p_state);
}
void GameWindow::angleChanged(float p_angle)
{
emit changeAngle(p_angle);
}
void GameWindow::powerChanged(float p_power)
{
emit changePower(p_power);
}
void GameWindow::keyPressEvent(QKeyEvent * KeyEvent)
{
//NOTE: Hack to simulate correctly the FPGA input
m_fpga.handlePressEvent(KeyEvent);
}
void GameWindow::customEvent(QEvent *event)
{
if(event->type() == FPGAEvent::customFPGAEvent) {
FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);
QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));
}
}
<commit_msg>Fix bug where you had to press tab to get focus<commit_after>#include "GameWindow.h"
GameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()
{
/****Central widget****/
GameModeWidget * m_gameModeWidget;
AngleStatusWidget * m_currentAngle;
FirePowerWidget * m_currentPower;
this->setCentralWidget(m_game.getView());
/****Bottom Widget (Information about player)****/
QWidget* bottomWidget = new QWidget;
QDockWidget* informationPanel = new QDockWidget;
informationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
informationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);
GameBottomLayout *bottomLayout = new GameBottomLayout;
m_gameModeWidget = new GameModeWidget;
bottomLayout->addWidget(m_gameModeWidget);
//This should be an object with custom paint method to make it interesting
m_currentAngle = new AngleStatusWidget;
m_currentAngle->setAngle(0);
//This will be an object with custom paint method to make it interesting
m_currentPower = new FirePowerWidget;
m_currentPower->setPower(50);
bottomLayout->addStretch();
bottomLayout->addWidget(m_currentAngle);
bottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);
bottomLayout->addWidget(m_currentPower);
bottomWidget->setLayout(bottomLayout);
informationPanel->setWidget(bottomWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);
connect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);
connect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);
connect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);
connect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);
/****Menus****/
m_menuBar = new QMenuBar;
m_menuFile = new QMenu("Fichier");
m_actionQuit = new QAction("Quitter", this);
m_actionNewGame = new QAction("New game", this);
connect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);
m_menuFile->addAction(m_actionNewGame);
m_menuFile->addSeparator();
m_menuFile->addAction(m_actionQuit);
m_menuBar->addMenu(m_menuFile);
this->setMenuBar(m_menuBar);
this->setWindowTitle("Scorch");
this->setStatusBar(new QStatusBar);
setFocus();
m_game.getView()->setFocusPolicy(Qt::NoFocus);
connect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);
/****Connect Game****/
connect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);
connect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);
connect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);
connect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);
}
GameWindow::~GameWindow()
{
}
void GameWindow::displayStatusMessage(QString message)
{
statusBar()->showMessage(message);
}
void GameWindow::playerChanged(Player p_player)
{
emit changePlayer(p_player);
}
void GameWindow::stateChanged(State p_state)
{
emit changeState(p_state);
}
void GameWindow::angleChanged(float p_angle)
{
emit changeAngle(p_angle);
}
void GameWindow::powerChanged(float p_power)
{
emit changePower(p_power);
}
void GameWindow::keyPressEvent(QKeyEvent * KeyEvent)
{
//NOTE: Hack to simulate correctly the FPGA input
m_fpga.handlePressEvent(KeyEvent);
}
void GameWindow::customEvent(QEvent *event)
{
if(event->type() == FPGAEvent::customFPGAEvent) {
FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);
QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));
}
}
<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "MobSpawner.h"
#include "Mobs/IncludeAllMonsters.h"
#include "World.h"
cMobSpawner::cMobSpawner(cMonster::eFamily a_MonsterFamily, const std::set<eMonsterType>& a_AllowedTypes) :
m_MonsterFamily(a_MonsterFamily),
m_NewPack(true),
m_MobType(mtInvalidType)
{
for (std::set<eMonsterType>::const_iterator itr = a_AllowedTypes.begin(); itr != a_AllowedTypes.end(); ++itr)
{
if (cMonster::FamilyFromType(*itr) == a_MonsterFamily)
{
m_AllowedTypes.insert(*itr);
}
}
}
bool cMobSpawner::CheckPackCenter(BLOCKTYPE a_BlockType)
{
// Packs of non-water mobs can only be centered on an air block
// Packs of water mobs can only be centered on a water block
if (m_MonsterFamily == cMonster::mfWater)
{
return IsBlockWater(a_BlockType);
}
else
{
return a_BlockType == E_BLOCK_AIR;
}
}
void cMobSpawner::addIfAllowed(eMonsterType toAdd, std::set<eMonsterType>& toAddIn)
{
std::set<eMonsterType>::iterator itr = m_AllowedTypes.find(toAdd);
if (itr != m_AllowedTypes.end())
{
toAddIn.insert(toAdd);
}
}
eMonsterType cMobSpawner::ChooseMobType(EMCSBiome a_Biome)
{
std::set<eMonsterType> allowedMobs;
if ((a_Biome == biMushroomIsland) || (a_Biome == biMushroomShore))
{
addIfAllowed(mtMooshroom, allowedMobs);
}
else if (a_Biome == biNether)
{
addIfAllowed(mtGhast, allowedMobs);
addIfAllowed(mtZombiePigman, allowedMobs);
addIfAllowed(mtMagmaCube, allowedMobs);
}
else if (a_Biome == biEnd)
{
addIfAllowed(mtEnderman, allowedMobs);
}
else
{
addIfAllowed(mtBat, allowedMobs);
addIfAllowed(mtSpider, allowedMobs);
addIfAllowed(mtZombie, allowedMobs);
addIfAllowed(mtSkeleton, allowedMobs);
addIfAllowed(mtCreeper, allowedMobs);
addIfAllowed(mtSquid, allowedMobs);
addIfAllowed(mtGuardian, allowedMobs);
if ((a_Biome != biDesert) && (a_Biome != biBeach) && (a_Biome != biOcean))
{
addIfAllowed(mtSheep, allowedMobs);
addIfAllowed(mtPig, allowedMobs);
addIfAllowed(mtCow, allowedMobs);
addIfAllowed(mtChicken, allowedMobs);
addIfAllowed(mtEnderman, allowedMobs);
addIfAllowed(mtRabbit, allowedMobs);
addIfAllowed(mtSlime, allowedMobs); // MG TODO : much more complicated rule
if ((a_Biome == biForest) || (a_Biome == biForestHills) || (a_Biome == biTaiga) || (a_Biome == biTaigaHills))
{
addIfAllowed(mtWolf, allowedMobs);
}
else if ((a_Biome == biJungle) || (a_Biome == biJungleHills))
{
addIfAllowed(mtOcelot, allowedMobs);
}
}
}
size_t allowedMobsSize = allowedMobs.size();
if (allowedMobsSize > 0)
{
std::set<eMonsterType>::iterator itr = allowedMobs.begin();
int iRandom = m_Random.NextInt(static_cast<int>(allowedMobsSize));
for (int i = 0; i < iRandom; i++)
{
++itr;
}
return *itr;
}
return mtInvalidType;
}
bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)
{
if (a_Chunk == nullptr)
{
return false;
}
cFastRandom Random;
BLOCKTYPE TargetBlock = a_Chunk->GetBlock(a_RelX, a_RelY, a_RelZ);
cPlayer * a_Closest_Player = a_Chunk->GetWorld()->FindClosestPlayer(a_Chunk->PositionToWorldPosition(a_RelX, a_RelY, a_RelZ), 24);
if (a_Closest_Player != nullptr) // Too close to a player, bail out
{
return false;
}
if ((a_RelY >= cChunkDef::Height - 1) || (a_RelY <= 0))
{
return false;
}
NIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);
NIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);
BLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);
BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);
SkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);
switch (a_MobType)
{
case mtGuardian:
{
return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
}
case mtSquid:
{
return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
}
case mtBat:
{
return (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);
}
case mtChicken:
case mtCow:
case mtPig:
case mtHorse:
case mtRabbit:
case mtSheep:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(BlockBelow == E_BLOCK_GRASS) &&
(SkyLight >= 9)
);
}
case mtOcelot:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)
) &&
(a_RelY >= 62) &&
(Random.NextInt(3) != 0)
);
}
case mtEnderman:
{
if (a_RelY < 250)
{
BLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);
if (BlockTop == E_BLOCK_AIR)
{
BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(BlockTop == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7)
);
}
}
break;
}
case mtSpider:
{
bool CanSpawn = true;
bool HasFloor = false;
for (int x = 0; x < 2; ++x)
{
for (int z = 0; z < 2; ++z)
{
CanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);
CanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);
if (!CanSpawn)
{
return false;
}
HasFloor = (
HasFloor ||
(
a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&
!cBlockInfo::IsTransparent(TargetBlock)
)
);
}
}
return CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);
}
case mtCaveSpider:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7) &&
(Random.NextInt(2) == 0)
);
}
case mtCreeper:
case mtSkeleton:
case mtZombie:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7) &&
(Random.NextInt(2) == 0)
);
}
case mtMagmaCube:
case mtSlime:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(
(a_RelY <= 40) || (a_Biome == biSwampland)
)
);
}
case mtGhast:
case mtZombiePigman:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(Random.NextInt(20) == 0)
);
}
case mtWolf:
{
return (
(TargetBlock == E_BLOCK_GRASS) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(a_Biome == biTaiga) ||
(a_Biome == biTaigaHills) ||
(a_Biome == biForest) ||
(a_Biome == biForestHills) ||
(a_Biome == biColdTaiga) ||
(a_Biome == biColdTaigaHills) ||
(a_Biome == biTaigaM) ||
(a_Biome == biMegaTaiga) ||
(a_Biome == biMegaTaigaHills)
)
);
}
case mtMooshroom:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(BlockBelow == E_BLOCK_MYCELIUM) &&
(
(a_Biome == biMushroomShore) ||
(a_Biome == biMushroomIsland)
)
);
}
default:
{
LOGD("MG TODO: Write spawning rule for mob type %d", a_MobType);
return false;
}
}
return false;
}
cMonster * cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int & a_MaxPackSize)
{
cMonster * toReturn = nullptr;
if (m_NewPack)
{
m_MobType = ChooseMobType(a_Biome);
if (m_MobType == mtInvalidType)
{
return toReturn;
}
if (m_MobType == mtWolf)
{
a_MaxPackSize = 8;
}
else if (m_MobType == mtGhast)
{
a_MaxPackSize = 1;
}
m_NewPack = false;
}
// Make sure we are looking at the right chunk to spawn in
a_Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);
if ((m_AllowedTypes.find(m_MobType) != m_AllowedTypes.end()) && CanSpawnHere(a_Chunk, a_RelX, a_RelY, a_RelZ, m_MobType, a_Biome))
{
cMonster * newMob = cMonster::NewMonsterFromType(m_MobType);
if (newMob)
{
m_Spawned.insert(newMob);
}
toReturn = newMob;
}
return toReturn;
}
void cMobSpawner::NewPack()
{
m_NewPack = true;
}
cMobSpawner::tSpawnedContainer & cMobSpawner::getSpawned(void)
{
return m_Spawned;
}
bool cMobSpawner::CanSpawnAnything(void)
{
return !m_AllowedTypes.empty();
}
<commit_msg>Mobs no longer spawn at the top of the nether.<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "MobSpawner.h"
#include "Mobs/IncludeAllMonsters.h"
#include "World.h"
cMobSpawner::cMobSpawner(cMonster::eFamily a_MonsterFamily, const std::set<eMonsterType>& a_AllowedTypes) :
m_MonsterFamily(a_MonsterFamily),
m_NewPack(true),
m_MobType(mtInvalidType)
{
for (std::set<eMonsterType>::const_iterator itr = a_AllowedTypes.begin(); itr != a_AllowedTypes.end(); ++itr)
{
if (cMonster::FamilyFromType(*itr) == a_MonsterFamily)
{
m_AllowedTypes.insert(*itr);
}
}
}
bool cMobSpawner::CheckPackCenter(BLOCKTYPE a_BlockType)
{
// Packs of non-water mobs can only be centered on an air block
// Packs of water mobs can only be centered on a water block
if (m_MonsterFamily == cMonster::mfWater)
{
return IsBlockWater(a_BlockType);
}
else
{
return a_BlockType == E_BLOCK_AIR;
}
}
void cMobSpawner::addIfAllowed(eMonsterType toAdd, std::set<eMonsterType>& toAddIn)
{
std::set<eMonsterType>::iterator itr = m_AllowedTypes.find(toAdd);
if (itr != m_AllowedTypes.end())
{
toAddIn.insert(toAdd);
}
}
eMonsterType cMobSpawner::ChooseMobType(EMCSBiome a_Biome)
{
std::set<eMonsterType> allowedMobs;
if ((a_Biome == biMushroomIsland) || (a_Biome == biMushroomShore))
{
addIfAllowed(mtMooshroom, allowedMobs);
}
else if (a_Biome == biNether)
{
addIfAllowed(mtGhast, allowedMobs);
addIfAllowed(mtZombiePigman, allowedMobs);
addIfAllowed(mtMagmaCube, allowedMobs);
}
else if (a_Biome == biEnd)
{
addIfAllowed(mtEnderman, allowedMobs);
}
else
{
addIfAllowed(mtBat, allowedMobs);
addIfAllowed(mtSpider, allowedMobs);
addIfAllowed(mtZombie, allowedMobs);
addIfAllowed(mtSkeleton, allowedMobs);
addIfAllowed(mtCreeper, allowedMobs);
addIfAllowed(mtSquid, allowedMobs);
addIfAllowed(mtGuardian, allowedMobs);
if ((a_Biome != biDesert) && (a_Biome != biBeach) && (a_Biome != biOcean))
{
addIfAllowed(mtSheep, allowedMobs);
addIfAllowed(mtPig, allowedMobs);
addIfAllowed(mtCow, allowedMobs);
addIfAllowed(mtChicken, allowedMobs);
addIfAllowed(mtEnderman, allowedMobs);
addIfAllowed(mtRabbit, allowedMobs);
addIfAllowed(mtSlime, allowedMobs); // MG TODO : much more complicated rule
if ((a_Biome == biForest) || (a_Biome == biForestHills) || (a_Biome == biTaiga) || (a_Biome == biTaigaHills))
{
addIfAllowed(mtWolf, allowedMobs);
}
else if ((a_Biome == biJungle) || (a_Biome == biJungleHills))
{
addIfAllowed(mtOcelot, allowedMobs);
}
}
}
size_t allowedMobsSize = allowedMobs.size();
if (allowedMobsSize > 0)
{
std::set<eMonsterType>::iterator itr = allowedMobs.begin();
int iRandom = m_Random.NextInt(static_cast<int>(allowedMobsSize));
for (int i = 0; i < iRandom; i++)
{
++itr;
}
return *itr;
}
return mtInvalidType;
}
bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)
{
if (a_Chunk == nullptr)
{
return false;
}
if (cChunkDef::IsValidHeight(a_RelY - 1) && (a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_BEDROCK))
{
return false; // Make sure mobs do not spawn on bedrock.
}
cFastRandom Random;
BLOCKTYPE TargetBlock = a_Chunk->GetBlock(a_RelX, a_RelY, a_RelZ);
cPlayer * a_Closest_Player = a_Chunk->GetWorld()->FindClosestPlayer(a_Chunk->PositionToWorldPosition(a_RelX, a_RelY, a_RelZ), 24);
if (a_Closest_Player != nullptr) // Too close to a player, bail out
{
return false;
}
if ((a_RelY >= cChunkDef::Height - 1) || (a_RelY <= 0))
{
return false;
}
NIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);
NIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);
BLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);
BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);
SkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);
switch (a_MobType)
{
case mtGuardian:
{
return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
}
case mtSquid:
{
return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
}
case mtBat:
{
return (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);
}
case mtChicken:
case mtCow:
case mtPig:
case mtHorse:
case mtRabbit:
case mtSheep:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(BlockBelow == E_BLOCK_GRASS) &&
(SkyLight >= 9)
);
}
case mtOcelot:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)
) &&
(a_RelY >= 62) &&
(Random.NextInt(3) != 0)
);
}
case mtEnderman:
{
if (a_RelY < 250)
{
BLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);
if (BlockTop == E_BLOCK_AIR)
{
BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(BlockTop == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7)
);
}
}
break;
}
case mtSpider:
{
bool CanSpawn = true;
bool HasFloor = false;
for (int x = 0; x < 2; ++x)
{
for (int z = 0; z < 2; ++z)
{
CanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);
CanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);
if (!CanSpawn)
{
return false;
}
HasFloor = (
HasFloor ||
(
a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&
!cBlockInfo::IsTransparent(TargetBlock)
)
);
}
}
return CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);
}
case mtCaveSpider:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7) &&
(Random.NextInt(2) == 0)
);
}
case mtCreeper:
case mtSkeleton:
case mtZombie:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7) &&
(Random.NextInt(2) == 0)
);
}
case mtMagmaCube:
case mtSlime:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(
(a_RelY <= 40) || (a_Biome == biSwampland)
)
);
}
case mtGhast:
case mtZombiePigman:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(Random.NextInt(20) == 0)
);
}
case mtWolf:
{
return (
(TargetBlock == E_BLOCK_GRASS) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(a_Biome == biTaiga) ||
(a_Biome == biTaigaHills) ||
(a_Biome == biForest) ||
(a_Biome == biForestHills) ||
(a_Biome == biColdTaiga) ||
(a_Biome == biColdTaigaHills) ||
(a_Biome == biTaigaM) ||
(a_Biome == biMegaTaiga) ||
(a_Biome == biMegaTaigaHills)
)
);
}
case mtMooshroom:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(BlockBelow == E_BLOCK_MYCELIUM) &&
(
(a_Biome == biMushroomShore) ||
(a_Biome == biMushroomIsland)
)
);
}
default:
{
LOGD("MG TODO: Write spawning rule for mob type %d", a_MobType);
return false;
}
}
return false;
}
cMonster * cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int & a_MaxPackSize)
{
cMonster * toReturn = nullptr;
if (m_NewPack)
{
m_MobType = ChooseMobType(a_Biome);
if (m_MobType == mtInvalidType)
{
return toReturn;
}
if (m_MobType == mtWolf)
{
a_MaxPackSize = 8;
}
else if (m_MobType == mtGhast)
{
a_MaxPackSize = 1;
}
m_NewPack = false;
}
// Make sure we are looking at the right chunk to spawn in
a_Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);
if ((m_AllowedTypes.find(m_MobType) != m_AllowedTypes.end()) && CanSpawnHere(a_Chunk, a_RelX, a_RelY, a_RelZ, m_MobType, a_Biome))
{
cMonster * newMob = cMonster::NewMonsterFromType(m_MobType);
if (newMob)
{
m_Spawned.insert(newMob);
}
toReturn = newMob;
}
return toReturn;
}
void cMobSpawner::NewPack()
{
m_NewPack = true;
}
cMobSpawner::tSpawnedContainer & cMobSpawner::getSpawned(void)
{
return m_Spawned;
}
bool cMobSpawner::CanSpawnAnything(void)
{
return !m_AllowedTypes.empty();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XMLRedlineImportHelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: dvo $ $Date: 2001-11-30 17:38:02 $
*
* 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 _XMLREDLINEIMPORTHELPER_HXX
#define _XMLREDLINEIMPORTHELPER_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _REDLINE_HXX
#include "redline.hxx"
#endif
#ifndef _REDLENUM_HXX
#include "redlenum.hxx"
#endif
#include <map>
class RedlineInfo;
class SwRedlineData;
class SwDoc;
namespace com { namespace sun { namespace star {
namespace text { class XTextCursor; }
namespace text { class XTextRange; }
namespace frame { class XModel; }
} } }
typedef ::std::map< ::rtl::OUString, RedlineInfo* > RedlineMapType;
class XMLRedlineImportHelper
{
const ::rtl::OUString sEmpty;
const ::rtl::OUString sInsertion;
const ::rtl::OUString sDeletion;
const ::rtl::OUString sFormatChange;
const ::rtl::OUString sShowChanges;
const ::rtl::OUString sRecordChanges;
const ::rtl::OUString sRedlineProtectionKey;
RedlineMapType aRedlineMap;
/// if sal_True, no redlines should be inserted into document
/// (This typically happen when a document is loaded in 'insert'-mode.)
sal_Bool bIgnoreRedlines;
/// save information for saving and reconstruction of the redline mode
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> xModelPropertySet;
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> xImportInfoPropertySet;
sal_Bool bShowChanges;
sal_Bool bRecordChanges;
::com::sun::star::uno::Sequence<sal_Int8> aProtectionKey;
public:
XMLRedlineImportHelper(
sal_Bool bIgnoreRedlines, /// ignore redlines mode
// property sets of model + import info for saving + restoring the
// redline mode
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rModel,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rImportInfoSet );
virtual ~XMLRedlineImportHelper();
/// create a redline object
/// (The redline will be inserted into the document after both start
/// and end cursor has been set.)
void Add(
const ::rtl::OUString& rType, /// redline type (insert, del,... )
const ::rtl::OUString& rId, /// use to identify this redline
const ::rtl::OUString& rAuthor, /// name of the author
const ::rtl::OUString& rComment, /// redline comment
const ::com::sun::star::util::DateTime& rDateTime, /// date+time
sal_Bool bMergeLastParagraph); /// merge last paragraph?
/// create a text section for the redline, and return an
/// XText/XTextCursor that may be used to write into it.
::com::sun::star::uno::Reference<
::com::sun::star::text::XTextCursor> CreateRedlineTextSection(
::com::sun::star::uno::Reference< /// needed to get the document
::com::sun::star::text::XTextCursor> xOldCursor,
const ::rtl::OUString& rId); /// ID used to RedlineAdd() call
/// Set start or end position for a redline in the text body.
/// Accepts XTextRange objects.
void SetCursor(
const ::rtl::OUString& rId, /// ID used in RedlineAdd() call
sal_Bool bStart, /// start or end Range
::com::sun::star::uno::Reference< /// the actual XTextRange
::com::sun::star::text::XTextRange> & rRange,
/// text range is (from an XML view) outside of a paragraph
/// (i.e. before a table)
sal_Bool bIsOusideOfParagraph);
/**
* Adjust the start (end) position for a redline that begins in a
* start node. It takes the cursor positions _inside_ the redlined
* element (e.g. section or table).
*
* We will do sanity checking of the given text range: It will
* only be considered valid if it points to the next text node
* after the position given in a previous SetCursor */
void AdjustStartNodeCursor(
const ::rtl::OUString& rId, /// ID used in RedlineAdd() call
sal_Bool bStart,
/// XTextRange _inside_ a table/section
::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange> & rRange);
/// set redline mode: show changes
void SetShowChanges( sal_Bool bShowChanges );
/// set redline mode: record changes
void SetRecordChanges( sal_Bool bRecordChanges );
/// set redline protection key
void SetProtectionKey(
const ::com::sun::star::uno::Sequence<sal_Int8> & rKey );
private:
inline sal_Bool IsReady(RedlineInfo* pRedline);
void InsertIntoDocument(RedlineInfo* pRedline);
SwRedlineData* ConvertRedline(
RedlineInfo* pRedline, /// RedlineInfo to be converted
SwDoc* pDoc); /// document needed for Author-ID conversion
/** save the redline mode (if rPropertySet is non-null) */
void SaveRedlineMode(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropertySet);
/** don't restore the saved redline mode */
void DontRestoreRedlineMode();
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.1436); FILE MERGED 2005/09/05 13:42:47 rt 1.5.1436.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLRedlineImportHelper.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:17:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLREDLINEIMPORTHELPER_HXX
#define _XMLREDLINEIMPORTHELPER_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _REDLINE_HXX
#include "redline.hxx"
#endif
#ifndef _REDLENUM_HXX
#include "redlenum.hxx"
#endif
#include <map>
class RedlineInfo;
class SwRedlineData;
class SwDoc;
namespace com { namespace sun { namespace star {
namespace text { class XTextCursor; }
namespace text { class XTextRange; }
namespace frame { class XModel; }
} } }
typedef ::std::map< ::rtl::OUString, RedlineInfo* > RedlineMapType;
class XMLRedlineImportHelper
{
const ::rtl::OUString sEmpty;
const ::rtl::OUString sInsertion;
const ::rtl::OUString sDeletion;
const ::rtl::OUString sFormatChange;
const ::rtl::OUString sShowChanges;
const ::rtl::OUString sRecordChanges;
const ::rtl::OUString sRedlineProtectionKey;
RedlineMapType aRedlineMap;
/// if sal_True, no redlines should be inserted into document
/// (This typically happen when a document is loaded in 'insert'-mode.)
sal_Bool bIgnoreRedlines;
/// save information for saving and reconstruction of the redline mode
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> xModelPropertySet;
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> xImportInfoPropertySet;
sal_Bool bShowChanges;
sal_Bool bRecordChanges;
::com::sun::star::uno::Sequence<sal_Int8> aProtectionKey;
public:
XMLRedlineImportHelper(
sal_Bool bIgnoreRedlines, /// ignore redlines mode
// property sets of model + import info for saving + restoring the
// redline mode
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rModel,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rImportInfoSet );
virtual ~XMLRedlineImportHelper();
/// create a redline object
/// (The redline will be inserted into the document after both start
/// and end cursor has been set.)
void Add(
const ::rtl::OUString& rType, /// redline type (insert, del,... )
const ::rtl::OUString& rId, /// use to identify this redline
const ::rtl::OUString& rAuthor, /// name of the author
const ::rtl::OUString& rComment, /// redline comment
const ::com::sun::star::util::DateTime& rDateTime, /// date+time
sal_Bool bMergeLastParagraph); /// merge last paragraph?
/// create a text section for the redline, and return an
/// XText/XTextCursor that may be used to write into it.
::com::sun::star::uno::Reference<
::com::sun::star::text::XTextCursor> CreateRedlineTextSection(
::com::sun::star::uno::Reference< /// needed to get the document
::com::sun::star::text::XTextCursor> xOldCursor,
const ::rtl::OUString& rId); /// ID used to RedlineAdd() call
/// Set start or end position for a redline in the text body.
/// Accepts XTextRange objects.
void SetCursor(
const ::rtl::OUString& rId, /// ID used in RedlineAdd() call
sal_Bool bStart, /// start or end Range
::com::sun::star::uno::Reference< /// the actual XTextRange
::com::sun::star::text::XTextRange> & rRange,
/// text range is (from an XML view) outside of a paragraph
/// (i.e. before a table)
sal_Bool bIsOusideOfParagraph);
/**
* Adjust the start (end) position for a redline that begins in a
* start node. It takes the cursor positions _inside_ the redlined
* element (e.g. section or table).
*
* We will do sanity checking of the given text range: It will
* only be considered valid if it points to the next text node
* after the position given in a previous SetCursor */
void AdjustStartNodeCursor(
const ::rtl::OUString& rId, /// ID used in RedlineAdd() call
sal_Bool bStart,
/// XTextRange _inside_ a table/section
::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange> & rRange);
/// set redline mode: show changes
void SetShowChanges( sal_Bool bShowChanges );
/// set redline mode: record changes
void SetRecordChanges( sal_Bool bRecordChanges );
/// set redline protection key
void SetProtectionKey(
const ::com::sun::star::uno::Sequence<sal_Int8> & rKey );
private:
inline sal_Bool IsReady(RedlineInfo* pRedline);
void InsertIntoDocument(RedlineInfo* pRedline);
SwRedlineData* ConvertRedline(
RedlineInfo* pRedline, /// RedlineInfo to be converted
SwDoc* pDoc); /// document needed for Author-ID conversion
/** save the redline mode (if rPropertySet is non-null) */
void SaveRedlineMode(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropertySet);
/** don't restore the saved redline mode */
void DontRestoreRedlineMode();
};
#endif
<|endoftext|> |
<commit_before>#include "scrapers/GamesDBScraper.h"
#include "Log.h"
#include "pugixml/pugixml.hpp"
#include "MetaData.h"
#include "Settings.h"
#include "Util.h"
#include <boost/assign.hpp>
using namespace PlatformIds;
const std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of
(THREEDO, "3DO")
(AMIGA, "Amiga")
(AMSTRAD_CPC, "Amstrad CPC")
// missing apple2
(ARCADE, "Arcade")
// missing atari 800
(ATARI_2600, "Atari 2600")
(ATARI_5200, "Atari 5200")
(ATARI_7800, "Atari 7800")
(ATARI_JAGUAR, "Atari Jaguar")
(ATARI_JAGUAR_CD, "Atari Jaguar CD")
(ATARI_LYNX, "Atari Lynx")
// missing atari ST/STE/Falcon
(ATARI_XE, "Atari XE")
(COLECOVISION, "Colecovision")
(COMMODORE_64, "Commodore 64")
(INTELLIVISION, "Intellivision")
(MAC_OS, "Mac OS")
(XBOX, "Microsoft Xbox")
(XBOX_360, "Microsoft Xbox 360")
// missing MSX
(NEOGEO, "NeoGeo")
(NEOGEO_POCKET, "Neo Geo Pocket")
(NEOGEO_POCKET_COLOR, "Neo Geo Pocket Color")
(NINTENDO_3DS, "Nintendo 3DS")
(NINTENDO_64, "Nintendo 64")
(NINTENDO_DS, "Nintendo DS")
(NINTENDO_ENTERTAINMENT_SYSTEM, "Nintendo Entertainment System (NES)")
(GAME_BOY, "Nintendo Game Boy")
(GAME_BOY_ADVANCE, "Nintendo Game Boy Advance")
(GAME_BOY_COLOR, "Nintendo Game Boy Color")
(NINTENDO_GAMECUBE, "Nintendo GameCube")
(NINTENDO_WII, "Nintendo Wii")
(NINTENDO_WII_U, "Nintendo Wii U")
(PC, "PC")
(SEGA_32X, "Sega 32X")
(SEGA_CD, "Sega CD")
(SEGA_DREAMCAST, "Sega Dreamcast")
(SEGA_GAME_GEAR, "Sega Game Gear")
(SEGA_GENESIS, "Sega Genesis")
(SEGA_MASTER_SYSTEM, "Sega Master System")
(SEGA_MEGA_DRIVE, "Sega Mega Drive")
(SEGA_SATURN, "Sega Saturn")
(PLAYSTATION, "Sony Playstation")
(PLAYSTATION_2, "Sony Playstation 2")
(PLAYSTATION_3, "Sony Playstation 3")
(PLAYSTATION_4, "Sony Playstation 4")
(PLAYSTATION_VITA, "Sony Playstation Vita")
(PLAYSTATION_PORTABLE, "Sony PSP")
(SUPER_NINTENDO, "Super Nintendo (SNES)")
(TURBOGRAFX_16, "TurboGrafx 16")
(WONDERSWAN, "WonderSwan")
(WONDERSWAN_COLOR, "WonderSwan Color")
(ZX_SPECTRUM, "Sinclair ZX Spectrum");
void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr<ScraperRequest> >& requests,
std::vector<ScraperSearchResult>& results)
{
std::string path = "thegamesdb.net/api/GetGame.php?";
std::string cleanName = params.nameOverride;
if(cleanName.empty())
cleanName = params.game->getCleanName();
path += "name=" + HttpReq::urlEncode(cleanName);
if(params.system->getPlatformIds().empty())
{
// no platform specified, we're done
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}else{
// go through the list, we need to split this into multiple requests
// because TheGamesDB API either sucks or I don't know how to use it properly...
std::string urlBase = path;
auto& platforms = params.system->getPlatformIds();
for(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++)
{
path = urlBase;
auto mapIt = gamesdb_platformid_map.find(*platformIt);
if(mapIt != gamesdb_platformid_map.end())
{
path += "&platform=";
path += HttpReq::urlEncode(mapIt->second);
}else{
LOG(LogWarning) << "TheGamesDB scraper warning - no support for platform " << getPlatformName(*platformIt);
}
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}
}
}
void TheGamesDBRequest::process(const std::unique_ptr<HttpReq>& req, std::vector<ScraperSearchResult>& results)
{
assert(req->status() == HttpReq::REQ_SUCCESS);
pugi::xml_document doc;
pugi::xml_parse_result parseResult = doc.load(req->getContent().c_str());
if(!parseResult)
{
std::stringstream ss;
ss << "GamesDBRequest - Error parsing XML. \n\t" << parseResult.description() << "";
std::string err = ss.str();
setError(err);
LOG(LogError) << err;
return;
}
pugi::xml_node data = doc.child("Data");
std::string baseImageUrl = data.child("baseImgUrl").text().get();
pugi::xml_node game = data.child("Game");
while(game && results.size() < MAX_SCRAPER_RESULTS)
{
ScraperSearchResult result;
result.mdl.set("name", game.child("GameTitle").text().get());
result.mdl.set("desc", game.child("Overview").text().get());
boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y");
result.mdl.setTime("releasedate", rd);
result.mdl.set("developer", game.child("Developer").text().get());
result.mdl.set("publisher", game.child("Publisher").text().get());
result.mdl.set("genre", game.child("Genres").first_child().text().get());
result.mdl.set("players", game.child("Players").text().get());
if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating"))
{
float ratingVal = (game.child("Rating").text().as_int() / 10.0f);
std::stringstream ss;
ss << ratingVal;
result.mdl.set("rating", ss.str());
}
pugi::xml_node images = game.child("Images");
if(images)
{
pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front");
if(art)
{
result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string();
result.imageUrl = baseImageUrl + art.text().get();
}
}
results.push_back(result);
game = game.next_sibling("Game");
}
}
<commit_msg>Update GamesDBScraper.cpp<commit_after>#include "scrapers/GamesDBScraper.h"
#include "Log.h"
#include "pugixml/pugixml.hpp"
#include "MetaData.h"
#include "Settings.h"
#include "Util.h"
#include <boost/assign.hpp>
using namespace PlatformIds;
const std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of
(THREEDO, "3DO")
(AMIGA, "Amiga")
(AMSTRAD_CPC, "Amstrad CPC")
// missing apple2
(ARCADE, "Arcade")
// missing atari 800
(ATARI_2600, "Atari 2600")
(ATARI_5200, "Atari 5200")
(ATARI_7800, "Atari 7800")
(ATARI_JAGUAR, "Atari Jaguar")
(ATARI_JAGUAR_CD, "Atari Jaguar CD")
(ATARI_LYNX, "Atari Lynx")
// missing atari ST/STE/Falcon
(ATARI_XE, "Atari XE")
(COLECOVISION, "Colecovision")
(COMMODORE_64, "Commodore 64")
(INTELLIVISION, "Intellivision")
(MAC_OS, "Mac OS")
(XBOX, "Microsoft Xbox")
(XBOX_360, "Microsoft Xbox 360")
// missing MSX
(NEOGEO, "Neo Geo")
(NEOGEO_POCKET, "Neo Geo Pocket")
(NEOGEO_POCKET_COLOR, "Neo Geo Pocket Color")
(NINTENDO_3DS, "Nintendo 3DS")
(NINTENDO_64, "Nintendo 64")
(NINTENDO_DS, "Nintendo DS")
(NINTENDO_ENTERTAINMENT_SYSTEM, "Nintendo Entertainment System (NES)")
(GAME_BOY, "Nintendo Game Boy")
(GAME_BOY_ADVANCE, "Nintendo Game Boy Advance")
(GAME_BOY_COLOR, "Nintendo Game Boy Color")
(NINTENDO_GAMECUBE, "Nintendo GameCube")
(NINTENDO_WII, "Nintendo Wii")
(NINTENDO_WII_U, "Nintendo Wii U")
(PC, "PC")
(SEGA_32X, "Sega 32X")
(SEGA_CD, "Sega CD")
(SEGA_DREAMCAST, "Sega Dreamcast")
(SEGA_GAME_GEAR, "Sega Game Gear")
(SEGA_GENESIS, "Sega Genesis")
(SEGA_MASTER_SYSTEM, "Sega Master System")
(SEGA_MEGA_DRIVE, "Sega Mega Drive")
(SEGA_SATURN, "Sega Saturn")
(PLAYSTATION, "Sony Playstation")
(PLAYSTATION_2, "Sony Playstation 2")
(PLAYSTATION_3, "Sony Playstation 3")
(PLAYSTATION_4, "Sony Playstation 4")
(PLAYSTATION_VITA, "Sony Playstation Vita")
(PLAYSTATION_PORTABLE, "Sony PSP")
(SUPER_NINTENDO, "Super Nintendo (SNES)")
(TURBOGRAFX_16, "TurboGrafx 16")
(WONDERSWAN, "WonderSwan")
(WONDERSWAN_COLOR, "WonderSwan Color")
(ZX_SPECTRUM, "Sinclair ZX Spectrum");
void thegamesdb_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr<ScraperRequest> >& requests,
std::vector<ScraperSearchResult>& results)
{
std::string path = "thegamesdb.net/api/GetGame.php?";
std::string cleanName = params.nameOverride;
if(cleanName.empty())
cleanName = params.game->getCleanName();
path += "name=" + HttpReq::urlEncode(cleanName);
if(params.system->getPlatformIds().empty())
{
// no platform specified, we're done
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}else{
// go through the list, we need to split this into multiple requests
// because TheGamesDB API either sucks or I don't know how to use it properly...
std::string urlBase = path;
auto& platforms = params.system->getPlatformIds();
for(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++)
{
path = urlBase;
auto mapIt = gamesdb_platformid_map.find(*platformIt);
if(mapIt != gamesdb_platformid_map.end())
{
path += "&platform=";
path += HttpReq::urlEncode(mapIt->second);
}else{
LOG(LogWarning) << "TheGamesDB scraper warning - no support for platform " << getPlatformName(*platformIt);
}
requests.push(std::unique_ptr<ScraperRequest>(new TheGamesDBRequest(results, path)));
}
}
}
void TheGamesDBRequest::process(const std::unique_ptr<HttpReq>& req, std::vector<ScraperSearchResult>& results)
{
assert(req->status() == HttpReq::REQ_SUCCESS);
pugi::xml_document doc;
pugi::xml_parse_result parseResult = doc.load(req->getContent().c_str());
if(!parseResult)
{
std::stringstream ss;
ss << "GamesDBRequest - Error parsing XML. \n\t" << parseResult.description() << "";
std::string err = ss.str();
setError(err);
LOG(LogError) << err;
return;
}
pugi::xml_node data = doc.child("Data");
std::string baseImageUrl = data.child("baseImgUrl").text().get();
pugi::xml_node game = data.child("Game");
while(game && results.size() < MAX_SCRAPER_RESULTS)
{
ScraperSearchResult result;
result.mdl.set("name", game.child("GameTitle").text().get());
result.mdl.set("desc", game.child("Overview").text().get());
boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y");
result.mdl.setTime("releasedate", rd);
result.mdl.set("developer", game.child("Developer").text().get());
result.mdl.set("publisher", game.child("Publisher").text().get());
result.mdl.set("genre", game.child("Genres").first_child().text().get());
result.mdl.set("players", game.child("Players").text().get());
if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating"))
{
float ratingVal = (game.child("Rating").text().as_int() / 10.0f);
std::stringstream ss;
ss << ratingVal;
result.mdl.set("rating", ss.str());
}
pugi::xml_node images = game.child("Images");
if(images)
{
pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front");
if(art)
{
result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string();
result.imageUrl = baseImageUrl + art.text().get();
}
}
results.push_back(result);
game = game.next_sibling("Game");
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Lech Kulina
*
* This file is part of the Realms Of Steel.
* For conditions of distribution and use, see copyright details in the LICENSE file.
*/
#include <cstdlib>
#include <boost/property_tree/info_parser.hpp>
#include <application/Logger.h>
#include <application/Application.h>
#include <resources/ResourceCache.h>
int main() {
int exitCode = EXIT_FAILURE;
ros::PropertyTree config;
boost::property_tree::read_info("Config.info", config);
if (!ros::Logger::initInstance(config.get_child("Logger")) ||
!ros::Application::initInstance(config.get_child("application")) ||
!ros::ResourceCache::initInstance(config.get_child("resources"))) {
return exitCode;
}
ros::ApplicationPtr application = ros::Application::getInstance();
if (application) {
exitCode = application->run();
application->uninit();
}
return exitCode;
}
<commit_msg>Initialize FileSystem and ResourcesCache from config file<commit_after>/*
* Copyright (c) 2016 Lech Kulina
*
* This file is part of the Realms Of Steel.
* For conditions of distribution and use, see copyright details in the LICENSE file.
*/
#include <cstdlib>
#include <boost/property_tree/info_parser.hpp>
#include <application/Logger.h>
#include <application/Application.h>
#include <resources/FileSystem.h>
#include <resources/ResourcesCache.h>
int main() {
int exitCode = EXIT_FAILURE;
ros::PropertyTree config;
boost::property_tree::read_info("Config.info", config);
if (!ros::Logger::initInstance(config.get_child("Logger")) ||
!ros::Application::initInstance(config.get_child("application")) ||
!ros::FileSystem::initInstance(config.get_child("file-system")) ||
!ros::ResourcesCache::initInstance(config.get_child("resources-cache"))) {
return exitCode;
}
ros::ApplicationPtr application = ros::Application::getInstance();
if (application) {
exitCode = application->run();
application->uninit();
}
return exitCode;
}
<|endoftext|> |
<commit_before>// RUN: %llvmgxx %s -fapple-kext -S -o -
// The extra check in 71555 caused this to crash on Darwin X86
// in an assert build.
class foo {
virtual ~foo ();
};
foo::~foo(){}
<commit_msg>Remove 2009-09-04-modify-crash.cpp as clang doesn't support 32-bit kext.<commit_after><|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <functional>
#include <mutex>
#include <cstdlib>
#ifdef WIN32
#define BIND_EVENT(IO,EV,FN) \
do{ \
socket::event_listener_aux l = FN;\
IO->on(EV,l);\
} while(0)
#else
#define BIND_EVENT(IO,EV,FN) \
IO->on(EV,FN)
#endif
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
_io(new client()),
m_typingItem(NULL),
m_dialog()
{
ui->setupUi(this);
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
using std::placeholders::_4;
socket::ptr sock = _io->socket();
BIND_EVENT(sock,"new message",std::bind(&MainWindow::OnNewMessage,this,_1,_2,_3,_4));
BIND_EVENT(sock,"user joined",std::bind(&MainWindow::OnUserJoined,this,_1,_2,_3,_4));
BIND_EVENT(sock,"user left",std::bind(&MainWindow::OnUserLeft,this,_1,_2,_3,_4));
BIND_EVENT(sock,"typing",std::bind(&MainWindow::OnTyping,this,_1,_2,_3,_4));
BIND_EVENT(sock,"stop typing",std::bind(&MainWindow::OnStopTyping,this,_1,_2,_3,_4));
BIND_EVENT(sock,"login",std::bind(&MainWindow::OnLogin,this,_1,_2,_3,_4));
_io->set_socket_open_listener(std::bind(&MainWindow::OnConnected,this,std::placeholders::_1));
_io->set_close_listener(std::bind(&MainWindow::OnClosed,this,_1));
_io->set_fail_listener(std::bind(&MainWindow::OnFailed,this));
connect(this,SIGNAL(RequestAddListItem(QListWidgetItem*)),this,SLOT(AddListItem(QListWidgetItem*)));
connect(this,SIGNAL(RequestRemoveListItem(QListWidgetItem*)),this,SLOT(RemoveListItem(QListWidgetItem*)));
connect(this,SIGNAL(RequestToggleInputs(bool)),this,SLOT(ToggleInputs(bool)));
}
MainWindow::~MainWindow()
{
_io->socket()->off_all();
_io->socket()->off_error();
delete ui;
}
void MainWindow::SendBtnClicked()
{
QLineEdit* messageEdit = this->findChild<QLineEdit*>("messageEdit");
QString text = messageEdit->text();
if(text.length()>0)
{
QByteArray bytes = text.toUtf8();
std::string msg(bytes.data(),bytes.length());
_io->socket()->emit("new message",msg);
text.append(" : You");
QListWidgetItem *item = new QListWidgetItem(text);
item->setTextAlignment(Qt::AlignRight);
Q_EMIT RequestAddListItem(item);
messageEdit->clear();
}
}
void MainWindow::OnMessageReturn()
{
this->SendBtnClicked();
}
void MainWindow::ShowLoginDialog()
{
m_dialog.reset(new NicknameDialog(this));
connect(m_dialog.get(),SIGNAL(accepted()),this,SLOT(NicknameAccept()));
connect(m_dialog.get(),SIGNAL(rejected()),this,SLOT(NicknameCancelled()));
m_dialog->exec();
}
void MainWindow::showEvent(QShowEvent *event)
{
ShowLoginDialog();
}
void MainWindow::TypingStop()
{
m_timer.reset();
_io->socket()->emit("stop typing","");
}
void MainWindow::TypingChanged()
{
if(m_timer&&m_timer->isActive())
{
m_timer->stop();
}
else
{
_io->socket()->emit("typing","");
}
m_timer.reset(new QTimer(this));
connect(m_timer.get(),SIGNAL(timeout()),this,SLOT(TypingStop()));
m_timer->setSingleShot(true);
m_timer->start(1000);
}
void MainWindow::NicknameAccept()
{
m_name = m_dialog->getNickname();
if(m_name.length()>0)
{
_io->connect("ws://localhost:3000");
}
}
void MainWindow::NicknameCancelled()
{
QApplication::exit();
}
void MainWindow::AddListItem(QListWidgetItem* item)
{
this->findChild<QListWidget*>("listView")->addItem(item);
}
void MainWindow::RemoveListItem(QListWidgetItem* item)
{
QListWidget* list = this->findChild<QListWidget*>("listView");
int row = list->row(item);
delete list->takeItem(row);
}
void MainWindow::OnNewMessage(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(data->get_flag() == message::flag_object)
{
std::string msg = data->get_map()["message"]->get_string();
std::string username = data->get_map()["username"]->get_string();
QString label = QString::fromUtf8(username.data(),username.length());
label.append(" : ");
label.append(QString::fromUtf8(msg.data(),msg.length()));
QListWidgetItem *item= new QListWidgetItem(label);
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnUserJoined(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(data->get_flag() == message::flag_object)
{
std::string name = data->get_map()["username"]->get_string();
int numUser = data->get_map()["numUsers"]->get_int();
QString label = QString::fromUtf8(name.data(),name.length());
bool plural = numUser != 1;
label.append(" joined\n");
label.append(plural?"there are ":"there's ");
QString digits;
while(numUser>=10)
{
digits.insert(0,QChar((numUser%10)+'0'));
numUser/=10;
}
digits.insert(0,QChar(numUser+'0'));
label.append(digits);
label.append(plural?" participants":" participant");
QListWidgetItem *item= new QListWidgetItem(label);
item->setTextAlignment(Qt::AlignHCenter);
QFont font;
font.setPointSize(9);
item->setFont(font);
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnUserLeft(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(data->get_flag() == message::flag_object)
{
std::string name = data->get_map()["username"]->get_string();
int numUser = data->get_map()["numUsers"]->get_int();
QString label = QString::fromUtf8(name.data(),name.length());
bool plural = numUser != 1;
label.append(" left\n");
label.append(plural?"there are ":"there's ");
QString digits;
while(numUser>=10)
{
digits.insert(0,QChar((numUser%10)+'0'));
numUser/=10;
}
digits.insert(0,QChar(numUser+'0'));
label.append(digits);
label.append(plural?" participants":" participant");
QListWidgetItem *item= new QListWidgetItem(label);
item->setTextAlignment(Qt::AlignHCenter);
QFont font;
font.setPointSize(9);
item->setFont(font);
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(m_typingItem == NULL)
{
std::string name = data->get_map()["username"]->get_string();
QString label = QString::fromUtf8(name.data(),name.length());
label.append(" is typing...");
QListWidgetItem *item = new QListWidgetItem(label);
item->setTextColor(QColor(200,200,200,255));
m_typingItem = item;
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnStopTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(m_typingItem != NULL)
{
Q_EMIT RequestRemoveListItem(m_typingItem);
m_typingItem = NULL;
}
}
void MainWindow::OnLogin(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
Q_EMIT RequestToggleInputs(true);
int numUser = data->get_map()["numUsers"]->get_int();
QString digits;
bool plural = numUser !=1;
while(numUser>=10)
{
digits.insert(0,QChar((numUser%10)+'0'));
numUser/=10;
}
digits.insert(0,QChar(numUser+'0'));
digits.insert(0,plural?"there are ":"there's ");
digits.append(plural? " participants":" participant");
QListWidgetItem *item = new QListWidgetItem(digits);
item->setTextAlignment(Qt::AlignHCenter);
QFont font;
font.setPointSize(9);
item->setFont(font);
Q_EMIT RequestAddListItem(item);
}
void MainWindow::OnConnected(std::string const& nsp)
{
QByteArray bytes = m_name.toUtf8();
std::string nickName(bytes.data(),bytes.length());
_io->socket()->emit("add user", nickName);
}
void MainWindow::OnClosed(client::close_reason const& reason)
{
Q_EMIT RequestToggleInputs(false);
}
void MainWindow::OnFailed()
{
Q_EMIT RequestToggleInputs(false);
}
void MainWindow::ToggleInputs(bool loginOrNot)
{
if(loginOrNot)//already login
{
this->findChild<QWidget*>("messageEdit")->setEnabled(true);
this->findChild<QWidget*>("listView")->setEnabled(true);
// this->findChild<QWidget*>("sendBtn")->setEnabled(true);
}
else
{
this->findChild<QWidget*>("messageEdit")->setEnabled(false);
this->findChild<QWidget*>("listView")->setEnabled(false);
// this->findChild<QWidget*>("sendBtn")->setEnabled(false);
ShowLoginDialog();
}
}
<commit_msg>use macro for host url<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <functional>
#include <mutex>
#include <cstdlib>
#define kURL "ws://localhost:3000"
#ifdef WIN32
#define BIND_EVENT(IO,EV,FN) \
do{ \
socket::event_listener_aux l = FN;\
IO->on(EV,l);\
} while(0)
#else
#define BIND_EVENT(IO,EV,FN) \
IO->on(EV,FN)
#endif
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
_io(new client()),
m_typingItem(NULL),
m_dialog()
{
ui->setupUi(this);
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
using std::placeholders::_4;
socket::ptr sock = _io->socket();
BIND_EVENT(sock,"new message",std::bind(&MainWindow::OnNewMessage,this,_1,_2,_3,_4));
BIND_EVENT(sock,"user joined",std::bind(&MainWindow::OnUserJoined,this,_1,_2,_3,_4));
BIND_EVENT(sock,"user left",std::bind(&MainWindow::OnUserLeft,this,_1,_2,_3,_4));
BIND_EVENT(sock,"typing",std::bind(&MainWindow::OnTyping,this,_1,_2,_3,_4));
BIND_EVENT(sock,"stop typing",std::bind(&MainWindow::OnStopTyping,this,_1,_2,_3,_4));
BIND_EVENT(sock,"login",std::bind(&MainWindow::OnLogin,this,_1,_2,_3,_4));
_io->set_socket_open_listener(std::bind(&MainWindow::OnConnected,this,std::placeholders::_1));
_io->set_close_listener(std::bind(&MainWindow::OnClosed,this,_1));
_io->set_fail_listener(std::bind(&MainWindow::OnFailed,this));
connect(this,SIGNAL(RequestAddListItem(QListWidgetItem*)),this,SLOT(AddListItem(QListWidgetItem*)));
connect(this,SIGNAL(RequestRemoveListItem(QListWidgetItem*)),this,SLOT(RemoveListItem(QListWidgetItem*)));
connect(this,SIGNAL(RequestToggleInputs(bool)),this,SLOT(ToggleInputs(bool)));
}
MainWindow::~MainWindow()
{
_io->socket()->off_all();
_io->socket()->off_error();
delete ui;
}
void MainWindow::SendBtnClicked()
{
QLineEdit* messageEdit = this->findChild<QLineEdit*>("messageEdit");
QString text = messageEdit->text();
if(text.length()>0)
{
QByteArray bytes = text.toUtf8();
std::string msg(bytes.data(),bytes.length());
_io->socket()->emit("new message",msg);
text.append(" : You");
QListWidgetItem *item = new QListWidgetItem(text);
item->setTextAlignment(Qt::AlignRight);
Q_EMIT RequestAddListItem(item);
messageEdit->clear();
}
}
void MainWindow::OnMessageReturn()
{
this->SendBtnClicked();
}
void MainWindow::ShowLoginDialog()
{
m_dialog.reset(new NicknameDialog(this));
connect(m_dialog.get(),SIGNAL(accepted()),this,SLOT(NicknameAccept()));
connect(m_dialog.get(),SIGNAL(rejected()),this,SLOT(NicknameCancelled()));
m_dialog->exec();
}
void MainWindow::showEvent(QShowEvent *event)
{
ShowLoginDialog();
}
void MainWindow::TypingStop()
{
m_timer.reset();
_io->socket()->emit("stop typing","");
}
void MainWindow::TypingChanged()
{
if(m_timer&&m_timer->isActive())
{
m_timer->stop();
}
else
{
_io->socket()->emit("typing","");
}
m_timer.reset(new QTimer(this));
connect(m_timer.get(),SIGNAL(timeout()),this,SLOT(TypingStop()));
m_timer->setSingleShot(true);
m_timer->start(1000);
}
void MainWindow::NicknameAccept()
{
m_name = m_dialog->getNickname();
if(m_name.length()>0)
{
_io->connect(kURL);
}
}
void MainWindow::NicknameCancelled()
{
QApplication::exit();
}
void MainWindow::AddListItem(QListWidgetItem* item)
{
this->findChild<QListWidget*>("listView")->addItem(item);
}
void MainWindow::RemoveListItem(QListWidgetItem* item)
{
QListWidget* list = this->findChild<QListWidget*>("listView");
int row = list->row(item);
delete list->takeItem(row);
}
void MainWindow::OnNewMessage(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(data->get_flag() == message::flag_object)
{
std::string msg = data->get_map()["message"]->get_string();
std::string username = data->get_map()["username"]->get_string();
QString label = QString::fromUtf8(username.data(),username.length());
label.append(" : ");
label.append(QString::fromUtf8(msg.data(),msg.length()));
QListWidgetItem *item= new QListWidgetItem(label);
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnUserJoined(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(data->get_flag() == message::flag_object)
{
std::string name = data->get_map()["username"]->get_string();
int numUser = data->get_map()["numUsers"]->get_int();
QString label = QString::fromUtf8(name.data(),name.length());
bool plural = numUser != 1;
label.append(" joined\n");
label.append(plural?"there are ":"there's ");
QString digits;
while(numUser>=10)
{
digits.insert(0,QChar((numUser%10)+'0'));
numUser/=10;
}
digits.insert(0,QChar(numUser+'0'));
label.append(digits);
label.append(plural?" participants":" participant");
QListWidgetItem *item= new QListWidgetItem(label);
item->setTextAlignment(Qt::AlignHCenter);
QFont font;
font.setPointSize(9);
item->setFont(font);
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnUserLeft(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(data->get_flag() == message::flag_object)
{
std::string name = data->get_map()["username"]->get_string();
int numUser = data->get_map()["numUsers"]->get_int();
QString label = QString::fromUtf8(name.data(),name.length());
bool plural = numUser != 1;
label.append(" left\n");
label.append(plural?"there are ":"there's ");
QString digits;
while(numUser>=10)
{
digits.insert(0,QChar((numUser%10)+'0'));
numUser/=10;
}
digits.insert(0,QChar(numUser+'0'));
label.append(digits);
label.append(plural?" participants":" participant");
QListWidgetItem *item= new QListWidgetItem(label);
item->setTextAlignment(Qt::AlignHCenter);
QFont font;
font.setPointSize(9);
item->setFont(font);
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(m_typingItem == NULL)
{
std::string name = data->get_map()["username"]->get_string();
QString label = QString::fromUtf8(name.data(),name.length());
label.append(" is typing...");
QListWidgetItem *item = new QListWidgetItem(label);
item->setTextColor(QColor(200,200,200,255));
m_typingItem = item;
Q_EMIT RequestAddListItem(item);
}
}
void MainWindow::OnStopTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
if(m_typingItem != NULL)
{
Q_EMIT RequestRemoveListItem(m_typingItem);
m_typingItem = NULL;
}
}
void MainWindow::OnLogin(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp)
{
Q_EMIT RequestToggleInputs(true);
int numUser = data->get_map()["numUsers"]->get_int();
QString digits;
bool plural = numUser !=1;
while(numUser>=10)
{
digits.insert(0,QChar((numUser%10)+'0'));
numUser/=10;
}
digits.insert(0,QChar(numUser+'0'));
digits.insert(0,plural?"there are ":"there's ");
digits.append(plural? " participants":" participant");
QListWidgetItem *item = new QListWidgetItem(digits);
item->setTextAlignment(Qt::AlignHCenter);
QFont font;
font.setPointSize(9);
item->setFont(font);
Q_EMIT RequestAddListItem(item);
}
void MainWindow::OnConnected(std::string const& nsp)
{
QByteArray bytes = m_name.toUtf8();
std::string nickName(bytes.data(),bytes.length());
_io->socket()->emit("add user", nickName);
}
void MainWindow::OnClosed(client::close_reason const& reason)
{
Q_EMIT RequestToggleInputs(false);
}
void MainWindow::OnFailed()
{
Q_EMIT RequestToggleInputs(false);
}
void MainWindow::ToggleInputs(bool loginOrNot)
{
if(loginOrNot)//already login
{
this->findChild<QWidget*>("messageEdit")->setEnabled(true);
this->findChild<QWidget*>("listView")->setEnabled(true);
// this->findChild<QWidget*>("sendBtn")->setEnabled(true);
}
else
{
this->findChild<QWidget*>("messageEdit")->setEnabled(false);
this->findChild<QWidget*>("listView")->setEnabled(false);
// this->findChild<QWidget*>("sendBtn")->setEnabled(false);
ShowLoginDialog();
}
}
<|endoftext|> |
<commit_before>/* Copyright 2020 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/core/grappler/utils/pattern_utils.h"
#include <algorithm>
namespace tensorflow {
namespace grappler {
namespace utils {
inline bool IsCommutativeOp(string op) {
// TODO(intel-tf): Add more ops to this list if needed.
static const std::vector<string> commutative_ops = {"Add", "AddV2", "Mul"};
return std::find(commutative_ops.begin(), commutative_ops.end(), op) !=
commutative_ops.end();
}
// op1 could be wildcard `*`, while op2 is some registered op in tensorflow.
inline bool IsSame(string op1, string op2) { return op1 == "*" || op1 == op2; }
// A subgraph pattern syntax implicitly defines a DAG having a single root. We
// traverse the syntax DAG in DFS manner. This function finds a match for
// current root of the pattern with the current node and recursively matches
// children subpatterns with the children of current node.
template <>
bool SubGraphMatcher<MatchingDirection::kFollowInputs>::DoesOpTypePatternMatch(
const OpTypePattern& pattern, MutableNodeView* node_view,
NodeViewMatch* match) {
// Currently no control inputs and outputs are allowed.
if (node_view->NumControllingFanins() > 0 ||
node_view->NumControlledFanouts() > 0)
return false;
bool op_type_matched = false;
if (pattern.op == "*") {
op_type_matched = true;
} else {
// The op field string of current pattern might express an op among multiple
// op types (mutually exclusive) separated by '|'.
std::vector<string> op_list = str_util::Split(pattern.op, '|');
for (const string& op : op_list) {
if (node_view->node()->op() == op) {
op_type_matched = true;
break;
}
}
}
if (op_type_matched) {
// If op type matches and current node is visited first time, insert current
// node to node_label_to_index_ map with the current label as the key.
// Multiple occurances of same label in the pattern syntax indicates that
// the same node needs to be visited for each of such occurances. Hence
// subsequent visits should find the corresponding label in the map as a key
// and the current node should be the value for that key.
if (node_label_to_index_.find(pattern.label) ==
node_label_to_index_.end()) {
node_label_to_index_[pattern.label] = node_view->node_index();
// Bookkeeping
matched_node_indices_.insert(node_view->node_index());
if (pattern.node_status == NodeStatus::kRemove) {
remove_node_indices_.insert(node_view->node_index());
}
} else if (node_label_to_index_[pattern.label] != node_view->node_index()) {
return false; // label constraint could not be satisfied.
} else {
DCHECK(node_label_to_index_[pattern.label] == node_view->node_index());
}
} else {
return false;
}
// Current root of the pattern syntax is matched with the current node.
match->node_view = node_view;
// Go for matching child subpattern.
if (!pattern.children.empty()) {
// Currently only direction toward inputs is implemented.
auto graph_children = node_view->GetRegularFanins();
int num_children = graph_children.size();
if (num_children != pattern.children.size()) {
return false;
} else {
// A pattern is a graph that we would like to match with a subgraph of
// a tensorflow computation graph. We travese both pattern-graph and the
// given graph in DFS manner and try to find one-to-one mapping between
// the nodes. However, commutative binary ops (e.g., Add, AddV2, Mul
// etc.) in the computation graph can have their inputs in different order
// than the pattern syntax graph. To allow such input permutation in a
// limited manner, we employ a heuristic of looking one level ahead in
// both graphs, whether visiting the right child of pattern is likely to
// match left child of the given graph. In that case, we simply swap the
// left subtree with right subtree of pattern syntax graph and continue
// matching children of pattern with the children of given computation
// graph. Note, we do not change anything in the computation graph during
// pattern matching, only the pattern graph is changed. By looking ahead
// one step in case of commutative ops, we keep the time comlexity of
// pattern matching linear. Since it is only a heuristic and we look only
// one step ahead it is not guranteed that all possible permutations will
// be matched. For example, when both the input ops to the commutative op
// are same, we cannot anticipate which of the permutation is likely to
// match unless we look two level down the graphs.
std::vector<int> pattern_child_indices(num_children);
std::iota(pattern_child_indices.begin(), pattern_child_indices.end(), 0);
string op_name = pattern.op;
if (IsCommutativeOp(op_name) && num_children == 2) {
MutableNodeView* graph_child0_node_view =
graph_view_->GetNode(graph_children[0].node_index());
MutableNodeView* graph_child1_node_view =
graph_view_->GetNode(graph_children[1].node_index());
if (!IsSame(pattern.children[0].op, graph_child0_node_view->GetOp()) &&
IsSame(pattern.children[1].op, graph_child0_node_view->GetOp()))
std::swap(pattern_child_indices[0], pattern_child_indices[1]);
}
for (int i = 0; i < num_children; ++i) {
auto child_node_index = graph_children[i].node_index();
// TODO (mdfaijul): Is it guaranted that GetNode will reuturn non null
// pointer.
MutableNodeView* child_node_view =
graph_view_->GetNode(child_node_index);
const OpTypePattern& child_pattern =
pattern.children[pattern_child_indices[i]];
match->children.push_back(NodeViewMatch());
NodeViewMatch* child_match = &(match->children.back());
if (!DoesOpTypePatternMatch(child_pattern, child_node_view,
child_match)) {
return false;
}
}
}
}
return true;
}
// Current implementation supports pattern maching toward node's inputs only.
template <>
bool SubGraphMatcher<MatchingDirection::kFollowInputs>::GetMatchedNodes(
const OpTypePattern& pattern, MutableNodeView* node_view,
std::map<string, int>* matched_nodes_map,
std::set<int>* remove_node_indices) {
bool found_match = false;
match_.reset(new NodeViewMatch());
if (DoesOpTypePatternMatch(pattern, node_view, match_.get())) {
if (!HasRemoveNodeExternalDependents()) {
found_match = true;
*matched_nodes_map = this->node_label_to_index_;
*remove_node_indices = this->remove_node_indices_;
}
} else {
found_match = false;
}
// Clear all bookkeeping data
match_->Clear();
match_.reset(nullptr);
matched_node_indices_.clear();
node_label_to_index_.clear();
remove_node_indices_.clear();
return found_match;
}
} // namespace utils
} // namespace grappler
} // namespace tensorflow
<commit_msg>Replaced vector with flat_hash_set.<commit_after>/* Copyright 2020 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/core/grappler/utils/pattern_utils.h"
#include <algorithm>
#include "absl/container/flat_hash_set.h"
namespace tensorflow {
namespace grappler {
namespace utils {
inline const bool IsCommutativeOp(const string& op) {
// TODO(intel-tf): Add more ops to this list if needed.
static const auto* commutative_ops =
new absl::flat_hash_set<string>({"Add", "AddV2", "Mul"});
return commutative_ops->contains(op);
}
// op1 is an op name in the pattern and it could be wildcard `*` or some
// registered op in tensorflow. op2 is an op name in the computation graph and
// is always one of the registered ops in tensorflow.
inline bool IsSame(string op1, string op2) { return op1 == "*" || op1 == op2; }
// A subgraph pattern syntax implicitly defines a DAG having a single root. We
// traverse the syntax DAG in DFS manner. This function finds a match for
// current root of the pattern with the current node and recursively matches
// children subpatterns with the children of current node.
template <>
bool SubGraphMatcher<MatchingDirection::kFollowInputs>::DoesOpTypePatternMatch(
const OpTypePattern& pattern, MutableNodeView* node_view,
NodeViewMatch* match) {
// Currently no control inputs and outputs are allowed.
if (node_view->NumControllingFanins() > 0 ||
node_view->NumControlledFanouts() > 0)
return false;
bool op_type_matched = false;
if (pattern.op == "*") {
op_type_matched = true;
} else {
// The op field string of current pattern might express an op among multiple
// op types (mutually exclusive) separated by '|'.
std::vector<string> op_list = str_util::Split(pattern.op, '|');
for (const string& op : op_list) {
if (node_view->node()->op() == op) {
op_type_matched = true;
break;
}
}
}
if (op_type_matched) {
// If op type matches and current node is visited first time, insert current
// node to node_label_to_index_ map with the current label as the key.
// Multiple occurances of same label in the pattern syntax indicates that
// the same node needs to be visited for each of such occurances. Hence
// subsequent visits should find the corresponding label in the map as a key
// and the current node should be the value for that key.
if (node_label_to_index_.find(pattern.label) ==
node_label_to_index_.end()) {
node_label_to_index_[pattern.label] = node_view->node_index();
// Bookkeeping
matched_node_indices_.insert(node_view->node_index());
if (pattern.node_status == NodeStatus::kRemove) {
remove_node_indices_.insert(node_view->node_index());
}
} else if (node_label_to_index_[pattern.label] != node_view->node_index()) {
return false; // label constraint could not be satisfied.
} else {
DCHECK(node_label_to_index_[pattern.label] == node_view->node_index());
}
} else {
return false;
}
// Current root of the pattern syntax is matched with the current node.
match->node_view = node_view;
// Go for matching child subpattern.
if (!pattern.children.empty()) {
// Currently only direction toward inputs is implemented.
auto graph_children = node_view->GetRegularFanins();
int num_children = graph_children.size();
if (num_children != pattern.children.size()) {
return false;
} else {
// A pattern is a graph that we would like to match with a subgraph of
// a tensorflow computation graph. We travese both pattern-graph and the
// given graph in DFS manner and try to find one-to-one mapping between
// the nodes. However, commutative binary ops (e.g., Add, AddV2, Mul
// etc.) in the computation graph can have their inputs in different order
// than the pattern syntax graph. To allow such input permutation in a
// limited manner, we employ a heuristic of looking one level ahead in
// both graphs, whether visiting the right child of pattern is likely to
// match left child of the given graph. In that case, we simply swap the
// left subtree with right subtree of pattern syntax graph and continue
// matching children of pattern with the children of given computation
// graph. Note, we do not change anything in the computation graph during
// pattern matching, only the pattern graph is changed. By looking ahead
// one step in case of commutative ops, we keep the time comlexity of
// pattern matching linear. Since it is only a heuristic and we look only
// one step ahead it is not guranteed that all possible permutations will
// be matched. For example, when both the input ops to the commutative op
// are same, we cannot anticipate which of the permutation is likely to
// match unless we look two level down the graphs.
std::vector<int> pattern_child_indices(num_children);
std::iota(pattern_child_indices.begin(), pattern_child_indices.end(), 0);
string op_name = pattern.op;
if (IsCommutativeOp(op_name) && num_children == 2) {
MutableNodeView* graph_child0_node_view =
graph_view_->GetNode(graph_children[0].node_index());
MutableNodeView* graph_child1_node_view =
graph_view_->GetNode(graph_children[1].node_index());
if (!IsSame(pattern.children[0].op, graph_child0_node_view->GetOp()) &&
IsSame(pattern.children[1].op, graph_child0_node_view->GetOp()))
std::swap(pattern_child_indices[0], pattern_child_indices[1]);
}
for (int i = 0; i < num_children; ++i) {
auto child_node_index = graph_children[i].node_index();
// TODO (mdfaijul): Is it guaranted that GetNode will reuturn non null
// pointer.
MutableNodeView* child_node_view =
graph_view_->GetNode(child_node_index);
const OpTypePattern& child_pattern =
pattern.children[pattern_child_indices[i]];
match->children.push_back(NodeViewMatch());
NodeViewMatch* child_match = &(match->children.back());
if (!DoesOpTypePatternMatch(child_pattern, child_node_view,
child_match)) {
return false;
}
}
}
}
return true;
}
// Current implementation supports pattern maching toward node's inputs only.
template <>
bool SubGraphMatcher<MatchingDirection::kFollowInputs>::GetMatchedNodes(
const OpTypePattern& pattern, MutableNodeView* node_view,
std::map<string, int>* matched_nodes_map,
std::set<int>* remove_node_indices) {
bool found_match = false;
match_.reset(new NodeViewMatch());
if (DoesOpTypePatternMatch(pattern, node_view, match_.get())) {
if (!HasRemoveNodeExternalDependents()) {
found_match = true;
*matched_nodes_map = this->node_label_to_index_;
*remove_node_indices = this->remove_node_indices_;
}
} else {
found_match = false;
}
// Clear all bookkeeping data
match_->Clear();
match_.reset(nullptr);
matched_node_indices_.clear();
node_label_to_index_.clear();
remove_node_indices_.clear();
return found_match;
}
} // namespace utils
} // namespace grappler
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2017 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.
==============================================================================*/
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/scatter_nd_op.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
namespace tensorflow {
typedef Eigen::GpuDevice GPUDevice;
namespace {
template <typename T, scatter_nd_op::UpdateOp Op>
struct LeftUpdate {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val);
};
template <typename T>
struct LeftUpdate<T, scatter_nd_op::UpdateOp::ASSIGN> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val) {
*out = val;
}
};
template <typename T>
struct LeftUpdate<T, scatter_nd_op::UpdateOp::ADD> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val) {
GpuAtomicAdd(out, val);
}
};
template <typename T>
struct LeftUpdate<T, scatter_nd_op::UpdateOp::SUB> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val) {
GpuAtomicSub(out, val);
}
};
// Specializations for std::complex, updating real and imaginary part
// individually. Even though this is not an atomic op anymore, it is safe
// because there is only one type of op per kernel.
template <typename T>
struct LeftUpdate<std::complex<T>, scatter_nd_op::UpdateOp::ADD> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(
std::complex<T>* out, const std::complex<T>& val) {
T* ptr = reinterpret_cast<T*>(out);
GpuAtomicAdd(ptr, val.real());
GpuAtomicAdd(ptr, val.imag());
}
};
template <typename T>
struct LeftUpdate<std::complex<T>, scatter_nd_op::UpdateOp::SUB> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(
std::complex<T>* out, const std::complex<T>& val) {
LeftUpdate<std::complex<T>, scatter_nd_op::UpdateOp::ADD>()(out, -val);
}
};
} // namespace
template <typename T, typename Index, scatter_nd_op::UpdateOp op, int IXDIM>
__global__ void ScatterNdOpKernel(
const Index* indices, const T* updates, T* out,
const Eigen::array<Eigen::DenseIndex, IXDIM> output_shape_prefix,
const Eigen::array<int64, IXDIM> batch_strides, const int64 num_indices,
const Index slice_size) {
auto update = LeftUpdate<T, op>();
GPU_1D_KERNEL_LOOP(index, num_indices) {
Index i = 0;
bool out_of_bounds = false;
#pragma unroll
for (int dim = 0; dim < IXDIM; ++dim) {
int offset = (IXDIM * index + dim);
const Index ix_d = internal::SubtleMustCopy(ldg(indices + offset));
out_of_bounds |= !FastBoundsCheck(ix_d, output_shape_prefix[dim]);
i += ix_d * batch_strides[dim] * slice_size;
}
if (!out_of_bounds) {
#pragma unroll
for (int si = 0; si < slice_size; si++) {
update(out + i + si, ldg(updates + (index * slice_size + si)));
}
}
}
}
namespace functor {
// Functor used by ScatterOp to do the computations.
template <typename T, typename Index, scatter_nd_op::UpdateOp op, int IXDIM>
struct ScatterNdFunctor<GPUDevice, T, Index, op, IXDIM> {
Index operator()(
const GPUDevice& d, const Index slice_size,
const Eigen::array<Eigen::DenseIndex, IXDIM> output_shape_prefix,
typename TTypes<T, 2>::Tensor Tparams,
typename TTypes<Index, 2>::ConstTensor Tindices,
typename TTypes<T, 2>::ConstTensor Tupdates,
typename TTypes<T, 2>::Tensor Toutput) {
// TODO(ebrevdo): The performance of this for small indices (large
// slices) is poor. Write a kernel whose splitting is
// independent of the slice size. Same for CPU. See the
// gather_nd kernel for an example.
const Eigen::DenseIndex batch_size = Tindices.dimension(0);
// Index batch_strides[IXDIM];
Eigen::array<int64, IXDIM> batch_strides;
for (int dim = IXDIM - 1; dim >= 0; --dim) {
if (dim == IXDIM - 1) {
batch_strides[dim] = 1;
} else {
batch_strides[dim] =
batch_strides[dim + 1] * output_shape_prefix[dim + 1];
}
}
GpuLaunchConfig config = GetGpuLaunchConfig(Toutput.size(), d);
TF_CHECK_OK(GpuLaunchKernel(ScatterNdOpKernel<T, Index, op, IXDIM>,
config.block_count, config.thread_per_block, 0,
d.stream(), Tindices.data(), Tupdates.data(),
Toutput.data(), output_shape_prefix,
batch_strides, batch_size, slice_size));
return -1;
}
};
} // namespace functor
#define DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, IXDIM) \
template struct functor::ScatterNdFunctor<GPUDevice, T, Index, op, IXDIM>;
#define DECLARE_GPU_SPECS_INDEX_OP(T, Index, op) \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 1); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 2); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 3); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 4); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 5); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 6); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 7);
#define DECLARE_GPU_SPECS_INDEX(T, Index) \
DECLARE_GPU_SPECS_INDEX_OP(T, Index, scatter_nd_op::UpdateOp::ASSIGN); \
DECLARE_GPU_SPECS_INDEX_OP(T, Index, scatter_nd_op::UpdateOp::ADD); \
DECLARE_GPU_SPECS_INDEX_OP(T, Index, scatter_nd_op::UpdateOp::SUB)
#define DECLARE_GPU_SPECS(T) \
DECLARE_GPU_SPECS_INDEX(T, int32); \
DECLARE_GPU_SPECS_INDEX(T, int64)
TF_CALL_int32(DECLARE_GPU_SPECS);
TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPECS);
TF_CALL_complex64(DECLARE_GPU_SPECS);
TF_CALL_complex128(DECLARE_GPU_SPECS);
#undef DECLARE_GPU_SPECS
#undef DECLARE_GPU_SPECS_INDEX
#undef DECLARE_GPU_SPECS_INDEX_OP
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
<commit_msg>fix msvc 16.3.0 + cuda 10.1.243 build break<commit_after>/* Copyright 2017 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.
==============================================================================*/
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/scatter_nd_op.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
namespace tensorflow {
typedef Eigen::GpuDevice GPUDevice;
namespace {
template <typename T, scatter_nd_op::UpdateOp Op>
struct LeftUpdate {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val);
};
template <typename T>
struct LeftUpdate<T, scatter_nd_op::UpdateOp::ASSIGN> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val) {
*out = val;
}
};
template <typename T>
struct LeftUpdate<T, scatter_nd_op::UpdateOp::ADD> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val) {
GpuAtomicAdd(out, val);
}
};
template <typename T>
struct LeftUpdate<T, scatter_nd_op::UpdateOp::SUB> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(T* out, const T& val) {
GpuAtomicSub(out, val);
}
};
// Specializations for std::complex, updating real and imaginary part
// individually. Even though this is not an atomic op anymore, it is safe
// because there is only one type of op per kernel.
template <typename T>
struct LeftUpdate<std::complex<T>, scatter_nd_op::UpdateOp::ADD> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(
std::complex<T>* out, const std::complex<T>& val) {
T* ptr = reinterpret_cast<T*>(out);
GpuAtomicAdd(ptr, val.real());
GpuAtomicAdd(ptr, val.imag());
}
};
template <typename T>
struct LeftUpdate<std::complex<T>, scatter_nd_op::UpdateOp::SUB> {
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void operator()(
std::complex<T>* out, const std::complex<T>& val) {
T* ptr = reinterpret_cast<T*>(out);
GpuAtomicAdd(ptr, -val.real());
GpuAtomicAdd(ptr, -val.imag());
}
};
} // namespace
template <typename T, typename Index, scatter_nd_op::UpdateOp op, int IXDIM>
__global__ void ScatterNdOpKernel(
const Index* indices, const T* updates, T* out,
const Eigen::array<Eigen::DenseIndex, IXDIM> output_shape_prefix,
const Eigen::array<int64, IXDIM> batch_strides, const int64 num_indices,
const Index slice_size) {
auto update = LeftUpdate<T, op>();
GPU_1D_KERNEL_LOOP(index, num_indices) {
Index i = 0;
bool out_of_bounds = false;
#pragma unroll
for (int dim = 0; dim < IXDIM; ++dim) {
int offset = (IXDIM * index + dim);
const Index ix_d = internal::SubtleMustCopy(ldg(indices + offset));
out_of_bounds |= !FastBoundsCheck(ix_d, output_shape_prefix[dim]);
i += ix_d * batch_strides[dim] * slice_size;
}
if (!out_of_bounds) {
#pragma unroll
for (int si = 0; si < slice_size; si++) {
update(out + i + si, ldg(updates + (index * slice_size + si)));
}
}
}
}
namespace functor {
// Functor used by ScatterOp to do the computations.
template <typename T, typename Index, scatter_nd_op::UpdateOp op, int IXDIM>
struct ScatterNdFunctor<GPUDevice, T, Index, op, IXDIM> {
Index operator()(
const GPUDevice& d, const Index slice_size,
const Eigen::array<Eigen::DenseIndex, IXDIM> output_shape_prefix,
typename TTypes<T, 2>::Tensor Tparams,
typename TTypes<Index, 2>::ConstTensor Tindices,
typename TTypes<T, 2>::ConstTensor Tupdates,
typename TTypes<T, 2>::Tensor Toutput) {
// TODO(ebrevdo): The performance of this for small indices (large
// slices) is poor. Write a kernel whose splitting is
// independent of the slice size. Same for CPU. See the
// gather_nd kernel for an example.
const Eigen::DenseIndex batch_size = Tindices.dimension(0);
// Index batch_strides[IXDIM];
Eigen::array<int64, IXDIM> batch_strides;
for (int dim = IXDIM - 1; dim >= 0; --dim) {
if (dim == IXDIM - 1) {
batch_strides[dim] = 1;
} else {
batch_strides[dim] =
batch_strides[dim + 1] * output_shape_prefix[dim + 1];
}
}
GpuLaunchConfig config = GetGpuLaunchConfig(Toutput.size(), d);
TF_CHECK_OK(GpuLaunchKernel(ScatterNdOpKernel<T, Index, op, IXDIM>,
config.block_count, config.thread_per_block, 0,
d.stream(), Tindices.data(), Tupdates.data(),
Toutput.data(), output_shape_prefix,
batch_strides, batch_size, slice_size));
return -1;
}
};
} // namespace functor
#define DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, IXDIM) \
template struct functor::ScatterNdFunctor<GPUDevice, T, Index, op, IXDIM>;
#define DECLARE_GPU_SPECS_INDEX_OP(T, Index, op) \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 1); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 2); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 3); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 4); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 5); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 6); \
DECLARE_GPU_SPECS_INDEX_OP_IXDIM(T, Index, op, 7);
#define DECLARE_GPU_SPECS_INDEX(T, Index) \
DECLARE_GPU_SPECS_INDEX_OP(T, Index, scatter_nd_op::UpdateOp::ASSIGN); \
DECLARE_GPU_SPECS_INDEX_OP(T, Index, scatter_nd_op::UpdateOp::ADD); \
DECLARE_GPU_SPECS_INDEX_OP(T, Index, scatter_nd_op::UpdateOp::SUB)
#define DECLARE_GPU_SPECS(T) \
DECLARE_GPU_SPECS_INDEX(T, int32); \
DECLARE_GPU_SPECS_INDEX(T, int64)
TF_CALL_int32(DECLARE_GPU_SPECS);
TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPECS);
TF_CALL_complex64(DECLARE_GPU_SPECS);
TF_CALL_complex128(DECLARE_GPU_SPECS);
#undef DECLARE_GPU_SPECS
#undef DECLARE_GPU_SPECS_INDEX
#undef DECLARE_GPU_SPECS_INDEX_OP
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// guaranteed_minimum_withdrawal_benefit.cpp
// -----------------------------------------
//
// Computes the price of a Guaranteed Minimum Withdrawal Benefit (GMWB) using an
// implicit, impulse control formulation.
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////
#include <QuantPDE/Core>
#include <QuantPDE/Modules/Lambdas>
#include <QuantPDE/Modules/Operators>
////////////////////////////////////////////////////////////////////////////////
#include <algorithm> // max, min
#include <iostream> // cout
#include <numeric> // accumulate
#include <tuple> // get
////////////////////////////////////////////////////////////////////////////////
using namespace QuantPDE;
using namespace QuantPDE::Modules;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
class Withdrawal final : public ControlledLinearSystem2 {
static constexpr Real epsilon = 1e-12;
RectilinearGrid2 &grid;
Noncontrollable2 contractRate, kappa;
Controllable2 control;
public:
template <typename G, typename F1, typename F2>
Withdrawal(G &grid, F1 &&contractRate, F2 &&kappa) noexcept :
grid(grid),
contractRate(contractRate),
kappa(kappa),
control( Control2(grid) )
{
registerControl( control );
}
virtual Matrix A(Real t) {
Matrix M(grid.size(), grid.size());
M.reserve(IntegerVector::Constant(grid.size(), 4));
Index i = 0;
for(auto node : grid) {
const Real S = node[0]; // Investment
const Real W = node[1]; // Withdrawal
// Contract rate of withdrawal
const Real Gdt = contractRate(t, S, W);
// Control
const Real q = control(t, S, W);
// Amount withdrawn, pre-penalty
const Real lambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);
// Interpolation data
auto data = interpolationData<2>(
grid,
{
max(S - lambdaW, 0.),
W - lambdaW
}
);
const Index i0 = get<0>( data[0] );
const Index i1 = get<0>( data[1] );
const Real w0 = get<1>( data[0] );
const Real w1 = get<1>( data[1] );
const Index j = grid.index(i0, i1);
M.insert(i, j ) = w0 * w1 ;
M.insert(i, j + grid[0].size()) = w0 * (1-w1);
M.insert(i, j + 1 ) = (1-w0) * w1 ;
M.insert(i, j + 1 + grid[0].size()) = (1-w0) * (1-w1);
++i;
}
M.makeCompressed();
return grid.identity() - M;
}
virtual Vector b(Real t) {
Vector b( grid.vector() );
for(auto node : accessor(grid, b)) {
const Real S = (&node)[0]; // Investment
const Real W = (&node)[1]; // Withdrawal
// You have no money :(
if(W <= epsilon) {
*node = 0.;
continue;
}
// Contract rate of withdrawal
const Real Gdt = contractRate(t, S, W);
// Control
const Real q = control(t, S, W);
// Amount withdrawn, pre-penalty
const Real lambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);
// Withdrawal at no penalty
if(lambdaW < Gdt) {
*node = lambdaW;
continue;
}
// Withdrawal at a penalty
*node = lambdaW - kappa(t, S, W) * (lambdaW - Gdt);
}
return b;
}
};
////////////////////////////////////////////////////////////////////////////////
int main() {
int n = 10; // Optimal control partition size
int N = 100; // Number of timesteps
Real T = 10.;
Real r = .05;
Real v = .20;
Real alpha = 0.; // Hedging fee
Real G = 10.; // Contract rate
Real kappa = 0.1; // Penalty rate
int refinement = 1;
////////////////////////////////////////////////////////////////////////
// Solution grid
////////////////////////////////////////////////////////////////////////
RectilinearGrid2 grid(
Axis {
0., 5., 10., 15., 20., 25.,
30., 35., 40., 45.,
50., 55., 60., 65., 70., 72.5, 75., 77.5, 80., 82., 84.,
86., 88., 90., 91., 92., 93., 94., 95.,
96., 97., 98., 99., 100.,
101., 102., 103., 104., 105., 106.,
107., 108., 109., 110., 112., 114.,
116., 118., 120., 123., 126.,
130., 135., 140., 145., 150., 160., 175., 200., 225.,
250., 300., 500., 750., 1000.
},
Axis::range(0., 2., 200.)
);
unsigned pow2l = 1; // 2^l
for(int l = 0; l < refinement; ++l) {
////////////////////////////////////////////////////////////////////////
// Control grid
////////////////////////////////////////////////////////////////////////
// Control partition 0 : 1/n : 1 (MATLAB notation)
RectilinearGrid1 controls( Axis::range(0., 1. / (n * pow2l), 2.) );
////////////////////////////////////////////////////////////////////////
// Iteration tree
////////////////////////////////////////////////////////////////////////
ReverseConstantStepper stepper(
0., // Initial time
T, // Expiry time
T / (N * pow2l) // Timestep size
);
ToleranceIteration tolerance;
stepper.setInnerIteration(tolerance);
////////////////////////////////////////////////////////////////////////
// Linear system tree
////////////////////////////////////////////////////////////////////////
BlackScholes<2, 0> bs(grid, r, v, alpha);
ReverseLinearBDFTwo bdf(grid, bs);
bdf.setIteration(stepper);
Withdrawal impulse(grid, G * T / (N * pow2l), kappa);
MinPolicyIteration2_1 policy(grid, controls, impulse);
PenaltyMethod penalty(grid, bdf, policy);
// TODO: It currently matters what order each linear system is
// associated with an iteration; fix this.
penalty.setIteration(tolerance);
policy.setIteration(tolerance);
////////////////////////////////////////////////////////////////////////
// Payoff
////////////////////////////////////////////////////////////////////////
Function2 payoff = [=] (Real S, Real W) {
return max(S, (1 - kappa) * W);
};
////////////////////////////////////////////////////////////////////////
// Running
////////////////////////////////////////////////////////////////////////
BiCGSTABSolver solver;
auto V = stepper.solve(
grid, // Domain
payoff, // Initial condition
penalty, // Root of linear system tree
solver // Linear system solver
);
////////////////////////////////////////////////////////////////////////
// Print solution
////////////////////////////////////////////////////////////////////////
RectilinearGrid2 printGrid(
Axis::range(0., 25., 200.),
Axis::range(0., 25., 200.)
);
cout << accessor( printGrid, V );
cout << endl;
auto its = tolerance.iterations();
Real inner = accumulate(its.begin(), its.end(), 0.)/its.size();
cout << "average number of inner iterations: " << inner << endl;
cout << endl;
pow2l *= 2;
////////////////////////////////////////////////////////////////////////
// Refine Solution grid
////////////////////////////////////////////////////////////////////////
grid.refine( RectilinearGrid2::NewTickBetweenEachPair() );
}
return 0;
}
<commit_msg>Better control node discretization.<commit_after>////////////////////////////////////////////////////////////////////////////////
// guaranteed_minimum_withdrawal_benefit.cpp
// -----------------------------------------
//
// Computes the price of a Guaranteed Minimum Withdrawal Benefit (GMWB) using an
// implicit, impulse control formulation.
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////
#include <QuantPDE/Core>
#include <QuantPDE/Modules/Lambdas>
#include <QuantPDE/Modules/Operators>
////////////////////////////////////////////////////////////////////////////////
#include <algorithm> // max, min
#include <iostream> // cout
#include <numeric> // accumulate
#include <tuple> // get
////////////////////////////////////////////////////////////////////////////////
using namespace QuantPDE;
using namespace QuantPDE::Modules;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
class Withdrawal final : public ControlledLinearSystem2 {
static constexpr Real epsilon = 1e-12;
RectilinearGrid2 &grid;
Noncontrollable2 contractRate, kappa;
Controllable2 control;
public:
template <typename G, typename F1, typename F2>
Withdrawal(G &grid, F1 &&contractRate, F2 &&kappa) noexcept :
grid(grid),
contractRate(contractRate),
kappa(kappa),
control( Control2(grid) )
{
registerControl( control );
}
virtual Matrix A(Real t) {
Matrix M(grid.size(), grid.size());
M.reserve(IntegerVector::Constant(grid.size(), 4));
Index i = 0;
for(auto node : grid) {
const Real S = node[0]; // Investment
const Real W = node[1]; // Withdrawal
// Contract rate of withdrawal
const Real Gdt = contractRate(t, S, W);
// Control
const Real q = control(t, S, W);
// Amount withdrawn, pre-penalty
//const Real lambdaW = q * W;
Real lambdaW;
if(Gdt <= W) {
lambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);
} else {
lambdaW = q/2.*W;
}
// Interpolation data
auto data = interpolationData<2>(
grid,
{
max(S - lambdaW, 0.),
W - lambdaW
}
);
const Index i0 = get<0>( data[0] );
const Index i1 = get<0>( data[1] );
const Real w0 = get<1>( data[0] );
const Real w1 = get<1>( data[1] );
const Index j = grid.index(i0, i1);
M.insert(i, j ) = w0 * w1 ;
M.insert(i, j + grid[0].size()) = w0 * (1-w1);
M.insert(i, j + 1 ) = (1-w0) * w1 ;
M.insert(i, j + 1 + grid[0].size()) = (1-w0) * (1-w1);
++i;
}
M.makeCompressed();
return grid.identity() - M;
}
virtual Vector b(Real t) {
Vector b( grid.vector() );
for(auto node : accessor(grid, b)) {
const Real S = (&node)[0]; // Investment
const Real W = (&node)[1]; // Withdrawal
// You have no money :(
if(W <= epsilon) {
*node = 0.;
continue;
}
// Contract rate of withdrawal
const Real Gdt = contractRate(t, S, W);
// Control
const Real q = control(t, S, W);
// Amount withdrawn, pre-penalty
//const Real lambdaW = q * W;
Real lambdaW;
if(Gdt <= W) {
lambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);
} else {
lambdaW = q/2.*W;
}
// Withdrawal at no penalty
if(lambdaW < Gdt) {
*node = lambdaW;
continue;
}
// Withdrawal at a penalty
*node = lambdaW - kappa(t, S, W) * (lambdaW - Gdt);
}
return b;
}
};
////////////////////////////////////////////////////////////////////////////////
int main() {
int n = 10; // Initial optimal control partition size
int N = 32; // Initial number of timesteps
Real T = 10.;
Real r = .05;
Real v = .2;
Real alpha = 0.013886; // Hedging fee
Real G = 10.; // Contract rate
Real kappa = 0.1; // Penalty rate
int refinement = 1;
////////////////////////////////////////////////////////////////////////
// Solution grid
////////////////////////////////////////////////////////////////////////
RectilinearGrid2 grid(
Axis {
0., 5., 10., 15., 20., 25.,
30., 35., 40., 45.,
50., 55., 60., 65., 70., 72.5, 75., 77.5, 80., 82., 84.,
86., 88., 90., 91., 92., 93., 94., 95.,
96., 97., 98., 99., 100.,
101., 102., 103., 104., 105., 106.,
107., 108., 109., 110., 112., 114.,
116., 118., 120., 123., 126.,
130., 135., 140., 145., 150., 160., 175., 200., 225.,
250., 300., 500., 750., 1000.
},
Axis::range(0., 2., 100.)
);
unsigned pow2l = 1; // 2^l
for(int l = 0; l < refinement; ++l) {
////////////////////////////////////////////////////////////////////////
// Control grid
////////////////////////////////////////////////////////////////////////
// Control partition 0 : 1/n : 1 (MATLAB notation)
RectilinearGrid1 controls( Axis::range(0., 1. / (n * pow2l), 2.) );
////////////////////////////////////////////////////////////////////////
// Iteration tree
////////////////////////////////////////////////////////////////////////
ReverseConstantStepper stepper(
0., // Initial time
T, // Expiry time
T / (N * pow2l) // Timestep size
);
ToleranceIteration tolerance;
stepper.setInnerIteration(tolerance);
////////////////////////////////////////////////////////////////////////
// Linear system tree
////////////////////////////////////////////////////////////////////////
BlackScholes<2, 0> bs(grid, r, v, alpha);
ReverseRannacher discretization(grid, bs);
discretization.setIteration(stepper);
Withdrawal impulse(grid, G * T / (N * pow2l), kappa);
MinPolicyIteration2_1 policy(grid, controls, impulse);
PenaltyMethod penalty(grid, discretization, policy);
// TODO: It currently matters what order each linear system is
// associated with an iteration; fix this.
penalty.setIteration(tolerance);
policy.setIteration(tolerance);
////////////////////////////////////////////////////////////////////////
// Payoff
////////////////////////////////////////////////////////////////////////
Function2 payoff = [=] (Real S, Real W) {
return max(S, (1 - kappa) * W);
};
////////////////////////////////////////////////////////////////////////
// Running
////////////////////////////////////////////////////////////////////////
BiCGSTABSolver solver;
auto V = stepper.solve(
grid, // Domain
payoff, // Initial condition
penalty, // Root of linear system tree
solver // Linear system solver
);
////////////////////////////////////////////////////////////////////////
// Print solution
////////////////////////////////////////////////////////////////////////
RectilinearGrid2 printGrid(
Axis::range(0., 25., 200.),
Axis { 100. }
);
cout << accessor( printGrid, V );
cout << endl;
auto its = tolerance.iterations();
Real inner = accumulate(its.begin(), its.end(), 0.)/its.size();
cout << "average number of inner iterations: " << inner << endl;
cout << endl;
pow2l *= 2;
////////////////////////////////////////////////////////////////////////
// Refine Solution grid
////////////////////////////////////////////////////////////////////////
grid.refine( RectilinearGrid2::NewTickBetweenEachPair() );
}
return 0;
}
<|endoftext|> |
<commit_before>#include "mediaplayer.h"
#include "ui_mediaplayer.h"
#include "medium.h"
#include <utility>
#include <QMouseEvent>
MediaPlayer::MediaPlayer(QWidget *parent) :
QWidget(parent),
ui(new Ui::MediaPlayer),
annotationPen(QColor(200,100,0)),
selectionPen(QColor(255,0,0)),
currentImageItem(nullptr),
currentSelection(nullptr)
{
ui->setupUi(this);
ui->graphicsView->setScene(&scene);
}
MediaPlayer::~MediaPlayer()
{
delete ui;
}
void MediaPlayer::display(Medium *medium)
{
if(currentImageItem != nullptr){
scene.removeItem(currentImageItem);
delete currentImageItem;
for(auto it = currentAnnotations.begin(); it != currentAnnotations.end(); ++it){
scene.removeItem(*it);
delete *it;
}
currentAnnotations.clear();
}
QImage image(medium->getFile());
currentImageItem = scene.addPixmap(QPixmap::fromImage(std::move(image))); // don't know how many copies are made here
scene.setSceneRect(0,0, image.width(), image.height()); // adjust visible area
for(auto it = medium->beginAnnotations(); it != medium->endAnnotatoins(); ++it){
currentAnnotations.push_back(scene.addRect(it->getRect(), annotationPen));
}
fit();
}
void MediaPlayer::resizeEvent(QResizeEvent *event)
{
fit();
}
void MediaPlayer::on_graphicsView_rubberBandChanged(const QRect &viewportRect, const QPointF &fromScenePoint, const QPointF &toScenePoint)
{
if(fromScenePoint.x() == 0 && fromScenePoint.y() == 0){
if(currentSelection != nullptr){
scene.removeItem(currentSelection);
delete currentSelection;
}
currentSelection = scene.addRect(currentRubberBand, selectionPen);
} else {
currentRubberBand.setLeft(fromScenePoint.x());
currentRubberBand.setTop(fromScenePoint.y());
currentRubberBand.setRight(toScenePoint.x());
currentRubberBand.setBottom(toScenePoint.y());
}
}
void MediaPlayer::fit()
{
qreal width = currentImageItem->sceneBoundingRect().width();
qreal height = currentImageItem->sceneBoundingRect().height();
ui->graphicsView->fitInView(QRect(0,0, qMax(width, (qreal)ui->graphicsView->width()), qMax(height, (qreal)ui->graphicsView->height())), Qt::KeepAspectRatio);
}
<commit_msg>Fixed media player prototype. Selection will now disappear when switching images.<commit_after>#include "mediaplayer.h"
#include "ui_mediaplayer.h"
#include "medium.h"
#include <utility>
#include <QMouseEvent>
MediaPlayer::MediaPlayer(QWidget *parent) :
QWidget(parent),
ui(new Ui::MediaPlayer),
annotationPen(QColor(200,100,0)),
selectionPen(QColor(255,0,0)),
currentImageItem(nullptr),
currentSelection(nullptr)
{
ui->setupUi(this);
ui->graphicsView->setScene(&scene);
}
MediaPlayer::~MediaPlayer()
{
delete ui;
}
void MediaPlayer::display(Medium *medium)
{
if(currentImageItem != nullptr){
scene.removeItem(currentImageItem);
delete currentImageItem;
for(auto it = currentAnnotations.begin(); it != currentAnnotations.end(); ++it){
scene.removeItem(*it);
delete *it;
}
currentAnnotations.clear();
currentImageItem = nullptr;
}
if(currentSelection != nullptr){
scene.removeItem(currentSelection);
delete currentSelection;
currentSelection = nullptr;
}
QImage image(medium->getFile());
currentImageItem = scene.addPixmap(QPixmap::fromImage(std::move(image))); // don't know how many copies are made here
scene.setSceneRect(0,0, image.width(), image.height()); // adjust visible area
for(auto it = medium->beginAnnotations(); it != medium->endAnnotatoins(); ++it){
currentAnnotations.push_back(scene.addRect(it->getRect(), annotationPen));
}
fit();
}
void MediaPlayer::resizeEvent(QResizeEvent *event)
{
fit();
}
void MediaPlayer::on_graphicsView_rubberBandChanged(const QRect &viewportRect, const QPointF &fromScenePoint, const QPointF &toScenePoint)
{
if(fromScenePoint.x() == 0 && fromScenePoint.y() == 0){
if(currentSelection != nullptr){
scene.removeItem(currentSelection);
delete currentSelection;
}
currentSelection = scene.addRect(currentRubberBand, selectionPen);
} else {
currentRubberBand.setLeft(fromScenePoint.x());
currentRubberBand.setTop(fromScenePoint.y());
currentRubberBand.setRight(toScenePoint.x());
currentRubberBand.setBottom(toScenePoint.y());
}
}
void MediaPlayer::fit()
{
qreal width = currentImageItem->sceneBoundingRect().width();
qreal height = currentImageItem->sceneBoundingRect().height();
ui->graphicsView->fitInView(QRect(0,0, qMax(width, (qreal)ui->graphicsView->width()), qMax(height, (qreal)ui->graphicsView->height())), Qt::KeepAspectRatio);
}
<|endoftext|> |
<commit_before>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
TEST(ProbLognormal, log_matches_lpdf) {
double y = 0.8;
double mu = 1.1;
double sigma = 2.3;
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf(y, mu, sigma)),
(stan::math::lognormal_log(y, mu, sigma)));
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf<true>(y, mu, sigma)),
(stan::math::lognormal_log<true>(y, mu, sigma)));
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf<false>(y, mu, sigma)),
(stan::math::lognormal_log<false>(y, mu, sigma)));
EXPECT_FLOAT_EQ(
(stan::math::lognormal_lpdf<true, double, double, double>(y, mu, sigma)),
(stan::math::lognormal_log<true, double, double, double>(y, mu, sigma)));
EXPECT_FLOAT_EQ(
(stan::math::lognormal_lpdf<false, double, double, double>(y, mu, sigma)),
(stan::math::lognormal_log<false, double, double, double>(y, mu, sigma)));
EXPECT_FLOAT_EQ(
(stan::math::lognormal_lpdf<double, double, double>(y, mu, sigma)),
(stan::math::lognormal_log<double, double, double>(y, mu, sigma)));
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf(0.8, 2.0, 2.0)),
(stan::math::lognormal_log(0.8, 2, 2)));
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
TEST(ProbLognormal, log_matches_lpdf) {
double y = 0.8;
double mu = 1.1;
double sigma = 2.3;
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf(y, mu, sigma)),
(stan::math::lognormal_log(y, mu, sigma)));
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf<true>(y, mu, sigma)),
(stan::math::lognormal_log<true>(y, mu, sigma)));
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf<false>(y, mu, sigma)),
(stan::math::lognormal_log<false>(y, mu, sigma)));
EXPECT_FLOAT_EQ(
(stan::math::lognormal_lpdf<true, double, double, double>(y, mu, sigma)),
(stan::math::lognormal_log<true, double, double, double>(y, mu, sigma)));
EXPECT_FLOAT_EQ(
(stan::math::lognormal_lpdf<false, double, double, double>(y, mu, sigma)),
(stan::math::lognormal_log<false, double, double, double>(y, mu, sigma)));
EXPECT_FLOAT_EQ(
(stan::math::lognormal_lpdf<double, double, double>(y, mu, sigma)),
(stan::math::lognormal_log<double, double, double>(y, mu, sigma)));
EXPECT_FLOAT_EQ((stan::math::lognormal_lpdf(0.8, 2.0, 2.0)),
(stan::math::lognormal_log(0.8, 2, 2)));
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-11-11 Jan Kleinert <Jan.Kleinert@dlr.de>
* 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.
*/
/**
* @file
* @brief Tests for rotor functions.
*/
#include "test.h" // Brings in the GTest framework
#include "tigl.h"
#include "CCPACSConfigurationManager.h"
#include "CTiglUIDManager.h"
#include "CTiglEngineNacelleBuilder.h"
/******************************************************************************/
class EngineNacelleBuilder : public ::testing::Test
{
protected:
void SetUp() OVERRIDE
{
const char* filename = "TestData/simpletest-pylon-nacelle.cpacs.xml";
ReturnCode tixiRet;
TiglReturnCode tiglRet;
tiglHandle = -1;
tixiHandle = -1;
tixiRet = tixiOpenDocument(filename, &tixiHandle);
ASSERT_EQ(tixiRet, SUCCESS);
tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "SimpleTest", &tiglHandle);
ASSERT_EQ(tiglRet, TIGL_SUCCESS);
uidMgr = &tigl::CCPACSConfigurationManager::GetInstance().GetConfiguration(tiglHandle).GetUIDManager();
}
void TearDown() OVERRIDE
{
ASSERT_EQ(tiglCloseCPACSConfiguration(tiglHandle), TIGL_SUCCESS);
ASSERT_EQ(tixiCloseDocument(tixiHandle), SUCCESS);
tiglHandle = -1;
tixiHandle = -1;
}
TixiDocumentHandle tixiHandle;
TiglCPACSConfigurationHandle tiglHandle;
tigl::CTiglUIDManager* uidMgr;
};
/******************************************************************************/
/**
* Tests for greeting planets
*/
TEST_F(EngineNacelleBuilder, integrationTest)
{
tigl::CTiglEngineNacelleBuilder builder(nacelle);
PNamedShape shape = builder.BuildShape();
}
<commit_msg>minor fix in unit test<commit_after>/*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-11-11 Jan Kleinert <Jan.Kleinert@dlr.de>
* 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.
*/
/**
* @file
* @brief Tests for rotor functions.
*/
#include "test.h" // Brings in the GTest framework
#include "tigl.h"
#include "CCPACSConfigurationManager.h"
#include "CTiglUIDManager.h"
#include "CTiglEngineNacelleBuilder.h"
/******************************************************************************/
class EngineNacelleBuilder : public ::testing::Test
{
protected:
void SetUp() OVERRIDE
{
const char* filename = "TestData/simpletest-pylon-nacelle.cpacs.xml";
ReturnCode tixiRet;
TiglReturnCode tiglRet;
tiglHandle = -1;
tixiHandle = -1;
tixiRet = tixiOpenDocument(filename, &tixiHandle);
ASSERT_EQ(tixiRet, SUCCESS);
tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "SimpleTest", &tiglHandle);
ASSERT_EQ(tiglRet, TIGL_SUCCESS);
uidMgr = &tigl::CCPACSConfigurationManager::GetInstance().GetConfiguration(tiglHandle).GetUIDManager();
}
void TearDown() OVERRIDE
{
ASSERT_EQ(tiglCloseCPACSConfiguration(tiglHandle), TIGL_SUCCESS);
ASSERT_EQ(tixiCloseDocument(tixiHandle), SUCCESS);
tiglHandle = -1;
tixiHandle = -1;
}
TixiDocumentHandle tixiHandle;
TiglCPACSConfigurationHandle tiglHandle;
tigl::CTiglUIDManager* uidMgr;
};
/******************************************************************************/
TEST_F(EngineNacelleBuilder, integrationTest)
{
tigl::CCPACSEngineNacelle& nacelle = uidMgr->ResolveObject<tigl::CCPACSEngineNacelle>("SimpleNacelle");
tigl::CTiglEngineNacelleBuilder builder(nacelle);
PNamedShape shape = builder.BuildShape();
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Morwenn
*
* 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 <iterator>
#include <string>
#include <type_traits>
#include <vector>
#include <cpp-sort/adapters/hybrid_adapter.h>
#include <cpp-sort/sort.h>
#include <cpp-sort/sorter_facade.h>
#include <catch.hpp>
namespace
{
// Type of sorter used for checks
enum class sorter_type
{
integer,
floating_point,
generic
};
struct integer_sorter_impl
{
template<typename RandomAccessIterator>
auto operator()(RandomAccessIterator, RandomAccessIterator) const
-> std::enable_if_t<
std::is_integral<
typename std::iterator_traits<RandomAccessIterator>::value_type
>::value,
sorter_type
>
{
return sorter_type::integer;
}
using iterator_category = std::random_access_iterator_tag;
};
struct float_sorter_impl
{
template<typename RandomAccessIterator>
auto operator()(RandomAccessIterator, RandomAccessIterator) const
-> std::enable_if_t<
std::is_floating_point<
typename std::iterator_traits<RandomAccessIterator>::value_type
>::value,
sorter_type
>
{
return sorter_type::floating_point;
}
using iterator_category = std::random_access_iterator_tag;
};
struct generic_sorter_impl
{
template<typename RandomAccessIterator>
auto operator()(RandomAccessIterator, RandomAccessIterator) const
-> sorter_type
{
return sorter_type::generic;
}
using iterator_category = std::random_access_iterator_tag;
};
struct integer_sorter:
cppsort::sorter_facade<integer_sorter_impl>
{};
struct float_sorter:
cppsort::sorter_facade<float_sorter_impl>
{};
struct generic_sorter:
cppsort::sorter_facade<generic_sorter_impl>
{};
}
TEST_CASE( "sfinae forwarding in hybrid_adapter",
"[hybrid_adapter][sfinae]" )
{
// Check that hybrid_adapter takes into account
// the SFINAE in the aggregated sorters
// Vectors to "sort"
std::vector<int> vec1(3);
std::vector<float> vec2(3);
std::vector<std::string> vec3(3);
using sorter = cppsort::hybrid_adapter<
float_sorter,
integer_sorter,
// Should act as a fallback
generic_sorter
>;
SECTION( "with iterators" )
{
sorter_type res1 = cppsort::sort(sorter{}, std::begin(vec1), std::end(vec1));
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, std::begin(vec2), std::end(vec2));
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, std::begin(vec3), std::end(vec3));
CHECK( res3 == sorter_type::generic );
}
SECTION( "with iterables" )
{
sorter_type res1 = cppsort::sort(sorter{}, vec1);
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, vec2);
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, vec3);
CHECK( res3 == sorter_type::generic );
}
}
TEST_CASE( "sfinae forwarding in nested hybrid_adapter",
"[hybrid_adapter][sfinae]" )
{
// Check that hybrid_adapter takes into account
// the SFINAE in the aggregated sorters
// Vectors to "sort"
std::vector<int> vec1(3);
std::vector<float> vec2(3);
std::vector<std::string> vec3(3);
using sorter = cppsort::hybrid_adapter<
cppsort::hybrid_adapter<
float_sorter,
integer_sorter
>,
// Should act as a fallback
generic_sorter
>;
SECTION( "with iterators" )
{
sorter_type res1 = cppsort::sort(sorter{}, std::begin(vec1), std::end(vec1));
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, std::begin(vec2), std::end(vec2));
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, std::begin(vec3), std::end(vec3));
CHECK( res3 == sorter_type::generic );
}
SECTION( "with iterables" )
{
sorter_type res1 = cppsort::sort(sorter{}, vec1);
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, vec2);
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, vec3);
CHECK( res3 == sorter_type::generic );
}
}
<commit_msg>Check that hybrid_adapter correctly works with temporary collections<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Morwenn
*
* 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 <iterator>
#include <string>
#include <type_traits>
#include <vector>
#include <catch.hpp>
#include <cpp-sort/adapters/hybrid_adapter.h>
#include <cpp-sort/sort.h>
#include <cpp-sort/sorter_facade.h>
#include "../span.h"
namespace
{
// Type of sorter used for checks
enum class sorter_type
{
integer,
floating_point,
generic
};
struct integer_sorter_impl
{
template<typename RandomAccessIterator>
auto operator()(RandomAccessIterator, RandomAccessIterator) const
-> std::enable_if_t<
std::is_integral<
typename std::iterator_traits<RandomAccessIterator>::value_type
>::value,
sorter_type
>
{
return sorter_type::integer;
}
using iterator_category = std::random_access_iterator_tag;
};
struct float_sorter_impl
{
template<typename RandomAccessIterator>
auto operator()(RandomAccessIterator, RandomAccessIterator) const
-> std::enable_if_t<
std::is_floating_point<
typename std::iterator_traits<RandomAccessIterator>::value_type
>::value,
sorter_type
>
{
return sorter_type::floating_point;
}
using iterator_category = std::random_access_iterator_tag;
};
struct generic_sorter_impl
{
template<typename RandomAccessIterator>
auto operator()(RandomAccessIterator, RandomAccessIterator) const
-> sorter_type
{
return sorter_type::generic;
}
using iterator_category = std::random_access_iterator_tag;
};
struct integer_sorter:
cppsort::sorter_facade<integer_sorter_impl>
{};
struct float_sorter:
cppsort::sorter_facade<float_sorter_impl>
{};
struct generic_sorter:
cppsort::sorter_facade<generic_sorter_impl>
{};
}
TEST_CASE( "sfinae forwarding in hybrid_adapter",
"[hybrid_adapter][sfinae]" )
{
// Check that hybrid_adapter takes into account
// the SFINAE in the aggregated sorters
// Vectors to "sort"
std::vector<int> vec1(3);
std::vector<float> vec2(3);
std::vector<std::string> vec3(3);
using sorter = cppsort::hybrid_adapter<
float_sorter,
integer_sorter,
// Should act as a fallback
generic_sorter
>;
SECTION( "with iterators" )
{
sorter_type res1 = cppsort::sort(sorter{}, std::begin(vec1), std::end(vec1));
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, std::begin(vec2), std::end(vec2));
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, std::begin(vec3), std::end(vec3));
CHECK( res3 == sorter_type::generic );
}
SECTION( "with iterables" )
{
sorter_type res1 = cppsort::sort(sorter{}, vec1);
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, vec2);
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, vec3);
CHECK( res3 == sorter_type::generic );
}
SECTION( "with span" )
{
sorter_type res1 = cppsort::sort(sorter{}, make_span(vec1));
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, make_span(vec2));
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, make_span(vec3));
CHECK( res3 == sorter_type::generic );
}
}
TEST_CASE( "sfinae forwarding in nested hybrid_adapter",
"[hybrid_adapter][sfinae]" )
{
// Check that hybrid_adapter takes into account
// the SFINAE in the aggregated sorters
// Vectors to "sort"
std::vector<int> vec1(3);
std::vector<float> vec2(3);
std::vector<std::string> vec3(3);
using sorter = cppsort::hybrid_adapter<
cppsort::hybrid_adapter<
float_sorter,
integer_sorter
>,
// Should act as a fallback
generic_sorter
>;
SECTION( "with iterators" )
{
sorter_type res1 = cppsort::sort(sorter{}, std::begin(vec1), std::end(vec1));
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, std::begin(vec2), std::end(vec2));
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, std::begin(vec3), std::end(vec3));
CHECK( res3 == sorter_type::generic );
}
SECTION( "with iterables" )
{
sorter_type res1 = cppsort::sort(sorter{}, vec1);
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, vec2);
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, vec3);
CHECK( res3 == sorter_type::generic );
}
SECTION( "with span" )
{
sorter_type res1 = cppsort::sort(sorter{}, make_span(vec1));
CHECK( res1 == sorter_type::integer );
sorter_type res2 = cppsort::sort(sorter{}, make_span(vec2));
CHECK( res2 == sorter_type::floating_point );
sorter_type res3 = cppsort::sort(sorter{}, make_span(vec3));
CHECK( res3 == sorter_type::generic );
}
}
<|endoftext|> |
<commit_before>/*
* Distributed under the MIT License (See accompanying file /LICENSE )
*/
#include "logger.h"
#include <spdlog/sinks/dist_sink.h>
#ifdef _WIN32
#include <spdlog/sinks/wincolor_sink.h>
#else
#include <spdlog/sinks/ansicolor_sink.h>
#endif
#if defined(_DEBUG) && defined(_MSC_VER)
#include <spdlog/sinks/msvc_sink.h>
#endif // _DEBUG && _MSC_VER
namespace ModernCppCI {
auto create_spdlog() {
#ifdef _WIN32
auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();
#else
auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();
#endif
auto dist_sink = std::make_shared<spdlog::sinks::dist_sink_st>();
dist_sink->add_sink(color_sink);
#if defined(_DEBUG) && defined(_MSC_VER)
auto debug_sink = std::make_shared<spdlog::sinks::msvc_sink_st>();
dist_sink->add_sink(debug_sink);
#endif // _DEBUG && _MSC_VER
return spdlog::details::registry::instance().create("console", dist_sink);
}
Logger::Logger(const std::string §ion) : section_{section} {
internal_logger_ = spdlog::get("console");
if (internal_logger_ == nullptr) {
internal_logger_ = create_spdlog();
}
}
Logger operator""_log(const char *p, size_t n) {
return Logger{std::string{p, n}};
}
} // namespace ModernCppCI
<commit_msg>remove unused operator<commit_after>/*
* Distributed under the MIT License (See accompanying file /LICENSE )
*/
#include "logger.h"
#include <spdlog/sinks/dist_sink.h>
#ifdef _WIN32
#include <spdlog/sinks/wincolor_sink.h>
#else
#include <spdlog/sinks/ansicolor_sink.h>
#endif
#if defined(_DEBUG) && defined(_MSC_VER)
#include <spdlog/sinks/msvc_sink.h>
#endif // _DEBUG && _MSC_VER
namespace ModernCppCI {
auto create_spdlog() {
#ifdef _WIN32
auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();
#else
auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();
#endif
auto dist_sink = std::make_shared<spdlog::sinks::dist_sink_st>();
dist_sink->add_sink(color_sink);
#if defined(_DEBUG) && defined(_MSC_VER)
auto debug_sink = std::make_shared<spdlog::sinks::msvc_sink_st>();
dist_sink->add_sink(debug_sink);
#endif // _DEBUG && _MSC_VER
return spdlog::details::registry::instance().create("console", dist_sink);
}
Logger::Logger(const std::string §ion) : section_{section} {
internal_logger_ = spdlog::get("console");
if (internal_logger_ == nullptr) {
internal_logger_ = create_spdlog();
}
}
} // namespace ModernCppCI
<|endoftext|> |
<commit_before>// Name: CglConicOA.cpp
// Author: Aykut Bulut
// Lehigh University
// email: aykut@lehigh.edu, aykutblt@gmail.com
//-----------------------------------------------------------------------------
// Copyright (C) 2015, Lehigh University. All Rights Reserved.
//-----------------------------------------------------
// Implements simple cutting plane solver for SOCO problems.
// Makes use of CglConicOA cut library.
//
// usage:
// cutting_plane_solver mpsFileName
// example:
// cutting_plane_solver ../../Data/Sample/p0033
//-----------------------------------------------------
#include <CglConicOA.hpp>
#include <ColaModel.hpp>
#include <OsiMskSolverInterface.hpp>
int main(int argc, char ** argv) {
// create conic solver interface
ColaModel * conic_solver = new ColaModel();
// read problem including conic constraints
conic_solver->readMps(argv[1]);
// solve initial problem ignoring conic constraints.
conic_solver->OsiClpSolverInterface::initialSolve();
CglConicOA cg;
OsiCuts * cuts;
int total_num_cuts = 0;
clock_t start_time = clock();
// solve problem while we can generate cuts.
do {
// ignore conic constraints and solve LP problem
conic_solver->OsiClpSolverInterface::resolve();
// generate cuts
cuts = new OsiCuts();
cg.generateCuts(*conic_solver, *cuts);
// add cuts to the problem
int num_cuts = cuts->sizeRowCuts();
if (num_cuts==0) {
break;
}
else {
std::cout << num_cuts << " many cuts produced." << std::endl;
}
total_num_cuts += num_cuts;
conic_solver->OsiSolverInterface::applyCuts(*cuts);
delete cuts;
} while(true);
clock_t duration = clock() - start_time;
// print solution status
conic_solver->report_feasibility();
std::cout << "Total number of cuts: " << total_num_cuts << std::endl;
std::cout << "Objective value: " << conic_solver->getObjValue() << std::endl;
std::cout << "CPU time: "
<< double(duration)/double(CLOCKS_PER_SEC) << std::endl;
delete conic_solver;
return 0;
}
<commit_msg>Example updated.<commit_after>// Name: CglConicOA.cpp
// Author: Aykut Bulut
// Lehigh University
// email: aykut@lehigh.edu, aykutblt@gmail.com
//-----------------------------------------------------------------------------
// Copyright (C) 2015, Lehigh University. All Rights Reserved.
//-----------------------------------------------------
// Implements simple cutting plane solver for SOCO problems.
// Makes use of CglConicOA cut library.
//
// usage:
// cutting_plane_solver mpsFileName
// example:
// cutting_plane_solver ../../Data/Sample/p0033
//-----------------------------------------------------
#include <CglConicOA.hpp>
#include <ColaModel.hpp>
#include <OsiMskSolverInterface.hpp>
int main(int argc, char ** argv) {
// create conic solver interface
ColaModel * conic_solver = new ColaModel();
// read problem including conic constraints
conic_solver->readMps(argv[1]);
// solve initial problem ignoring conic constraints.
conic_solver->OsiClpSolverInterface::initialSolve();
CglConicOA cg(1e-5);
OsiCuts * cuts;
int total_num_cuts = 0;
clock_t start_time = clock();
// solve problem while we can generate cuts.
do {
// ignore conic constraints and solve LP problem
conic_solver->OsiClpSolverInterface::resolve();
// generate cuts
cuts = new OsiCuts();
cg.generateCuts(*conic_solver, *cuts);
// add cuts to the problem
int num_cuts = cuts->sizeRowCuts();
if (num_cuts==0) {
break;
}
else {
std::cout << num_cuts << " many cuts produced." << std::endl;
}
total_num_cuts += num_cuts;
conic_solver->OsiSolverInterface::applyCuts(*cuts);
delete cuts;
} while(true);
clock_t duration = clock() - start_time;
// print solution status
conic_solver->report_feasibility();
std::cout << "Total number of cuts: " << total_num_cuts << std::endl;
std::cout << "Objective value: " << conic_solver->getObjValue() << std::endl;
std::cout << "CPU time: "
<< double(duration)/double(CLOCKS_PER_SEC) << std::endl;
delete conic_solver;
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/Lazy.hpp"
#include "libbirch/SharedPtr.hpp"
#include "libbirch/FiberState.hpp"
#include "libbirch/Optional.hpp"
namespace libbirch {
/**
* Fiber.
*
* @ingroup libbirch
*
* @tparam Yield Yield type.
* @tparam Return Return type.
*/
template<class Yield, class Return>
class Fiber {
public:
using yield_type = Yield;
using return_type = Return;
using state_type = Lazy<SharedPtr<FiberState<Yield,Return>>>;
/**
* Constructor. Used:
*
* @li for an uninitialized fiber handle, and
* @li for returns in fibers with a return type of `void`, where no state
* or resume function is required, and no value is returned.
*/
Fiber() {
//
}
/**
* Constructor. Used:
*
* @li in the initialization function of all fibers, where a state and
* start function are required, but no value is yielded, and
* @li for yields in fibers with a yield type of `void`, where a state and
* resume function are required, but no value is yielded.
*/
Fiber(const state_type& state) :
state(state) {
//
}
/**
* Constructor. Used for yields in fibers with a yield type that is not
* `void`, where a state and resume function are required, along with a
* yield value.
*/
Fiber(const yield_type& yieldValue, const state_type& state) :
yieldValue(yieldValue),
state(state) {
//
}
/**
* Constructor. Used for returns in fibers with a return type that is not
* `void`, where a state and resume function are not required, and a value
* is returned.
*/
Fiber(const return_type& returnValue) :
returnValue(returnValue) {
//
}
/**
* Accept visitor.
*/
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(yieldValue);
v.visit(returnValue);
v.visit(state);
}
/**
* Run to next yield point.
*
* @return Was a value yielded?
*/
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
/**
* Run to next yield point.
*
* @return Was a value yielded?
*/
bool query() const {
return const_cast<Fiber*>(this)->query();
}
/**
* Get the current yield value.
*/
auto get() const {
return yieldValue.get();
}
private:
/**
* Yield value.
*/
Optional<yield_type> yieldValue;
/**
* Return value.
*/
Optional<return_type> returnValue;
/**
* Fiber state.
*/
Optional<state_type> state;
};
template<class Return>
class Fiber<void,Return> {
public:
using yield_type = void;
using return_type = Return;
using state_type = Lazy<SharedPtr<FiberState<yield_type,return_type>>>;
Fiber() {
//
}
Fiber(const state_type& state) :
state(state) {
//
}
Fiber(const return_type& returnValue) :
returnValue(returnValue) {
//
}
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(returnValue);
v.visit(state);
}
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
bool query() const {
return const_cast<Fiber*>(this)->query();
}
private:
Optional<return_type> returnValue;
Optional<state_type> state;
};
template<class Yield>
class Fiber<Yield,void> {
public:
using yield_type = Yield;
using return_type = void;
using state_type = Lazy<SharedPtr<FiberState<yield_type,return_type>>>;
Fiber() {
//
}
Fiber(const state_type& state) :
state(state) {
//
}
Fiber(const yield_type& yieldValue, const state_type& state) :
yieldValue(yieldValue),
state(state) {
//
}
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(yieldValue);
v.visit(state);
}
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
bool query() const {
return const_cast<Fiber*>(this)->query();
}
auto get() const {
return yieldValue.get();
}
private:
Optional<yield_type> yieldValue;
Optional<state_type> state;
};
template<>
class Fiber<void,void> {
public:
using yield_type = void;
using return_type = void;
using state_type = Lazy<SharedPtr<FiberState<yield_type,return_type>>>;
Fiber() {
//
}
Fiber(const state_type& state) :
state(state) {
//
}
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(state);
}
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
bool query() const {
return const_cast<Fiber*>(this)->query();
}
private:
Optional<state_type> state;
};
template<class Yield, class Return>
struct is_value<Fiber<Yield,Return>> {
static const bool value = false;
};
}
<commit_msg>Added spin() functions to Fiber to retrieve return value.<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/Lazy.hpp"
#include "libbirch/SharedPtr.hpp"
#include "libbirch/FiberState.hpp"
#include "libbirch/Optional.hpp"
namespace libbirch {
/**
* Fiber.
*
* @ingroup libbirch
*
* @tparam Yield Yield type.
* @tparam Return Return type.
*/
template<class Yield, class Return>
class Fiber {
public:
using yield_type = Yield;
using return_type = Return;
using state_type = Lazy<SharedPtr<FiberState<Yield,Return>>>;
/**
* Constructor. Used:
*
* @li for an uninitialized fiber handle, and
* @li for returns in fibers with a return type of `void`, where no state
* or resume function is required, and no value is returned.
*/
Fiber() {
//
}
/**
* Constructor. Used:
*
* @li in the initialization function of all fibers, where a state and
* start function are required, but no value is yielded, and
* @li for yields in fibers with a yield type of `void`, where a state and
* resume function are required, but no value is yielded.
*/
Fiber(const state_type& state) :
state(state) {
//
}
/**
* Constructor. Used for yields in fibers with a yield type that is not
* `void`, where a state and resume function are required, along with a
* yield value.
*/
Fiber(const yield_type& yieldValue, const state_type& state) :
yieldValue(yieldValue),
state(state) {
//
}
/**
* Constructor. Used for returns in fibers with a return type that is not
* `void`, where a state and resume function are not required, and a value
* is returned.
*/
Fiber(const return_type& returnValue) :
returnValue(returnValue) {
//
}
/**
* Accept visitor.
*/
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(yieldValue);
v.visit(returnValue);
v.visit(state);
}
/**
* Run to next yield point.
*
* @return Was a value yielded?
*/
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
/**
* Run to next yield point.
*
* @return Was a value yielded?
*/
bool query() const {
return const_cast<Fiber*>(this)->query();
}
/**
* Get the current yield value.
*/
auto get() const {
return yieldValue.get();
}
/**
* Get the current return value.
*/
auto spin() const {
return returnValue.get();
}
private:
/**
* Yield value.
*/
Optional<yield_type> yieldValue;
/**
* Return value.
*/
Optional<return_type> returnValue;
/**
* Fiber state.
*/
Optional<state_type> state;
};
template<class Return>
class Fiber<void,Return> {
public:
using yield_type = void;
using return_type = Return;
using state_type = Lazy<SharedPtr<FiberState<yield_type,return_type>>>;
Fiber() {
//
}
Fiber(const state_type& state) :
state(state) {
//
}
Fiber(const return_type& returnValue) :
returnValue(returnValue) {
//
}
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(returnValue);
v.visit(state);
}
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
bool query() const {
return const_cast<Fiber*>(this)->query();
}
auto spin() const {
return returnValue.get();
}
private:
Optional<return_type> returnValue;
Optional<state_type> state;
};
template<class Yield>
class Fiber<Yield,void> {
public:
using yield_type = Yield;
using return_type = void;
using state_type = Lazy<SharedPtr<FiberState<yield_type,return_type>>>;
Fiber() {
//
}
Fiber(const state_type& state) :
state(state) {
//
}
Fiber(const yield_type& yieldValue, const state_type& state) :
yieldValue(yieldValue),
state(state) {
//
}
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(yieldValue);
v.visit(state);
}
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
bool query() const {
return const_cast<Fiber*>(this)->query();
}
auto get() const {
return yieldValue.get();
}
private:
Optional<yield_type> yieldValue;
Optional<state_type> state;
};
template<>
class Fiber<void,void> {
public:
using yield_type = void;
using return_type = void;
using state_type = Lazy<SharedPtr<FiberState<yield_type,return_type>>>;
Fiber() {
//
}
Fiber(const state_type& state) :
state(state) {
//
}
template<class Visitor>
void accept_(const Visitor& v) {
v.visit(state);
}
bool query() {
if (state.query()) {
*this = state.get()->query();
}
return state.query();
}
bool query() const {
return const_cast<Fiber*>(this)->query();
}
private:
Optional<state_type> state;
};
template<class Yield, class Return>
struct is_value<Fiber<Yield,Return>> {
static const bool value = false;
};
}
<|endoftext|> |
<commit_before>/*
fskit: a library for creating multi-threaded in-RAM filesystems
Copyright (C) 2014 Jude Nelson
This program is dual-licensed: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 3 or later as
published by the Free Software Foundation. For the terms of this
license, see LICENSE.LGPLv3+ or <http://www.gnu.org/licenses/>.
You are free to use this program under the terms of the GNU Lesser General
Public License, 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.
Alternatively, you are free to use this program under the terms of the
Internet Software Consortium License, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For the terms of this license, see LICENSE.ISC or
<http://www.isc.org/downloads/software-support-policy/isc-license/>.
*/
#include <fskit/mknod.h>
#include <fskit/path.h>
#include <fskit/open.h>
#include <fskit/route.h>
#include <fskit/util.h>
// get the user-supplied inode data for creating a node
int fskit_run_user_mknod( struct fskit_core* core, char const* path, struct fskit_entry* fent, mode_t mode, dev_t dev, void** inode_data ) {
int rc = 0;
int cbrc = 0;
struct fskit_route_dispatch_args dargs;
fskit_route_mknod_args( &dargs, mode, dev );
rc = fskit_route_call_mknod( core, path, fent, &dargs, &cbrc );
if( rc == -EPERM ) {
// no routes
*inode_data = NULL;
return 0;
}
else if( cbrc != 0 ) {
// callback failed
return cbrc;
}
else {
// callback succeded
*inode_data = dargs.inode_data;
return 0;
}
}
// make a node
int fskit_mknod( struct fskit_core* core, char const* fs_path, mode_t mode, dev_t dev, uint64_t user, uint64_t group ) {
int err = 0;
void* inode_data = NULL;
struct fskit_entry* child = NULL;
// sanity check
size_t basename_len = fskit_basename_len( fs_path );
if( basename_len > FSKIT_FILESYSTEM_NAMEMAX ) {
return -ENAMETOOLONG;
}
char* path = strdup( fs_path );
fskit_sanitize_path( path );
// get the parent directory and lock it
char* path_dirname = fskit_dirname( path, NULL );
struct fskit_entry* parent = fskit_entry_resolve_path( core, path_dirname, user, group, true, &err );
fskit_safe_free( path_dirname );
if( err != 0 || parent == NULL ) {
fskit_safe_free( path );
return err;
}
if( !FSKIT_ENTRY_IS_DIR_SEARCHABLE( parent->mode, parent->owner, parent->group, user, group ) ) {
// not searchable
fskit_entry_unlock( parent );
fskit_safe_free( path );
return -EACCES;
}
if( !FSKIT_ENTRY_IS_WRITEABLE( parent->mode, parent->owner, parent->group, user, group ) ) {
// not writeable
fskit_entry_unlock( parent );
fskit_safe_free( path );
return -EACCES;
}
char* path_basename = fskit_basename( path, NULL );
child = fskit_entry_set_find_name( parent->children, path_basename );
if( child != NULL ) {
fskit_entry_wlock( child );
// it might have been marked for garbage-collection
err = fskit_entry_try_garbage_collect( core, path, parent, child );
if( err >= 0 ) {
if( err == 0 ) {
// not destroyed
fskit_entry_unlock( child );
}
// name is free
child = NULL;
}
else {
// can't garbage-collect
fskit_entry_unlock( parent );
fskit_entry_unlock( child );
fskit_safe_free( path );
if( err == -EEXIST ) {
return -EEXIST;
}
else {
// shouldn't happen
fskit_error("BUG: fskit_entry_try_garbage_collect(%s) rc = %d\n", path, err );
return -EIO;
}
}
}
child = CALLOC_LIST( struct fskit_entry, 1 );
mode_t mmode = 0;
char const* method_name = NULL;
if( S_ISREG(mode) ) {
// regular file
mmode = (mode & 0777) | S_IFREG;
method_name = "fskit_entry_init_file";
err = fskit_entry_init_file( child, 0, path_basename, user, group, mmode );
}
else if( S_ISFIFO(mode) ) {
// fifo
mmode = (mode & 0777) | S_IFIFO;
method_name = "fskit_entry_init_fifo";
err = fskit_entry_init_fifo( child, 0, path_basename, user, group, mmode );
}
else if( S_ISSOCK(mode) ) {
// socket
mmode = (mode & 0777) | S_IFSOCK;
method_name = "fskit_entry_init_sock";
err = fskit_entry_init_sock( child, 0, path_basename, user, group, mmode );
}
else if( S_ISCHR(mode) ) {
// character device
mmode = (mode & 0777) | S_IFCHR;
method_name = "fskit_entry_init_chr";
err = fskit_entry_init_chr( child, 0, path_basename, user, group, mmode, dev );
}
else if( S_ISBLK(mode) ) {
// block device
mmode = (mode & 0777) | S_IFBLK;
method_name = "fskit_entry_init_blk";
err = fskit_entry_init_blk( child, 0, path_basename, user, group, mmode, dev );
}
else {
fskit_error("Invalid/unsupported mode %o\n", mode );
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_entry_destroy( core, child, false );
fskit_safe_free( child );
fskit_safe_free( path );
return -EINVAL;
}
if( err == 0 ) {
// success! get the inode number
uint64_t file_id = fskit_core_inode_alloc( core, parent, child );
if( file_id == 0 ) {
fskit_error("fskit_core_inode_alloc(%s) failed\n", path );
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_entry_destroy( core, child, false );
fskit_safe_free( child );
fskit_safe_free( path );
return -EIO;
}
fskit_entry_wlock( child );
child->file_id = file_id;
// perform any user-defined creations
err = fskit_run_user_mknod( core, path, child, mode, dev, &inode_data );
if( err != 0 ) {
// failed. abort creation
fskit_error("fskit_run_user_mknod(%s) rc = %d\n", path, err );
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_entry_destroy( core, child, true );
fskit_safe_free( child );
fskit_safe_free( path );
return err;
}
// attach the file
fskit_entry_attach_lowlevel( parent, child );
fskit_entry_unlock( child );
// update the number of files
fskit_file_count_update( core, 1 );
}
else {
fskit_error("%s(%s) rc = %d\n", method_name, path, err );
fskit_entry_destroy( core, child, false );
fskit_safe_free( child );
}
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_safe_free( path );
return err;
}
<commit_msg>Pass the write-locked parent directory inode to the user mknod route. It is sometimes necessary for the user route to have this information available.<commit_after>/*
fskit: a library for creating multi-threaded in-RAM filesystems
Copyright (C) 2014 Jude Nelson
This program is dual-licensed: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 3 or later as
published by the Free Software Foundation. For the terms of this
license, see LICENSE.LGPLv3+ or <http://www.gnu.org/licenses/>.
You are free to use this program under the terms of the GNU Lesser General
Public License, 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.
Alternatively, you are free to use this program under the terms of the
Internet Software Consortium License, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For the terms of this license, see LICENSE.ISC or
<http://www.isc.org/downloads/software-support-policy/isc-license/>.
*/
#include <fskit/mknod.h>
#include <fskit/path.h>
#include <fskit/open.h>
#include <fskit/route.h>
#include <fskit/util.h>
// get the user-supplied inode data for creating a node
int fskit_run_user_mknod( struct fskit_core* core, char const* path, struct fskit_entry* parent, struct fskit_entry* fent, mode_t mode, dev_t dev, void** inode_data ) {
int rc = 0;
int cbrc = 0;
struct fskit_route_dispatch_args dargs;
fskit_route_mknod_args( &dargs, parent, mode, dev );
rc = fskit_route_call_mknod( core, path, fent, &dargs, &cbrc );
if( rc == -EPERM ) {
// no routes
*inode_data = NULL;
return 0;
}
else if( cbrc != 0 ) {
// callback failed
return cbrc;
}
else {
// callback succeded
*inode_data = dargs.inode_data;
return 0;
}
}
// make a node
int fskit_mknod( struct fskit_core* core, char const* fs_path, mode_t mode, dev_t dev, uint64_t user, uint64_t group ) {
int err = 0;
void* inode_data = NULL;
struct fskit_entry* child = NULL;
// sanity check
size_t basename_len = fskit_basename_len( fs_path );
if( basename_len > FSKIT_FILESYSTEM_NAMEMAX ) {
return -ENAMETOOLONG;
}
char* path = strdup( fs_path );
fskit_sanitize_path( path );
// get the parent directory and lock it
char* path_dirname = fskit_dirname( path, NULL );
struct fskit_entry* parent = fskit_entry_resolve_path( core, path_dirname, user, group, true, &err );
fskit_safe_free( path_dirname );
if( err != 0 || parent == NULL ) {
fskit_safe_free( path );
return err;
}
if( !FSKIT_ENTRY_IS_DIR_SEARCHABLE( parent->mode, parent->owner, parent->group, user, group ) ) {
// not searchable
fskit_entry_unlock( parent );
fskit_safe_free( path );
return -EACCES;
}
if( !FSKIT_ENTRY_IS_WRITEABLE( parent->mode, parent->owner, parent->group, user, group ) ) {
// not writeable
fskit_entry_unlock( parent );
fskit_safe_free( path );
return -EACCES;
}
char* path_basename = fskit_basename( path, NULL );
child = fskit_entry_set_find_name( parent->children, path_basename );
if( child != NULL ) {
fskit_entry_wlock( child );
// it might have been marked for garbage-collection
err = fskit_entry_try_garbage_collect( core, path, parent, child );
if( err >= 0 ) {
if( err == 0 ) {
// not destroyed
fskit_entry_unlock( child );
}
// name is free
child = NULL;
}
else {
// can't garbage-collect
fskit_entry_unlock( parent );
fskit_entry_unlock( child );
fskit_safe_free( path );
if( err == -EEXIST ) {
return -EEXIST;
}
else {
// shouldn't happen
fskit_error("BUG: fskit_entry_try_garbage_collect(%s) rc = %d\n", path, err );
return -EIO;
}
}
}
child = CALLOC_LIST( struct fskit_entry, 1 );
mode_t mmode = 0;
char const* method_name = NULL;
if( S_ISREG(mode) ) {
// regular file
mmode = (mode & 0777) | S_IFREG;
method_name = "fskit_entry_init_file";
err = fskit_entry_init_file( child, 0, path_basename, user, group, mmode );
}
else if( S_ISFIFO(mode) ) {
// fifo
mmode = (mode & 0777) | S_IFIFO;
method_name = "fskit_entry_init_fifo";
err = fskit_entry_init_fifo( child, 0, path_basename, user, group, mmode );
}
else if( S_ISSOCK(mode) ) {
// socket
mmode = (mode & 0777) | S_IFSOCK;
method_name = "fskit_entry_init_sock";
err = fskit_entry_init_sock( child, 0, path_basename, user, group, mmode );
}
else if( S_ISCHR(mode) ) {
// character device
mmode = (mode & 0777) | S_IFCHR;
method_name = "fskit_entry_init_chr";
err = fskit_entry_init_chr( child, 0, path_basename, user, group, mmode, dev );
}
else if( S_ISBLK(mode) ) {
// block device
mmode = (mode & 0777) | S_IFBLK;
method_name = "fskit_entry_init_blk";
err = fskit_entry_init_blk( child, 0, path_basename, user, group, mmode, dev );
}
else {
fskit_error("Invalid/unsupported mode %o\n", mode );
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_entry_destroy( core, child, false );
fskit_safe_free( child );
fskit_safe_free( path );
return -EINVAL;
}
if( err == 0 ) {
// success! get the inode number
uint64_t file_id = fskit_core_inode_alloc( core, parent, child );
if( file_id == 0 ) {
fskit_error("fskit_core_inode_alloc(%s) failed\n", path );
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_entry_destroy( core, child, false );
fskit_safe_free( child );
fskit_safe_free( path );
return -EIO;
}
fskit_entry_wlock( child );
child->file_id = file_id;
// perform any user-defined creations
err = fskit_run_user_mknod( core, path, parent, child, mode, dev, &inode_data );
if( err != 0 ) {
// failed. abort creation
fskit_error("fskit_run_user_mknod(%s) rc = %d\n", path, err );
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_entry_destroy( core, child, true );
fskit_safe_free( child );
fskit_safe_free( path );
return err;
}
// attach the file
fskit_entry_attach_lowlevel( parent, child );
fskit_entry_unlock( child );
// update the number of files
fskit_file_count_update( core, 1 );
}
else {
fskit_error("%s(%s) rc = %d\n", method_name, path, err );
fskit_entry_destroy( core, child, false );
fskit_safe_free( child );
}
fskit_entry_unlock( parent );
fskit_safe_free( path_basename );
fskit_safe_free( path );
return err;
}
<|endoftext|> |
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2012 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen 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 details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INGEN_ENGINE_DIRECT_DRIVER_HPP
#define INGEN_ENGINE_DIRECT_DRIVER_HPP
#include "Driver.hpp"
namespace Ingen {
namespace Server {
/** Driver for running Ingen directly as a library.
* \ingroup engine
*/
class DirectDriver : public Driver {
public:
DirectDriver(double sample_rate, SampleCount block_length)
: _sample_rate(sample_rate)
, _block_length(block_length)
{}
virtual ~DirectDriver() {}
virtual void activate() {}
virtual void deactivate() {}
virtual EnginePort* create_port(DuplexPort* graph_port) {
return NULL;
}
virtual EnginePort* get_port(const Raul::Path& path) { return NULL; }
virtual void add_port(ProcessContext& context, EnginePort* port) {}
virtual void remove_port(ProcessContext& context, EnginePort* port) {}
virtual void rename_port(const Raul::Path& old_path,
const Raul::Path& new_path) {}
virtual void register_port(EnginePort& port) {}
virtual void unregister_port(EnginePort& port) {}
virtual SampleCount block_length() const { return _block_length; }
virtual SampleCount sample_rate() const { return _sample_rate; }
virtual SampleCount frame_time() const {
return 0;
}
virtual bool is_realtime() const {
return false;
}
virtual void append_time_events(ProcessContext& context,
Buffer& buffer) {}
private:
SampleCount _sample_rate;
SampleCount _block_length;
};
} // namespace Server
} // namespace Ingen
#endif // INGEN_ENGINE_DIRECT_DRIVER_HPP
<commit_msg>Implement port methods for DirectDriver.<commit_after>/*
This file is part of Ingen.
Copyright 2007-2012 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen 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 details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INGEN_ENGINE_DIRECT_DRIVER_HPP
#define INGEN_ENGINE_DIRECT_DRIVER_HPP
#include <boost/intrusive/list.hpp>
#include "Driver.hpp"
namespace Ingen {
namespace Server {
/** Driver for running Ingen directly as a library.
* \ingroup engine
*/
class DirectDriver : public Driver {
public:
DirectDriver(double sample_rate, SampleCount block_length)
: _sample_rate(sample_rate)
, _block_length(block_length)
{}
virtual ~DirectDriver() {}
virtual void activate() {}
virtual void deactivate() {}
virtual EnginePort* create_port(DuplexPort* graph_port) {
return new EnginePort(graph_port);
}
virtual EnginePort* get_port(const Raul::Path& path) {
for (auto& p : _ports) {
if (p.graph_port()->path() == path) {
return &p;
}
}
return NULL;
}
virtual void add_port(ProcessContext& context, EnginePort* port) {
_ports.push_back(*port);
}
virtual void remove_port(ProcessContext& context, EnginePort* port) {
_ports.erase(_ports.iterator_to(*port));
}
virtual void rename_port(const Raul::Path& old_path,
const Raul::Path& new_path) {}
virtual void register_port(EnginePort& port) {}
virtual void unregister_port(EnginePort& port) {}
virtual SampleCount block_length() const { return _block_length; }
virtual SampleCount sample_rate() const { return _sample_rate; }
virtual SampleCount frame_time() const { return 0; }
virtual bool is_realtime() const { return false; }
virtual void append_time_events(ProcessContext& context,
Buffer& buffer) {}
private:
typedef boost::intrusive::list<EnginePort> Ports;
Ports _ports;
SampleCount _sample_rate;
SampleCount _block_length;
};
} // namespace Server
} // namespace Ingen
#endif // INGEN_ENGINE_DIRECT_DRIVER_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
*
* 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 "binary_server.h"
#ifdef XAPIAND_CLUSTERING
#include <errno.h> // for errno
#include <sysexits.h> // for EX_SOFTWARE
#include "binary.h" // for Binary
#include "binary_client.h" // for BinaryClient
#include "cassert.h" // for ASSERT
#include "endpoint.h" // for Endpoints
#include "error.hh" // for error:name, error::description
#include "fs.hh" // for exists
#include "ignore_unused.h" // for ignore_unused
#include "manager.h" // for XapiandManager::manager
#include "readable_revents.hh" // for readable_revents
#include "repr.hh" // for repr
#include "tcp.h" // for TCP::socket
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_EV
// #define L_EV L_MEDIUM_PURPLE
BinaryServer::BinaryServer(const std::shared_ptr<Binary>& binary_, ev::loop_ref* ev_loop_, unsigned int ev_flags_)
: MetaBaseServer<BinaryServer>(binary_, ev_loop_, ev_flags_, binary_->port, "Binary", TCP_TCP_NODELAY | TCP_SO_REUSEPORT),
binary(*binary_),
trigger_replication_async(*ev_loop)
{
trigger_replication_async.set<BinaryServer, &BinaryServer::trigger_replication_async_cb>(this);
trigger_replication_async.start();
L_EV("Start binary's async trigger replication signal event");
}
BinaryServer::~BinaryServer() noexcept
{
try {
Worker::deinit();
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
void
BinaryServer::start_impl()
{
L_CALL("BinaryServer::start_impl()");
Worker::start_impl();
#if defined(__linux) || defined(__linux__) || defined(linux) || defined(SO_REUSEPORT_LB)
// In Linux, accept(2) on sockets using SO_REUSEPORT do a load balancing
// of the incoming clients. It's not the case in other systems; FreeBSD is
// adding SO_REUSEPORT_LB for that.
binary.close(true);
bind(1);
io.start(sock, ev::READ);
L_EV("Start binary's server accept event {sock:%d}", sock);
#else
io.start(binary.sock, ev::READ);
L_EV("Start binary's server accept event {sock:%d}", binary.sock);
#endif
}
void
BinaryServer::trigger_replication()
{
L_CALL("BinaryServer::trigger_replication()");
trigger_replication_async.send();
}
void
BinaryServer::trigger_replication_async_cb(ev::async&, int revents)
{
L_CALL("BinaryServer::trigger_replication_async_cb(<watcher>, 0x%x (%s))", revents, readable_revents(revents));
L_EV_BEGIN("BinaryServer::trigger_replication_async_cb:BEGIN");
L_EV_END("BinaryServer::trigger_replication_async_cb:END");
ignore_unused(revents);
TriggerReplicationArgs args;
while (binary.trigger_replication_args.try_dequeue(args)) {
trigger_replication(args);
}
}
int
BinaryServer::accept()
{
L_CALL("BinaryServer::accept()");
if (sock != -1) {
// If using SO_REUSEPORT for load balancing, this->sock
// will be opened and binary.sock will not.
return TCP::accept();
}
return binary.accept();
}
void
BinaryServer::io_accept_cb(ev::io& watcher, int revents)
{
L_CALL("BinaryServer::io_accept_cb(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd);
L_EV_BEGIN("BinaryServer::io_accept_cb:BEGIN");
L_EV_END("BinaryServer::io_accept_cb:END");
ignore_unused(watcher);
ASSERT(sock == -1 || sock == watcher.fd);
L_DEBUG_HOOK("BinaryServer::io_accept_cb", "BinaryServer::io_accept_cb(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd);
if ((EV_ERROR & revents) != 0) {
L_EV("ERROR: got invalid binary event {sock:%d}: %s (%d): %s", watcher.fd, error::name(errno), errno, error::description(errno));
return;
}
int client_sock = accept();
if (client_sock != -1) {
auto client = Worker::make_shared<BinaryClient>(share_this<BinaryServer>(), ev_loop, ev_flags, client_sock, active_timeout, idle_timeout);
if (!client->init_remote()) {
client->destroy();
return;
}
client->start();
}
}
void
BinaryServer::trigger_replication(const TriggerReplicationArgs& args)
{
if (args.src_endpoint.is_local()) {
ASSERT(!args.cluster_database);
return;
}
bool replicated = false;
if (args.src_endpoint.path == ".") {
// Cluster database is always updated
replicated = true;
}
if (!replicated && exists(std::string(args.src_endpoint.path) + "/iamglass")) {
// If database is already there, its also always updated
replicated = true;
}
if (!replicated) {
// Otherwise, check if the local node resolves as replicator
auto local_node = Node::local_node();
auto nodes = XapiandManager::manager->resolve_index_nodes(args.src_endpoint.path);
for (const auto& node : nodes) {
if (Node::is_equal(node, local_node)) {
replicated = true;
break;
}
}
}
if (!replicated) {
ASSERT(!args.cluster_database);
return;
}
int client_sock = TCP::socket();
if (client_sock == -1) {
if (args.cluster_database) {
L_CRIT("Cannot replicate cluster database");
sig_exit(-EX_SOFTWARE);
}
return;
}
auto client = Worker::make_shared<BinaryClient>(share_this<BinaryServer>(), ev_loop, ev_flags, client_sock, active_timeout, idle_timeout, args.cluster_database);
if (!client->init_replication(args.src_endpoint, args.dst_endpoint)) {
client->destroy();
return;
}
client->start();
L_DEBUG("Database %s being synchronized from %s%s" + DEBUG_COL + "...", repr(args.src_endpoint.to_string()), args.src_endpoint.node.col().ansi(), args.src_endpoint.node.name());
}
std::string
BinaryServer::__repr__() const
{
return string::format("<BinaryServer {cnt:%ld, sock:%d}%s%s%s>",
use_count(),
sock == -1 ? binary.sock : sock,
is_runner() ? " (runner)" : " (worker)",
is_running_loop() ? " (running loop)" : " (stopped loop)",
is_detaching() ? " (deteaching)" : "");
}
#endif /* XAPIAND_CLUSTERING */
<commit_msg>BinaryServer: Detach clients which didn't init<commit_after>/*
* Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
*
* 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 "binary_server.h"
#ifdef XAPIAND_CLUSTERING
#include <errno.h> // for errno
#include <sysexits.h> // for EX_SOFTWARE
#include "binary.h" // for Binary
#include "binary_client.h" // for BinaryClient
#include "cassert.h" // for ASSERT
#include "endpoint.h" // for Endpoints
#include "error.hh" // for error:name, error::description
#include "fs.hh" // for exists
#include "ignore_unused.h" // for ignore_unused
#include "manager.h" // for XapiandManager::manager
#include "readable_revents.hh" // for readable_revents
#include "repr.hh" // for repr
#include "tcp.h" // for TCP::socket
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_EV
// #define L_EV L_MEDIUM_PURPLE
BinaryServer::BinaryServer(const std::shared_ptr<Binary>& binary_, ev::loop_ref* ev_loop_, unsigned int ev_flags_)
: MetaBaseServer<BinaryServer>(binary_, ev_loop_, ev_flags_, binary_->port, "Binary", TCP_TCP_NODELAY | TCP_SO_REUSEPORT),
binary(*binary_),
trigger_replication_async(*ev_loop)
{
trigger_replication_async.set<BinaryServer, &BinaryServer::trigger_replication_async_cb>(this);
trigger_replication_async.start();
L_EV("Start binary's async trigger replication signal event");
}
BinaryServer::~BinaryServer() noexcept
{
try {
Worker::deinit();
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
void
BinaryServer::start_impl()
{
L_CALL("BinaryServer::start_impl()");
Worker::start_impl();
#if defined(__linux) || defined(__linux__) || defined(linux) || defined(SO_REUSEPORT_LB)
// In Linux, accept(2) on sockets using SO_REUSEPORT do a load balancing
// of the incoming clients. It's not the case in other systems; FreeBSD is
// adding SO_REUSEPORT_LB for that.
binary.close(true);
bind(1);
io.start(sock, ev::READ);
L_EV("Start binary's server accept event {sock:%d}", sock);
#else
io.start(binary.sock, ev::READ);
L_EV("Start binary's server accept event {sock:%d}", binary.sock);
#endif
}
void
BinaryServer::trigger_replication()
{
L_CALL("BinaryServer::trigger_replication()");
trigger_replication_async.send();
}
void
BinaryServer::trigger_replication_async_cb(ev::async&, int revents)
{
L_CALL("BinaryServer::trigger_replication_async_cb(<watcher>, 0x%x (%s))", revents, readable_revents(revents));
L_EV_BEGIN("BinaryServer::trigger_replication_async_cb:BEGIN");
L_EV_END("BinaryServer::trigger_replication_async_cb:END");
ignore_unused(revents);
TriggerReplicationArgs args;
while (binary.trigger_replication_args.try_dequeue(args)) {
trigger_replication(args);
}
}
int
BinaryServer::accept()
{
L_CALL("BinaryServer::accept()");
if (sock != -1) {
// If using SO_REUSEPORT for load balancing, this->sock
// will be opened and binary.sock will not.
return TCP::accept();
}
return binary.accept();
}
void
BinaryServer::io_accept_cb(ev::io& watcher, int revents)
{
L_CALL("BinaryServer::io_accept_cb(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd);
L_EV_BEGIN("BinaryServer::io_accept_cb:BEGIN");
L_EV_END("BinaryServer::io_accept_cb:END");
ignore_unused(watcher);
ASSERT(sock == -1 || sock == watcher.fd);
L_DEBUG_HOOK("BinaryServer::io_accept_cb", "BinaryServer::io_accept_cb(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd);
if ((EV_ERROR & revents) != 0) {
L_EV("ERROR: got invalid binary event {sock:%d}: %s (%d): %s", watcher.fd, error::name(errno), errno, error::description(errno));
return;
}
int client_sock = accept();
if (client_sock != -1) {
auto client = Worker::make_shared<BinaryClient>(share_this<BinaryServer>(), ev_loop, ev_flags, client_sock, active_timeout, idle_timeout);
if (!client->init_remote()) {
client->detach();
return;
}
client->start();
}
}
void
BinaryServer::trigger_replication(const TriggerReplicationArgs& args)
{
if (args.src_endpoint.is_local()) {
ASSERT(!args.cluster_database);
return;
}
bool replicated = false;
if (args.src_endpoint.path == ".") {
// Cluster database is always updated
replicated = true;
}
if (!replicated && exists(std::string(args.src_endpoint.path) + "/iamglass")) {
// If database is already there, its also always updated
replicated = true;
}
if (!replicated) {
// Otherwise, check if the local node resolves as replicator
auto local_node = Node::local_node();
auto nodes = XapiandManager::manager->resolve_index_nodes(args.src_endpoint.path);
for (const auto& node : nodes) {
if (Node::is_equal(node, local_node)) {
replicated = true;
break;
}
}
}
if (!replicated) {
ASSERT(!args.cluster_database);
return;
}
int client_sock = TCP::socket();
if (client_sock == -1) {
if (args.cluster_database) {
L_CRIT("Cannot replicate cluster database");
sig_exit(-EX_SOFTWARE);
}
return;
}
auto client = Worker::make_shared<BinaryClient>(share_this<BinaryServer>(), ev_loop, ev_flags, client_sock, active_timeout, idle_timeout, args.cluster_database);
if (!client->init_replication(args.src_endpoint, args.dst_endpoint)) {
client->detach();
return;
}
client->start();
L_DEBUG("Database %s being synchronized from %s%s" + DEBUG_COL + "...", repr(args.src_endpoint.to_string()), args.src_endpoint.node.col().ansi(), args.src_endpoint.node.name());
}
std::string
BinaryServer::__repr__() const
{
return string::format("<BinaryServer {cnt:%ld, sock:%d}%s%s%s>",
use_count(),
sock == -1 ? binary.sock : sock,
is_runner() ? " (runner)" : " (worker)",
is_running_loop() ? " (running loop)" : " (stopped loop)",
is_detaching() ? " (deteaching)" : "");
}
#endif /* XAPIAND_CLUSTERING */
<|endoftext|> |
<commit_before>/**
* @file simpleConnectionPool.cc
* @author Rafal Slota
* @copyright (C) 2013 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in 'LICENSE.txt'
*/
#include "simpleConnectionPool.h"
#include "glog/logging.h"
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <iterator>
#include <algorithm>
#include <boost/thread/thread_time.hpp>
using namespace boost;
using namespace std;
namespace veil {
SimpleConnectionPool::SimpleConnectionPool(string hostname, int port, string certPath, bool (*updateCert)()) :
m_hostname(hostname),
updateCertCB(updateCert),
m_port(port),
m_certPath(certPath)
{
m_connectionPools[META_POOL] = ConnectionPoolInfo(DEFAULT_POOL_SIZE);
m_connectionPools[DATA_POOL] = ConnectionPoolInfo(DEFAULT_POOL_SIZE);
}
SimpleConnectionPool::~SimpleConnectionPool() {}
void SimpleConnectionPool::resetAllConnections(PoolType type)
{
m_connectionPools[type].connections.clear();
setPoolSize(type, m_connectionPools[type].size); // Force connection reinitialization
}
boost::shared_ptr<CommunicationHandler> SimpleConnectionPool::newConnection(PoolType type)
{
boost::unique_lock< boost::recursive_mutex > lock(m_access);
ConnectionPoolInfo &poolInfo = m_connectionPools[type];
boost::shared_ptr<CommunicationHandler> conn;
// Check if certificate is OK and generate new one if needed and possible
if(updateCertCB) {
if(!updateCertCB())
{
LOG(ERROR) << "Could not find valid certificate.";
return boost::shared_ptr<CommunicationHandler>();
}
}
lock.unlock();
list<string> ips = dnsQuery(m_hostname);
lock.lock();
list<string>::iterator it = m_hostnamePool.begin();
while(it != m_hostnamePool.end()) // Delete all hostname from m_hostnamePool which are not present in dnsQuery response
{
list<string>::const_iterator itIP = find(ips.begin(), ips.end(), (*it));
if(itIP == ips.end())
it = m_hostnamePool.erase(it);
else ++it;
}
for(it = ips.begin(); it != ips.end(); ++it)
{
list<string>::const_iterator itIP = find(m_hostnamePool.begin(), m_hostnamePool.end(), (*it));
if(itIP == m_hostnamePool.end())
m_hostnamePool.push_back((*it));
}
// Connect to first working host
int hostnameCount = m_hostnamePool.size();
while(hostnameCount--)
{
string connectTo = m_hostnamePool.front();
m_hostnamePool.pop_front();
m_hostnamePool.push_back(connectTo);
lock.unlock();
conn.reset(new CommunicationHandler(connectTo, m_port, m_certPath));
conn->setFuseID(m_fuseId); // Set FuseID that shall be used by this connection as session ID
if(m_pushCallback) // Set callback that shall be used for PUSH messages and error messages
conn->setPushCallback(m_pushCallback); // Note that this doesnt enable/register PUSH channel !
if(m_pushCallback && m_fuseId.size() > 0 && type == META_POOL) // Enable PUSH channel (will register itself when possible)
conn->enablePushChannel();
if(conn->openConnection() == 0) {
break;
}
lock.lock();
conn.reset();
LOG(WARNING) << "Cannot connect to host: " << connectTo << ":" << m_port;
}
if(conn)
poolInfo.connections.push_front(make_pair(conn, time(NULL)));
else
LOG(ERROR) << "Opening new connection (type: " << type << ") failed!";
return conn;
}
boost::shared_ptr<CommunicationHandler> SimpleConnectionPool::selectConnection(PoolType type)
{
boost::unique_lock< boost::recursive_mutex > lock(m_access);
boost::shared_ptr<CommunicationHandler> conn;
ConnectionPoolInfo &poolInfo = m_connectionPools[type];
// Delete first connection in pool if its error counter is way to big
if(poolInfo.connections.size() > 0 && poolInfo.connections.front().first->getErrorCount() > MAX_CONNECTION_ERROR_COUNT)
poolInfo.connections.pop_front();
// Remove redundant connections
while(poolInfo.connections.size() > poolInfo.size)
poolInfo.connections.pop_back();
// Check if pool size matches config
long toStart = poolInfo.size - poolInfo.connections.size();
while(toStart-- > 0) // Current pool is too small, we should create some connection(s)
{
LOG(INFO) << "Connection pool (" << type << " is to small (" << poolInfo.connections.size() << " connections - expected: " << poolInfo.size << "). Opening new connection...";
if(poolInfo.connections.size() > 0) {
boost::thread t = thread(boost::bind(&SimpleConnectionPool::newConnection, shared_from_this(), type));
t.detach();
}
else
conn = newConnection(type);
}
if(poolInfo.connections.size() > 0)
{
conn = poolInfo.connections.front().first;
// Round-robin
poolInfo.connections.push_back(poolInfo.connections.front());
poolInfo.connections.pop_front();
}
return conn;
}
void SimpleConnectionPool::releaseConnection(boost::shared_ptr<CommunicationHandler> conn)
{
return;
}
void SimpleConnectionPool::setPoolSize(PoolType type, unsigned int s)
{
boost::unique_lock< boost::recursive_mutex > lock(m_access);
m_connectionPools[type].size = s;
// Insert new connections to pool if needed (async)
long toStart = m_connectionPools[type].size - m_connectionPools[type].connections.size();
while(toStart-- > 0) {
boost::thread t = thread(boost::bind(&SimpleConnectionPool::newConnection, shared_from_this(), type));
t.detach();
}
}
void SimpleConnectionPool::setPushCallback(std::string fuseId, push_callback hdl)
{
m_fuseId = fuseId;
m_pushCallback = hdl;
}
list<string> SimpleConnectionPool::dnsQuery(string hostname)
{
list<string> lst;
struct addrinfo *result;
struct addrinfo *res;
if(getaddrinfo(hostname.c_str(), NULL, NULL, &result) == 0) {
for(res = result; res != NULL; res = res->ai_next) {
char ip[INET_ADDRSTRLEN + 1] = "";
switch(res->ai_addr->sa_family) {
case AF_INET:
if(inet_ntop(res->ai_addr->sa_family, &((struct sockaddr_in*)res->ai_addr)->sin_addr, ip, INET_ADDRSTRLEN + 1) != NULL)
lst.push_back(string(ip));
case AF_INET6:
// Not supported
break;
default:
break;
}
}
freeaddrinfo(result);
}
if(lst.size() == 0) {
LOG(ERROR) << "DNS lookup failed for host: " << hostname;
lst.push_back(hostname); // Make sure that returned list is not empty but adding argument to it
}
return lst;
}
} // namespace veil<commit_msg>VFS-292: debug<commit_after>/**
* @file simpleConnectionPool.cc
* @author Rafal Slota
* @copyright (C) 2013 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in 'LICENSE.txt'
*/
#include "simpleConnectionPool.h"
#include "glog/logging.h"
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <iterator>
#include <algorithm>
#include <boost/thread/thread_time.hpp>
using namespace boost;
using namespace std;
namespace veil {
SimpleConnectionPool::SimpleConnectionPool(string hostname, int port, string certPath, bool (*updateCert)()) :
m_hostname(hostname),
updateCertCB(updateCert),
m_port(port),
m_certPath(certPath)
{
m_connectionPools[META_POOL] = ConnectionPoolInfo(DEFAULT_POOL_SIZE);
m_connectionPools[DATA_POOL] = ConnectionPoolInfo(DEFAULT_POOL_SIZE);
}
SimpleConnectionPool::~SimpleConnectionPool() {}
void SimpleConnectionPool::resetAllConnections(PoolType type)
{
m_connectionPools[type].connections.clear();
setPoolSize(type, m_connectionPools[type].size); // Force connection reinitialization
}
boost::shared_ptr<CommunicationHandler> SimpleConnectionPool::newConnection(PoolType type)
{
boost::unique_lock< boost::recursive_mutex > lock(m_access);
ConnectionPoolInfo &poolInfo = m_connectionPools[type];
boost::shared_ptr<CommunicationHandler> conn;
// Check if certificate is OK and generate new one if needed and possible
if(updateCertCB) {
if(!updateCertCB())
{
LOG(ERROR) << "Could not find valid certificate.";
return boost::shared_ptr<CommunicationHandler>();
}
}
lock.unlock();
list<string> ips = dnsQuery(m_hostname);
lock.lock();
list<string>::iterator it = m_hostnamePool.begin();
while(it != m_hostnamePool.end()) // Delete all hostname from m_hostnamePool which are not present in dnsQuery response
{
list<string>::const_iterator itIP = find(ips.begin(), ips.end(), (*it));
if(itIP == ips.end())
it = m_hostnamePool.erase(it);
else ++it;
}
for(it = ips.begin(); it != ips.end(); ++it)
{
list<string>::const_iterator itIP = find(m_hostnamePool.begin(), m_hostnamePool.end(), (*it));
if(itIP == m_hostnamePool.end())
m_hostnamePool.push_back((*it));
}
// Connect to first working host
int hostnameCount = m_hostnamePool.size();
while(hostnameCount--)
{
string connectTo = m_hostnamePool.front();
m_hostnamePool.pop_front();
m_hostnamePool.push_back(connectTo);
lock.unlock();
conn.reset(new CommunicationHandler(connectTo, m_port, m_certPath));
conn->setFuseID(m_fuseId); // Set FuseID that shall be used by this connection as session ID
if(m_pushCallback) // Set callback that shall be used for PUSH messages and error messages
conn->setPushCallback(m_pushCallback); // Note that this doesnt enable/register PUSH channel !
if(m_pushCallback && m_fuseId.size() > 0 && type == META_POOL) // Enable PUSH channel (will register itself when possible)
conn->enablePushChannel();
if(conn->openConnection() == 0) {
break;
}
lock.lock();
conn.reset();
LOG(WARNING) << "Cannot connect to host: " << connectTo << ":" << m_port;
}
if(conn)
poolInfo.connections.push_front(make_pair(conn, time(NULL)));
else
LOG(ERROR) << "Opening new connection (type: " << type << ") failed!";
return conn;
}
boost::shared_ptr<CommunicationHandler> SimpleConnectionPool::selectConnection(PoolType type)
{
boost::unique_lock< boost::recursive_mutex > lock(m_access);
boost::shared_ptr<CommunicationHandler> conn;
ConnectionPoolInfo &poolInfo = m_connectionPools[type];
// Delete first connection in pool if its error counter is way to big
if(poolInfo.connections.size() > 0 && poolInfo.connections.front().first->getErrorCount() >= MAX_CONNECTION_ERROR_COUNT)
poolInfo.connections.pop_front();
else if(poolInfo.connections.size() > 0)
DLOG(INFO) << "Getting connection with error count: " << poolInfo.connections.front().first->getErrorCount();
// Remove redundant connections
while(poolInfo.connections.size() > poolInfo.size)
poolInfo.connections.pop_back();
// Check if pool size matches config
long toStart = poolInfo.size - poolInfo.connections.size();
while(toStart-- > 0) // Current pool is too small, we should create some connection(s)
{
LOG(INFO) << "Connection pool (" << type << " is to small (" << poolInfo.connections.size() << " connections - expected: " << poolInfo.size << "). Opening new connection...";
if(poolInfo.connections.size() > 0) {
boost::thread t = thread(boost::bind(&SimpleConnectionPool::newConnection, shared_from_this(), type));
t.detach();
}
else
conn = newConnection(type);
}
if(poolInfo.connections.size() > 0)
{
conn = poolInfo.connections.front().first;
// Round-robin
poolInfo.connections.push_back(poolInfo.connections.front());
poolInfo.connections.pop_front();
}
return conn;
}
void SimpleConnectionPool::releaseConnection(boost::shared_ptr<CommunicationHandler> conn)
{
return;
}
void SimpleConnectionPool::setPoolSize(PoolType type, unsigned int s)
{
boost::unique_lock< boost::recursive_mutex > lock(m_access);
m_connectionPools[type].size = s;
// Insert new connections to pool if needed (async)
long toStart = m_connectionPools[type].size - m_connectionPools[type].connections.size();
while(toStart-- > 0) {
boost::thread t = thread(boost::bind(&SimpleConnectionPool::newConnection, shared_from_this(), type));
t.detach();
}
}
void SimpleConnectionPool::setPushCallback(std::string fuseId, push_callback hdl)
{
m_fuseId = fuseId;
m_pushCallback = hdl;
}
list<string> SimpleConnectionPool::dnsQuery(string hostname)
{
list<string> lst;
struct addrinfo *result;
struct addrinfo *res;
if(getaddrinfo(hostname.c_str(), NULL, NULL, &result) == 0) {
for(res = result; res != NULL; res = res->ai_next) {
char ip[INET_ADDRSTRLEN + 1] = "";
switch(res->ai_addr->sa_family) {
case AF_INET:
if(inet_ntop(res->ai_addr->sa_family, &((struct sockaddr_in*)res->ai_addr)->sin_addr, ip, INET_ADDRSTRLEN + 1) != NULL)
lst.push_back(string(ip));
case AF_INET6:
// Not supported
break;
default:
break;
}
}
freeaddrinfo(result);
}
if(lst.size() == 0) {
LOG(ERROR) << "DNS lookup failed for host: " << hostname;
lst.push_back(hostname); // Make sure that returned list is not empty but adding argument to it
}
return lst;
}
} // namespace veil<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
#include "libgearman/ssl.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-private-field"
namespace libtest {
class SimpleClient {
public:
SimpleClient(const std::string& hostname_, in_port_t port_);
~SimpleClient();
bool send_data(const libtest::vchar_t&, libtest::vchar_t&);
bool send_message(const std::string&);
bool send_message(const std::string&, std::string&);
bool response(std::string&);
bool response(libtest::vchar_t&);
private:
bool is_valid();
public:
const std::string& error() const
{
return _error;
}
bool is_error() const
{
return _error.size() ? true : false;
}
const char* error_file() const
{
return _error_file;
}
int error_line() const
{
return _error_line;
}
private:
void free_addrinfo()
{
freeaddrinfo(_ai);
_ai= NULL;
}
private: // Methods
void error(const char* file, int line, const std::string& error_);
void close_socket();
bool instance_connect();
struct addrinfo* lookup();
bool message(const char* ptr, const size_t len);
bool ready(int event_);
void init_ssl();
private:
bool _is_connected;
bool _is_ssl;
std::string _hostname;
in_port_t _port;
int sock_fd;
std::string _error;
const char* _error_file;
int _error_line;
int requested_message;
SSL_CTX* _ctx_ssl;
SSL* _ssl;
struct addrinfo *_ai;
};
} // namespace libtest
#pragma GCC diagnostic pop
<commit_msg>Adding ignore for pragmas<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
#include "libgearman/ssl.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wunused-private-field"
namespace libtest {
class SimpleClient {
public:
SimpleClient(const std::string& hostname_, in_port_t port_);
~SimpleClient();
bool send_data(const libtest::vchar_t&, libtest::vchar_t&);
bool send_message(const std::string&);
bool send_message(const std::string&, std::string&);
bool response(std::string&);
bool response(libtest::vchar_t&);
private:
bool is_valid();
public:
const std::string& error() const
{
return _error;
}
bool is_error() const
{
return _error.size() ? true : false;
}
const char* error_file() const
{
return _error_file;
}
int error_line() const
{
return _error_line;
}
private:
void free_addrinfo()
{
freeaddrinfo(_ai);
_ai= NULL;
}
private: // Methods
void error(const char* file, int line, const std::string& error_);
void close_socket();
bool instance_connect();
struct addrinfo* lookup();
bool message(const char* ptr, const size_t len);
bool ready(int event_);
void init_ssl();
private:
bool _is_connected;
bool _is_ssl;
std::string _hostname;
in_port_t _port;
int sock_fd;
std::string _error;
const char* _error_file;
int _error_line;
int requested_message;
SSL_CTX* _ctx_ssl;
SSL* _ssl;
struct addrinfo *_ai;
};
} // namespace libtest
#pragma GCC diagnostic pop
<|endoftext|> |
<commit_before>#include "platform.h"
#include <stdlib.h>
#include <boost/filesystem.hpp>
#include <iostream>
#include <codecvt>
std::string getHomePath()
{
std::string homePath;
// this should give you something like "/home/YOUR_USERNAME" on Linux and "C:\Users\YOUR_USERNAME\" on Windows
const char * envHome = getenv("HOME");
if(envHome != nullptr)
{
homePath = envHome;
}
#ifdef WIN32
// but does not seem to work for Windows XP or Vista, so try something else
if (homePath.empty()) {
const char * envDir = getenv("HOMEDRIVE");
const char * envPath = getenv("HOMEPATH");
if (envDir != nullptr && envPath != nullptr) {
homePath = envDir;
homePath += envPath;
for(unsigned int i = 0; i < homePath.length(); i++)
if(homePath[i] == '\\')
homePath[i] = '/';
}
}
#endif
// convert path to generic directory seperators
boost::filesystem::path genericPath(homePath);
return genericPath.generic_string();
}
int runShutdownCommand()
{
#ifdef WIN32 // windows
return system("shutdown -s -t 0");
#else // osx / linux
return system("sudo shutdown -h now");
#endif
}
int runRestartCommand()
{
#ifdef WIN32 // windows
return system("shutdown -r -t 0");
#else // osx / linux
return system("sudo shutdown -r now");
#endif
}
int runSystemCommand(const std::string& cmd_utf8)
{
#ifdef WIN32
// on Windows we use _wsystem to support non-ASCII paths
// which requires converting from utf8 to a wstring
typedef std::codecvt_utf8<wchar_t> convert_type;
std::wstring_convert<convert_type, wchar_t> converter;
std::wstring wchar_str = converter.from_bytes(cmd_utf8);
return _wsystem(wchar_str.c_str());
#else
return system(cmd_utf8.c_str());
#endif
}<commit_msg>Only include codecvt on Windows.<commit_after>#include "platform.h"
#include <stdlib.h>
#include <boost/filesystem.hpp>
#include <iostream>
#ifdef WIN32
#include <codecvt>
#endif
std::string getHomePath()
{
std::string homePath;
// this should give you something like "/home/YOUR_USERNAME" on Linux and "C:\Users\YOUR_USERNAME\" on Windows
const char * envHome = getenv("HOME");
if(envHome != nullptr)
{
homePath = envHome;
}
#ifdef WIN32
// but does not seem to work for Windows XP or Vista, so try something else
if (homePath.empty()) {
const char * envDir = getenv("HOMEDRIVE");
const char * envPath = getenv("HOMEPATH");
if (envDir != nullptr && envPath != nullptr) {
homePath = envDir;
homePath += envPath;
for(unsigned int i = 0; i < homePath.length(); i++)
if(homePath[i] == '\\')
homePath[i] = '/';
}
}
#endif
// convert path to generic directory seperators
boost::filesystem::path genericPath(homePath);
return genericPath.generic_string();
}
int runShutdownCommand()
{
#ifdef WIN32 // windows
return system("shutdown -s -t 0");
#else // osx / linux
return system("sudo shutdown -h now");
#endif
}
int runRestartCommand()
{
#ifdef WIN32 // windows
return system("shutdown -r -t 0");
#else // osx / linux
return system("sudo shutdown -r now");
#endif
}
int runSystemCommand(const std::string& cmd_utf8)
{
#ifdef WIN32
// on Windows we use _wsystem to support non-ASCII paths
// which requires converting from utf8 to a wstring
typedef std::codecvt_utf8<wchar_t> convert_type;
std::wstring_convert<convert_type, wchar_t> converter;
std::wstring wchar_str = converter.from_bytes(cmd_utf8);
return _wsystem(wchar_str.c_str());
#else
return system(cmd_utf8.c_str());
#endif
}<|endoftext|> |
<commit_before>/*
* Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
*/
#include <Fabric/Core/IO/Helpers.h>
#include <Fabric/Base/Exception.h>
#include <Fabric/Base/Config.h>
#include <Fabric/Core/Util/Format.h>
#include <errno.h>
#include <stdlib.h>
#if defined(FABRIC_POSIX)
# include <dirent.h>
# include <errno.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/types.h>
#elif defined(FABRIC_WIN32)
# include <windows.h>
#endif
namespace Fabric
{
namespace IO
{
void validateEntry( std::string const &entry )
{
if ( entry.length() == 0 )
throw Exception("driectory entries cannot be empty");
if ( entry == "." || entry == ".." )
throw Exception("directory entries cannot be '.' or '..'");
size_t length = entry.length();
for ( size_t i=0; i<length; ++i )
{
char ch = entry[i];
#if defined(FABRIC_POSIX)
if ( ch == '/' )
throw Exception("directory entries cannot contain '/'");
#elif defined(FABRIC_WIN32)
if ( strchr( "<>:\"/\\|?*", ch ) != 0 )
throw Exception("directory entries cannot contain any of '<>:\"/\\|?*'");
#else
# error "missing platform!"
#endif
}
}
std::string const &getRootPath()
{
static std::string s_rootPath;
if ( s_rootPath.length() == 0 )
{
char const *homeDir = 0;
#if defined(FABRIC_POSIX)
homeDir = getenv( "HOME" );
#elif defined(FABRIC_WIN32)
homeDir = getenv( "APPDATA" );
#else
# error "Unsupported platform"
#endif
if ( !homeDir || !*homeDir )
throw Exception("unable to obtain home directory");
#if defined(FABRIC_POSIX)
s_rootPath = JoinPath( homeDir, ".fabric" );
if ( mkdir( s_rootPath.c_str(), 0777 ) && errno != EEXIST )
throw Exception("unable to create directory " + _(s_rootPath));
#elif defined(FABRIC_WIN32)
s_rootPath = JoinPath( homeDir, "Fabric" );
if ( !::CreateDirectoryA( s_rootPath.c_str(), NULL ) && ::GetLastError() != ERROR_ALREADY_EXISTS )
throw Exception("unable to create directory " + _(s_rootPath));
#else
# error "Unsupported platform"
#endif
}
return s_rootPath;
}
std::string JoinPath( std::string const &lhs, std::string const &rhs )
{
#if defined(FABRIC_POSIX)
static const char *s_pathSeparator = "/";
#elif defined(FABRIC_WIN32)
static const char *s_pathSeparator = "\\";
#else
# error "Unsupported platform"
#endif
if ( lhs.length() == 0 )
return rhs;
else if ( rhs.length() == 0 )
return lhs;
else
return lhs + s_pathSeparator + rhs;
}
/*
void safeCall( int fd, void (*callback)( int fd ) )
{
FABRIC_IO_TRACE( "safeCall( %d, %p )", fd, callback );
pid_t childPID = fork();
if ( childPID == 0 )
{
chroot( getRootPathSpec().c_str() );
callback( fd );
_exit(0);
}
else
{
int childStatus;
if ( waitpid( childPID, &childStatus, 0 ) == -1 )
throw Exception("safeCall failure");
}
}
*/
void CreateDir( std::string const &fullPath )
{
#if defined(FABRIC_POSIX)
if ( mkdir( fullPath.c_str(), 0777 ) && errno != EEXIST )
throw Exception("unable to create directory");
#elif defined(FABRIC_WIN32)
if ( !::CreateDirectoryA( fullPath.c_str(), NULL ) && GetLastError() != ERROR_ALREADY_EXISTS )
throw Exception("unable to create directory");
#endif
}
bool DirExists( std::string const &fullPath )
{
bool result;
#if defined(FABRIC_POSIX)
struct stat st;
result = stat( fullPath.c_str(), &st ) && S_ISDIR(st.st_mode);
#elif defined(FABRIC_WIN32)
DWORD dwAttrib = ::GetFileAttributesA( fullPath.c_str() );
result = (dwAttrib != INVALID_FILE_ATTRIBUTES)
&& (dwAttrib & FILE_ATTRIBUTE_DIRECTORY);
#endif
return result;
}
std::vector<std::string> GetSubDirEntries( std::string const &dirPath )
{
std::vector<std::string> result;
#if defined(FABRIC_POSIX)
DIR *dir = opendir( dirPath.length() > 0? dirPath.c_str(): "." );
if ( !dir )
throw Exception("unable to open directory");
for (;;)
{
struct dirent *de = readdir( dir );
if ( !de )
break;
if ( de->d_type != DT_DIR )
continue;
std::string entry( de->d_name );
if ( entry == "." || entry == ".." )
continue;
result.push_back( entry );
}
closedir( dir );
#elif defined(FABRIC_WIN32)
WIN32_FIND_DATAA fd;
::ZeroMemory( &fd, sizeof( fd ) );
std::string searchGlob = JoinPath( dirPath.length() > 0? dirPath.c_str(): ".", "*" );
HANDLE hDir = ::FindFirstFileA( searchGlob.c_str(), &fd );
if( hDir == INVALID_HANDLE_VALUE )
throw Exception("unable to open directory");
do
{
if( !( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) )
continue;
std::string entry( fd.cFileName );
if ( entry == "." || entry == ".." )
continue;
result.push_back( entry );
} while( ::FindNextFileA( hDir, &fd ) );
::FindClose( hDir );
#endif
return result;
}
static inline bool EqInsensitive( std::string const &lhs, std::string const &rhs )
{
#if defined(FABRIC_POSIX)
return strcasecmp( lhs.c_str(), rhs.c_str() ) == 0;
#elif defined(FABRIC_WIN32)
return stricmp( lhs.c_str(), rhs.c_str() ) == 0;
#endif
}
void GlobDirPaths( std::string const &dirPathSpec, std::vector<std::string> &result )
{
size_t asteriskPos = dirPathSpec.rfind( '*' );
if ( asteriskPos == std::string::npos )
result.push_back( dirPathSpec );
else
{
std::string prefixDirPathSpec;
std::string prefixEntry;
#if defined(FABRIC_POSIX)
char dirSep = '/';
#elif defined(FABRIC_WIN32)
char dirSep = '\\';
#endif
size_t dirSepPos = dirPathSpec.rfind( dirSep, asteriskPos );
if ( dirSepPos == std::string::npos )
{
prefixDirPathSpec = "";
prefixEntry = dirPathSpec.substr( 0, asteriskPos );
}
else
{
prefixDirPathSpec = dirPathSpec.substr( 0, dirSepPos );
prefixEntry = dirPathSpec.substr( dirSepPos + 1, asteriskPos - (dirSepPos + 1) );
}
std::string suffixDirPath;
size_t postDirSepPos = dirPathSpec.find( dirSep, asteriskPos );
if ( postDirSepPos == std::string::npos )
{
suffixDirPath = "";
}
else
{
suffixDirPath = dirPathSpec.substr( postDirSepPos + 1 );
}
std::vector<std::string> prefixDirPaths;
GlobDirPaths( prefixDirPathSpec, prefixDirPaths );
for ( std::vector<std::string>::const_iterator it=prefixDirPaths.begin(); it!=prefixDirPaths.end(); ++it )
{
std::string const &prefixDirPath = *it;
std::vector<std::string> subDirEntries;
try
{
subDirEntries = GetSubDirEntries( prefixDirPath );
}
catch ( Exception e )
{
continue;
}
for ( std::vector<std::string>::const_iterator jt=subDirEntries.begin(); jt!=subDirEntries.end(); ++jt )
{
std::string const &subDirEntry = *jt;
if ( subDirEntry.length() >= prefixEntry.length()
&& EqInsensitive( subDirEntry.substr( 0, prefixEntry.length() ), prefixEntry ) )
{
result.push_back( JoinPath( prefixDirPath, subDirEntry, suffixDirPath ) );
}
}
}
}
}
};
};
<commit_msg>Fix check for existence of directories<commit_after>/*
* Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
*/
#include <Fabric/Core/IO/Helpers.h>
#include <Fabric/Base/Exception.h>
#include <Fabric/Base/Config.h>
#include <Fabric/Core/Util/Format.h>
#include <errno.h>
#include <stdlib.h>
#if defined(FABRIC_POSIX)
# include <dirent.h>
# include <errno.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/types.h>
#elif defined(FABRIC_WIN32)
# include <windows.h>
#endif
namespace Fabric
{
namespace IO
{
void validateEntry( std::string const &entry )
{
if ( entry.length() == 0 )
throw Exception("driectory entries cannot be empty");
if ( entry == "." || entry == ".." )
throw Exception("directory entries cannot be '.' or '..'");
size_t length = entry.length();
for ( size_t i=0; i<length; ++i )
{
char ch = entry[i];
#if defined(FABRIC_POSIX)
if ( ch == '/' )
throw Exception("directory entries cannot contain '/'");
#elif defined(FABRIC_WIN32)
if ( strchr( "<>:\"/\\|?*", ch ) != 0 )
throw Exception("directory entries cannot contain any of '<>:\"/\\|?*'");
#else
# error "missing platform!"
#endif
}
}
std::string const &getRootPath()
{
static std::string s_rootPath;
if ( s_rootPath.length() == 0 )
{
char const *homeDir = 0;
#if defined(FABRIC_POSIX)
homeDir = getenv( "HOME" );
#elif defined(FABRIC_WIN32)
homeDir = getenv( "APPDATA" );
#else
# error "Unsupported platform"
#endif
if ( !homeDir || !*homeDir )
throw Exception("unable to obtain home directory");
#if defined(FABRIC_POSIX)
s_rootPath = JoinPath( homeDir, ".fabric" );
if ( mkdir( s_rootPath.c_str(), 0777 ) && errno != EEXIST )
throw Exception("unable to create directory " + _(s_rootPath));
#elif defined(FABRIC_WIN32)
s_rootPath = JoinPath( homeDir, "Fabric" );
if ( !::CreateDirectoryA( s_rootPath.c_str(), NULL ) && ::GetLastError() != ERROR_ALREADY_EXISTS )
throw Exception("unable to create directory " + _(s_rootPath));
#else
# error "Unsupported platform"
#endif
}
return s_rootPath;
}
std::string JoinPath( std::string const &lhs, std::string const &rhs )
{
#if defined(FABRIC_POSIX)
static const char *s_pathSeparator = "/";
#elif defined(FABRIC_WIN32)
static const char *s_pathSeparator = "\\";
#else
# error "Unsupported platform"
#endif
if ( lhs.length() == 0 )
return rhs;
else if ( rhs.length() == 0 )
return lhs;
else
return lhs + s_pathSeparator + rhs;
}
/*
void safeCall( int fd, void (*callback)( int fd ) )
{
FABRIC_IO_TRACE( "safeCall( %d, %p )", fd, callback );
pid_t childPID = fork();
if ( childPID == 0 )
{
chroot( getRootPathSpec().c_str() );
callback( fd );
_exit(0);
}
else
{
int childStatus;
if ( waitpid( childPID, &childStatus, 0 ) == -1 )
throw Exception("safeCall failure");
}
}
*/
void CreateDir( std::string const &fullPath )
{
#if defined(FABRIC_POSIX)
if ( mkdir( fullPath.c_str(), 0777 ) && errno != EEXIST )
throw Exception("unable to create directory");
#elif defined(FABRIC_WIN32)
if ( !::CreateDirectoryA( fullPath.c_str(), NULL ) && GetLastError() != ERROR_ALREADY_EXISTS )
throw Exception("unable to create directory");
#endif
}
bool DirExists( std::string const &fullPath )
{
bool result;
#if defined(FABRIC_POSIX)
struct stat st;
result = stat( fullPath.c_str(), &st ) == 0 && S_ISDIR(st.st_mode);
#elif defined(FABRIC_WIN32)
DWORD dwAttrib = ::GetFileAttributesA( fullPath.c_str() );
result = (dwAttrib != INVALID_FILE_ATTRIBUTES)
&& (dwAttrib & FILE_ATTRIBUTE_DIRECTORY);
#endif
return result;
}
std::vector<std::string> GetSubDirEntries( std::string const &dirPath )
{
std::vector<std::string> result;
#if defined(FABRIC_POSIX)
DIR *dir = opendir( dirPath.length() > 0? dirPath.c_str(): "." );
if ( !dir )
throw Exception("unable to open directory");
for (;;)
{
struct dirent *de = readdir( dir );
if ( !de )
break;
if ( de->d_type != DT_DIR )
continue;
std::string entry( de->d_name );
if ( entry == "." || entry == ".." )
continue;
result.push_back( entry );
}
closedir( dir );
#elif defined(FABRIC_WIN32)
WIN32_FIND_DATAA fd;
::ZeroMemory( &fd, sizeof( fd ) );
std::string searchGlob = JoinPath( dirPath.length() > 0? dirPath.c_str(): ".", "*" );
HANDLE hDir = ::FindFirstFileA( searchGlob.c_str(), &fd );
if( hDir == INVALID_HANDLE_VALUE )
throw Exception("unable to open directory");
do
{
if( !( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) )
continue;
std::string entry( fd.cFileName );
if ( entry == "." || entry == ".." )
continue;
result.push_back( entry );
} while( ::FindNextFileA( hDir, &fd ) );
::FindClose( hDir );
#endif
return result;
}
static inline bool EqInsensitive( std::string const &lhs, std::string const &rhs )
{
#if defined(FABRIC_POSIX)
return strcasecmp( lhs.c_str(), rhs.c_str() ) == 0;
#elif defined(FABRIC_WIN32)
return stricmp( lhs.c_str(), rhs.c_str() ) == 0;
#endif
}
void GlobDirPaths( std::string const &dirPathSpec, std::vector<std::string> &result )
{
size_t asteriskPos = dirPathSpec.rfind( '*' );
if ( asteriskPos == std::string::npos )
result.push_back( dirPathSpec );
else
{
std::string prefixDirPathSpec;
std::string prefixEntry;
#if defined(FABRIC_POSIX)
char dirSep = '/';
#elif defined(FABRIC_WIN32)
char dirSep = '\\';
#endif
size_t dirSepPos = dirPathSpec.rfind( dirSep, asteriskPos );
if ( dirSepPos == std::string::npos )
{
prefixDirPathSpec = "";
prefixEntry = dirPathSpec.substr( 0, asteriskPos );
}
else
{
prefixDirPathSpec = dirPathSpec.substr( 0, dirSepPos );
prefixEntry = dirPathSpec.substr( dirSepPos + 1, asteriskPos - (dirSepPos + 1) );
}
std::string suffixDirPath;
size_t postDirSepPos = dirPathSpec.find( dirSep, asteriskPos );
if ( postDirSepPos == std::string::npos )
{
suffixDirPath = "";
}
else
{
suffixDirPath = dirPathSpec.substr( postDirSepPos + 1 );
}
std::vector<std::string> prefixDirPaths;
GlobDirPaths( prefixDirPathSpec, prefixDirPaths );
for ( std::vector<std::string>::const_iterator it=prefixDirPaths.begin(); it!=prefixDirPaths.end(); ++it )
{
std::string const &prefixDirPath = *it;
std::vector<std::string> subDirEntries;
try
{
subDirEntries = GetSubDirEntries( prefixDirPath );
}
catch ( Exception e )
{
continue;
}
for ( std::vector<std::string>::const_iterator jt=subDirEntries.begin(); jt!=subDirEntries.end(); ++jt )
{
std::string const &subDirEntry = *jt;
if ( subDirEntry.length() >= prefixEntry.length()
&& EqInsensitive( subDirEntry.substr( 0, prefixEntry.length() ), prefixEntry ) )
{
result.push_back( JoinPath( prefixDirPath, subDirEntry, suffixDirPath ) );
}
}
}
}
}
};
};
<|endoftext|> |
<commit_before>#include "CFremenGridSet.h"
using namespace std;
CFremenGridSet::CFremenGridSet()
{
numFremenGrids = 0;
activeIndex = 0;
active = NULL;
}
CFremenGridSet::~CFremenGridSet()
{
for (int i=0;i<numFremenGrids;i++) delete fremengrid[i];
}
int CFremenGridSet::add(const char* name, float originX,float originY,float originZ,int dimX,int dimY,int dimZ,float cellSize)
{
int exists = find(name);
if (exists >= 0) return -1;
else
{
fremengrid[numFremenGrids++] = new CFremenGrid(name, originX, originY, originZ, dimX, dimY, dimZ, cellSize);
activeIndex = numFremenGrids-1;
active = fremengrid[numFremenGrids-1];
}
return 0;
//printf("Add %i %s \n",activeIndex,active->id);
//grid->incorporate(x,y,z,d,len,timestamp);
//return active->incorporate( *x, *y, *z, *d, size, t);
}
int CFremenGridSet::incorporate(const char *name, float *x,float *y,float *z,float *d,int size,uint32_t t)
{
int exists = find(name);
if (exists < 0) return -1;
else return active->incorporate( x, y, z, d, size, t);
}
//int CFremenGridSet::evaluate(const char *name,uint32_t times[],unsigned char states[],int length,int order,float errors[])
//{
// if (find(name) < 0) return -1;
// return active->evaluate(times,states,length,order,errors);;
//}
float CFremenGridSet::estimate(const char *name, unsigned int index, uint32_t timeStamp)
{
find(name);
return active->estimate(index, timeStamp);
}
float CFremenGridSet::retrieve(const char *name, unsigned int index, uint32_t timeStamp)
{
find(name);
return active->retrieve(index);
}
float CFremenGridSet::dominant(const char *name, unsigned int index, uint32_t period)
{
find(name);
return active->getDominant(index, period);
}
int CFremenGridSet::estimateEntropy(const char *name,float x,float y,float z,float range,uint32_t t)
{
if (find(name) < 0) return -1;
//printf("Estimate %i %s \n",activeIndex,active->id);
float info = active->estimateInformation(x,y,z,range,t);
printf("EstimateInformation %i %s %f\n",activeIndex,active->id, info);
return info;//active->estimateInformation(x, y, z, range, t);
}
int CFremenGridSet::find(const char *name)
{
int i = 0;
for (i =0;(i<numFremenGrids) && (strcmp(fremengrid[i]->id,name)!=0);i++) {}
if (i==numFremenGrids) return -1;
activeIndex = i;
active = fremengrid[i];
return activeIndex;
}
int CFremenGridSet::remove(const char *name)
{
if (find(name) < 0) return -numFremenGrids;
delete fremengrid[activeIndex];
fremengrid[activeIndex] = fremengrid[--numFremenGrids];
return numFremenGrids+1;
}
bool CFremenGridSet::update(const char* name,int order)
{
if (find(name) < 0) return false;
active->update();
return true;
}
bool CFremenGridSet::print(bool verbosityLevel)
{
for (int i = 0;i<numFremenGrids;i++) fremengrid[i]->print(verbosityLevel);
}
bool CFremenGridSet::load(const char* name)
{
}
bool CFremenGridSet::save(const char* name)
{
FILE* file = fopen(name,"w+");
fwrite(&numFremenGrids,sizeof(int),1,file);
for (int i = 0;i<numFremenGrids;i++) fremengrid[i]->saveSmart(name);
fclose(file);
}
<commit_msg>debugging<commit_after>#include "CFremenGridSet.h"
using namespace std;
CFremenGridSet::CFremenGridSet()
{
numFremenGrids = 0;
activeIndex = 0;
active = NULL;
}
CFremenGridSet::~CFremenGridSet()
{
for (int i=0;i<numFremenGrids;i++) delete fremengrid[i];
}
int CFremenGridSet::add(const char* name, float originX,float originY,float originZ,int dimX,int dimY,int dimZ,float cellSize)
{
int exists = find(name);
printf("Add %i %s \n",activeIndex,active->id);
if (exists >= 0)
{
printf("grid already exists %i %s \n",activeIndex,active->id);
return -1;
}
else
{
fremengrid[numFremenGrids++] = new CFremenGrid(name, originX, originY, originZ, dimX, dimY, dimZ, cellSize);
activeIndex = numFremenGrids-1;
active = fremengrid[numFremenGrids-1];
printf("Added grid %i %s \n",activeIndex,active->id);
}
return 0;
//printf("Add %i %s \n",activeIndex,active->id);
//grid->incorporate(x,y,z,d,len,timestamp);
//return active->incorporate( *x, *y, *z, *d, size, t);
}
int CFremenGridSet::incorporate(const char *name, float *x,float *y,float *z,float *d,int size,uint32_t t)
{
int exists = find(name);
if (exists < 0) return -1;
else return active->incorporate( x, y, z, d, size, t);
}
//int CFremenGridSet::evaluate(const char *name,uint32_t times[],unsigned char states[],int length,int order,float errors[])
//{
// if (find(name) < 0) return -1;
// return active->evaluate(times,states,length,order,errors);;
//}
float CFremenGridSet::estimate(const char *name, unsigned int index, uint32_t timeStamp)
{
find(name);
return active->estimate(index, timeStamp);
}
float CFremenGridSet::retrieve(const char *name, unsigned int index, uint32_t timeStamp)
{
find(name);
return active->retrieve(index);
}
float CFremenGridSet::dominant(const char *name, unsigned int index, uint32_t period)
{
find(name);
return active->getDominant(index, period);
}
int CFremenGridSet::estimateEntropy(const char *name,float x,float y,float z,float range,uint32_t t)
{
if (find(name) < 0) return -1;
//printf("Estimate %i %s \n",activeIndex,active->id);
float info = active->estimateInformation(x,y,z,range,t);
printf("EstimateInformation %i %s %f\n",activeIndex,active->id, info);
return info;//active->estimateInformation(x, y, z, range, t);
}
int CFremenGridSet::find(const char *name)
{
int i = 0;
for (i =0;(i<numFremenGrids) && (strcmp(fremengrid[i]->id,name)!=0);i++) {}
if (i==numFremenGrids) return -1;
activeIndex = i;
active = fremengrid[i];
return activeIndex;
}
int CFremenGridSet::remove(const char *name)
{
if (find(name) < 0) return -numFremenGrids;
delete fremengrid[activeIndex];
fremengrid[activeIndex] = fremengrid[--numFremenGrids];
return numFremenGrids+1;
}
bool CFremenGridSet::update(const char* name,int order)
{
if (find(name) < 0) return false;
active->update();
return true;
}
bool CFremenGridSet::print(bool verbosityLevel)
{
for (int i = 0;i<numFremenGrids;i++) fremengrid[i]->print(verbosityLevel);
}
bool CFremenGridSet::load(const char* name)
{
}
bool CFremenGridSet::save(const char* name)
{
FILE* file = fopen(name,"w+");
fwrite(&numFremenGrids,sizeof(int),1,file);
for (int i = 0;i<numFremenGrids;i++) fremengrid[i]->saveSmart(name);
fclose(file);
}
<|endoftext|> |
<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA
//////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include "ShDebug.hpp"
#include "ShVariableNode.hpp"
#include "ShError.hpp"
#include "ShAlgebra.hpp"
#include "ShFixedManipulator.hpp"
namespace SH {
ShFixedManipulatorNode::ShFixedManipulatorNode() {
}
ShFixedManipulatorNode::~ShFixedManipulatorNode() {
}
ShKeepNode::ShKeepNode(int numChannels)
: m_numChannels(numChannels) {
}
ShProgram ShKeepNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
for(int i = 0; i < m_numChannels; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram channels for shKeep manipulator"));
}
ShVariable inout = (*finger)->clone(SH_INOUT);
}
} SH_END;
return result;
}
ShProgram ShKeepNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
return applyToInputs(finger, end);
}
ShFixedManipulator shKeep(int numChannels) {
return new ShKeepNode(numChannels);
}
ShLoseNode::ShLoseNode(int numChannels)
: m_numChannels(numChannels) {
}
ShProgram ShLoseNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
//SH_DEBUG_PRINT( "Applying lose " << m_numChannels );
ShProgram result = SH_BEGIN_PROGRAM() {
for(int i = 0; i < m_numChannels; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram input channels for shLose manipulator"));
}
ShVariable output((*finger)->clone(SH_OUTPUT));
}
} SH_END;
return result;
}
ShProgram ShLoseNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
for(int i = 0; i < m_numChannels; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram output channels for shLose manipulator"));
}
ShVariable input((*finger)->clone(SH_INPUT));
}
} SH_END;
return result;
}
ShFixedManipulator shLose(int numChannels) {
return new ShLoseNode(numChannels);
}
ShDupNode::ShDupNode(int numDups)
: m_numDups(numDups) {
}
ShProgram ShDupNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
ShVariable input;
for(int i = 0; i < m_numDups; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram input channels for shDup manipulator"));
}
if(i == 0) {
input = (*finger)->clone(SH_INPUT);
}
if((*finger)->size() != input.size()) {
shError(ShAlgebraException("Duplicating type " + input.node()->nameOfType()
+ " to incompatible type " + (*finger)->nameOfType()));
}
ShVariable output((*finger)->clone(SH_OUTPUT));
shASN(output, input);
}
} SH_END;
return result;
}
ShProgram ShDupNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram output channels for shDup manipulator"));
}
ShVariable input((*finger)->clone(SH_INPUT));
for(int i = 0; i < m_numDups; ++i) {
ShVariable output((*finger)->clone(SH_OUTPUT));
shASN(output, input);
}
++finger;
} SH_END;
return result;
}
ShFixedManipulator shDup(int numDups) {
return new ShDupNode(numDups);
}
ShProgramManipNode::ShProgramManipNode(const ShProgram &p)
: p(p) {
}
ShProgram ShProgramManipNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
std::size_t i;
for(i = 0; i < p.node()->outputs.size() && finger != end; ++i, ++finger);
// allow extra outputs from p
return p;
}
ShProgram ShProgramManipNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
std::size_t i;
for(i = 0; i < p.node()->inputs.size() && finger != end; ++i, ++finger);
// allow extra inputs from p
return p;
}
ShTreeManipNode::ShTreeManipNode(const ShFixedManipulator &a, const ShFixedManipulator &b)
: a(a), b(b) {
SH_DEBUG_ASSERT(a);
SH_DEBUG_ASSERT(b);
}
ShProgram ShTreeManipNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram aProgram = a->applyToInputs(finger, end);
ShProgram bProgram = b->applyToInputs(finger, end);
return aProgram & bProgram;
}
ShProgram ShTreeManipNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram aProgram = a->applyToOutputs(finger, end);
ShProgram bProgram = b->applyToOutputs(finger, end);
return aProgram & bProgram;
}
ShProgram operator<<(const ShProgram &p, const ShFixedManipulator &m) {
ShManipVarIterator finger = p.node()->inputs.begin();
ShProgram manipulator = m->applyToInputs(finger, p.node()->inputs.end());
return p << manipulator;
}
ShProgram operator<<(const ShFixedManipulator &m, const ShProgram &p) {
ShManipVarIterator finger = p.node()->outputs.begin();
ShProgram manipulator = m->applyToOutputs(finger, p.node()->outputs.end());
return manipulator << p;
}
ShFixedManipulator operator&(const ShFixedManipulator &m, const ShFixedManipulator &n) {
if (!m) {
return n;
}
if (!n) {
return m;
}
return new ShTreeManipNode(m, n);
}
ShFixedManipulator operator&(const ShFixedManipulator &m, const ShProgram &p) {
return m & new ShProgramManipNode(p);
}
ShFixedManipulator operator&(const ShProgram &p, const ShFixedManipulator &m) {
return new ShProgramManipNode(p) & m;
}
}
<commit_msg>CRLF->LF<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA
//////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include "ShDebug.hpp"
#include "ShVariableNode.hpp"
#include "ShError.hpp"
#include "ShAlgebra.hpp"
#include "ShFixedManipulator.hpp"
namespace SH {
ShFixedManipulatorNode::ShFixedManipulatorNode() {
}
ShFixedManipulatorNode::~ShFixedManipulatorNode() {
}
ShKeepNode::ShKeepNode(int numChannels)
: m_numChannels(numChannels) {
}
ShProgram ShKeepNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
for(int i = 0; i < m_numChannels; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram channels for shKeep manipulator"));
}
ShVariable inout = (*finger)->clone(SH_INOUT);
}
} SH_END;
return result;
}
ShProgram ShKeepNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
return applyToInputs(finger, end);
}
ShFixedManipulator shKeep(int numChannels) {
return new ShKeepNode(numChannels);
}
ShLoseNode::ShLoseNode(int numChannels)
: m_numChannels(numChannels) {
}
ShProgram ShLoseNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
//SH_DEBUG_PRINT( "Applying lose " << m_numChannels );
ShProgram result = SH_BEGIN_PROGRAM() {
for(int i = 0; i < m_numChannels; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram input channels for shLose manipulator"));
}
ShVariable output((*finger)->clone(SH_OUTPUT));
}
} SH_END;
return result;
}
ShProgram ShLoseNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
for(int i = 0; i < m_numChannels; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram output channels for shLose manipulator"));
}
ShVariable input((*finger)->clone(SH_INPUT));
}
} SH_END;
return result;
}
ShFixedManipulator shLose(int numChannels) {
return new ShLoseNode(numChannels);
}
ShDupNode::ShDupNode(int numDups)
: m_numDups(numDups) {
}
ShProgram ShDupNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
ShVariable input;
for(int i = 0; i < m_numDups; ++i, ++finger) {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram input channels for shDup manipulator"));
}
if(i == 0) {
input = (*finger)->clone(SH_INPUT);
}
if((*finger)->size() != input.size()) {
shError(ShAlgebraException("Duplicating type " + input.node()->nameOfType()
+ " to incompatible type " + (*finger)->nameOfType()));
}
ShVariable output((*finger)->clone(SH_OUTPUT));
shASN(output, input);
}
} SH_END;
return result;
}
ShProgram ShDupNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram result = SH_BEGIN_PROGRAM() {
if(finger == end) {
shError(ShAlgebraException("Not enough ShProgram output channels for shDup manipulator"));
}
ShVariable input((*finger)->clone(SH_INPUT));
for(int i = 0; i < m_numDups; ++i) {
ShVariable output((*finger)->clone(SH_OUTPUT));
shASN(output, input);
}
++finger;
} SH_END;
return result;
}
ShFixedManipulator shDup(int numDups) {
return new ShDupNode(numDups);
}
ShProgramManipNode::ShProgramManipNode(const ShProgram &p)
: p(p) {
}
ShProgram ShProgramManipNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
std::size_t i;
for(i = 0; i < p.node()->outputs.size() && finger != end; ++i, ++finger);
// allow extra outputs from p
return p;
}
ShProgram ShProgramManipNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
std::size_t i;
for(i = 0; i < p.node()->inputs.size() && finger != end; ++i, ++finger);
// allow extra inputs from p
return p;
}
ShTreeManipNode::ShTreeManipNode(const ShFixedManipulator &a, const ShFixedManipulator &b)
: a(a), b(b) {
SH_DEBUG_ASSERT(a);
SH_DEBUG_ASSERT(b);
}
ShProgram ShTreeManipNode::applyToInputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram aProgram = a->applyToInputs(finger, end);
ShProgram bProgram = b->applyToInputs(finger, end);
return aProgram & bProgram;
}
ShProgram ShTreeManipNode::applyToOutputs(ShManipVarIterator &finger, ShManipVarIterator end) const {
ShProgram aProgram = a->applyToOutputs(finger, end);
ShProgram bProgram = b->applyToOutputs(finger, end);
return aProgram & bProgram;
}
ShProgram operator<<(const ShProgram &p, const ShFixedManipulator &m) {
ShManipVarIterator finger = p.node()->inputs.begin();
ShProgram manipulator = m->applyToInputs(finger, p.node()->inputs.end());
return p << manipulator;
}
ShProgram operator<<(const ShFixedManipulator &m, const ShProgram &p) {
ShManipVarIterator finger = p.node()->outputs.begin();
ShProgram manipulator = m->applyToOutputs(finger, p.node()->outputs.end());
return manipulator << p;
}
ShFixedManipulator operator&(const ShFixedManipulator &m, const ShFixedManipulator &n) {
if (!m) {
return n;
}
if (!n) {
return m;
}
return new ShTreeManipNode(m, n);
}
ShFixedManipulator operator&(const ShFixedManipulator &m, const ShProgram &p) {
return m & new ShProgramManipNode(p);
}
ShFixedManipulator operator&(const ShProgram &p, const ShFixedManipulator &m) {
return new ShProgramManipNode(p) & m;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* 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: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $
#include <string>
#include <algorithm>
#include <set>
#include <sstream>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include "connection_manager.hpp"
#include "postgis.hpp"
DATASOURCE_PLUGIN(postgis_datasource)
const std::string postgis_datasource::GEOMETRY_COLUMNS="geometry_columns";
const std::string postgis_datasource::SPATIAL_REF_SYS="spatial_ref_system";
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::shared_ptr;
postgis_datasource::postgis_datasource(parameters const& params)
: datasource (params),
table_(params.get("table")),
type_(datasource::Vector),
extent_initialized_(false),
desc_(params.get("type")),
creator_(params.get("host"),
params.get("port"),
params.get("dbname"),
params.get("user"),
params.get("password"))
{
unsigned initial_size;
unsigned max_size;
try
{
initial_size = boost::lexical_cast<unsigned>(params_.get("initial_size"));
}
catch (bad_lexical_cast& )
{
initial_size = 1;
}
try
{
max_size = boost::lexical_cast<unsigned>(params_.get("initial_size"));
}
catch (bad_lexical_cast&)
{
max_size = 10;
}
ConnectionManager *mgr=ConnectionManager::instance();
mgr->registerPool(creator_, initial_size, max_size);
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::string table_name=table_from_sql(table_);
std::ostringstream s;
s << "select f_geometry_column,srid,type from ";
s << GEOMETRY_COLUMNS <<" where f_table_name='" << table_name<<"'";
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
srid_ = lexical_cast<int>(rs->getValue("srid"));
desc_.set_srid(srid_);
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
geometryColumn_=rs->getValue("f_geometry_column");
std::string postgisType=rs->getValue("type");
}
rs->close();
// collect attribute desc
s.str("");
s << "select * from "<<table_<<" limit 1";
rs=conn->executeQuery(s.str());
if (rs->next())
{
int count = rs->getNumFields();
for (int i=0;i<count;++i)
{
std::string fld_name=rs->getFieldName(i);
int length = rs->getFieldLength(i);
int type_oid = rs->getTypeOID(i);
switch (type_oid)
{
case 21: // int2
case 23: // int4
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));
break;
case 700: // float4
case 701: // float8
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));
case 1042: // bpchar
case 1043: // varchar
case 25: // text
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
default: // shouldn't get here
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
}
std::string const postgis_datasource::name_="postgis";
std::string postgis_datasource::name()
{
return name_;
}
int postgis_datasource::type() const
{
return type_;
}
layer_descriptor postgis_datasource::get_descriptor() const
{
return desc_;
}
std::string postgis_datasource::table_from_sql(const std::string& sql)
{
std::string table_name(sql);
transform(table_name.begin(),table_name.end(),table_name.begin(),tolower);
std::string::size_type idx=table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
table_name=table_name.substr(idx);
idx=table_name.find_first_of(" )");
return table_name.substr(0,idx);
}
return table_name;
}
featureset_ptr postgis_datasource::features(const query& q) const
{
Envelope<double> const& box=q.get_bbox();
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary("<<geometryColumn_<<") as geom";
std::set<std::string> const& props=q.property_names();
std::set<std::string>::const_iterator pos=props.begin();
while (pos!=props.end())
{
s <<",\""<<*pos<<"\"";
++pos;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << box.minx() << " " << box.miny() << ",";
s << box.maxx() << " " << box.maxy() << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs,props.size()));
}
}
return featureset_ptr();
}
featureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const
{
return featureset_ptr();
}
Envelope<double> postgis_datasource::envelope() const
{
if (extent_initialized_) return extent_;
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
std::ostringstream s;
std::string table_name = table_from_sql(table_);
if (params_.get("estimate_extent") == "true")
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select estimated_extent('"
<< table_name <<"','"
<< geometryColumn_ << "') as ext) as tmp";
}
else
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select extent(" <<geometryColumn_<< ") as ext from "
<< table_name << ") as tmp";
}
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
double lox=lexical_cast<double>(rs->getValue(0));
double loy=lexical_cast<double>(rs->getValue(1));
double hix=lexical_cast<double>(rs->getValue(2));
double hiy=lexical_cast<double>(rs->getValue(3));
extent_.init(lox,loy,hix,hiy);
extent_initialized_ = true;
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
}
rs->close();
}
}
return extent_;
}
postgis_datasource::~postgis_datasource() {}
<commit_msg>features at point impl<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* 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: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $
#include <string>
#include <algorithm>
#include <set>
#include <sstream>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include "connection_manager.hpp"
#include "postgis.hpp"
DATASOURCE_PLUGIN(postgis_datasource)
const std::string postgis_datasource::GEOMETRY_COLUMNS="geometry_columns";
const std::string postgis_datasource::SPATIAL_REF_SYS="spatial_ref_system";
using std::clog;
using std::endl;
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::shared_ptr;
postgis_datasource::postgis_datasource(parameters const& params)
: datasource (params),
table_(params.get("table")),
type_(datasource::Vector),
extent_initialized_(false),
desc_(params.get("type")),
creator_(params.get("host"),
params.get("port"),
params.get("dbname"),
params.get("user"),
params.get("password"))
{
unsigned initial_size;
unsigned max_size;
try
{
initial_size = boost::lexical_cast<unsigned>(params_.get("initial_size"));
}
catch (bad_lexical_cast& )
{
initial_size = 1;
}
try
{
max_size = boost::lexical_cast<unsigned>(params_.get("initial_size"));
}
catch (bad_lexical_cast&)
{
max_size = 10;
}
ConnectionManager *mgr=ConnectionManager::instance();
mgr->registerPool(creator_, initial_size, max_size);
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::string table_name=table_from_sql(table_);
std::ostringstream s;
s << "select f_geometry_column,srid,type from ";
s << GEOMETRY_COLUMNS <<" where f_table_name='" << table_name<<"'";
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
srid_ = lexical_cast<int>(rs->getValue("srid"));
desc_.set_srid(srid_);
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
geometryColumn_=rs->getValue("f_geometry_column");
std::string postgisType=rs->getValue("type");
}
rs->close();
// collect attribute desc
s.str("");
s << "select * from "<<table_<<" limit 1";
rs=conn->executeQuery(s.str());
if (rs->next())
{
int count = rs->getNumFields();
for (int i=0;i<count;++i)
{
std::string fld_name=rs->getFieldName(i);
int length = rs->getFieldLength(i);
int type_oid = rs->getTypeOID(i);
switch (type_oid)
{
case 21: // int2
case 23: // int4
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));
break;
case 700: // float4
case 701: // float8
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));
case 1042: // bpchar
case 1043: // varchar
case 25: // text
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
default: // shouldn't get here
#ifdef MAPNIK_DEBUG
clog << "unknown type_oid="<<type_oid<<endl;
#endif
break;
}
}
}
}
}
}
std::string const postgis_datasource::name_="postgis";
std::string postgis_datasource::name()
{
return name_;
}
int postgis_datasource::type() const
{
return type_;
}
layer_descriptor postgis_datasource::get_descriptor() const
{
return desc_;
}
std::string postgis_datasource::table_from_sql(const std::string& sql)
{
std::string table_name(sql);
transform(table_name.begin(),table_name.end(),table_name.begin(),tolower);
std::string::size_type idx=table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
table_name=table_name.substr(idx);
idx=table_name.find_first_of(" )");
return table_name.substr(0,idx);
}
return table_name;
}
featureset_ptr postgis_datasource::features(const query& q) const
{
Envelope<double> const& box=q.get_bbox();
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary("<<geometryColumn_<<") as geom";
std::set<std::string> const& props=q.property_names();
std::set<std::string>::const_iterator pos=props.begin();
std::set<std::string>::const_iterator end=props.end();
while (pos != end)
{
s <<",\""<<*pos<<"\"";
++pos;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << box.minx() << " " << box.miny() << ",";
s << box.maxx() << " " << box.maxy() << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs,props.size()));
}
}
return featureset_ptr();
}
featureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const
{
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);
std::ostringstream s;
s << "select asbinary(" << geometryColumn_ << ") as geom";
std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();
std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();
unsigned size=0;
while (itr != end)
{
s <<",\""<< itr->get_name() << "\"";
++itr;
++size;
}
s << " from " << table_<<" where "<<geometryColumn_<<" && setSRID('BOX3D(";
s << std::setprecision(16);
s << pt.x << " " << pt.y << ",";
s << pt.x << " " << pt.y << ")'::box3d,"<<srid_<<")";
#ifdef MAPNIK_DEBUG
std::clog << s.str() << "\n";
#endif
shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);
return featureset_ptr(new postgis_featureset(rs, size));
}
}
return featureset_ptr();
}
Envelope<double> postgis_datasource::envelope() const
{
if (extent_initialized_) return extent_;
ConnectionManager *mgr=ConnectionManager::instance();
shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());
if (pool)
{
shared_ptr<Connection> conn = pool->borrowObject();
if (conn && conn->isOK())
{
std::ostringstream s;
std::string table_name = table_from_sql(table_);
if (params_.get("estimate_extent") == "true")
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select estimated_extent('"
<< table_name <<"','"
<< geometryColumn_ << "') as ext) as tmp";
}
else
{
s << "select xmin(ext),ymin(ext),xmax(ext),ymax(ext)"
<< " from (select extent(" <<geometryColumn_<< ") as ext from "
<< table_name << ") as tmp";
}
shared_ptr<ResultSet> rs=conn->executeQuery(s.str());
if (rs->next())
{
try
{
double lox=lexical_cast<double>(rs->getValue(0));
double loy=lexical_cast<double>(rs->getValue(1));
double hix=lexical_cast<double>(rs->getValue(2));
double hiy=lexical_cast<double>(rs->getValue(3));
extent_.init(lox,loy,hix,hiy);
extent_initialized_ = true;
}
catch (bad_lexical_cast &ex)
{
clog << ex.what() << endl;
}
}
rs->close();
}
}
return extent_;
}
postgis_datasource::~postgis_datasource() {}
<|endoftext|> |
<commit_before>/********** tell emacs we use -*- c++ -*- style comments *******************
$Revision: 1.6 $ $Author: trey $ $Date: 2006-10-03 03:18:36 $
@file BlindLBInitializer.cc
@brief No brief
Copyright (c) 2005, Trey Smith. 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 <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include "zmdpCommonDefs.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "BlindLBInitializer.h"
using namespace std;
using namespace sla;
using namespace MatrixUtils;
#define PRUNE_EPS (1e-10)
#define POMDP_LONG_TERM_UNBOUNDED (99e+20)
namespace zmdp {
BlindLBInitializer::BlindLBInitializer(const MDP* _pomdp, MaxPlanesLowerBound* _bound) {
pomdp = (const Pomdp*) _pomdp;
bound = _bound;
}
void BlindLBInitializer::initialize(double targetPrecision)
{
initBlind(targetPrecision);
}
void BlindLBInitializer::initBlindWorstCase(alpha_vector& weakAlpha)
{
// set alpha to be a lower bound on the value of the best blind policy
double worstStateVal;
int safestAction = -1;
double worstCaseReward = -99e+20;
// calculate worstCaseReward = max_a min_s R(s,a)
// safestAction = argmax_a min_s R(s,a)
FOR (a, pomdp->getNumActions()) {
worstStateVal = 99e+20;
FOR (s, pomdp->numStates) {
worstStateVal = std::min(worstStateVal, pomdp->R(s,a));
}
if (worstStateVal > worstCaseReward) {
safestAction = a;
worstCaseReward = worstStateVal;
}
}
dvector worstCaseDVector(pomdp->getNumStateDimensions());
double longTermFactor = POMDP_LONG_TERM_UNBOUNDED;
if (pomdp->getDiscount() < 1.0) {
longTermFactor = std::min(longTermFactor, 1.0 / (1.0 - pomdp->getDiscount()));
}
if (pomdp->maxHorizon != -1) {
longTermFactor = std::min(longTermFactor, (double) pomdp->maxHorizon);
}
assert(longTermFactor != POMDP_LONG_TERM_UNBOUNDED);
double worstCaseLongTerm = worstCaseReward * longTermFactor;
FOR (i, pomdp->numStates) {
worstCaseDVector(i) = worstCaseLongTerm;
}
// post-process: make sure the value for all terminal states
// is exactly 0, since that is how the lbVal field of terminal
// nodes is initialized.
FOR (i, pomdp->numStates) {
if (pomdp->isPomdpTerminalState[i]) {
worstCaseDVector(i) = 0.0;
}
}
copy(weakAlpha, worstCaseDVector);
#if USE_DEBUG_PRINT
cout << "initLowerBoundBlindWorstCase: alpha=" << sparseRep(weakAlpha) << endl;
#endif
}
void BlindLBInitializer::initBlind(double targetPrecision)
{
alpha_vector al(pomdp->numStates);
alpha_vector nextAl, tmp, diff;
alpha_vector weakAl;
double maxResidual;
#if USE_MASKED_ALPHA
alpha_vector full_mask;
mask_set_all( full_mask, pomdp->numStates );
#endif
initBlindWorstCase(weakAl);
bound->planes.clear();
// produce one alpha vector for each fixed policy "always take action a"
FOR (a, pomdp->numActions) {
al = weakAl;
do {
// calculate nextAl
mult(nextAl, pomdp->T[a], al);
nextAl *= pomdp->discount;
copy_from_column(tmp, pomdp->R, a);
nextAl += tmp;
// calculate residual
diff = nextAl;
diff -= al;
maxResidual = norm_inf(diff);
al = nextAl;
} while (maxResidual > targetPrecision);
#if USE_DEBUG_PRINT
cout << "initLowerBoundBlind: a=" << a << " al=" << sparseRep(al) << endl;
#endif
#if USE_MASKED_ALPHA
bound->addLBPlane(new LBPlane(al, a, full_mask));
#else
bound->addLBPlane(new LBPlane(al, a));
#endif
}
}
}; // namespace zmdp
/***************************************************************************
* REVISION HISTORY:
* $Log: not supported by cvs2svn $
* Revision 1.5 2006/07/14 15:08:34 trey
* removed belief argument to addLBPlane()
*
* Revision 1.4 2006/06/03 10:58:45 trey
* added exact initialization rule for terminal states
*
* Revision 1.3 2006/04/28 17:57:41 trey
* changed to use apache license
*
* Revision 1.2 2006/04/27 23:08:40 trey
* put some output in USE_DEBUG_PRINT
*
* Revision 1.1 2006/04/05 21:43:20 trey
* collected and renamed several classes into pomdpBounds
*
* Revision 1.4 2006/02/14 19:33:55 trey
* added targetPrecision argument for bounds initialization
*
* Revision 1.3 2006/02/01 01:09:38 trey
* renamed pomdp namespace -> zmdp
*
* Revision 1.2 2006/01/31 20:13:45 trey
* changed when MDP* arguments are passed into bounds initialization
*
* Revision 1.1 2006/01/31 19:18:24 trey
* initial check-in
*
*
***************************************************************************/
<commit_msg>for kicks, now calculate a smaller value for longTermFactor when both discount < 1 and maxHorizon is defined<commit_after>/********** tell emacs we use -*- c++ -*- style comments *******************
$Revision: 1.7 $ $Author: trey $ $Date: 2006-10-25 18:32:21 $
@file BlindLBInitializer.cc
@brief No brief
Copyright (c) 2005, Trey Smith. 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 <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include "zmdpCommonDefs.h"
#include "MatrixUtils.h"
#include "Pomdp.h"
#include "BlindLBInitializer.h"
using namespace std;
using namespace sla;
using namespace MatrixUtils;
#define PRUNE_EPS (1e-10)
#define POMDP_LONG_TERM_UNBOUNDED (99e+20)
namespace zmdp {
BlindLBInitializer::BlindLBInitializer(const MDP* _pomdp, MaxPlanesLowerBound* _bound) {
pomdp = (const Pomdp*) _pomdp;
bound = _bound;
}
void BlindLBInitializer::initialize(double targetPrecision)
{
initBlind(targetPrecision);
}
void BlindLBInitializer::initBlindWorstCase(alpha_vector& weakAlpha)
{
// set alpha to be a lower bound on the value of the best blind policy
double worstStateVal;
int safestAction = -1;
double worstCaseReward = -99e+20;
// calculate worstCaseReward = max_a min_s R(s,a)
// safestAction = argmax_a min_s R(s,a)
FOR (a, pomdp->getNumActions()) {
worstStateVal = 99e+20;
FOR (s, pomdp->numStates) {
worstStateVal = std::min(worstStateVal, pomdp->R(s,a));
}
if (worstStateVal > worstCaseReward) {
safestAction = a;
worstCaseReward = worstStateVal;
}
}
dvector worstCaseDVector(pomdp->getNumStateDimensions());
double longTermFactor = POMDP_LONG_TERM_UNBOUNDED;
if (pomdp->getDiscount() < 1.0) {
if (pomdp->maxHorizon != -1) {
longTermFactor = (1.0 - pow(pomdp->getDiscount(), pomdp->maxHorizon+1))
/ (1.0 - pomdp->getDiscount());
} else {
longTermFactor = 1.0 / (1.0 - pomdp->getDiscount());
}
}
if (pomdp->maxHorizon != -1) {
longTermFactor = std::min(longTermFactor, (double) pomdp->maxHorizon);
}
assert(longTermFactor != POMDP_LONG_TERM_UNBOUNDED);
double worstCaseLongTerm = worstCaseReward * longTermFactor;
FOR (i, pomdp->numStates) {
worstCaseDVector(i) = worstCaseLongTerm;
}
// post-process: make sure the value for all terminal states
// is exactly 0, since that is how the lbVal field of terminal
// nodes is initialized.
FOR (i, pomdp->numStates) {
if (pomdp->isPomdpTerminalState[i]) {
worstCaseDVector(i) = 0.0;
}
}
copy(weakAlpha, worstCaseDVector);
#if USE_DEBUG_PRINT
cout << "initLowerBoundBlindWorstCase: alpha=" << sparseRep(weakAlpha) << endl;
#endif
}
void BlindLBInitializer::initBlind(double targetPrecision)
{
alpha_vector al(pomdp->numStates);
alpha_vector nextAl, tmp, diff;
alpha_vector weakAl;
double maxResidual;
#if USE_MASKED_ALPHA
alpha_vector full_mask;
mask_set_all( full_mask, pomdp->numStates );
#endif
initBlindWorstCase(weakAl);
bound->planes.clear();
// produce one alpha vector for each fixed policy "always take action a"
FOR (a, pomdp->numActions) {
al = weakAl;
do {
// calculate nextAl
mult(nextAl, pomdp->T[a], al);
nextAl *= pomdp->discount;
copy_from_column(tmp, pomdp->R, a);
nextAl += tmp;
// calculate residual
diff = nextAl;
diff -= al;
maxResidual = norm_inf(diff);
al = nextAl;
} while (maxResidual > targetPrecision);
#if USE_DEBUG_PRINT
cout << "initLowerBoundBlind: a=" << a << " al=" << sparseRep(al) << endl;
#endif
#if USE_MASKED_ALPHA
bound->addLBPlane(new LBPlane(al, a, full_mask));
#else
bound->addLBPlane(new LBPlane(al, a));
#endif
}
}
}; // namespace zmdp
/***************************************************************************
* REVISION HISTORY:
* $Log: not supported by cvs2svn $
* Revision 1.6 2006/10/03 03:18:36 trey
* added support for maxHorizon parameter of pomdp
*
* Revision 1.5 2006/07/14 15:08:34 trey
* removed belief argument to addLBPlane()
*
* Revision 1.4 2006/06/03 10:58:45 trey
* added exact initialization rule for terminal states
*
* Revision 1.3 2006/04/28 17:57:41 trey
* changed to use apache license
*
* Revision 1.2 2006/04/27 23:08:40 trey
* put some output in USE_DEBUG_PRINT
*
* Revision 1.1 2006/04/05 21:43:20 trey
* collected and renamed several classes into pomdpBounds
*
* Revision 1.4 2006/02/14 19:33:55 trey
* added targetPrecision argument for bounds initialization
*
* Revision 1.3 2006/02/01 01:09:38 trey
* renamed pomdp namespace -> zmdp
*
* Revision 1.2 2006/01/31 20:13:45 trey
* changed when MDP* arguments are passed into bounds initialization
*
* Revision 1.1 2006/01/31 19:18:24 trey
* initial check-in
*
*
***************************************************************************/
<|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 "printing/backend/print_backend.h"
#include <algorithm>
#include "third_party/icu/public/common/unicode/uchar.h"
#include "ui/base/text/text_elider.h"
namespace {
const wchar_t kDefaultDocumentTitle[] = L"Untitled Document";
const int kMaxDocumentTitleLength = 50;
} // namespace
namespace printing {
PrinterBasicInfo::PrinterBasicInfo()
: printer_status(0),
is_default(false) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterSemanticCapsAndDefaults::PrinterSemanticCapsAndDefaults()
: color_capable(false),
duplex_capable(false),
color_default(false),
duplex_default(UNKNOWN_DUPLEX_MODE) {}
PrinterSemanticCapsAndDefaults::~PrinterSemanticCapsAndDefaults() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
string16 PrintBackend::SimplifyDocumentTitle(const string16& title) {
string16 no_controls(title);
no_controls.erase(
std::remove_if(no_controls.begin(), no_controls.end(), &u_iscntrl),
no_controls.end());
string16 result;
ui::ElideString(no_controls, kMaxDocumentTitleLength, &result);
return result;
}
} // namespace printing
<commit_msg>Linux: fix build with system ICU.<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 "printing/backend/print_backend.h"
#include <algorithm>
#include "ui/base/text/text_elider.h"
#include "unicode/uchar.h"
namespace {
const wchar_t kDefaultDocumentTitle[] = L"Untitled Document";
const int kMaxDocumentTitleLength = 50;
} // namespace
namespace printing {
PrinterBasicInfo::PrinterBasicInfo()
: printer_status(0),
is_default(false) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterSemanticCapsAndDefaults::PrinterSemanticCapsAndDefaults()
: color_capable(false),
duplex_capable(false),
color_default(false),
duplex_default(UNKNOWN_DUPLEX_MODE) {}
PrinterSemanticCapsAndDefaults::~PrinterSemanticCapsAndDefaults() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
string16 PrintBackend::SimplifyDocumentTitle(const string16& title) {
string16 no_controls(title);
no_controls.erase(
std::remove_if(no_controls.begin(), no_controls.end(), &u_iscntrl),
no_controls.end());
string16 result;
ui::ElideString(no_controls, kMaxDocumentTitleLength, &result);
return result;
}
} // namespace printing
<|endoftext|> |
<commit_before>#include <babylon/GL/framebuffer_canvas.h>
#include <babylon/babylon_imgui/babylon_logs_window.h>
#include <babylon/babylon_imgui/babylon_studio.h>
#include <babylon/cameras/free_camera.h>
#include <babylon/core/filesystem.h>
#include <babylon/core/system.h>
#include <babylon/inspector/components/actiontabs/action_tabs_component.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <imgui.h>
#include <imgui_internal.h>
#include <imgui_runner_babylon/runner_babylon.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <babylon/babylon_imgui/babylon_studio_layout.h>
#include <babylon/core/logging.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <iostream>
namespace BABYLON {
struct EmptyScene : public BABYLON::IRenderableScene {
const char* getName() override
{
return "Empty Scene";
}
void initializeScene(BABYLON::ICanvas*, BABYLON::Scene* scene) override
{
auto camera = BABYLON::FreeCamera::New("camera1", Vector3(0.f, 0.f, 0.f), scene);
}
};
class BabylonStudioApp {
public:
BabylonStudioApp()
{
std::string exePath = BABYLON::System::getExecutablePath();
std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);
std::string playgroundPath = exeFolder + "/../../../src/BabylonStudio/playground.cpp";
playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath);
_playgroundCodeEditor.setFiles({playgroundPath});
_playgroundCodeEditor.setLightPalette();
}
void RunApp(const std::shared_ptr<BABYLON::IRenderableScene>& initialScene,
const BabylonStudioOptions& options)
{
_appContext._options = options;
_appContext._options._appWindowParams.ShowMenuBar = true;
auto showGuiLambda = [this]() -> bool {
bool r = this->render();
for (auto f : _appContext._options._heartbeatCallbacks)
f();
if (_appContext._options._playgroundCompilerCallback) {
PlaygroundCompilerStatus playgroundCompilerStatus
= _appContext._options._playgroundCompilerCallback();
if (playgroundCompilerStatus._renderableScene)
setRenderableScene(playgroundCompilerStatus._renderableScene);
_appContext._isCompiling = playgroundCompilerStatus._isCompiling;
}
return r;
};
auto initSceneLambda = [=]() {
this->initScene();
this->setRenderableScene(initialScene);
};
_appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) {
_studioLayout.PrepareLayout(mainDockId);
};
ImGuiUtils::ImGuiRunner::InvokeRunnerBabylon(
_appContext._options._appWindowParams,
showGuiLambda,
initSceneLambda
);
}
private:
void registerRenderFunctions()
{
static bool registered = false;
if (registered)
return;
// clang-format off
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Inspector,
[this]() {
if (_appContext._inspector)
_appContext._inspector->render();
});
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Logs,
[]() { BABYLON::BabylonLogsWindow::instance().render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Scene3d,
[this]() { render3d(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SamplesCodeViewer,
[this]() { _samplesCodeEditor.render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SampleBrowser,
[this]() { _appContext._sampleListComponent.render(); });
#ifdef BABYLON_BUILD_PLAYGROUND
_studioLayout.registerGuiRenderFunction(
DockableWindowId::PlaygroundEditor,
[this]() { renderPlayground(); });
#endif
// clang-format on
registered = true;
}
void initScene()
{
std::cout << "initScene 1 \n";
_appContext._sampleListComponent.OnNewRenderableScene
= [&](std::shared_ptr<IRenderableScene> scene) {
this->setRenderableScene(scene);
_studioLayout.FocusWindow(DockableWindowId::Scene3d);
};
std::cout << "initScene 2 \n";
_appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string>& files) {
_samplesCodeEditor.setFiles(files);
_studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true);
_studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer);
};
std::cout << "initScene 3 \n";
_appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string>& samples) {
_appContext._loopSamples.flagLoop = true;
_appContext._loopSamples.samplesToLoop = samples;
_appContext._loopSamples.currentIdx = 0;
};
std::cout << "initScene 4 \n";
_appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(ImVec2(640.f, 480.f));
std::cout << "initScene 5 \n";
_appContext._sceneWidget->OnBeforeResize.push_back(
[this]() { _appContext._inspector.release(); });
std::cout << "initScene 6 \n";
}
void prepareSceneInspector()
{
auto currentScene = _appContext._sceneWidget->getScene();
if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) {
_appContext._inspector
= std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene());
_appContext._inspector->setScene(currentScene);
}
}
// returns true if exit required
bool renderMenu()
{
ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar;
bool shallExit = false;
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Quit"))
shallExit = true;
if (ImGui::MenuItem("Save Screenshot"))
saveScreenshot();
ImGui::EndMenu();
}
_studioLayout.renderMenu();
renderStatus();
ImGui::EndMenuBar();
}
return shallExit;
}
void renderStatus()
{
ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f };
if (_studioLayout.isVisible(DockableWindowId::Scene3d))
{
ImGui::SameLine(ImGui::GetIO().DisplaySize.x / 2.f);
std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName();
ImGui::TextColored(statusTextColor, "%s", sceneName.c_str());
}
ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f);
ImGui::TextColored(statusTextColor, "FPS: %.1f", ImGui::GetIO().Framerate);
}
// renders the GUI. Returns true when exit required
bool render()
{
static bool wasInitialLayoutApplied = false;
if (!wasInitialLayoutApplied)
{
this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser);
wasInitialLayoutApplied = true;
}
prepareSceneInspector();
registerRenderFunctions();
bool shallExit = renderMenu();
_studioLayout.renderGui();
handleLoopSamples();
if (_appContext._options._flagScreenshotOneSampleAndExit)
return saveScreenshotAfterFewFrames();
else
return shallExit;
}
void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene)
{
if (_appContext._inspector)
_appContext._inspector->setScene(nullptr);
_appContext._sceneWidget->setRenderableScene(scene);
if (_appContext._inspector)
_appContext._inspector->setScene(_appContext._sceneWidget->getScene());
}
void saveScreenshot(std::string filename = "")
{
if (filename.empty())
filename = std::string(_appContext._sceneWidget->getRenderableScene()->getName()) + ".jpg";
int imageWidth = 200;
int jpgQuality = 75;
this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg(
filename.c_str(), jpgQuality, imageWidth);
}
// Saves a screenshot after few frames (returns true when done)
[[nodiscard]] bool saveScreenshotAfterFewFrames()
{
_appContext._frameCounter++;
if (_appContext._frameCounter < 30)
return false;
saveScreenshot(_appContext._options._sceneName + ".jpg");
return true;
}
bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size)
{
ImGui::SetNextWindowPos(position);
ImGui::SetNextWindowSize(size);
ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground;
std::string id = label + "##ButtonInOverlayWindow";
ImGui::Begin(label.c_str(), nullptr, flags);
bool clicked = ImGui::Button(label.c_str());
ImGui::End();
return clicked;
}
void renderHud(ImVec2 cursorScene3dTopLeft)
{
auto asSceneWithHud
= dynamic_cast<IRenderableSceneWithHud*>(_appContext._sceneWidget->getRenderableScene());
if (!asSceneWithHud)
return;
if (!asSceneWithHud->hudGui)
return;
static bool showHud = false;
ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f);
ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f);
if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f)))
showHud = !showHud;
if (showHud) {
ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once);
ImGui::SetNextWindowBgAlpha(0.5f);
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("HUD", &showHud, flags);
asSceneWithHud->hudGui();
ImGui::End();
}
}
void render3d()
{
ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size;
sceneSize.y -= 35.f;
sceneSize.x = (float)((int)((sceneSize.x) / 4) * 4);
ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos();
_appContext._sceneWidget->render(sceneSize);
renderHud(cursorPosBeforeScene3d);
}
void renderPlayground()
{
ImGui::Button(ICON_FA_QUESTION_CIRCLE);
if (ImGui::IsItemHovered())
ImGui::SetTooltip(
"Playground : you can edit the code below! As soon as you save it, the code will be "
"compiled and the 3D scene "
"will be updated");
ImGui::SameLine();
if (_appContext._isCompiling) {
ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling");
_studioLayout.setVisible(DockableWindowId::Logs, true);
}
if (ImGui::Button(ICON_FA_PLAY " Run"))
_playgroundCodeEditor.saveAll();
ImGui::SameLine();
_playgroundCodeEditor.render();
}
private:
void handleLoopSamples()
{
if (!_appContext._loopSamples.flagLoop)
return;
static int frame_counter = 0;
const int max_frames = 60;
if (frame_counter > max_frames) {
std::string sampleName
= _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx];
BABYLON_LOG_ERROR("LoopSample", sampleName)
auto scene = Samples::SamplesIndex::Instance().createRenderableScene(sampleName, nullptr);
this->setRenderableScene(scene);
if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2)
_appContext._loopSamples.currentIdx++;
else
_appContext._loopSamples.flagLoop = false;
frame_counter = 0;
}
else
frame_counter++;
}
//
// BabylonStudioContext
//
struct AppContext {
std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget;
std::unique_ptr<BABYLON::Inspector> _inspector;
BABYLON::SamplesBrowser _sampleListComponent;
int _frameCounter = 0;
BabylonStudioOptions _options;
bool _isCompiling = false;
struct {
bool flagLoop = false;
size_t currentIdx = 0;
std::vector<std::string> samplesToLoop;
} _loopSamples;
};
AppContext _appContext;
BabylonStudioLayout _studioLayout;
ImGuiUtils::CodeEditor _samplesCodeEditor
= ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly
ImGuiUtils::CodeEditor _playgroundCodeEditor;
}; // end of class BabylonInspectorApp
// public API
void runBabylonStudio(const std::shared_ptr<BABYLON::IRenderableScene>& scene,
BabylonStudioOptions options /* = SceneWithInspectorOptions() */
)
{
BABYLON::BabylonStudioApp app;
std::shared_ptr<BABYLON::IRenderableScene> sceneNotNull =
scene ? scene : std::make_shared<EmptyScene>();
app.RunApp(sceneNotNull, options);
}
} // namespace BABYLON
<commit_msg>BabylonStudioApp: global context for emscripten<commit_after>#include <babylon/GL/framebuffer_canvas.h>
#include <babylon/babylon_imgui/babylon_logs_window.h>
#include <babylon/babylon_imgui/babylon_studio.h>
#include <babylon/cameras/free_camera.h>
#include <babylon/core/filesystem.h>
#include <babylon/core/system.h>
#include <babylon/inspector/components/actiontabs/action_tabs_component.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <imgui.h>
#include <imgui_internal.h>
#include <imgui_runner_babylon/runner_babylon.h>
#include <imgui_utils/icons_font_awesome_5.h>
#include <babylon/babylon_imgui/babylon_studio_layout.h>
#include <babylon/core/logging.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <iostream>
namespace BABYLON {
struct EmptyScene : public BABYLON::IRenderableScene {
const char* getName() override
{
return "Empty Scene";
}
void initializeScene(BABYLON::ICanvas*, BABYLON::Scene* scene) override
{
auto camera = BABYLON::FreeCamera::New("camera1", Vector3(0.f, 0.f, 0.f), scene);
}
};
class BabylonStudioApp {
public:
BabylonStudioApp()
{
std::string exePath = BABYLON::System::getExecutablePath();
std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);
std::string playgroundPath = exeFolder + "/../../../src/BabylonStudio/playground.cpp";
playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath);
_playgroundCodeEditor.setFiles({playgroundPath});
_playgroundCodeEditor.setLightPalette();
}
void RunApp(const std::shared_ptr<BABYLON::IRenderableScene>& initialScene,
const BabylonStudioOptions& options)
{
_appContext._options = options;
_appContext._options._appWindowParams.ShowMenuBar = true;
auto showGuiLambda = [this]() -> bool {
bool r = this->render();
for (auto f : _appContext._options._heartbeatCallbacks)
f();
if (_appContext._options._playgroundCompilerCallback) {
PlaygroundCompilerStatus playgroundCompilerStatus
= _appContext._options._playgroundCompilerCallback();
if (playgroundCompilerStatus._renderableScene)
setRenderableScene(playgroundCompilerStatus._renderableScene);
_appContext._isCompiling = playgroundCompilerStatus._isCompiling;
}
return r;
};
auto initSceneLambda = [=]() {
this->initScene();
this->setRenderableScene(initialScene);
};
_appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) {
_studioLayout.PrepareLayout(mainDockId);
};
ImGuiUtils::ImGuiRunner::InvokeRunnerBabylon(
_appContext._options._appWindowParams,
showGuiLambda,
initSceneLambda
);
}
private:
void registerRenderFunctions()
{
static bool registered = false;
if (registered)
return;
// clang-format off
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Inspector,
[this]() {
if (_appContext._inspector)
_appContext._inspector->render();
});
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Logs,
[]() { BABYLON::BabylonLogsWindow::instance().render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::Scene3d,
[this]() { render3d(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SamplesCodeViewer,
[this]() { _samplesCodeEditor.render(); });
_studioLayout.registerGuiRenderFunction(
DockableWindowId::SampleBrowser,
[this]() { _appContext._sampleListComponent.render(); });
#ifdef BABYLON_BUILD_PLAYGROUND
_studioLayout.registerGuiRenderFunction(
DockableWindowId::PlaygroundEditor,
[this]() { renderPlayground(); });
#endif
// clang-format on
registered = true;
}
void initScene()
{
std::cout << "initScene 1 \n";
_appContext._sampleListComponent.OnNewRenderableScene
= [&](std::shared_ptr<IRenderableScene> scene) {
this->setRenderableScene(scene);
_studioLayout.FocusWindow(DockableWindowId::Scene3d);
};
std::cout << "initScene 2 \n";
_appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string>& files) {
_samplesCodeEditor.setFiles(files);
_studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true);
_studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer);
};
std::cout << "initScene 3 \n";
_appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string>& samples) {
_appContext._loopSamples.flagLoop = true;
_appContext._loopSamples.samplesToLoop = samples;
_appContext._loopSamples.currentIdx = 0;
};
std::cout << "initScene 4 \n";
_appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(ImVec2(640.f, 480.f));
std::cout << "initScene 5 \n";
_appContext._sceneWidget->OnBeforeResize.push_back(
[this]() { _appContext._inspector.release(); });
std::cout << "initScene 6 \n";
}
void prepareSceneInspector()
{
auto currentScene = _appContext._sceneWidget->getScene();
if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) {
_appContext._inspector
= std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene());
_appContext._inspector->setScene(currentScene);
}
}
// returns true if exit required
bool renderMenu()
{
ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar;
bool shallExit = false;
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Quit"))
shallExit = true;
if (ImGui::MenuItem("Save Screenshot"))
saveScreenshot();
ImGui::EndMenu();
}
_studioLayout.renderMenu();
renderStatus();
ImGui::EndMenuBar();
}
return shallExit;
}
void renderStatus()
{
ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f };
if (_studioLayout.isVisible(DockableWindowId::Scene3d))
{
ImGui::SameLine(ImGui::GetIO().DisplaySize.x / 2.f);
std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName();
ImGui::TextColored(statusTextColor, "%s", sceneName.c_str());
}
ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f);
ImGui::TextColored(statusTextColor, "FPS: %.1f", ImGui::GetIO().Framerate);
}
// renders the GUI. Returns true when exit required
bool render()
{
static bool wasInitialLayoutApplied = false;
if (!wasInitialLayoutApplied)
{
this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser);
wasInitialLayoutApplied = true;
}
prepareSceneInspector();
registerRenderFunctions();
bool shallExit = renderMenu();
_studioLayout.renderGui();
handleLoopSamples();
if (_appContext._options._flagScreenshotOneSampleAndExit)
return saveScreenshotAfterFewFrames();
else
return shallExit;
}
void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene)
{
if (_appContext._inspector)
_appContext._inspector->setScene(nullptr);
_appContext._sceneWidget->setRenderableScene(scene);
if (_appContext._inspector)
_appContext._inspector->setScene(_appContext._sceneWidget->getScene());
}
void saveScreenshot(std::string filename = "")
{
if (filename.empty())
filename = std::string(_appContext._sceneWidget->getRenderableScene()->getName()) + ".jpg";
int imageWidth = 200;
int jpgQuality = 75;
this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg(
filename.c_str(), jpgQuality, imageWidth);
}
// Saves a screenshot after few frames (returns true when done)
[[nodiscard]] bool saveScreenshotAfterFewFrames()
{
_appContext._frameCounter++;
if (_appContext._frameCounter < 30)
return false;
saveScreenshot(_appContext._options._sceneName + ".jpg");
return true;
}
bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size)
{
ImGui::SetNextWindowPos(position);
ImGui::SetNextWindowSize(size);
ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground;
std::string id = label + "##ButtonInOverlayWindow";
ImGui::Begin(label.c_str(), nullptr, flags);
bool clicked = ImGui::Button(label.c_str());
ImGui::End();
return clicked;
}
void renderHud(ImVec2 cursorScene3dTopLeft)
{
auto asSceneWithHud
= dynamic_cast<IRenderableSceneWithHud*>(_appContext._sceneWidget->getRenderableScene());
if (!asSceneWithHud)
return;
if (!asSceneWithHud->hudGui)
return;
static bool showHud = false;
ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f);
ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f);
if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f)))
showHud = !showHud;
if (showHud) {
ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once);
ImGui::SetNextWindowBgAlpha(0.5f);
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("HUD", &showHud, flags);
asSceneWithHud->hudGui();
ImGui::End();
}
}
void render3d()
{
ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size;
sceneSize.y -= 35.f;
sceneSize.x = (float)((int)((sceneSize.x) / 4) * 4);
ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos();
_appContext._sceneWidget->render(sceneSize);
renderHud(cursorPosBeforeScene3d);
}
void renderPlayground()
{
ImGui::Button(ICON_FA_QUESTION_CIRCLE);
if (ImGui::IsItemHovered())
ImGui::SetTooltip(
"Playground : you can edit the code below! As soon as you save it, the code will be "
"compiled and the 3D scene "
"will be updated");
ImGui::SameLine();
if (_appContext._isCompiling) {
ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling");
_studioLayout.setVisible(DockableWindowId::Logs, true);
}
if (ImGui::Button(ICON_FA_PLAY " Run"))
_playgroundCodeEditor.saveAll();
ImGui::SameLine();
_playgroundCodeEditor.render();
}
private:
void handleLoopSamples()
{
if (!_appContext._loopSamples.flagLoop)
return;
static int frame_counter = 0;
const int max_frames = 60;
if (frame_counter > max_frames) {
std::string sampleName
= _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx];
BABYLON_LOG_ERROR("LoopSample", sampleName)
auto scene = Samples::SamplesIndex::Instance().createRenderableScene(sampleName, nullptr);
this->setRenderableScene(scene);
if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2)
_appContext._loopSamples.currentIdx++;
else
_appContext._loopSamples.flagLoop = false;
frame_counter = 0;
}
else
frame_counter++;
}
//
// BabylonStudioContext
//
struct AppContext {
std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget;
std::unique_ptr<BABYLON::Inspector> _inspector;
BABYLON::SamplesBrowser _sampleListComponent;
int _frameCounter = 0;
BabylonStudioOptions _options;
bool _isCompiling = false;
struct {
bool flagLoop = false;
size_t currentIdx = 0;
std::vector<std::string> samplesToLoop;
} _loopSamples;
};
AppContext _appContext;
BabylonStudioLayout _studioLayout;
ImGuiUtils::CodeEditor _samplesCodeEditor
= ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly
ImGuiUtils::CodeEditor _playgroundCodeEditor;
}; // end of class BabylonInspectorApp
// public API
#ifdef __EMSCRIPTEN__
BABYLON::BabylonStudioApp app;
#endif
void runBabylonStudio(const std::shared_ptr<BABYLON::IRenderableScene>& scene,
BabylonStudioOptions options /* = SceneWithInspectorOptions() */
)
{
#ifndef __EMSCRIPTEN__
BABYLON::BabylonStudioApp app;
#endif
std::shared_ptr<BABYLON::IRenderableScene> sceneNotNull =
scene ? scene : std::make_shared<EmptyScene>();
app.RunApp(sceneNotNull, options);
}
} // namespace BABYLON
<|endoftext|> |
<commit_before>//===============================================================================
// @ Game.cpp
// ------------------------------------------------------------------------------
// Game core routines
//
// Copyright (C) 2008-2015 by James M. Van Verth and Lars M. Bishop.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This code example shows how to invert the OpenGL projection matrix to do
// picking. Game::GetPickRay() computes the pick ray based on a standard
// gluPerspective() matrix and the inverse view matrix.
//
// The key commands are:
//
// Click with left (or only) mouse button to move teapot around
//
//===============================================================================
//-------------------------------------------------------------------------------
//-- Dependencies ---------------------------------------------------------------
//-------------------------------------------------------------------------------
#include <math.h>
#include <IvClock.h>
#include <IvRenderer.h>
#include <IvEventHandler.h>
#include <IvMath.h>
#include <IvMatrix33.h>
#include <IvMatrix44.h>
#include <IvRendererHelp.h>
#include <IvVector4.h>
#include "Game.h"
//-------------------------------------------------------------------------------
//-- Static Members -------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-- Methods --------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
// @ IvGame::Create()
//-------------------------------------------------------------------------------
// Static constructor
//-------------------------------------------------------------------------------
bool
IvGame::Create()
{
IvGame::mGame = new Game();
return ( IvGame::mGame != 0 );
} // End of IvGame::Create()
//-------------------------------------------------------------------------------
// @ Game::Game()
//-------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------
Game::Game() : IvGame(),
mClickPosition( 0.0f, 0.0f, 0.0f )
{
} // End of Game::Game()
//-------------------------------------------------------------------------------
// @ Game::~Game()
//-------------------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------------------
Game::~Game()
{
} // End of Game::~Game()
//-------------------------------------------------------------------------------
// @ Game::PostRendererInitialize()
//-------------------------------------------------------------------------------
// Set up internal subsystems
//-------------------------------------------------------------------------------
bool
Game::PostRendererInitialize()
{
// Set up base class
if ( !IvGame::PostRendererInitialize() )
return false;
::IvSetDefaultLighting();
return true;
} // End of Game::PostRendererInitialize()
//-------------------------------------------------------------------------------
// @ Game::Update()
//-------------------------------------------------------------------------------
// Main update loop
//-------------------------------------------------------------------------------
void
Game::UpdateObjects( float /*dt*/ )
{
// handle picking
unsigned int h, v;
if (mEventHandler->IsMouseDown( h, v ))
{
// get the pick ray
IvVector3 ray = GetPickRay( (float) h, (float) v, IvRenderer::mRenderer->GetFOV(),
(float) IvRenderer::mRenderer->GetWidth(), (float) IvRenderer::mRenderer->GetHeight() );
// compute intersection with z=0 plane
float t = -mEyePoint.z/ray.z;
mClickPosition = mEyePoint + t*ray;
mEventHandler->MouseUp();
}
} // End of Game::Update()
//-------------------------------------------------------------------------------
// @ Game::Render()
//-------------------------------------------------------------------------------
// Render stuff
//-------------------------------------------------------------------------------
void
Game::Render() // Here's Where We Do All The Drawing
{
// look from (-10, 2, 10) at the origin
LookAt( IvVector3(-10.0f, 2.0f, 10.0f), IvVector3::origin, IvVector3::zAxis );
// draw axes
IvDrawAxes();
// draw a floor
IvDrawFloor();
// draw the main object
IvMatrix44 worldTransform;
worldTransform.Translation( mClickPosition );
IvSetWorldMatrix( worldTransform );
IvDrawTeapot();
}
//-------------------------------------------------------------------------------
// @ Game::LookAt()
//-------------------------------------------------------------------------------
// Basic camera lookAt code
//-------------------------------------------------------------------------------
void
Game::LookAt( const IvVector3& eye, const IvVector3& lookAt, const IvVector3& up )
{
mEyePoint = eye;
// compute view vectors
IvVector3 view = lookAt - eye;
IvVector3 right;
IvVector3 viewUp;
view.Normalize();
right = view.Cross( up );
right.Normalize();
viewUp = right.Cross( view );
viewUp.Normalize();
// now set up matrices
// base rotation matrix
IvMatrix33 rotate;
if ( IvRenderer::mRenderer->GetAPI() == kOpenGL )
{
rotate.SetColumns( right, viewUp, -view );
}
else
{
rotate.SetColumns( right, viewUp, view );
}
// view->world transform
// set rotation
mViewToWorldMatrix.Rotation(rotate);
// set translation (eye position)
mViewToWorldMatrix(0,3) = eye.x;
mViewToWorldMatrix(1,3) = eye.y;
mViewToWorldMatrix(2,3) = eye.z;
// world->view transform
// set rotation
rotate.Transpose();
mWorldToViewMatrix.Rotation(rotate);
// set translation (rotate into view space)
IvVector3 invEye = -(rotate*eye);
mWorldToViewMatrix(0,3) = invEye.x;
mWorldToViewMatrix(1,3) = invEye.y;
mWorldToViewMatrix(2,3) = invEye.z;
// send to OpenGL
IvSetViewMatrix( mWorldToViewMatrix );
}
//-------------------------------------------------------------------------------
// @ Game::GetPickRay()
//-------------------------------------------------------------------------------
// Get pick ray from screen position
//-------------------------------------------------------------------------------
IvVector3
Game::GetPickRay( float sx, float sy, float fov, float width, float height )
{
float d = 1.0f/IvTan(fov*kPI/360.0f);
float aspect = width/height;
IvVector3 viewPoint( 2.0f*aspect*sx/width - aspect, -2.0f*sy/height + 1.0f,
IvRenderer::mRenderer->GetAPI() == kOpenGL ? -d : d );
viewPoint = mViewToWorldMatrix.TransformPoint( viewPoint );
return viewPoint-mEyePoint;
}
<commit_msg>Fix picking example to use mouse pressed event<commit_after>//===============================================================================
// @ Game.cpp
// ------------------------------------------------------------------------------
// Game core routines
//
// Copyright (C) 2008-2015 by James M. Van Verth and Lars M. Bishop.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This code example shows how to invert the OpenGL projection matrix to do
// picking. Game::GetPickRay() computes the pick ray based on a standard
// gluPerspective() matrix and the inverse view matrix.
//
// The key commands are:
//
// Click with left (or only) mouse button to move teapot around
//
//===============================================================================
//-------------------------------------------------------------------------------
//-- Dependencies ---------------------------------------------------------------
//-------------------------------------------------------------------------------
#include <math.h>
#include <IvClock.h>
#include <IvRenderer.h>
#include <IvEventHandler.h>
#include <IvMath.h>
#include <IvMatrix33.h>
#include <IvMatrix44.h>
#include <IvRendererHelp.h>
#include <IvVector4.h>
#include "Game.h"
//-------------------------------------------------------------------------------
//-- Static Members -------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-- Methods --------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
// @ IvGame::Create()
//-------------------------------------------------------------------------------
// Static constructor
//-------------------------------------------------------------------------------
bool
IvGame::Create()
{
IvGame::mGame = new Game();
return ( IvGame::mGame != 0 );
} // End of IvGame::Create()
//-------------------------------------------------------------------------------
// @ Game::Game()
//-------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------
Game::Game() : IvGame(),
mClickPosition( 0.0f, 0.0f, 0.0f )
{
} // End of Game::Game()
//-------------------------------------------------------------------------------
// @ Game::~Game()
//-------------------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------------------
Game::~Game()
{
} // End of Game::~Game()
//-------------------------------------------------------------------------------
// @ Game::PostRendererInitialize()
//-------------------------------------------------------------------------------
// Set up internal subsystems
//-------------------------------------------------------------------------------
bool
Game::PostRendererInitialize()
{
// Set up base class
if ( !IvGame::PostRendererInitialize() )
return false;
::IvSetDefaultLighting();
return true;
} // End of Game::PostRendererInitialize()
//-------------------------------------------------------------------------------
// @ Game::Update()
//-------------------------------------------------------------------------------
// Main update loop
//-------------------------------------------------------------------------------
void
Game::UpdateObjects( float /*dt*/ )
{
// handle picking
unsigned int h, v;
if (mEventHandler->IsMousePressed( h, v ))
{
// get the pick ray
IvVector3 ray = GetPickRay( (float) h, (float) v, IvRenderer::mRenderer->GetFOV(),
(float) IvRenderer::mRenderer->GetWidth(), (float) IvRenderer::mRenderer->GetHeight() );
// compute intersection with z=0 plane
float t = -mEyePoint.z/ray.z;
mClickPosition = mEyePoint + t*ray;
}
} // End of Game::Update()
//-------------------------------------------------------------------------------
// @ Game::Render()
//-------------------------------------------------------------------------------
// Render stuff
//-------------------------------------------------------------------------------
void
Game::Render() // Here's Where We Do All The Drawing
{
// look from (-10, 2, 10) at the origin
LookAt( IvVector3(-10.0f, 2.0f, 10.0f), IvVector3::origin, IvVector3::zAxis );
// draw axes
IvDrawAxes();
// draw a floor
IvDrawFloor();
// draw the main object
IvMatrix44 worldTransform;
worldTransform.Translation( mClickPosition );
IvSetWorldMatrix( worldTransform );
IvDrawTeapot();
}
//-------------------------------------------------------------------------------
// @ Game::LookAt()
//-------------------------------------------------------------------------------
// Basic camera lookAt code
//-------------------------------------------------------------------------------
void
Game::LookAt( const IvVector3& eye, const IvVector3& lookAt, const IvVector3& up )
{
mEyePoint = eye;
// compute view vectors
IvVector3 view = lookAt - eye;
IvVector3 right;
IvVector3 viewUp;
view.Normalize();
right = view.Cross( up );
right.Normalize();
viewUp = right.Cross( view );
viewUp.Normalize();
// now set up matrices
// base rotation matrix
IvMatrix33 rotate;
if ( IvRenderer::mRenderer->GetAPI() == kOpenGL )
{
rotate.SetColumns( right, viewUp, -view );
}
else
{
rotate.SetColumns( right, viewUp, view );
}
// view->world transform
// set rotation
mViewToWorldMatrix.Rotation(rotate);
// set translation (eye position)
mViewToWorldMatrix(0,3) = eye.x;
mViewToWorldMatrix(1,3) = eye.y;
mViewToWorldMatrix(2,3) = eye.z;
// world->view transform
// set rotation
rotate.Transpose();
mWorldToViewMatrix.Rotation(rotate);
// set translation (rotate into view space)
IvVector3 invEye = -(rotate*eye);
mWorldToViewMatrix(0,3) = invEye.x;
mWorldToViewMatrix(1,3) = invEye.y;
mWorldToViewMatrix(2,3) = invEye.z;
// send to OpenGL
IvSetViewMatrix( mWorldToViewMatrix );
}
//-------------------------------------------------------------------------------
// @ Game::GetPickRay()
//-------------------------------------------------------------------------------
// Get pick ray from screen position
//-------------------------------------------------------------------------------
IvVector3
Game::GetPickRay( float sx, float sy, float fov, float width, float height )
{
float d = 1.0f/IvTan(fov*kPI/360.0f);
float aspect = width/height;
IvVector3 viewPoint( 2.0f*aspect*sx/width - aspect, -2.0f*sy/height + 1.0f,
IvRenderer::mRenderer->GetAPI() == kOpenGL ? -d : d );
viewPoint = mViewToWorldMatrix.TransformPoint( viewPoint );
return viewPoint-mEyePoint;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "partition_version.hh"
// Allows iterating over rows of mutation_partition represented by given partition_snapshot.
//
// The cursor initially has a position before all rows and is not pointing at any row.
// To position the cursor, use advance_to().
//
// All methods should be called with the region of the snapshot locked. The cursor is invalidated
// when that lock section is left, or if the snapshot is modified.
//
// When the cursor is invalidated, it still maintains its previous position. It can be brought
// back to validity by calling maybe_refresh(), or advance_to().
//
class partition_snapshot_row_cursor final {
struct position_in_version {
mutation_partition::rows_type::iterator it;
mutation_partition::rows_type::iterator end;
int version_no;
struct less_compare {
rows_entry::tri_compare _cmp;
public:
explicit less_compare(const schema& s) : _cmp(s) { }
bool operator()(const position_in_version& a, const position_in_version& b) {
auto res = _cmp(*a.it, *b.it);
return res > 0 || (res == 0 && a.version_no > b.version_no);
}
};
};
const schema& _schema;
partition_snapshot& _snp;
std::vector<position_in_version> _heap;
std::vector<position_in_version> _current_row;
position_in_partition _position;
partition_snapshot::change_mark _change_mark;
// Removes the next row from _heap and puts it into _current_row
void recreate_current_row() {
position_in_version::less_compare heap_less(_schema);
position_in_partition::equal_compare eq(_schema);
do {
boost::range::pop_heap(_heap, heap_less);
_current_row.push_back(_heap.back());
_heap.pop_back();
} while (!_heap.empty() && eq(_current_row[0].it->position(), _heap[0].it->position()));
_position = position_in_partition(_current_row[0].it->position());
}
public:
partition_snapshot_row_cursor(const schema& s, partition_snapshot& snp)
: _schema(s)
, _snp(snp)
, _position(position_in_partition::static_row_tag_t{})
{ }
bool has_up_to_date_row_from_latest_version() const {
return up_to_date() && _current_row[0].version_no == 0;
}
mutation_partition::rows_type::iterator get_iterator_in_latest_version() const {
return _current_row[0].it;
}
bool up_to_date() const {
return _snp.get_change_mark() == _change_mark;
}
// Brings back the cursor to validity.
// Can be only called when cursor is pointing at a row.
//
// Semantically equivalent to:
//
// advance_to(position());
//
// but avoids work if not necessary.
bool maybe_refresh() {
if (!up_to_date()) {
return advance_to(_position);
}
return true;
}
// Moves the cursor to the first entry with position >= pos.
//
// The caller must ensure that such entry exists.
//
// Returns true iff there can't be any clustering row entries
// between lower_bound (inclusive) and the entry to which the cursor
// was advanced.
//
// May be called when cursor is not valid.
// The cursor is valid after the call.
// Must be called under reclaim lock.
bool advance_to(position_in_partition_view lower_bound) {
rows_entry::compare less(_schema);
position_in_version::less_compare heap_less(_schema);
_heap.clear();
_current_row.clear();
int version_no = 0;
for (auto&& v : _snp.versions()) {
auto& rows = v.partition().clustered_rows();
auto pos = rows.lower_bound(lower_bound, less);
auto end = rows.end();
if (pos != end) {
_heap.push_back({pos, end, version_no});
}
++version_no;
}
boost::range::make_heap(_heap, heap_less);
_change_mark = _snp.get_change_mark();
bool found = no_clustering_row_between(_schema, lower_bound, _heap[0].it->position());
recreate_current_row();
return found;
}
// Advances the cursor to the next row.
// If there is no next row, returns false and the cursor is no longer pointing at a row.
// Can be only called on a valid cursor pointing at a row.
bool next() {
position_in_version::less_compare heap_less(_schema);
assert(up_to_date());
for (auto&& curr : _current_row) {
++curr.it;
if (curr.it != curr.end) {
_heap.push_back(curr);
boost::range::push_heap(_heap, heap_less);
}
}
_current_row.clear();
if (_heap.empty()) {
return false;
}
recreate_current_row();
return true;
}
// Can be called only when cursor is valid and pointing at a row.
bool continuous() const { return bool(_current_row[0].it->continuous()); }
// Can be called only when cursor is valid and pointing at a row.
bool dummy() const { return bool(_current_row[0].it->dummy()); }
// Can be called only when cursor is valid and pointing at a row, and !dummy().
const clustering_key& key() const { return _current_row[0].it->key(); }
// Can be called only when cursor is valid and pointing at a row.
mutation_fragment row() const {
auto it = _current_row.begin();
auto mf = mutation_fragment(clustering_row(*it->it));
auto& cr = mf.as_mutable_clustering_row();
for (++it; it != _current_row.end(); ++it) {
cr.apply(_schema, *it->it);
}
return mf;
}
// Can be called when cursor is pointing at a row, even when invalid.
const position_in_partition& position() const {
return _position;
}
bool is_in_latest_version() const;
bool previous_row_in_latest_version_has_key(const clustering_key_prefix& key) const;
void set_continuous(bool val);
friend std::ostream& operator<<(std::ostream& out, const partition_snapshot_row_cursor& cur) {
out << "{cursor: position=" << cur._position << ", ";
if (!cur.iterators_valid()) {
return out << " iterators invalid}";
}
out << "current=[";
bool first = true;
for (auto&& v : cur._current_row) {
if (!first) {
out << ", ";
}
first = false;
out << v.version_no;
}
out << "], heap=[";
first = true;
for (auto&& v : cur._heap) {
if (!first) {
out << ", ";
}
first = false;
out << "{v=" << v.version_no << ", pos=" << v.it->position() << "}";
}
return out << "]}";
};
};
inline
bool partition_snapshot_row_cursor::is_in_latest_version() const {
return _current_row[0].version_no == 0;
}
inline
bool partition_snapshot_row_cursor::previous_row_in_latest_version_has_key(const clustering_key_prefix& key) const {
if (_current_row[0].it == _snp.version()->partition().clustered_rows().begin()) {
return false;
}
auto prev_it = _current_row[0].it;
--prev_it;
clustering_key_prefix::equality eq(_schema);
return eq(prev_it->key(), key);
}
inline
void partition_snapshot_row_cursor::set_continuous(bool val) {
_current_row[0].it->set_continuous(val);
}
<commit_msg>mvcc: Keep track of all iterators in partition_snapshot_row_cursor<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "partition_version.hh"
// Allows iterating over rows of mutation_partition represented by given partition_snapshot.
//
// The cursor initially has a position before all rows and is not pointing at any row.
// To position the cursor, use advance_to().
//
// All methods should be called with the region of the snapshot locked. The cursor is invalidated
// when that lock section is left, or if the snapshot is modified.
//
// When the cursor is invalidated, it still maintains its previous position. It can be brought
// back to validity by calling maybe_refresh(), or advance_to().
//
class partition_snapshot_row_cursor final {
struct position_in_version {
mutation_partition::rows_type::iterator it;
mutation_partition::rows_type::iterator end;
int version_no;
struct less_compare {
rows_entry::tri_compare _cmp;
public:
explicit less_compare(const schema& s) : _cmp(s) { }
bool operator()(const position_in_version& a, const position_in_version& b) {
auto res = _cmp(*a.it, *b.it);
return res > 0 || (res == 0 && a.version_no > b.version_no);
}
};
};
const schema& _schema;
partition_snapshot& _snp;
std::vector<position_in_version> _heap;
std::vector<mutation_partition::rows_type::iterator> _iterators;
std::vector<position_in_version> _current_row;
position_in_partition _position;
partition_snapshot::change_mark _change_mark;
// Removes the next row from _heap and puts it into _current_row
void recreate_current_row() {
position_in_version::less_compare heap_less(_schema);
position_in_partition::equal_compare eq(_schema);
do {
boost::range::pop_heap(_heap, heap_less);
_current_row.push_back(_heap.back());
_heap.pop_back();
} while (!_heap.empty() && eq(_current_row[0].it->position(), _heap[0].it->position()));
_position = position_in_partition(_current_row[0].it->position());
}
public:
partition_snapshot_row_cursor(const schema& s, partition_snapshot& snp)
: _schema(s)
, _snp(snp)
, _position(position_in_partition::static_row_tag_t{})
{ }
bool has_up_to_date_row_from_latest_version() const {
return up_to_date() && _current_row[0].version_no == 0;
}
mutation_partition::rows_type::iterator get_iterator_in_latest_version() const {
return _iterators[0];
}
bool up_to_date() const {
return _snp.get_change_mark() == _change_mark;
}
// Brings back the cursor to validity.
// Can be only called when cursor is pointing at a row.
//
// Semantically equivalent to:
//
// advance_to(position());
//
// but avoids work if not necessary.
bool maybe_refresh() {
if (!up_to_date()) {
return advance_to(_position);
}
return true;
}
// Moves the cursor to the first entry with position >= pos.
//
// The caller must ensure that such entry exists.
//
// Returns true iff there can't be any clustering row entries
// between lower_bound (inclusive) and the entry to which the cursor
// was advanced.
//
// May be called when cursor is not valid.
// The cursor is valid after the call.
// Must be called under reclaim lock.
bool advance_to(position_in_partition_view lower_bound) {
rows_entry::compare less(_schema);
position_in_version::less_compare heap_less(_schema);
_heap.clear();
_current_row.clear();
_iterators.clear();
int version_no = 0;
for (auto&& v : _snp.versions()) {
auto& rows = v.partition().clustered_rows();
auto pos = rows.lower_bound(lower_bound, less);
auto end = rows.end();
_iterators.push_back(pos);
if (pos != end) {
_heap.push_back({pos, end, version_no});
}
++version_no;
}
boost::range::make_heap(_heap, heap_less);
_change_mark = _snp.get_change_mark();
bool found = no_clustering_row_between(_schema, lower_bound, _heap[0].it->position());
recreate_current_row();
return found;
}
// Advances the cursor to the next row.
// If there is no next row, returns false and the cursor is no longer pointing at a row.
// Can be only called on a valid cursor pointing at a row.
bool next() {
position_in_version::less_compare heap_less(_schema);
assert(up_to_date());
for (auto&& curr : _current_row) {
++curr.it;
_iterators[curr.version_no] = curr.it;
if (curr.it != curr.end) {
_heap.push_back(curr);
boost::range::push_heap(_heap, heap_less);
}
}
_current_row.clear();
if (_heap.empty()) {
return false;
}
recreate_current_row();
return true;
}
// Can be called only when cursor is valid and pointing at a row.
bool continuous() const { return bool(_current_row[0].it->continuous()); }
// Can be called only when cursor is valid and pointing at a row.
bool dummy() const { return bool(_current_row[0].it->dummy()); }
// Can be called only when cursor is valid and pointing at a row, and !dummy().
const clustering_key& key() const { return _current_row[0].it->key(); }
// Can be called only when cursor is valid and pointing at a row.
mutation_fragment row() const {
auto it = _current_row.begin();
auto mf = mutation_fragment(clustering_row(*it->it));
auto& cr = mf.as_mutable_clustering_row();
for (++it; it != _current_row.end(); ++it) {
cr.apply(_schema, *it->it);
}
return mf;
}
// Can be called when cursor is pointing at a row, even when invalid.
const position_in_partition& position() const {
return _position;
}
bool is_in_latest_version() const;
bool previous_row_in_latest_version_has_key(const clustering_key_prefix& key) const;
void set_continuous(bool val);
friend std::ostream& operator<<(std::ostream& out, const partition_snapshot_row_cursor& cur) {
out << "{cursor: position=" << cur._position << ", ";
if (!cur.iterators_valid()) {
return out << " iterators invalid}";
}
out << "current=[";
bool first = true;
for (auto&& v : cur._current_row) {
if (!first) {
out << ", ";
}
first = false;
out << v.version_no;
}
out << "], heap=[";
first = true;
for (auto&& v : cur._heap) {
if (!first) {
out << ", ";
}
first = false;
out << "{v=" << v.version_no << ", pos=" << v.it->position() << "}";
}
return out << "]}";
};
};
inline
bool partition_snapshot_row_cursor::is_in_latest_version() const {
return _current_row[0].version_no == 0;
}
inline
bool partition_snapshot_row_cursor::previous_row_in_latest_version_has_key(const clustering_key_prefix& key) const {
if (_current_row[0].it == _snp.version()->partition().clustered_rows().begin()) {
return false;
}
auto prev_it = _current_row[0].it;
--prev_it;
clustering_key_prefix::equality eq(_schema);
return eq(prev_it->key(), key);
}
inline
void partition_snapshot_row_cursor::set_continuous(bool val) {
_current_row[0].it->set_continuous(val);
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2017 Robert Ou <rqou@robertou.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ExtractReducePass : public Pass
{
enum GateType {
And,
Or,
Xor
};
ExtractReducePass() : Pass("extract_reduce", "converts gate chains into $reduce_* cells") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" extract_reduce [options] [selection]\n");
log("\n");
log("converts gate chains into $reduce_* cells\n");
log("\n");
log("This command finds chains of $_AND_, $_OR_, and $_XOR_ cells and replaces them\n");
log("with their corresponding $reduce_* cells. Because this command only operates on\n");
log("these cell types, it is recommended to map the design to only these cell types\n");
log("using the `abc -g` command. Note that, in some cases, it may be more effective\n");
log("to map the design to only $_AND_ cells, run extract_reduce, map the remaining\n");
log("parts of the design to AND/OR/XOR cells, and run extract_reduce a second time.\n");
log("\n");
log(" -allow-off-chain\n");
log(" Allows matching of cells that have loads outside the chain. These cells\n");
log(" will be replicated and folded into the $reduce_* cell, but the original\n");
log(" cell will remain, driving its original loads.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header(design, "Executing EXTRACT_REDUCE pass.\n");
log_push();
size_t argidx;
bool allow_off_chain = false;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-allow-off-chain")
{
allow_off_chain = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
{
SigMap sigmap(module);
// Index all of the nets in the module
dict<SigBit, Cell*> sig_to_driver;
dict<SigBit, pool<Cell*>> sig_to_sink;
for (auto cell : module->selected_cells())
{
for (auto &conn : cell->connections())
{
if (cell->output(conn.first))
for (auto bit : sigmap(conn.second))
sig_to_driver[bit] = cell;
if (cell->input(conn.first))
{
for (auto bit : sigmap(conn.second))
{
if (sig_to_sink.count(bit) == 0)
sig_to_sink[bit] = pool<Cell*>();
sig_to_sink[bit].insert(cell);
}
}
}
}
// Need to check if any wires connect to module ports
pool<SigBit> port_sigs;
for (auto wire : module->selected_wires())
if (wire->port_input || wire->port_output)
for (auto bit : sigmap(wire))
port_sigs.insert(bit);
// Actual logic starts here
pool<Cell*> consumed_cells;
pool<Cell*> head_cells;
for (auto cell : module->selected_cells())
{
if (consumed_cells.count(cell))
continue;
GateType gt;
if (cell->type == "$_AND_")
gt = GateType::And;
else if (cell->type == "$_OR_")
gt = GateType::Or;
else if (cell->type == "$_XOR_")
gt = GateType::Xor;
else
continue;
log("Working on cell %s...\n", cell->name.c_str());
// Go all the way to the sink
Cell* head_cell = cell;
Cell* x = cell;
while (true)
{
if (!((x->type == "$_AND_" && gt == GateType::And) ||
(x->type == "$_OR_" && gt == GateType::Or) ||
(x->type == "$_XOR_" && gt == GateType::Xor)))
break;
head_cell = x;
auto y = sigmap(x->getPort("\\Y"));
log_assert(y.size() == 1);
// Should only continue if there is one fanout back into a cell (not to a port)
if (sig_to_sink[y[0]].size() != 1)
break;
x = *sig_to_sink[y[0]].begin();
}
log(" Head cell is %s\n", head_cell->name.c_str());
pool<Cell*> cur_supercell;
std::deque<Cell*> bfs_queue = {head_cell};
while (bfs_queue.size())
{
Cell* x = bfs_queue.front();
bfs_queue.pop_front();
cur_supercell.insert(x);
auto a = sigmap(x->getPort("\\A"));
log_assert(a.size() == 1);
// Must have only one sink
// XXX: Check that it is indeed this node?
if (sig_to_sink[a[0]].size() + port_sigs.count(a[0]) == 1)
{
Cell* cell_a = sig_to_driver[a[0]];
if (cell_a && ((cell_a->type == "$_AND_" && gt == GateType::And) ||
(cell_a->type == "$_OR_" && gt == GateType::Or) ||
(cell_a->type == "$_XOR_" && gt == GateType::Xor)))
{
// The cell here is the correct type, and it's definitely driving only
// this current cell.
bfs_queue.push_back(cell_a);
}
}
auto b = sigmap(x->getPort("\\B"));
log_assert(b.size() == 1);
// Must have only one sink
// XXX: Check that it is indeed this node?
if (sig_to_sink[b[0]].size() + port_sigs.count(b[0]) == 1)
{
Cell* cell_b = sig_to_driver[b[0]];
if (cell_b && ((cell_b->type == "$_AND_" && gt == GateType::And) ||
(cell_b->type == "$_OR_" && gt == GateType::Or) ||
(cell_b->type == "$_XOR_" && gt == GateType::Xor)))
{
// The cell here is the correct type, and it's definitely driving only
// this current cell.
bfs_queue.push_back(cell_b);
}
}
}
log(" Cells:\n");
for (auto x : cur_supercell)
log(" %s\n", x->name.c_str());
if (cur_supercell.size() > 1)
{
// Worth it to create reduce cell
log(" Creating $reduce_* cell!\n");
pool<SigBit> input_pool;
pool<SigBit> input_pool_intermed;
for (auto x : cur_supercell)
{
input_pool.insert(sigmap(x->getPort("\\A"))[0]);
input_pool.insert(sigmap(x->getPort("\\B"))[0]);
input_pool_intermed.insert(sigmap(x->getPort("\\Y"))[0]);
}
SigSpec input;
for (auto b : input_pool)
if (input_pool_intermed.count(b) == 0)
input.append_bit(b);
SigBit output = sigmap(head_cell->getPort("\\Y")[0]);
auto new_reduce_cell = module->addCell(NEW_ID,
gt == GateType::And ? "$reduce_and" :
gt == GateType::Or ? "$reduce_or" :
gt == GateType::Xor ? "$reduce_xor" : "");
new_reduce_cell->setParam("\\A_SIGNED", 0);
new_reduce_cell->setParam("\\A_WIDTH", input.size());
new_reduce_cell->setParam("\\Y_WIDTH", 1);
new_reduce_cell->setPort("\\A", input);
new_reduce_cell->setPort("\\Y", output);
for (auto x : cur_supercell)
consumed_cells.insert(x);
head_cells.insert(head_cell);
}
}
// Remove all of the head cells, since we supplant them.
// Do not remove the upstream cells since some might still be in use ("clean" will get rid of unused ones)
for (auto cell : head_cells)
module->remove(cell);
}
log_pop();
}
} ExtractReducePass;
PRIVATE_NAMESPACE_END
<commit_msg>Implemented off-chain support for extract_reduce<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2017 Robert Ou <rqou@robertou.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ExtractReducePass : public Pass
{
enum GateType {
And,
Or,
Xor
};
ExtractReducePass() : Pass("extract_reduce", "converts gate chains into $reduce_* cells") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" extract_reduce [options] [selection]\n");
log("\n");
log("converts gate chains into $reduce_* cells\n");
log("\n");
log("This command finds chains of $_AND_, $_OR_, and $_XOR_ cells and replaces them\n");
log("with their corresponding $reduce_* cells. Because this command only operates on\n");
log("these cell types, it is recommended to map the design to only these cell types\n");
log("using the `abc -g` command. Note that, in some cases, it may be more effective\n");
log("to map the design to only $_AND_ cells, run extract_reduce, map the remaining\n");
log("parts of the design to AND/OR/XOR cells, and run extract_reduce a second time.\n");
log("\n");
log(" -allow-off-chain\n");
log(" Allows matching of cells that have loads outside the chain. These cells\n");
log(" will be replicated and folded into the $reduce_* cell, but the original\n");
log(" cell will remain, driving its original loads.\n");
log("\n");
}
inline bool IsRightType(Cell* cell, GateType gt)
{
return (cell->type == "$_AND_" && gt == GateType::And) ||
(cell->type == "$_OR_" && gt == GateType::Or) ||
(cell->type == "$_XOR_" && gt == GateType::Xor);
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header(design, "Executing EXTRACT_REDUCE pass.\n");
log_push();
size_t argidx;
bool allow_off_chain = false;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-allow-off-chain")
{
allow_off_chain = true;
continue;
}
}
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
{
SigMap sigmap(module);
// Index all of the nets in the module
dict<SigBit, Cell*> sig_to_driver;
dict<SigBit, pool<Cell*>> sig_to_sink;
for (auto cell : module->selected_cells())
{
for (auto &conn : cell->connections())
{
if (cell->output(conn.first))
for (auto bit : sigmap(conn.second))
sig_to_driver[bit] = cell;
if (cell->input(conn.first))
{
for (auto bit : sigmap(conn.second))
{
if (sig_to_sink.count(bit) == 0)
sig_to_sink[bit] = pool<Cell*>();
sig_to_sink[bit].insert(cell);
}
}
}
}
// Need to check if any wires connect to module ports
pool<SigBit> port_sigs;
for (auto wire : module->selected_wires())
if (wire->port_input || wire->port_output)
for (auto bit : sigmap(wire))
port_sigs.insert(bit);
// Actual logic starts here
pool<Cell*> consumed_cells;
for (auto cell : module->selected_cells())
{
if (consumed_cells.count(cell))
continue;
GateType gt;
if (cell->type == "$_AND_")
gt = GateType::And;
else if (cell->type == "$_OR_")
gt = GateType::Or;
else if (cell->type == "$_XOR_")
gt = GateType::Xor;
else
continue;
log("Working on cell %s...\n", cell->name.c_str());
// If looking for a single chain, follow linearly to the sink
pool<Cell*> sinks;
if(!allow_off_chain)
{
Cell* head_cell = cell;
Cell* x = cell;
while (true)
{
if(!IsRightType(x, gt))
break;
head_cell = x;
auto y = sigmap(x->getPort("\\Y"));
log_assert(y.size() == 1);
// Should only continue if there is one fanout back into a cell (not to a port)
if (sig_to_sink[y[0]].size() != 1)
break;
x = *sig_to_sink[y[0]].begin();
}
sinks.insert(head_cell);
}
//If off-chain loads are allowed, we have to do a wider traversal to see what the longest chain is
else
{
//BFS, following all chains until they hit a cell of a different type
//Pick the longest one
auto y = sigmap(cell->getPort("\\Y"));
pool<Cell*> current_loads = sig_to_sink[y];
pool<Cell*> next_loads;
while(!current_loads.empty())
{
//Find each sink and see what they are
for(auto x : current_loads)
{
//Not one of our gates? Don't follow any further
//(but add the originating cell to the list of sinks)
if(!IsRightType(x, gt))
{
sinks.insert(cell);
continue;
}
//If this signal drives a port, add it to the sinks
//(even though it may not be the end of a chain)
if(port_sigs.count(x) && !consumed_cells.count(x))
sinks.insert(x);
//It's a match, search everything out from it
auto& next = sig_to_sink[x];
for(auto z : next)
next_loads.insert(z);
}
//If we couldn't find any downstream loads, stop.
//Create a reduction for each of the max-length chains we found
if(next_loads.empty())
{
for(auto s : current_loads)
{
//Not one of our gates? Don't follow any further
if(!IsRightType(s, gt))
continue;
sinks.insert(s);
}
break;
}
//Otherwise, continue down the chain
current_loads = next_loads;
next_loads.clear();
}
}
//We have our list, go act on it
for(auto head_cell : sinks)
{
log(" Head cell is %s\n", head_cell->name.c_str());
//Avoid duplication if we already were covered
if(consumed_cells.count(head_cell))
continue;
pool<Cell*> cur_supercell;
std::deque<Cell*> bfs_queue = {head_cell};
while (bfs_queue.size())
{
Cell* x = bfs_queue.front();
bfs_queue.pop_front();
cur_supercell.insert(x);
auto a = sigmap(x->getPort("\\A"));
log_assert(a.size() == 1);
// Must have only one sink unless we're going off chain
// XXX: Check that it is indeed this node?
if( allow_off_chain || (sig_to_sink[a[0]].size() + port_sigs.count(a[0]) == 1) )
{
Cell* cell_a = sig_to_driver[a[0]];
if(cell_a && IsRightType(cell_a, gt))
{
// The cell here is the correct type, and it's definitely driving
// this current cell.
bfs_queue.push_back(cell_a);
}
}
auto b = sigmap(x->getPort("\\B"));
log_assert(b.size() == 1);
// Must have only one sink
// XXX: Check that it is indeed this node?
if( allow_off_chain || (sig_to_sink[b[0]].size() + port_sigs.count(b[0]) == 1) )
{
Cell* cell_b = sig_to_driver[b[0]];
if(cell_b && IsRightType(cell_b, gt))
{
// The cell here is the correct type, and it's definitely driving only
// this current cell.
bfs_queue.push_back(cell_b);
}
}
}
log(" Cells:\n");
for (auto x : cur_supercell)
log(" %s\n", x->name.c_str());
if (cur_supercell.size() > 1)
{
// Worth it to create reduce cell
log(" Creating $reduce_* cell!\n");
pool<SigBit> input_pool;
pool<SigBit> input_pool_intermed;
for (auto x : cur_supercell)
{
input_pool.insert(sigmap(x->getPort("\\A"))[0]);
input_pool.insert(sigmap(x->getPort("\\B"))[0]);
input_pool_intermed.insert(sigmap(x->getPort("\\Y"))[0]);
}
SigSpec input;
for (auto b : input_pool)
if (input_pool_intermed.count(b) == 0)
input.append_bit(b);
SigBit output = sigmap(head_cell->getPort("\\Y")[0]);
auto new_reduce_cell = module->addCell(NEW_ID,
gt == GateType::And ? "$reduce_and" :
gt == GateType::Or ? "$reduce_or" :
gt == GateType::Xor ? "$reduce_xor" : "");
new_reduce_cell->setParam("\\A_SIGNED", 0);
new_reduce_cell->setParam("\\A_WIDTH", input.size());
new_reduce_cell->setParam("\\Y_WIDTH", 1);
new_reduce_cell->setPort("\\A", input);
new_reduce_cell->setPort("\\Y", output);
if(allow_off_chain)
consumed_cells.insert(head_cell);
else
{
for (auto x : cur_supercell)
consumed_cells.insert(x);
}
}
}
}
// Remove all of the head cells, since we supplant them.
// Do not remove the upstream cells since some might still be in use ("clean" will get rid of unused ones)
for (auto cell : consumed_cells)
module->remove(cell);
}
log_pop();
}
} ExtractReducePass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Quanta Research Cambridge, Inc.
// 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 <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include "PortalPerfIndicationWrapper.h"
#include "PortalPerfRequestProxy.h"
#include "GeneratedTypes.h"
//#define DEBUG 1
#ifdef DEBUG
#define DEBUGWHERE() \
fprintf(stderr, "at %s, %s:%d\n", __FUNCTION__, __FILE__, __LINE__)
#else
#define DEBUGWHERE()
#endif
#define LOOP_COUNT 50
#define SEPARATE_EVENT_THREAD
//#define USE_MUTEX_SYNC
PortalPerfRequestProxy *portalPerfRequestProxy = 0;
#ifndef SEPARATE_EVENT_THREAD
typedef int SEM_TYPE;
#define SEMPOST(A) (*(A))++
#define SEMWAIT pthread_worker
#elif defined(USE_MUTEX_SYNC)
typedef pthread_mutex_t SEM_TYPE;
#define SEMINIT(A) pthread_mutex_lock(A);
#define SEMWAIT(A) pthread_mutex_lock(A);
#define SEMPOST(A) pthread_mutex_unlock(A);
#else // use semaphores
typedef sem_t SEM_TYPE;
#define SEMINIT(A) sem_init(A, 0, 0);
#define SEMWAIT(A) sem_wait(A);
#define SEMPOST(A) sem_post(A)
#endif
#ifdef SEPARATE_EVENT_THREAD
#define PREPAREWAIT(A)
#define CHECKSEM(A) 1
#else // use inline sync
#define PREPAREWAIT(A) (A) = 0
#define CHECKSEM(A) (!(A))
#endif
static SEM_TYPE sem_heard;
PortalPoller *poller = 0;
#ifdef SEPARATE_EVENT_THREAD
static void *pthread_worker(void *p)
{
void *rc = NULL;
while (CHECKSEM(sem_heard) && !rc && !poller->stopping)
rc = poller->portalExec_event(poller->portalExec_timeout);
return rc;
}
#endif
static void init_thread()
{
#ifdef SEPARATE_EVENT_THREAD
pthread_t threaddata;
SEMINIT(&sem_heard);
pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller);
#endif
}
class PortalPerfIndication : public PortalPerfIndicationWrapper
{
public:
virtual void spitl(uint32_t v1) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitll(uint32_t v1, uint32_t v2) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitlll(uint32_t v1, uint32_t v2, uint32_t v3) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitllll(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitd(uint64_t v1) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitdd(uint64_t v1, uint64_t v2) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitddd(uint64_t v1, uint64_t v2, uint64_t v3) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
virtual void spitdddd(uint64_t v1, uint64_t v2, uint64_t v3, uint64_t v4) {
DEBUGWHERE();
catch_timer(20);
SEMPOST(&sem_heard);
}
PortalPerfIndication(unsigned int id, PortalPoller *poller) : PortalPerfIndicationWrapper(id, poller) {}
};
uint32_t vl1, vl2, vl3, vl4;
uint64_t vd1, vd2, vd3, vd4;
void call_swallowl(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowl(vl1);
catch_timer(19);
}
void call_swallowll(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowll(vl1, vl2);
catch_timer(19);
}
void call_swallowlll(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowlll(vl1, vl2, vl3);
catch_timer(19);
}
void call_swallowllll(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowllll(vl1, vl2, vl3, vl4);
catch_timer(19);
}
void call_swallowd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowd(vd1);
catch_timer(19);
}
void call_swallowdd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowdd(vd1, vd2);
catch_timer(19);
}
void call_swallowddd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowddd(vd1, vd2, vd3);
catch_timer(19);
}
void call_swallowdddd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowdddd(vd1, vd2, vd3, vd4);
catch_timer(19);
}
void call_dospitl(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitl();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitll(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitll();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitlll(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitlll();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitllll(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitllll();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitd(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitd();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitdd(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitdd();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitddd(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitddd();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void call_dospitdddd(void)
{
DEBUGWHERE();
start_timer(0);
PREPAREWAIT(sem_heard);
catch_timer(0);
portalPerfRequestProxy->dospitdddd();
catch_timer(19);
SEMWAIT(&sem_heard);
catch_timer(30);
}
void dotest(const char *testname, void (*testfn)(void))
{
uint64_t elapsed;
init_timer();
start_timer(1);
for (int i = 0; i < LOOP_COUNT; i++) {
testfn();
}
elapsed = lap_timer(1);
printf("test %s: elapsed %g average %g\n", testname, (double) elapsed, (double) elapsed/ (double) LOOP_COUNT);
print_timer(LOOP_COUNT);
}
int main(int argc, const char **argv)
{
poller = new PortalPoller();
PortalPerfIndication *portalPerfIndication = new PortalPerfIndication(IfcNames_PortalPerfIndication, poller);
// these use the default poller
portalPerfRequestProxy = new PortalPerfRequestProxy(IfcNames_PortalPerfRequest);
poller->portalExec_init();
init_thread();
portalExec_start();
printf("Timer tests\n");
init_timer();
for (int i = 0; i < 1000; i++) {
start_timer(0);
catch_timer(1);
catch_timer(2);
catch_timer(3);
catch_timer(4);
catch_timer(5);
catch_timer(6);
catch_timer(7);
catch_timer(8);
}
printf("Each line 1-8 is one more call to catch_timer()\n");
print_timer(1000);
printf("TEST TYPE: "
#ifndef SEPARATE_EVENT_THREAD
"INLINE"
#elif defined(USE_MUTEX_SYNC)
"MUTEX"
#else
"SEM"
#endif
"\n");
dotest("swallowl", call_swallowl);
dotest("swallowll", call_swallowll);
dotest("swallowlll", call_swallowlll);
dotest("swallowllll", call_swallowllll);
dotest("swallowd", call_swallowd);
dotest("swallowdd", call_swallowdd);
dotest("swallowddd", call_swallowddd);
dotest("swallowdddd", call_swallowdddd);
dotest("spitl", call_dospitl);
dotest("spitll", call_dospitll);
dotest("spitlll", call_dospitlll);
dotest("spitllll", call_dospitllll);
dotest("spitd", call_dospitd);
dotest("spitdd", call_dospitdd);
dotest("spitddd", call_dospitddd);
dotest("spitdddd", call_dospitdddd);
poller->portalExec_end();
portalExec_end();
return 0;
}
<commit_msg>save indication values for checking<commit_after>// Copyright (c) 2014 Quanta Research Cambridge, Inc.
// 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "PortalPerfIndicationWrapper.h"
#include "PortalPerfRequestProxy.h"
#include "GeneratedTypes.h"
//#define DEBUG 1
#ifdef DEBUG
#define DEBUGWHERE() \
fprintf(stderr, "at %s, %s:%d\n", __FUNCTION__, __FILE__, __LINE__)
#else
#define DEBUGWHERE()
#endif
#define LOOP_COUNT 50
PortalPerfRequestProxy *portalPerfRequestProxy = 0;
int heard_count;
static void *wait_for(int n)
{
void *rc = NULL;
while ((heard_count != n) && !rc)
rc = portalExec_event(0);
return rc;
}
uint32_t vrl1, vrl2, vrl3, vrl4;
uint64_t vrd1, vrd2, vrd3, vrd4;
class PortalPerfIndication : public PortalPerfIndicationWrapper
{
public:
virtual void spit() {
DEBUGWHERE();
heard_count++;
}
virtual void spitl(uint32_t v1) {
DEBUGWHERE();
heard_count++;
vrl1 = v1;
}
virtual void spitll(uint32_t v1, uint32_t v2) {
DEBUGWHERE();
heard_count++;
vrl1 = v1;
vrl2 = v2;
}
virtual void spitlll(uint32_t v1, uint32_t v2, uint32_t v3) {
DEBUGWHERE();
heard_count++;
vrl1 = v1;
vrl2 = v2;
vrl3 = v3;
}
virtual void spitllll(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4) {
DEBUGWHERE();
heard_count++;
vrl1 = v1;
vrl2 = v2;
vrl3 = v3;
vrl4 = v4;
}
virtual void spitd(uint64_t v1) {
DEBUGWHERE();
heard_count++;
vrd1 = v1;
}
virtual void spitdd(uint64_t v1, uint64_t v2) {
DEBUGWHERE();
heard_count++;
vrd1 = v1;
vrd2 = v2;
}
virtual void spitddd(uint64_t v1, uint64_t v2, uint64_t v3) {
DEBUGWHERE();
heard_count++;
vrd1 = v1;
vrd2 = v2;
vrd3 = v3;
}
virtual void spitdddd(uint64_t v1, uint64_t v2, uint64_t v3, uint64_t v4) {
DEBUGWHERE();
heard_count++;
vrd1 = v1;
vrd2 = v2;
vrd3 = v3;
vrd4 = v4;
}
PortalPerfIndication(unsigned int id) : PortalPerfIndicationWrapper(id) {}
};
uint32_t vl1, vl2, vl3, vl4;
uint64_t vd1, vd2, vd3, vd4;
void call_swallow(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallow();
catch_timer(19);
}
void call_swallowl(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowl(vl1);
catch_timer(19);
}
void call_swallowll(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowll(vl1, vl2);
catch_timer(19);
}
void call_swallowlll(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowlll(vl1, vl2, vl3);
catch_timer(19);
}
void call_swallowllll(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowllll(vl1, vl2, vl3, vl4);
catch_timer(19);
}
void call_swallowd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowd(vd1);
catch_timer(19);
}
void call_swallowdd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowdd(vd1, vd2);
catch_timer(19);
}
void call_swallowddd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowddd(vd1, vd2, vd3);
catch_timer(19);
}
void call_swallowdddd(void)
{
DEBUGWHERE();
start_timer(0);
catch_timer(0);
portalPerfRequestProxy->swallowdddd(vd1, vd2, vd3, vd4);
catch_timer(19);
}
void dotestout(const char *testname, void (*testfn)(void))
{
uint64_t elapsed;
init_timer();
start_timer(1);
for (int i = 0; i < LOOP_COUNT; i++) {
testfn();
}
elapsed = lap_timer(1);
printf("test %s: elapsed %g average %g\n", testname, (double) elapsed, (double) elapsed/ (double) LOOP_COUNT);
print_timer(LOOP_COUNT);
}
void dotestin(const char *testname, int which)
{
uint64_t elapsed;
heard_count = 0;
printf("starting test %s, which %d\n", testname, which);
init_timer();
start_timer(1);
portalPerfRequestProxy->startspit(which, LOOP_COUNT);
wait_for(LOOP_COUNT);
elapsed = lap_timer(1);
printf("test %s: heard %d elapsed %g average %g\n", testname, heard_count, (double) elapsed, (double) elapsed/ (double) LOOP_COUNT);
//print_timer(LOOP_COUNT);
}
int main(int argc, const char **argv)
{
PortalPerfIndication *portalPerfIndication = new PortalPerfIndication(IfcNames_PortalPerfIndication);
portalPerfRequestProxy = new PortalPerfRequestProxy(IfcNames_PortalPerfRequest);
portalExec_init();
printf("Timer tests\n");
init_timer();
for (int i = 0; i < 1000; i++) {
start_timer(0);
catch_timer(1);
catch_timer(2);
catch_timer(3);
catch_timer(4);
catch_timer(5);
catch_timer(6);
catch_timer(7);
catch_timer(8);
}
printf("Each line 1-8 is one more call to catch_timer()\n");
print_timer(1000);
vl1 = 0xfeed000000000011;
vl2 = 0xface000000000012;
vl3 = 0xdead000000000013;
vl4 = 0xbeef000000000014;
vd1 = 0xfeed0000000000000021LL;
vd2 = 0xface0000000000000022LL;
vd3 = 0xdead0000000000000023LL;
vd4 = 0xbeef0000000000000024LL;
dotestout("swallow", call_swallow);
dotestout("swallowl", call_swallowl);
dotestout("swallowll", call_swallowll);
dotestout("swallowlll", call_swallowlll);
dotestout("swallowllll", call_swallowllll);
dotestout("swallowd", call_swallowd);
dotestout("swallowdd", call_swallowdd);
dotestout("swallowddd", call_swallowddd);
dotestout("swallowdddd", call_swallowdddd);
dotestin("spitl", 1);
dotestin("spit", 0);
dotestin("spitll", 2);
dotestin("spitlll", 3);
dotestin("spitllll", 4);
dotestin("spitd", 5);
dotestin("spitdd", 6);
dotestin("spitddd", 7);
dotestin("spitdddd", 8);
portalExec_end();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysethelper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 14:08:48 $
*
* 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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "unotools/propertysetinfo.hxx"
#include "unotools/propertysethelper.hxx"
///////////////////////////////////////////////////////////////////////
using namespace ::utl;
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
namespace utl
{
class PropertySetHelperImpl
{
public:
PropertyMapEntry* find( const OUString& aName ) const throw();
PropertySetInfo* mpInfo;
};
}
PropertyMapEntry* PropertySetHelperImpl::find( const OUString& aName ) const throw()
{
PropertyMap::const_iterator aIter = mpInfo->getPropertyMap()->find( aName );
if( mpInfo->getPropertyMap()->end() != aIter )
{
return (*aIter).second;
}
else
{
return NULL;
}
}
///////////////////////////////////////////////////////////////////////
PropertySetHelper::PropertySetHelper( utl::PropertySetInfo* pInfo ) throw()
{
mp = new PropertySetHelperImpl;
mp->mpInfo = pInfo;
pInfo->acquire();
}
PropertySetHelper::~PropertySetHelper() throw()
{
mp->mpInfo->release();
delete mp;
}
// XPropertySet
Reference< XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo( ) throw(RuntimeException)
{
return mp->mpInfo;
}
void SAL_CALL PropertySetHelper::setPropertyValue( const ::rtl::OUString& aPropertyName, const Any& aValue ) throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
PropertyMapEntry* aEntries[2];
aEntries[0] = mp->find( aPropertyName );
if( NULL == aEntries[0] )
throw UnknownPropertyException();
aEntries[1] = NULL;
_setPropertyValues( (const PropertyMapEntry**)aEntries, &aValue );
}
Any SAL_CALL PropertySetHelper::getPropertyValue( const ::rtl::OUString& PropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
PropertyMapEntry* aEntries[2];
aEntries[0] = mp->find( PropertyName );
if( NULL == aEntries[0] )
throw UnknownPropertyException();
aEntries[1] = NULL;
Any aAny;
_getPropertyValues( (const PropertyMapEntry**)aEntries, &aAny );
return aAny;
}
void SAL_CALL PropertySetHelper::addPropertyChangeListener( const ::rtl::OUString& /*aPropertyName*/, const Reference< XPropertyChangeListener >& /*xListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::removePropertyChangeListener( const ::rtl::OUString& /*aPropertyName*/, const Reference< XPropertyChangeListener >& /*aListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::addVetoableChangeListener( const ::rtl::OUString& /*PropertyName*/, const Reference< XVetoableChangeListener >& /*aListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::removeVetoableChangeListener( const ::rtl::OUString& /*PropertyName*/, const Reference< XVetoableChangeListener >& /*aListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
// XMultiPropertySet
void SAL_CALL PropertySetHelper::setPropertyValues( const Sequence< ::rtl::OUString >& aPropertyNames, const Sequence< Any >& aValues ) throw(PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
const sal_Int32 nCount = aPropertyNames.getLength();
if( nCount != aValues.getLength() )
throw IllegalArgumentException();
if( nCount )
{
PropertyMapEntry** pEntries = new PropertyMapEntry*[nCount+1];
const OUString* pNames = aPropertyNames.getConstArray();
sal_Bool bUnknown = sal_False;
sal_Int32 n;
for( n = 0; !bUnknown && ( n < nCount ); n++, pNames++ )
{
pEntries[n] = mp->find( *pNames );
bUnknown = NULL == pEntries[n];
}
if( !bUnknown )
_setPropertyValues( (const PropertyMapEntry**)pEntries, aValues.getConstArray() );
delete pEntries;
if( bUnknown )
throw UnknownPropertyException();
}
}
Sequence< Any > SAL_CALL PropertySetHelper::getPropertyValues( const Sequence< ::rtl::OUString >& aPropertyNames ) throw(RuntimeException)
{
const sal_Int32 nCount = aPropertyNames.getLength();
Sequence< Any > aValues;
if( nCount )
{
PropertyMapEntry** pEntries = new PropertyMapEntry*[nCount+1];
const OUString* pNames = aPropertyNames.getConstArray();
sal_Bool bUnknown = sal_False;
sal_Int32 n;
for( n = 0; !bUnknown && ( n < nCount ); n++, pNames++ )
{
pEntries[n] = mp->find( *pNames );
bUnknown = NULL == pEntries[n];
}
if( !bUnknown )
_getPropertyValues( (const PropertyMapEntry**)pEntries, aValues.getArray() );
delete pEntries;
if( bUnknown )
throw UnknownPropertyException();
}
return aValues;
}
void SAL_CALL PropertySetHelper::addPropertiesChangeListener( const Sequence< ::rtl::OUString >& /*aPropertyNames*/, const Reference< XPropertiesChangeListener >& /*xListener*/ ) throw(RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::removePropertiesChangeListener( const Reference< XPropertiesChangeListener >& /*xListener*/ ) throw(RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::firePropertiesChangeEvent( const Sequence< ::rtl::OUString >& /*aPropertyNames*/, const Reference< XPropertiesChangeListener >& /*xListener*/ ) throw(RuntimeException)
{
// todo
}
// XPropertyState
PropertyState SAL_CALL PropertySetHelper::getPropertyState( const ::rtl::OUString& PropertyName ) throw(UnknownPropertyException, RuntimeException)
{
PropertyMapEntry* aEntries[2];
aEntries[0] = mp->find( PropertyName );
if( aEntries[0] == NULL )
throw UnknownPropertyException();
aEntries[1] = NULL;
PropertyState aState;
_getPropertyStates( (const PropertyMapEntry**)aEntries, &aState );
return aState;
}
Sequence< PropertyState > SAL_CALL PropertySetHelper::getPropertyStates( const Sequence< ::rtl::OUString >& aPropertyName ) throw(UnknownPropertyException, RuntimeException)
{
const sal_Int32 nCount = aPropertyName.getLength();
Sequence< PropertyState > aStates( nCount );
if( nCount )
{
const OUString* pNames = aPropertyName.getConstArray();
sal_Bool bUnknown = sal_False;
PropertyMapEntry** pEntries = new PropertyMapEntry*[nCount+1];
sal_Int32 n;
for( n = 0; !bUnknown && (n < nCount); n++, pNames++ )
{
pEntries[n] = mp->find( *pNames );
bUnknown = NULL == pEntries[n];
}
pEntries[nCount] = NULL;
if( !bUnknown )
_getPropertyStates( (const PropertyMapEntry**)pEntries, aStates.getArray() );
delete pEntries;
if( bUnknown )
throw UnknownPropertyException();
}
return aStates;
}
void SAL_CALL PropertySetHelper::setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(UnknownPropertyException, RuntimeException)
{
PropertyMapEntry *pEntry = mp->find( PropertyName );
if( NULL == pEntry )
throw UnknownPropertyException();
_setPropertyToDefault( pEntry );
}
Any SAL_CALL PropertySetHelper::getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
PropertyMapEntry* pEntry = mp->find( aPropertyName );
if( NULL == pEntry )
throw UnknownPropertyException();
return _getPropertyDefault( pEntry );
}
void PropertySetHelper::_getPropertyStates( const utl::PropertyMapEntry** /*ppEntries*/, PropertyState* /*pStates*/ ) throw(UnknownPropertyException )
{
DBG_ERROR( "you have to implement this yourself!" );
}
void PropertySetHelper::_setPropertyToDefault( const utl::PropertyMapEntry* /*pEntry*/ ) throw(UnknownPropertyException )
{
DBG_ERROR( "you have to implement this yourself!" );
}
Any PropertySetHelper::_getPropertyDefault( const utl::PropertyMapEntry* /*pEntry*/ ) throw(UnknownPropertyException, WrappedTargetException )
{
DBG_ERROR( "you have to implement this yourself!" );
Any aAny;
return aAny;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.16); FILE MERGED 2006/09/01 17:56:25 kaib 1.3.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysethelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 01:28:32 $
*
* 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_unotools.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "unotools/propertysetinfo.hxx"
#include "unotools/propertysethelper.hxx"
///////////////////////////////////////////////////////////////////////
using namespace ::utl;
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
namespace utl
{
class PropertySetHelperImpl
{
public:
PropertyMapEntry* find( const OUString& aName ) const throw();
PropertySetInfo* mpInfo;
};
}
PropertyMapEntry* PropertySetHelperImpl::find( const OUString& aName ) const throw()
{
PropertyMap::const_iterator aIter = mpInfo->getPropertyMap()->find( aName );
if( mpInfo->getPropertyMap()->end() != aIter )
{
return (*aIter).second;
}
else
{
return NULL;
}
}
///////////////////////////////////////////////////////////////////////
PropertySetHelper::PropertySetHelper( utl::PropertySetInfo* pInfo ) throw()
{
mp = new PropertySetHelperImpl;
mp->mpInfo = pInfo;
pInfo->acquire();
}
PropertySetHelper::~PropertySetHelper() throw()
{
mp->mpInfo->release();
delete mp;
}
// XPropertySet
Reference< XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo( ) throw(RuntimeException)
{
return mp->mpInfo;
}
void SAL_CALL PropertySetHelper::setPropertyValue( const ::rtl::OUString& aPropertyName, const Any& aValue ) throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
PropertyMapEntry* aEntries[2];
aEntries[0] = mp->find( aPropertyName );
if( NULL == aEntries[0] )
throw UnknownPropertyException();
aEntries[1] = NULL;
_setPropertyValues( (const PropertyMapEntry**)aEntries, &aValue );
}
Any SAL_CALL PropertySetHelper::getPropertyValue( const ::rtl::OUString& PropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
PropertyMapEntry* aEntries[2];
aEntries[0] = mp->find( PropertyName );
if( NULL == aEntries[0] )
throw UnknownPropertyException();
aEntries[1] = NULL;
Any aAny;
_getPropertyValues( (const PropertyMapEntry**)aEntries, &aAny );
return aAny;
}
void SAL_CALL PropertySetHelper::addPropertyChangeListener( const ::rtl::OUString& /*aPropertyName*/, const Reference< XPropertyChangeListener >& /*xListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::removePropertyChangeListener( const ::rtl::OUString& /*aPropertyName*/, const Reference< XPropertyChangeListener >& /*aListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::addVetoableChangeListener( const ::rtl::OUString& /*PropertyName*/, const Reference< XVetoableChangeListener >& /*aListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::removeVetoableChangeListener( const ::rtl::OUString& /*PropertyName*/, const Reference< XVetoableChangeListener >& /*aListener*/ ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
// todo
}
// XMultiPropertySet
void SAL_CALL PropertySetHelper::setPropertyValues( const Sequence< ::rtl::OUString >& aPropertyNames, const Sequence< Any >& aValues ) throw(PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
const sal_Int32 nCount = aPropertyNames.getLength();
if( nCount != aValues.getLength() )
throw IllegalArgumentException();
if( nCount )
{
PropertyMapEntry** pEntries = new PropertyMapEntry*[nCount+1];
const OUString* pNames = aPropertyNames.getConstArray();
sal_Bool bUnknown = sal_False;
sal_Int32 n;
for( n = 0; !bUnknown && ( n < nCount ); n++, pNames++ )
{
pEntries[n] = mp->find( *pNames );
bUnknown = NULL == pEntries[n];
}
if( !bUnknown )
_setPropertyValues( (const PropertyMapEntry**)pEntries, aValues.getConstArray() );
delete pEntries;
if( bUnknown )
throw UnknownPropertyException();
}
}
Sequence< Any > SAL_CALL PropertySetHelper::getPropertyValues( const Sequence< ::rtl::OUString >& aPropertyNames ) throw(RuntimeException)
{
const sal_Int32 nCount = aPropertyNames.getLength();
Sequence< Any > aValues;
if( nCount )
{
PropertyMapEntry** pEntries = new PropertyMapEntry*[nCount+1];
const OUString* pNames = aPropertyNames.getConstArray();
sal_Bool bUnknown = sal_False;
sal_Int32 n;
for( n = 0; !bUnknown && ( n < nCount ); n++, pNames++ )
{
pEntries[n] = mp->find( *pNames );
bUnknown = NULL == pEntries[n];
}
if( !bUnknown )
_getPropertyValues( (const PropertyMapEntry**)pEntries, aValues.getArray() );
delete pEntries;
if( bUnknown )
throw UnknownPropertyException();
}
return aValues;
}
void SAL_CALL PropertySetHelper::addPropertiesChangeListener( const Sequence< ::rtl::OUString >& /*aPropertyNames*/, const Reference< XPropertiesChangeListener >& /*xListener*/ ) throw(RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::removePropertiesChangeListener( const Reference< XPropertiesChangeListener >& /*xListener*/ ) throw(RuntimeException)
{
// todo
}
void SAL_CALL PropertySetHelper::firePropertiesChangeEvent( const Sequence< ::rtl::OUString >& /*aPropertyNames*/, const Reference< XPropertiesChangeListener >& /*xListener*/ ) throw(RuntimeException)
{
// todo
}
// XPropertyState
PropertyState SAL_CALL PropertySetHelper::getPropertyState( const ::rtl::OUString& PropertyName ) throw(UnknownPropertyException, RuntimeException)
{
PropertyMapEntry* aEntries[2];
aEntries[0] = mp->find( PropertyName );
if( aEntries[0] == NULL )
throw UnknownPropertyException();
aEntries[1] = NULL;
PropertyState aState;
_getPropertyStates( (const PropertyMapEntry**)aEntries, &aState );
return aState;
}
Sequence< PropertyState > SAL_CALL PropertySetHelper::getPropertyStates( const Sequence< ::rtl::OUString >& aPropertyName ) throw(UnknownPropertyException, RuntimeException)
{
const sal_Int32 nCount = aPropertyName.getLength();
Sequence< PropertyState > aStates( nCount );
if( nCount )
{
const OUString* pNames = aPropertyName.getConstArray();
sal_Bool bUnknown = sal_False;
PropertyMapEntry** pEntries = new PropertyMapEntry*[nCount+1];
sal_Int32 n;
for( n = 0; !bUnknown && (n < nCount); n++, pNames++ )
{
pEntries[n] = mp->find( *pNames );
bUnknown = NULL == pEntries[n];
}
pEntries[nCount] = NULL;
if( !bUnknown )
_getPropertyStates( (const PropertyMapEntry**)pEntries, aStates.getArray() );
delete pEntries;
if( bUnknown )
throw UnknownPropertyException();
}
return aStates;
}
void SAL_CALL PropertySetHelper::setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(UnknownPropertyException, RuntimeException)
{
PropertyMapEntry *pEntry = mp->find( PropertyName );
if( NULL == pEntry )
throw UnknownPropertyException();
_setPropertyToDefault( pEntry );
}
Any SAL_CALL PropertySetHelper::getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
PropertyMapEntry* pEntry = mp->find( aPropertyName );
if( NULL == pEntry )
throw UnknownPropertyException();
return _getPropertyDefault( pEntry );
}
void PropertySetHelper::_getPropertyStates( const utl::PropertyMapEntry** /*ppEntries*/, PropertyState* /*pStates*/ ) throw(UnknownPropertyException )
{
DBG_ERROR( "you have to implement this yourself!" );
}
void PropertySetHelper::_setPropertyToDefault( const utl::PropertyMapEntry* /*pEntry*/ ) throw(UnknownPropertyException )
{
DBG_ERROR( "you have to implement this yourself!" );
}
Any PropertySetHelper::_getPropertyDefault( const utl::PropertyMapEntry* /*pEntry*/ ) throw(UnknownPropertyException, WrappedTargetException )
{
DBG_ERROR( "you have to implement this yourself!" );
Any aAny;
return aAny;
}
<|endoftext|> |
<commit_before>#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_alternative.hpp>
#include <iostream>
#include <string>
#include "db.h"
#include "lefLayerPropParser.h"
#include "lefin.h"
namespace lefTechLayerCutSpacing {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
using ascii::char_;
using boost::fusion::at_c;
using boost::spirit::ascii::space_type;
using boost::spirit::ascii::string;
using boost::spirit::qi::lit;
using qi::lexeme;
using qi::double_;
using qi::int_;
// using qi::_1;
using ascii::space;
using phoenix::ref;
void setCutSpacing(double value,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
parser->curRule = odb::dbTechLayerCutSpacingRule::create(layer);
parser->curRule->setCutSpacing(lefin->dbdist(value));
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::NONE);
}
void setCenterToCenter(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setCenterToCenter(true);
}
void setSameMetal(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setSameMetal(true);
}
void setSameNet(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setSameNet(true);
}
void setSameVia(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setSameVias(true);
}
void addMaxXYSubRule(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::MAXXY);
}
void addLayerSubRule(
boost::fusion::vector<std::string, boost::optional<std::string>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::LAYER);
auto name = at_c<0>(params);
auto secondLayer = layer->getTech()->findLayer(name.c_str());
if (secondLayer != nullptr)
parser->curRule->setSecondLayer(secondLayer);
else
return;
auto stack = at_c<1>(params);
if (stack.is_initialized())
parser->curRule->setStack(true);
}
void addAdjacentCutsSubRule(
boost::fusion::vector<std::string,
boost::optional<int>,
double,
boost::optional<std::string>,
boost::optional<std::string>,
boost::optional<std::string>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::ADJACENTCUTS);
// auto var = at_c<0>(params);
auto cuts = at_c<0>(params);
auto aligned = at_c<1>(params);
auto within = at_c<2>(params);
auto except_same_pgnet = at_c<3>(params);
auto className = at_c<4>(params);
auto sideParallelOverLap = at_c<5>(params);
uint cuts_int = (uint) cuts[0] - (uint) '0';
parser->curRule->setAdjacentCuts(cuts_int);
if (aligned.is_initialized()) {
parser->curRule->setExactAligned(true);
parser->curRule->setNumCuts(aligned.value());
}
parser->curRule->setWithin(lefin->dbdist(within));
if (except_same_pgnet.is_initialized())
parser->curRule->setExceptSamePgnet(true);
if (className.is_initialized()) {
auto cutClassName = className.value();
auto cutClass = layer->findTechLayerCutClassRule(cutClassName.c_str());
if (cutClass != nullptr)
parser->curRule->setCutClass(cutClass);
}
if (sideParallelOverLap.is_initialized())
parser->curRule->setSideParallelOverlap(true);
}
void addParallelOverlapSubRule(boost::optional<std::string> except,
odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::PARALLELOVERLAP);
if (except.is_initialized()) {
auto exceptWhat = except.value();
if (exceptWhat == "EXCEPTSAMENET")
parser->curRule->setExceptSameNet(true);
else if (exceptWhat == "EXCEPTSAMEMETAL")
parser->curRule->setExceptSameMetal(true);
else if (exceptWhat == "EXCEPTSAMEVIA")
parser->curRule->setExceptSameVia(true);
}
}
void addParallelWithinSubRule(
boost::fusion::vector<double, boost::optional<std::string>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::PARALLELWITHIN);
parser->curRule->setWithin(lefin->dbdist(at_c<0>(params)));
auto except = at_c<1>(params);
if (except.is_initialized())
parser->curRule->setExceptSameNet(true);
}
void addSameMetalSharedEdgeSubRule(
boost::fusion::vector<double,
boost::optional<std::string>,
boost::optional<std::string>,
boost::optional<std::string>,
boost::optional<int>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::SAMEMETALSHAREDEDGE);
auto within = at_c<0>(params);
auto ABOVE = at_c<1>(params);
auto CUTCLASS = at_c<2>(params);
auto EXCEPTTWOEDGES = at_c<3>(params);
auto EXCEPTSAMEVIA = at_c<4>(params);
parser->curRule->setWithin(lefin->dbdist(within));
if (ABOVE.is_initialized())
parser->curRule->setAbove(true);
if (CUTCLASS.is_initialized()) {
auto cutClassName = CUTCLASS.value();
auto cutClass = layer->findTechLayerCutClassRule(cutClassName.c_str());
if (cutClass != nullptr)
parser->curRule->setCutClass(cutClass);
}
if (EXCEPTTWOEDGES.is_initialized())
parser->curRule->setExceptTwoEdges(true);
if (EXCEPTSAMEVIA.is_initialized()) {
parser->curRule->setExceptSameVia(true);
auto numCut = EXCEPTSAMEVIA.value();
parser->curRule->setNumCuts(numCut);
}
}
void addAreaSubRule(double value,
odb::lefTechLayerCutSpacingParser* parser,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::AREA);
parser->curRule->setCutArea(lefin->dbdist(value));
}
template <typename Iterator>
bool parse(Iterator first,
Iterator last,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
qi::rule<Iterator, std::string(), ascii::space_type> _string;
_string %= lexeme[+(char_ - ' ')];
qi::rule<std::string::iterator, space_type> LAYER
= (lit("LAYER") >> _string
>> -string("STACK"))[boost::bind(&addLayerSubRule, _1, parser, layer)];
qi::rule<std::string::iterator, space_type> ADJACENTCUTS
= (lit("ADJACENTCUTS") >> (string("1") | string("2") | string("3"))
>> -(lit("EXACTALIGNED") >> int_) >> lit("WITHIN") >> double_
>> -string("EXCEPTSAMEPGNET") >> -(lit("CUTCLASS") >> _string)
>> -string("SIDEPARALLELOVERLAP"))[boost::bind(
&addAdjacentCutsSubRule, _1, parser, layer, lefin)];
qi::rule<std::string::iterator, space_type> PARALLELOVERLAP
= (lit("PARALLELOVERLAP")
>> -(string("EXCEPTSAMENET") | string("EXCEPTSAMEMETAL")
| string("EXCEPTSAMEVIA")))
[boost::bind(&addParallelOverlapSubRule, _1, parser)];
qi::rule<std::string::iterator, space_type> PARALLELWITHIN
= (lit("PARALLELWITHIN") >> double_
>> -string("EXCEPTSAMENET"))[boost::bind(
&addParallelWithinSubRule, _1, parser, lefin)];
qi::rule<std::string::iterator, space_type> SAMEMETALSHAREDEDGE
= (lit("SAMEMETALSHAREDEDGE") >> double_ >> -string("ABOVE")
>> -(lit("CUTCLASS") >> _string) >> -string("EXCEPTTWOEDGES")
>> -(lit("EXCEPTSAMEVIA") >> int_))[boost::bind(
&addSameMetalSharedEdgeSubRule, _1, parser, layer, lefin)];
qi::rule<std::string::iterator, space_type> AREA
= (lit("AREA")
>> double_)[boost::bind(&addAreaSubRule, _1, parser, lefin)];
qi::rule<std::string::iterator, space_type> LEF58_SPACING = (+(
lit("SPACING")
>> double_[boost::bind(&setCutSpacing, _1, parser, layer, lefin)]
>> -(lit("MAXXY")[boost::bind(&addMaxXYSubRule, parser)]
| -lit("CENTERTOCENTER")[boost::bind(&setCenterToCenter, parser)]
>> -(lit("SAMENET")[boost::bind(&setSameNet, parser)]
| lit("SAMEMETAL")[boost::bind(&setSameMetal, parser)]
| lit("SAMEVIA")[boost::bind(&setSameVia, parser)])
>> -(LAYER))
>> lit(";")));
bool valid = qi::phrase_parse(first, last, LEF58_SPACING, space);
if (!valid && parser->curRule != nullptr)
odb::dbTechLayerCutSpacingRule::destroy(parser->curRule);
return valid && first == last;
}
} // namespace lefTechLayerCutSpacing
namespace odb {
bool lefTechLayerCutSpacingParser::parse(std::string s,
odb::dbTechLayer* layer,
odb::lefin* l)
{
return lefTechLayerCutSpacing::parse(s.begin(), s.end(), this, layer, l);
}
} // namespace odb
<commit_msg>CutSpacing Parse All Types<commit_after>#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_alternative.hpp>
#include <iostream>
#include <string>
#include "db.h"
#include "lefLayerPropParser.h"
#include "lefin.h"
namespace lefTechLayerCutSpacing {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
using ascii::char_;
using boost::fusion::at_c;
using boost::spirit::ascii::space_type;
using boost::spirit::ascii::string;
using boost::spirit::qi::lit;
using qi::lexeme;
using qi::double_;
using qi::int_;
// using qi::_1;
using ascii::space;
using phoenix::ref;
void setCutSpacing(double value,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
parser->curRule = odb::dbTechLayerCutSpacingRule::create(layer);
parser->curRule->setCutSpacing(lefin->dbdist(value));
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::NONE);
}
void setCenterToCenter(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setCenterToCenter(true);
}
void setSameMetal(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setSameMetal(true);
}
void setSameNet(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setSameNet(true);
}
void setSameVia(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setSameVias(true);
}
void addMaxXYSubRule(odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::MAXXY);
}
void addLayerSubRule(
boost::fusion::vector<std::string, boost::optional<std::string>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::LAYER);
auto name = at_c<0>(params);
auto secondLayer = layer->getTech()->findLayer(name.c_str());
if (secondLayer != nullptr)
parser->curRule->setSecondLayer(secondLayer);
else
return;
auto stack = at_c<1>(params);
if (stack.is_initialized())
parser->curRule->setStack(true);
}
void addAdjacentCutsSubRule(
boost::fusion::vector<std::string,
boost::optional<int>,
double,
boost::optional<std::string>,
boost::optional<std::string>,
boost::optional<std::string>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::ADJACENTCUTS);
// auto var = at_c<0>(params);
auto cuts = at_c<0>(params);
auto aligned = at_c<1>(params);
auto within = at_c<2>(params);
auto except_same_pgnet = at_c<3>(params);
auto className = at_c<4>(params);
auto sideParallelOverLap = at_c<5>(params);
uint cuts_int = (uint) cuts[0] - (uint) '0';
parser->curRule->setAdjacentCuts(cuts_int);
if (aligned.is_initialized()) {
parser->curRule->setExactAligned(true);
parser->curRule->setNumCuts(aligned.value());
}
parser->curRule->setWithin(lefin->dbdist(within));
if (except_same_pgnet.is_initialized())
parser->curRule->setExceptSamePgnet(true);
if (className.is_initialized()) {
auto cutClassName = className.value();
auto cutClass = layer->findTechLayerCutClassRule(cutClassName.c_str());
if (cutClass != nullptr)
parser->curRule->setCutClass(cutClass);
}
if (sideParallelOverLap.is_initialized())
parser->curRule->setSideParallelOverlap(true);
}
void addParallelOverlapSubRule(boost::optional<std::string> except,
odb::lefTechLayerCutSpacingParser* parser)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::PARALLELOVERLAP);
if (except.is_initialized()) {
auto exceptWhat = except.value();
if (exceptWhat == "EXCEPTSAMENET")
parser->curRule->setExceptSameNet(true);
else if (exceptWhat == "EXCEPTSAMEMETAL")
parser->curRule->setExceptSameMetal(true);
else if (exceptWhat == "EXCEPTSAMEVIA")
parser->curRule->setExceptSameVia(true);
}
}
void addParallelWithinSubRule(
boost::fusion::vector<double, boost::optional<std::string>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::PARALLELWITHIN);
parser->curRule->setWithin(lefin->dbdist(at_c<0>(params)));
auto except = at_c<1>(params);
if (except.is_initialized())
parser->curRule->setExceptSameNet(true);
}
void addSameMetalSharedEdgeSubRule(
boost::fusion::vector<double,
boost::optional<std::string>,
boost::optional<std::string>,
boost::optional<std::string>,
boost::optional<int>>& params,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::SAMEMETALSHAREDEDGE);
auto within = at_c<0>(params);
auto ABOVE = at_c<1>(params);
auto CUTCLASS = at_c<2>(params);
auto EXCEPTTWOEDGES = at_c<3>(params);
auto EXCEPTSAMEVIA = at_c<4>(params);
parser->curRule->setWithin(lefin->dbdist(within));
if (ABOVE.is_initialized())
parser->curRule->setAbove(true);
if (CUTCLASS.is_initialized()) {
auto cutClassName = CUTCLASS.value();
auto cutClass = layer->findTechLayerCutClassRule(cutClassName.c_str());
if (cutClass != nullptr)
parser->curRule->setCutClass(cutClass);
}
if (EXCEPTTWOEDGES.is_initialized())
parser->curRule->setExceptTwoEdges(true);
if (EXCEPTSAMEVIA.is_initialized()) {
parser->curRule->setExceptSameVia(true);
auto numCut = EXCEPTSAMEVIA.value();
parser->curRule->setNumCuts(numCut);
}
}
void addAreaSubRule(double value,
odb::lefTechLayerCutSpacingParser* parser,
odb::lefin* lefin)
{
parser->curRule->setType(
odb::dbTechLayerCutSpacingRule::CutSpacingType::AREA);
parser->curRule->setCutArea(lefin->dbdist(value));
}
template <typename Iterator>
bool parse(Iterator first,
Iterator last,
odb::lefTechLayerCutSpacingParser* parser,
odb::dbTechLayer* layer,
odb::lefin* lefin)
{
qi::rule<Iterator, std::string(), ascii::space_type> _string;
_string %= lexeme[+(char_ - ' ')];
qi::rule<std::string::iterator, space_type> LAYER
= (lit("LAYER") >> _string
>> -string("STACK"))[boost::bind(&addLayerSubRule, _1, parser, layer)];
qi::rule<std::string::iterator, space_type> ADJACENTCUTS
= (lit("ADJACENTCUTS") >> (string("1") | string("2") | string("3"))
>> -(lit("EXACTALIGNED") >> int_) >> lit("WITHIN") >> double_
>> -string("EXCEPTSAMEPGNET") >> -(lit("CUTCLASS") >> _string)
>> -string("SIDEPARALLELOVERLAP"))[boost::bind(
&addAdjacentCutsSubRule, _1, parser, layer, lefin)];
qi::rule<std::string::iterator, space_type> PARALLELOVERLAP
= (lit("PARALLELOVERLAP")
>> -(string("EXCEPTSAMENET") | string("EXCEPTSAMEMETAL")
| string("EXCEPTSAMEVIA")))
[boost::bind(&addParallelOverlapSubRule, _1, parser)];
qi::rule<std::string::iterator, space_type> PARALLELWITHIN
= (lit("PARALLELWITHIN") >> double_
>> -string("EXCEPTSAMENET"))[boost::bind(
&addParallelWithinSubRule, _1, parser, lefin)];
qi::rule<std::string::iterator, space_type> SAMEMETALSHAREDEDGE
= (lit("SAMEMETALSHAREDEDGE") >> double_ >> -string("ABOVE")
>> -(lit("CUTCLASS") >> _string) >> -string("EXCEPTTWOEDGES")
>> -(lit("EXCEPTSAMEVIA") >> int_))[boost::bind(
&addSameMetalSharedEdgeSubRule, _1, parser, layer, lefin)];
qi::rule<std::string::iterator, space_type> AREA
= (lit("AREA")
>> double_)[boost::bind(&addAreaSubRule, _1, parser, lefin)];
qi::rule<std::string::iterator, space_type> LEF58_SPACING = (+(
lit("SPACING")
>> double_[boost::bind(&setCutSpacing, _1, parser, layer, lefin)]
>> -(lit("MAXXY")[boost::bind(&addMaxXYSubRule, parser)]
| -lit("CENTERTOCENTER")[boost::bind(&setCenterToCenter, parser)]
>> -(lit("SAMENET")[boost::bind(&setSameNet, parser)]
| lit("SAMEMETAL")[boost::bind(&setSameMetal, parser)]
| lit("SAMEVIA")[boost::bind(&setSameVia, parser)])
>> -(LAYER | ADJACENTCUTS | PARALLELOVERLAP | PARALLELWITHIN | SAMEMETALSHAREDEDGE | AREA))
>> lit(";")));
bool valid = qi::phrase_parse(first, last, LEF58_SPACING, space);
if (!valid && parser->curRule != nullptr)
odb::dbTechLayerCutSpacingRule::destroy(parser->curRule);
return valid && first == last;
}
} // namespace lefTechLayerCutSpacing
namespace odb {
bool lefTechLayerCutSpacingParser::parse(std::string s,
odb::dbTechLayer* layer,
odb::lefin* l)
{
return lefTechLayerCutSpacing::parse(s.begin(), s.end(), this, layer, l);
}
} // namespace odb
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <EEPROM.h>
#include <avr/pgmspace.h>
void setup() {
pinMode(8, OUTPUT);
digitalWrite(8, HIGH); // turn on the radio
Serial.begin(115200);
}
void printHex(Stream& str, uint16_t value, int digits) {
static const char hex[] PROGMEM = "0123456789ABCDEF";
value = value << ((4 - digits) * 4);
for (int d = 0; d < digits; d++) {
str.print((char)pgm_read_byte_near(hex + ((value >> 12) & 0xf)));
value = value << 4;
}
}
void dump(int addr) {
printHex(Serial, addr, 4);
Serial.print(": ");
for (int n = 0; n < 16; n++) {
printHex(Serial, EEPROM.read(addr + n), 2);
Serial.print(" ");
}
Serial.println();
}
void processBuffer(const char* buffer) {
Serial.println("");
Serial.println(buffer);
dump(0);
}
const size_t bufferSize = 32;
char inputBuffer[bufferSize + 1];
size_t inputIndex = 0;
void loop() {
int in = Serial.read();
if (in > 0) {
if (in == 8 && inputIndex > 0) {
inputIndex--;
Serial.print((char)in);
}
if (in == '\r') {
inputBuffer[inputIndex] = 0;
processBuffer(inputBuffer);
inputIndex = 0;
} else {
if (in >= ' ' && inputIndex < bufferSize) {
inputBuffer[inputIndex++] = (char)in;
Serial.print((char)in);
}
}
}
}<commit_msg>adding hex parser<commit_after>#include <Arduino.h>
#include <EEPROM.h>
#include <avr/pgmspace.h>
void setup() {
pinMode(8, OUTPUT);
digitalWrite(8, HIGH); // turn on the radio
Serial.begin(115200);
}
void printHex(Stream& str, uint16_t value, int digits) {
static const char hex[] PROGMEM = "0123456789ABCDEF";
value = value << ((4 - digits) * 4);
for (int d = 0; d < digits; d++) {
str.print((char)pgm_read_byte_near(hex + ((value >> 12) & 0xf)));
value = value << 4;
}
}
int parseHex(const char* str, uint16_t& value) {
int count = 0;
value = 0;
while (true) {
if (*str >= '0' && *str <= '9') {
value <<= 4;
value += *str++ - '0';
} else if (*str >= 'a' && *str <= 'f') {
value <<= 4;
value += *str++ - 'a' + 0xa;
} else if (*str >= 'A' && *str <= 'F') {
value <<= 4;
value += *str++ - 'A' + 0xa;
} else {
return count;
}
}
}
void dump(int addr) {
printHex(Serial, addr, 4);
Serial.print(": ");
for (int n = 0; n < 16; n++) {
printHex(Serial, EEPROM.read(addr + n), 2);
Serial.print(" ");
}
Serial.println();
}
void processBuffer(const char* buffer) {
uint16_t val;
parseHex(buffer, val);
Serial.println("");
printHex(Serial, val, 4);
Serial.println("");
// Serial.println(buffer);
dump(0);
}
const size_t bufferSize = 32;
char inputBuffer[bufferSize + 1];
size_t inputIndex = 0;
void loop() {
int in = Serial.read();
if (in > 0) {
if (in == 8 && inputIndex > 0) {
inputIndex--;
Serial.print((char)in);
}
if (in == '\r') {
inputBuffer[inputIndex] = 0;
processBuffer(inputBuffer);
inputIndex = 0;
} else {
if (in >= ' ' && inputIndex < bufferSize) {
inputBuffer[inputIndex++] = (char)in;
Serial.print((char)in);
}
}
}
}<|endoftext|> |
<commit_before>#ifndef _EIGEN3_HDF5_HPP
#define _EIGEN3_HDF5_HPP
#include <array>
#include <cassert>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <vector>
//#include <hdf5.h>
#include <H5Cpp.h>
#include <Eigen/Dense>
namespace EigenHDF5
{
template <typename T>
H5::PredType get_datatype (void);
template <>
H5::PredType get_datatype<float> (void)
{
return H5::PredType::NATIVE_FLOAT;
}
template <>
H5::PredType get_datatype<double> (void)
{
return H5::PredType::NATIVE_DOUBLE;
}
template <>
H5::PredType get_datatype<long double> (void)
{
return H5::PredType::NATIVE_LDOUBLE;
}
template <>
H5::PredType get_datatype<int> (void)
{
return H5::PredType::NATIVE_INT;
}
template <>
H5::PredType get_datatype<unsigned int> (void)
{
return H5::PredType::NATIVE_UINT;
}
// see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename Derived>
void save (H5::H5File &file, const std::string &name, const Eigen::EigenBase<Derived> &mat)
{
typedef typename Derived::Scalar Scalar;
const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat);
const std::array<hsize_t, 2> dimensions = { {
static_cast<hsize_t>(mat.rows()),
static_cast<hsize_t>(mat.cols())
} };
H5::DataSpace dataspace(dimensions.size(), dimensions.data());
H5::PredType datatype = get_datatype<Scalar>();
H5::DataSet dataset = file.createDataSet(name, datatype, dataspace);
dataset.write(row_major_mat.data(), datatype);
}
template <typename Derived>
void load (H5::H5File &file, const std::string &name, const Eigen::DenseBase<Derived> &mat)
{
typedef typename Derived::Scalar Scalar;
H5::DataSet dataset = file.openDataSet(name);
H5::DataSpace dataspace = dataset.getSpace();
const std::size_t ndims = dataspace.getSimpleExtentNdims();
assert(ndims > 0);
std::array<hsize_t, 2> dimensions;
dimensions[1] = 1; // in case it's 1D
if (ndims > dimensions.size()) {
throw std::runtime_error("HDF5 array has too many dimensions.");
}
dataspace.getSimpleExtentDims(dimensions.data());
const hsize_t rows = dimensions[0], cols = dimensions[1];
std::vector<Scalar> data(rows * cols);
const H5::PredType datatype = get_datatype<Scalar>();
dataset.read(data.data(), datatype, dataspace);
// see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat);
mat_.derived().resize(rows, cols);
mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols);
}
} // namespace EigenHDF5
#endif
<commit_msg>inline get_datatype() so we can call it from multiple files<commit_after>#ifndef _EIGEN3_HDF5_HPP
#define _EIGEN3_HDF5_HPP
#include <array>
#include <cassert>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <vector>
//#include <hdf5.h>
#include <H5Cpp.h>
#include <Eigen/Dense>
namespace EigenHDF5
{
template <typename T>
static H5::PredType get_datatype (void);
template <>
inline H5::PredType get_datatype<float> (void)
{
return H5::PredType::NATIVE_FLOAT;
}
template <>
inline H5::PredType get_datatype<double> (void)
{
return H5::PredType::NATIVE_DOUBLE;
}
template <>
inline H5::PredType get_datatype<long double> (void)
{
return H5::PredType::NATIVE_LDOUBLE;
}
template <>
inline H5::PredType get_datatype<int> (void)
{
return H5::PredType::NATIVE_INT;
}
template <>
inline H5::PredType get_datatype<unsigned int> (void)
{
return H5::PredType::NATIVE_UINT;
}
// see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename Derived>
void save (H5::H5File &file, const std::string &name, const Eigen::EigenBase<Derived> &mat)
{
typedef typename Derived::Scalar Scalar;
const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat);
const std::array<hsize_t, 2> dimensions = { {
static_cast<hsize_t>(mat.rows()),
static_cast<hsize_t>(mat.cols())
} };
H5::DataSpace dataspace(dimensions.size(), dimensions.data());
H5::PredType datatype = get_datatype<Scalar>();
H5::DataSet dataset = file.createDataSet(name, datatype, dataspace);
dataset.write(row_major_mat.data(), datatype);
}
template <typename Derived>
void load (H5::H5File &file, const std::string &name, const Eigen::DenseBase<Derived> &mat)
{
typedef typename Derived::Scalar Scalar;
H5::DataSet dataset = file.openDataSet(name);
H5::DataSpace dataspace = dataset.getSpace();
const std::size_t ndims = dataspace.getSimpleExtentNdims();
assert(ndims > 0);
std::array<hsize_t, 2> dimensions;
dimensions[1] = 1; // in case it's 1D
if (ndims > dimensions.size()) {
throw std::runtime_error("HDF5 array has too many dimensions.");
}
dataspace.getSimpleExtentDims(dimensions.data());
const hsize_t rows = dimensions[0], cols = dimensions[1];
std::vector<Scalar> data(rows * cols);
const H5::PredType datatype = get_datatype<Scalar>();
dataset.read(data.data(), datatype, dataspace);
// see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat);
mat_.derived().resize(rows, cols);
mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols);
}
} // namespace EigenHDF5
#endif
<|endoftext|> |
<commit_before>#include "Pythia8/Pythia.h"
#include "Pythia8Plugins/FastJet3.h"
#include <stdio.h>
#include <stdlib.h>
using namespace Pythia8;
void JetAnalysis( Event& event, const char* fname,
double R, double JpTMin, double etaMax, double TR, double TJpTMin ) {
// Find leading pT jet in event with anti-kt algorithm (params R, JpTMin, etaMax).
// Find subjets by re-cluster jet using kt algorith (params TR, TJpTMin).
// Write jet properties, constituents to fname_jets.csv, fname_csts.csv.
// Set up FastJet jet finder.
fastjet::JetDefinition jetDef( fastjet::genkt_algorithm, R, -1 );
std::vector <fastjet::PseudoJet> fjInputs;
fjInputs.resize(0);
// Begin FastJet analysis: extract particles from event record.
Vec4 pTemp;
for ( int i = 0; i < event.size(); ++i ) if ( event[i].isFinal() ) {
// Require visible particles inside detector.
if ( !event[i].isVisible() ) continue;
if ( etaMax < 20. && abs(event[i].eta()) > etaMax ) continue;
// Create a PseudoJet from the complete Pythia particle.
fastjet::PseudoJet particleTemp = event[i];
// Store acceptable particles as input to Fastjet.
// Conversion to PseudoJet is performed automatically
// with the help of the code in FastJet3.h.
fjInputs.push_back( particleTemp );
}
// Run Fastjet algorithm and sort jets in pT order.
vector <fastjet::PseudoJet> inclusiveJets, sortedJets;
fastjet::ClusterSequence clustSeq( fjInputs, jetDef ); // Segmentation fault here sometimes.
inclusiveJets = clustSeq.inclusive_jets( JpTMin );
sortedJets = sorted_by_pt(inclusiveJets);
// Get details and constituents from leading jet.
vector <fastjet::PseudoJet> Jconstits = sortedJets[0].constituents();
double JpT = sortedJets[0].perp();
double Jeta = sortedJets[0].eta();
double Jphi = sortedJets[0].phi_std();
int Jsize = Jconstits.size();
// Open output files.
char fjetsName[10+strlen(fname)];
strcpy( fjetsName, fname );
strcat( fjetsName, "_jets.csv" );
FILE *f_jets = fopen(fjetsName, "w");
char fcstsName[10+strlen(fname)];
strcpy( fcstsName, fname );
strcat( fcstsName, "_csts.csv" );
FILE *f_csts = fopen(fcstsName, "w");
// Output leading jet details.
fprintf( f_jets, "%g, %g, %g, %i\n", JpT, Jeta, Jphi, Jsize );
// Set up FastJet jet trimmer.
fastjet::JetDefinition TjetDef( fastjet::genkt_algorithm, TR, 1 );
std::vector <fastjet::PseudoJet> TfjInputs;
TfjInputs.resize(0);
for ( int i = 0; i < Jsize; ++i ) {
// Store constituents from leading jet.
TfjInputs.push_back( Jconstits[i] );
}
// Run Fastjet trimmer on leading jet.
vector <fastjet::PseudoJet> TinclusiveJets, TsortedJets;
fastjet::ClusterSequence TclustSeq( TfjInputs, TjetDef );
TinclusiveJets = TclustSeq.inclusive_jets( JpT*TJpTMin );
TsortedJets = sorted_by_pt(TinclusiveJets);
// Get details and constituents from subjets.
for ( int j = 0; j < int( TsortedJets.size() ); ++j ) {
Jconstits = TsortedJets[j].constituents();
JpT = TsortedJets[j].perp();
Jeta = TsortedJets[j].eta();
Jphi = TsortedJets[j].phi_std();
Jsize = Jconstits.size();
// Output subjet details.
fprintf( f_jets, "%g, %g, %g, %i\n", JpT, Jeta, Jphi, Jsize );
for (int i = 0; i < Jsize; ++i) {
double cE = Jconstits[i].E();
double cEt = Jconstits[i].Et();
double ceta = Jconstits[i].eta();
double cphi = Jconstits[i].phi_std();
// Output constituent details.
fprintf( f_csts, "%g, %g, %g, %g\n", cE, cEt, ceta, cphi );
}
fprintf( f_csts, "\n" );
}
// Close output files.
fclose( f_jets );
fclose( f_csts );
}
int main() {
// Generates W' events:
// W' -> W Z; W -> q q', Z -> nu nu.
// Performs jet analysis required to form jet images.
// *** Need to specify location of Pythia xmldoc directory (xmldocDir)! ***
// Main program settings.
double eCM = 13000.0;
int nEvent = 1;
int nAbort = 3;
const char* xmldocDir = "/Users/barney800/Tools/Pythia8/share/Pythia8/xmldoc";
// Parameters for FastJet analyses.
double R = 0.6; // Jet size
double JpTMin = 12.5; // Min jet pT
double etaMax = 5.0; // Pseudorapidity range of detector
double TR = 0.3; // Subjet size
double TJpTMin = 0.05; // Min subjet pT (fraction of jet pT)
const char* fname = "test"; // Filename for outputs.
// Other parameters.
double WpTMin = 250.0; // Min W pT
double WpTMax = 300.0; // Max W pT
// Generator. Shorthand for the event.
Pythia pythia( xmldocDir );
Event& event = pythia.event;
// Use variable random seed: -1 = default, 0 = clock.
pythia.settings.flag("Random:setSeed", "on");
pythia.settings.mode("Random:seed", 0);
// Set up beams: p p is default so only need set energy.
pythia.settings.parm("Beams:eCM", eCM);
// W' pair production.
pythia.readString("NewGaugeBoson:ffbar2Wprime = on");
pythia.readString("34:m0 = 700.0");
// W' decays.
pythia.readString("Wprime:coup2WZ = 1.0");
pythia.readString("34:onMode = off");
pythia.readString("34:onIfAny = 24");
// W and Z decays.
pythia.readString("24:onMode = off");
pythia.readString("24:onIfAny = 1 2 3 4 5 6");
pythia.readString("23:onMode = off");
pythia.readString("23:onIfAny = 12 14 16");
// Switch on/off particle data and event listings.
pythia.readString("Init:showChangedSettings = off");
pythia.readString("Init:showChangedParticleData = off");
pythia.readString("Next:numberShowInfo = 1");
pythia.readString("Next:numberShowProcess = 1");
pythia.readString("Next:numberShowEvent = 0");
// Initialize.
pythia.init();
// Begin event loop.
int iAbort = 0;
int iEvent = 0;
while ( iEvent < nEvent ) {
// Generate event. Quit if failure.
if ( !pythia.next() ) {
if ( ++iAbort < nAbort ) continue;
cout << " Event generation aborted prematurely, owing to error.\n";
break;
}
// Check W pT.
int checkWpT = 0;
double WpT = 0.0;
double Weta = 0.0;
double Wphi = 0.0;
for ( int i = 0; i < event.size(); ++i ) {
if ( event[i].id() == 24 || event[i].id() == -24 ) {
WpT = abs(event[i].pT());
Weta = event[i].eta();
Wphi = event[i].phi();
if ( WpT < WpTMin || WpT > WpTMax ) {
break;
}
else {
checkWpT = 1;
break;
}
}
}
if ( checkWpT == 0 ) continue;
++iEvent;
// Perform jet analysis.
JetAnalysis( event, fname, R, JpTMin, etaMax, TR, TJpTMin );
// End of event loop.
}
// Done.
return 0;
}
<commit_msg>WprimeJetGen bugfix<commit_after>#include "Pythia8/Pythia.h"
#include "Pythia8Plugins/FastJet3.h"
#include <stdio.h>
#include <stdlib.h>
using namespace Pythia8;
void JetAnalysis( Event& event, const char* fname,
double R, double JpTMin, double etaMax, double TR, double TJpTMin ) {
// Find leading pT jet in event with anti-kt algorithm (params R, JpTMin, etaMax).
// Find subjets by re-cluster jet using kt algorith (params TR, TJpTMin).
// Write jet properties, constituents to fname_jets.csv, fname_csts.csv.
// Set up FastJet jet finder.
fastjet::JetDefinition jetDef( fastjet::genkt_algorithm, R, -1 );
std::vector <fastjet::PseudoJet> fjInputs;
fjInputs.resize(0);
// Begin FastJet analysis: extract particles from event record.
Vec4 pTemp;
for ( int i = 0; i < event.size(); ++i ) if ( event[i].isFinal() ) {
// Require visible particles inside detector.
if ( !event[i].isVisible() ) continue;
if ( etaMax < 20. && abs(event[i].eta()) > etaMax ) continue;
// Create a PseudoJet from the complete Pythia particle.
fastjet::PseudoJet particleTemp = event[i];
// Store acceptable particles as input to Fastjet.
// Conversion to PseudoJet is performed automatically
// with the help of the code in FastJet3.h.
fjInputs.push_back( particleTemp );
}
// Run Fastjet algorithm and sort jets in pT order.
vector <fastjet::PseudoJet> inclusiveJets, sortedJets;
fastjet::ClusterSequence clustSeq( fjInputs, jetDef ); // Segmentation fault here sometimes.
inclusiveJets = clustSeq.inclusive_jets( JpTMin );
sortedJets = sorted_by_pt(inclusiveJets);
// Get details and constituents from leading jet.
vector <fastjet::PseudoJet> Jconstits = sortedJets[0].constituents();
double JpT = sortedJets[0].perp();
double Jeta = sortedJets[0].eta();
double Jphi = sortedJets[0].phi_std();
int Jsize = Jconstits.size();
// Open output files.
char fjetsName[10+strlen(fname)];
strcpy( fjetsName, fname );
strcat( fjetsName, "_jets.csv" );
FILE *f_jets = fopen(fjetsName, "w");
char fcstsName[10+strlen(fname)];
strcpy( fcstsName, fname );
strcat( fcstsName, "_csts.csv" );
FILE *f_csts = fopen(fcstsName, "w");
// Output leading jet details.
fprintf( f_jets, "%g, %g, %g, %i\n", JpT, Jeta, Jphi, Jsize );
// Set up FastJet jet trimmer.
fastjet::JetDefinition TjetDef( fastjet::genkt_algorithm, TR, 1 );
std::vector <fastjet::PseudoJet> TfjInputs;
TfjInputs.resize(0);
for ( int i = 0; i < Jsize; ++i ) {
// Store constituents from leading jet.
TfjInputs.push_back( Jconstits[i] );
}
// Run Fastjet trimmer on leading jet.
vector <fastjet::PseudoJet> TinclusiveJets, TsortedJets;
fastjet::ClusterSequence TclustSeq( TfjInputs, TjetDef );
TinclusiveJets = TclustSeq.inclusive_jets( JpT*TJpTMin );
TsortedJets = sorted_by_pt(TinclusiveJets);
// Get details and constituents from subjets.
for ( int j = 0; j < int( TsortedJets.size() ); ++j ) {
Jconstits = TsortedJets[j].constituents();
JpT = TsortedJets[j].perp();
Jeta = TsortedJets[j].eta();
Jphi = TsortedJets[j].phi_std();
Jsize = Jconstits.size();
// Output subjet details.
fprintf( f_jets, "%g, %g, %g, %i\n", JpT, Jeta, Jphi, Jsize );
for (int i = 0; i < Jsize; ++i) {
double cE = Jconstits[i].E();
double cEt = Jconstits[i].Et();
double ceta = Jconstits[i].eta();
double cphi = Jconstits[i].phi_std();
// Output constituent details.
fprintf( f_csts, "%g, %g, %g, %g\n", cE, cEt, ceta, cphi );
}
fprintf( f_csts, "\n" );
}
// Close output files.
fclose( f_jets );
fclose( f_csts );
}
int main() {
// Generates W' events:
// W' -> W Z; W -> q q', Z -> nu nu.
// Performs jet analysis required to form jet images.
// *** Need to specify location of Pythia xmldoc directory (xmldocDir)! ***
// Main program settings.
double eCM = 14000.0;
int nEvent = 1;
int nAbort = 3;
const char* xmldocDir = "/Users/barney800/Tools/Pythia8/share/Pythia8/xmldoc";
// Parameters for FastJet analyses.
double R = 0.6; // Jet size
double JpTMin = 12.5; // Min jet pT
double etaMax = 5.0; // Pseudorapidity range of detector
double TR = 0.3; // Subjet size
double TJpTMin = 0.05; // Min subjet pT (fraction of jet pT)
const char* fname = "test"; // Filename for outputs.
// Other parameters.
double WpTMin = 250.0; // Min W pT
double WpTMax = 300.0; // Max W pT
// Generator. Shorthand for the event.
Pythia pythia( xmldocDir );
Event& event = pythia.event;
// Use variable random seed: -1 = default, 0 = clock.
pythia.settings.flag("Random:setSeed", "on");
pythia.settings.mode("Random:seed", 0);
// Set up beams: p p is default so only need set energy.
pythia.settings.parm("Beams:eCM", eCM);
// W' pair production.
pythia.readString("NewGaugeBoson:ffbar2Wprime = on");
pythia.readString("34:m0 = 700.0");
// W' decays.
pythia.readString("Wprime:coup2WZ = 1.0");
pythia.readString("34:onMode = off");
pythia.readString("34:onIfAny = 24");
// W and Z decays.
pythia.readString("24:onMode = off");
pythia.readString("24:onIfAny = 1 2 3 4 5 6");
pythia.readString("23:onMode = off");
pythia.readString("23:onIfAny = 12 14 16");
// Switch on/off particle data and event listings.
pythia.readString("Init:showChangedSettings = off");
pythia.readString("Init:showChangedParticleData = off");
pythia.readString("Next:numberShowInfo = 1");
pythia.readString("Next:numberShowProcess = 1");
pythia.readString("Next:numberShowEvent = 0");
// Initialize.
pythia.init();
// Begin event loop.
int iAbort = 0;
int iEvent = 0;
while ( iEvent < nEvent ) {
// Generate event. Quit if failure.
if ( !pythia.next() ) {
if ( ++iAbort < nAbort ) continue;
cout << " Event generation aborted prematurely, owing to error.\n";
break;
}
// Check W pT.
int checkWpT = 0;
for ( int i = 0; i < event.size(); ++i ) {
if ( event[i].id() == 24 || event[i].id() == -24 ) {
double WpT = event[i].pT();
if ( WpT < WpTMin || WpT > WpTMax ) {
break;
}
else {
checkWpT = 1;
break;
}
}
}
if ( checkWpT == 0 ) continue;
++iEvent;
// Perform jet analysis.
JetAnalysis( event, fname, R, JpTMin, etaMax, TR, TJpTMin );
// End of event loop.
}
// Done.
return 0;
}
<|endoftext|> |
<commit_before>#include "player.h"
#include <iostream>
#include "exit.h"
Player::Player(const char* name, const char* description, Room* parent) : Creature(name, description, parent)
{
Type = PLAYER;
}
Player::~Player()
{
}
void Player::Look(const vector<string> &args) const
{
if (args.size() > 1)
{
if (args[1] == "me")
{
Creature::Look();
}
else
{
string arg = args[1];
Entity* entity = parent->Find(arg);
if (entity != nullptr)
{
entity->Look();
}
}
}
else
{
CurrentRoom()->Look();
}
}
void Player::Inventory() const
{
list<Entity*> inventory;
FindAll(ITEM, inventory);
if (inventory.size() == 0)
{
cout << "You don't own anything :(" << endl;
}
else
{
cout << "You own:" << endl;
for (Entity* item : inventory)
{
cout << " - " << item->Name;
if (item == armour)
{
cout << " (as armour)";
}
else if (item == weapon)
{
cout << " (as weapon)";
}
cout << endl;
}
}
}
bool Player::Pick(const arglist& args)
{
bool ret = true;
if (args.size() == 2)
{
Entity* item = parent->Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(this);
cout << "You picked up " << item->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << endl;
}
}
else if (args.size() == 4)
{
Entity* container = parent->Find(args[3], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = Find(args[3], ITEM);
}
if (container == nullptr)
{
cout << "Couldn't find the container " << args[3] << endl;
}
else
{
Entity* item = container->Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(this);
cout << "You picked up " << item->Name << " from " << container->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << " in container " << args[3] << endl;
}
}
}
else
{
ret = false;
}
return ret;
}
bool Player::Drop(const arglist& args)
{
bool ret = true;
if (args.size() == 2)
{
Entity* item = Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(parent);
cout << "You dropped " << item->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << "in your inventory." << endl;
}
}
else if (args.size() == 4)
{
Item* container = (Item*)parent->Find(args[3], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[3], ITEM);
}
if (container == nullptr)
{
cout << "Couldn't find the container " << args[3] << endl;
}
else if (container->Closed)
{
cout << "The " << args[3] << " is closed!" << endl;
}
else
{
Entity* item = Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(container);
cout << "You dropped " << item->Name << " into " << container->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << " in your inventory." << endl;
}
}
}
else
{
ret = false;
}
return ret;
}
bool Player::Move(const arglist& args)
{
Exit* exit = CurrentRoom()->GetExitAt(args[0]);
if (exit == nullptr)
{
cout << "There's no exit in that direction (" << args[0] << ")." << endl;
}
else
{
if (exit->Locked)
{
cout << "This exit is locked!" << endl;
}
else if (exit->Closed)
{
cout << "This exit is closed!." << endl;
}
else
{
cout << "You go through the " << args[0] << " exit..." << endl;
Room* newRoom = exit->GetExitDestinationFrom(CurrentRoom());
ChangeParent(newRoom);
newRoom->Look();
}
}
return true;
}
void Player::Open(const arglist& args)
{
if (args.size() >= 3 && args[2] == "door")
{
Exit* exit = CurrentRoom()->GetExitAt(args[1]);
if (exit == nullptr)
{
cout << "There's no exit in that direction (" << args[1] << ")." << endl;
}
else if (exit->Locked)
{
cout << "That exit is locked with a key!" << endl;
}
else if (!exit->Closed)
{
cout << "That exit is already opened!" << endl;
}
else
{
exit->Closed = false;
cout << "You opened the " << args[1] << " exit!" << endl;
}
}
else
{
Item* container = (Item*)CurrentRoom()->Find(args[1], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[1], ITEM);
}
if (container == nullptr || !container->Openable)
{
cout << "There's no openable object called " << args[1] << endl;
}
else if (!container->Closed)
{
cout << "This container is already opened!" << endl;
}
else
{
container->Closed = false;
cout << "You opened " << args[1] << "!" << endl;
}
}
}
void Player::Close(const arglist& args)
{
if (args.size() >= 3 && args[2] == "door")
{
Exit* exit = CurrentRoom()->GetExitAt(args[1]);
if (exit == nullptr)
{
cout << "There's no exit in that direction (" << args[1] << ")." << endl;
}
else if (exit->Closed)
{
cout << "That exit is already closed!" << endl;
}
else
{
exit->Closed = true;
cout << "You closed the " << args[1] << " exit!" << endl;
}
}
else
{
Item* container = (Item*)CurrentRoom()->Find(args[1], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[1], ITEM);
}
if (container == nullptr || !container->Openable)
{
cout << "There's no closeable object called " << args[1] << endl;
}
else if (container->Closed)
{
cout << "This container is already closed!" << endl;
}
else
{
container->Closed = true;
cout << "You closed " << args[1] << "!" << endl;
}
}
}
void Player::UnLock(const arglist& args)
{
}
void Player::Lock(const arglist& args)
{
}
<commit_msg>Fix pickup error<commit_after>#include "player.h"
#include <iostream>
#include "exit.h"
Player::Player(const char* name, const char* description, Room* parent) : Creature(name, description, parent)
{
Type = PLAYER;
}
Player::~Player()
{
}
void Player::Look(const vector<string> &args) const
{
if (args.size() > 1)
{
if (args[1] == "me")
{
Creature::Look();
}
else
{
string arg = args[1];
Entity* entity = parent->Find(arg);
if (entity != nullptr)
{
entity->Look();
}
}
}
else
{
CurrentRoom()->Look();
}
}
void Player::Inventory() const
{
list<Entity*> inventory;
FindAll(ITEM, inventory);
if (inventory.size() == 0)
{
cout << "You don't own anything :(" << endl;
}
else
{
cout << "You own:" << endl;
for (Entity* item : inventory)
{
cout << " - " << item->Name;
if (item == armour)
{
cout << " (as armour)";
}
else if (item == weapon)
{
cout << " (as weapon)";
}
cout << endl;
}
}
}
bool Player::Pick(const arglist& args)
{
bool ret = true;
if (args.size() == 2)
{
Entity* item = parent->Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(this);
cout << "You picked up " << item->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << endl;
}
}
else if (args.size() == 4)
{
Item* container = (Item*)parent->Find(args[3], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[3], ITEM);
}
if (container == nullptr)
{
cout << "Couldn't find the container " << args[3] << endl;
}
else if (container->Closed)
{
cout << "The " << args[3] << " is closed!" << endl;
}
else
{
Entity* item = container->Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(this);
cout << "You picked up " << item->Name << " from " << container->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << " in container " << args[3] << endl;
}
}
}
else
{
ret = false;
}
return ret;
}
bool Player::Drop(const arglist& args)
{
bool ret = true;
if (args.size() == 2)
{
Entity* item = Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(parent);
cout << "You dropped " << item->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << "in your inventory." << endl;
}
}
else if (args.size() == 4)
{
Item* container = (Item*)parent->Find(args[3], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[3], ITEM);
}
if (container == nullptr)
{
cout << "Couldn't find the container " << args[3] << endl;
}
else if (container->Closed)
{
cout << "The " << args[3] << " is closed!" << endl;
}
else
{
Entity* item = Find(args[1], ITEM);
if (item != nullptr)
{
item->ChangeParent(container);
cout << "You dropped " << item->Name << " into " << container->Name << endl;
}
else
{
cout << "Couldn't find item " << args[1] << " in your inventory." << endl;
}
}
}
else
{
ret = false;
}
return ret;
}
bool Player::Move(const arglist& args)
{
Exit* exit = CurrentRoom()->GetExitAt(args[0]);
if (exit == nullptr)
{
cout << "There's no exit in that direction (" << args[0] << ")." << endl;
}
else
{
if (exit->Locked)
{
cout << "This exit is locked!" << endl;
}
else if (exit->Closed)
{
cout << "This exit is closed!." << endl;
}
else
{
cout << "You go through the " << args[0] << " exit..." << endl;
Room* newRoom = exit->GetExitDestinationFrom(CurrentRoom());
ChangeParent(newRoom);
newRoom->Look();
}
}
return true;
}
void Player::Open(const arglist& args)
{
if (args.size() >= 3 && args[2] == "door")
{
Exit* exit = CurrentRoom()->GetExitAt(args[1]);
if (exit == nullptr)
{
cout << "There's no exit in that direction (" << args[1] << ")." << endl;
}
else if (exit->Locked)
{
cout << "That exit is locked with a key!" << endl;
}
else if (!exit->Closed)
{
cout << "That exit is already opened!" << endl;
}
else
{
exit->Closed = false;
cout << "You opened the " << args[1] << " exit!" << endl;
}
}
else
{
Item* container = (Item*)CurrentRoom()->Find(args[1], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[1], ITEM);
}
if (container == nullptr || !container->Openable)
{
cout << "There's no openable object called " << args[1] << endl;
}
else if (!container->Closed)
{
cout << "This container is already opened!" << endl;
}
else
{
container->Closed = false;
cout << "You opened " << args[1] << "!" << endl;
}
}
}
void Player::Close(const arglist& args)
{
if (args.size() >= 3 && args[2] == "door")
{
Exit* exit = CurrentRoom()->GetExitAt(args[1]);
if (exit == nullptr)
{
cout << "There's no exit in that direction (" << args[1] << ")." << endl;
}
else if (exit->Closed)
{
cout << "That exit is already closed!" << endl;
}
else
{
exit->Closed = true;
cout << "You closed the " << args[1] << " exit!" << endl;
}
}
else
{
Item* container = (Item*)CurrentRoom()->Find(args[1], ITEM);
if (container == nullptr) // If it is not in the room, try to find it in the inventory
{
container = (Item*)Find(args[1], ITEM);
}
if (container == nullptr || !container->Openable)
{
cout << "There's no closeable object called " << args[1] << endl;
}
else if (container->Closed)
{
cout << "This container is already closed!" << endl;
}
else
{
container->Closed = true;
cout << "You closed " << args[1] << "!" << endl;
}
}
}
void Player::UnLock(const arglist& args)
{
}
void Player::Lock(const arglist& args)
{
}
<|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/info_bubble_gtk.h"
#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>
#include "app/gfx/path.h"
#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/gfx/gtk_util.h"
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
namespace {
// The height of the arrow, and the width will be about twice the height.
const int kArrowSize = 5;
// Number of pixels to the start of the arrow from the edge of the window.
const int kArrowX = 13;
// Number of pixels between the tip of the arrow and the region we're
// pointing to.
const int kArrowToContentPadding = -6;
// We draw flat diagonal corners, each corner is an NxN square.
const int kCornerSize = 3;
// Margins around the content.
const int kTopMargin = kArrowSize + kCornerSize + 6;
const int kBottomMargin = kCornerSize + 6;
const int kLeftMargin = kCornerSize + 6;
const int kRightMargin = kCornerSize + 6;
const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xff, 0xff, 0xff);
const GdkColor kFrameColor = GDK_COLOR_RGB(0x63, 0x63, 0x63);
const gchar* kInfoBubbleToplevelKey = "__INFO_BUBBLE_TOPLEVEL__";
enum FrameType {
FRAME_MASK,
FRAME_STROKE,
};
// Make the points for our polygon frame, either for fill (the mask), or for
// when we stroke the border. NOTE: This seems a bit overcomplicated, but it
// requires a bunch of careful fudging to get the pixels rasterized exactly
// where we want them, the arrow to have a 1 pixel point, etc.
// TODO(deanm): Windows draws with Skia and uses some PNG images for the
// corners. This is a lot more work, but they get anti-aliasing.
std::vector<GdkPoint> MakeFramePolygonPoints(int width,
int height,
FrameType type) {
using gtk_util::MakeBidiGdkPoint;
std::vector<GdkPoint> points;
bool ltr = l10n_util::GetTextDirection() == l10n_util::LEFT_TO_RIGHT;
// If we have a stroke, we have to offset some of our points by 1 pixel.
// We have to inset by 1 pixel when we draw horizontal lines that are on the
// bottom or when we draw vertical lines that are closer to the end (end is
// right for ltr).
int y_off = (type == FRAME_MASK) ? 0 : -1;
// We use this one for LTR.
int x_off_l = ltr ? y_off : 0;
// We use this one for RTL.
int x_off_r = !ltr ? -y_off : 0;
// Top left corner.
points.push_back(MakeBidiGdkPoint(
x_off_r, kArrowSize + kCornerSize - 1, width, ltr));
points.push_back(MakeBidiGdkPoint(
kCornerSize + x_off_r - 1, kArrowSize, width, ltr));
// The arrow.
points.push_back(MakeBidiGdkPoint(
kArrowX - kArrowSize + x_off_r, kArrowSize, width, ltr));
points.push_back(MakeBidiGdkPoint(
kArrowX + x_off_r, 0, width, ltr));
points.push_back(MakeBidiGdkPoint(
kArrowX + 1 + x_off_l, 0, width, ltr));
points.push_back(MakeBidiGdkPoint(
kArrowX + kArrowSize + 1 + x_off_l, kArrowSize, width, ltr));
// Top right corner.
points.push_back(MakeBidiGdkPoint(
width - kCornerSize + 1 + x_off_l, kArrowSize, width, ltr));
points.push_back(MakeBidiGdkPoint(
width + x_off_l, kArrowSize + kCornerSize - 1, width, ltr));
// Bottom right corner.
points.push_back(MakeBidiGdkPoint(
width + x_off_l, height - kCornerSize, width, ltr));
points.push_back(MakeBidiGdkPoint(
width - kCornerSize + x_off_r, height + y_off, width, ltr));
// Bottom left corner.
points.push_back(MakeBidiGdkPoint(
kCornerSize + x_off_l, height + y_off, width, ltr));
points.push_back(MakeBidiGdkPoint(
x_off_r, height - kCornerSize, width, ltr));
return points;
}
gboolean HandleExpose(GtkWidget* widget,
GdkEventExpose* event,
gpointer unused) {
GdkDrawable* drawable = GDK_DRAWABLE(event->window);
GdkGC* gc = gdk_gc_new(drawable);
gdk_gc_set_rgb_fg_color(gc, &kFrameColor);
// Stroke the frame border.
std::vector<GdkPoint> points = MakeFramePolygonPoints(
widget->allocation.width, widget->allocation.height, FRAME_STROKE);
gdk_draw_polygon(drawable, gc, FALSE, &points[0], points.size());
g_object_unref(gc);
return FALSE; // Propagate so our children paint, etc.
}
} // namespace
// static
InfoBubbleGtk* InfoBubbleGtk::Show(GtkWindow* transient_toplevel,
const gfx::Rect& rect,
GtkWidget* content,
GtkThemeProvider* provider,
InfoBubbleGtkDelegate* delegate) {
InfoBubbleGtk* bubble = new InfoBubbleGtk(provider);
bubble->Init(transient_toplevel, rect, content);
bubble->set_delegate(delegate);
return bubble;
}
InfoBubbleGtk::InfoBubbleGtk(GtkThemeProvider* provider)
: delegate_(NULL),
window_(NULL),
theme_provider_(provider),
accel_group_(gtk_accel_group_new()),
screen_x_(0),
screen_y_(0) {
}
InfoBubbleGtk::~InfoBubbleGtk() {
g_object_unref(accel_group_);
}
void InfoBubbleGtk::Init(GtkWindow* transient_toplevel,
const gfx::Rect& rect,
GtkWidget* content) {
DCHECK(!window_);
rect_ = rect;
window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
// Mark the info bubble as a utility window so it doesn't show up in the
// taskbar.
gtk_window_set_type_hint(GTK_WINDOW(window_), GDK_WINDOW_TYPE_HINT_UTILITY);
gtk_window_set_transient_for(GTK_WINDOW(window_), transient_toplevel);
gtk_window_set_decorated(GTK_WINDOW(window_), FALSE);
gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
gtk_widget_set_app_paintable(window_, TRUE);
// Have GTK double buffer around the expose signal.
gtk_widget_set_double_buffered(window_, TRUE);
// Make sure that our window can be focused.
GTK_WIDGET_SET_FLAGS(window_, GTK_CAN_FOCUS);
// Attach our accelerator group to the window with an escape accelerator.
gtk_accel_group_connect(accel_group_, GDK_Escape,
static_cast<GdkModifierType>(0), static_cast<GtkAccelFlags>(0),
g_cclosure_new(G_CALLBACK(&HandleEscapeThunk), this, NULL));
gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group_);
GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(alignment),
kTopMargin, kBottomMargin,
kLeftMargin, kRightMargin);
gtk_container_add(GTK_CONTAINER(alignment), content);
gtk_container_add(GTK_CONTAINER(window_), alignment);
// GtkWidget only exposes the bitmap mask interface. Use GDK to more
// efficently mask a GdkRegion. Make sure the window is realized during
// HandleSizeAllocate, so the mask can be applied to the GdkWindow.
gtk_widget_realize(window_);
UpdateScreenX();
screen_y_ = rect.y() + rect.height() + kArrowToContentPadding;
// For RTL, we will have to move the window again when it is allocated, but
// this should be somewhat close to its final position.
gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_);
GtkRequisition req;
gtk_widget_size_request(window_, &req);
gtk_widget_add_events(window_, GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK);
g_signal_connect(window_, "expose-event",
G_CALLBACK(HandleExpose), NULL);
g_signal_connect(window_, "size-allocate",
G_CALLBACK(HandleSizeAllocateThunk), this);
g_signal_connect(window_, "configure-event",
G_CALLBACK(&HandleConfigureThunk), this);
g_signal_connect(window_, "button-press-event",
G_CALLBACK(&HandleButtonPressThunk), this);
g_signal_connect(window_, "destroy",
G_CALLBACK(&HandleDestroyThunk), this);
// Set some data which helps the browser know whether it should appear
// active.
g_object_set_data(G_OBJECT(window_->window), kInfoBubbleToplevelKey,
transient_toplevel);
gtk_widget_show_all(window_);
// Make sure our window has focus, is brought to the top, etc.
gtk_window_present(GTK_WINDOW(window_));
// We add a GTK (application level) grab. This means we will get all
// keyboard and mouse events for our application, even if they were delivered
// on another window. This allows us to close when the user clicks outside
// of the info bubble. We don't use an X grab since that would steal
// keystrokes from your window manager, prevent you from interacting with
// other applications, etc.
//
// Before adding the grab, we need to ensure that the bubble is added
// to the window group of the top level window. This ensures that the
// grab only affects the current browser window, and not all the open
// browser windows in the application.
gtk_window_group_add_window(gtk_window_get_group(transient_toplevel),
GTK_WINDOW(window_));
gtk_grab_add(window_);
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
theme_provider_->InitThemesFor(this);
}
void InfoBubbleGtk::UpdateScreenX() {
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
screen_x_ = rect_.x() + (rect_.width() / 2) - window_->allocation.width
+ kArrowX;
}
else {
screen_x_ = rect_.x() + (rect_.width() / 2) - kArrowX;
}
}
void InfoBubbleGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(type.value, NotificationType::BROWSER_THEME_CHANGED);
if (theme_provider_->UseGtkTheme()) {
gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, NULL);
} else {
// Set the background color, so we don't need to paint it manually.
gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, &kBackgroundColor);
}
}
// static
GtkWindow* InfoBubbleGtk::GetToplevelForInfoBubble(
const GdkWindow* bubble_window) {
if (!bubble_window)
return NULL;
return reinterpret_cast<GtkWindow*>(
g_object_get_data(G_OBJECT(bubble_window), kInfoBubbleToplevelKey));
}
void InfoBubbleGtk::Close(bool closed_by_escape) {
// Notify the delegate that we're about to close. This gives the chance
// to save state / etc from the hosted widget before it's destroyed.
if (delegate_)
delegate_->InfoBubbleClosing(this, closed_by_escape);
DCHECK(window_);
gtk_widget_destroy(window_);
// |this| has been deleted, see HandleDestroy.
}
gboolean InfoBubbleGtk::HandleEscape() {
Close(true); // Close by escape.
return TRUE;
}
// When our size is initially allocated or changed, we need to recompute
// and apply our shape mask region.
void InfoBubbleGtk::HandleSizeAllocate() {
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
UpdateScreenX();
gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_);
}
DCHECK(window_->allocation.x == 0 && window_->allocation.y == 0);
std::vector<GdkPoint> points = MakeFramePolygonPoints(
window_->allocation.width, window_->allocation.height, FRAME_MASK);
GdkRegion* mask_region = gdk_region_polygon(&points[0],
points.size(),
GDK_EVEN_ODD_RULE);
gdk_window_shape_combine_region(window_->window, mask_region, 0, 0);
gdk_region_destroy(mask_region);
}
gboolean InfoBubbleGtk::HandleConfigure(GdkEventConfigure* event) {
// If the window is moved someplace besides where we want it, move it back.
// TODO(deanm): In the end, I will probably remove this code and just let
// the user move around the bubble like a normal dialog. I want to try
// this for now and see if it causes problems when any window managers.
if (event->x != screen_x_ || event->y != screen_y_)
gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_);
return FALSE;
}
gboolean InfoBubbleGtk::HandleButtonPress(GdkEventButton* event) {
// If we got a click in our own window, that's ok.
if (event->window == window_->window)
return FALSE; // Propagate.
// Otherwise we had a click outside of our window, close ourself.
Close();
return TRUE;
}
gboolean InfoBubbleGtk::HandleDestroy() {
// We are self deleting, we have a destroy signal setup to catch when we
// destroy the widget manually, or the window was closed via X. This will
// delete the InfoBubbleGtk object.
delete this;
return FALSE; // Propagate.
}
<commit_msg>Revert "Set the info bubble popups as _NET_WM_WINDOW_TYPE_UTILITY so they" It caused a window frame to be drawn around the info bubble under sawfish.<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/info_bubble_gtk.h"
#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>
#include "app/gfx/path.h"
#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/gfx/gtk_util.h"
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
namespace {
// The height of the arrow, and the width will be about twice the height.
const int kArrowSize = 5;
// Number of pixels to the start of the arrow from the edge of the window.
const int kArrowX = 13;
// Number of pixels between the tip of the arrow and the region we're
// pointing to.
const int kArrowToContentPadding = -6;
// We draw flat diagonal corners, each corner is an NxN square.
const int kCornerSize = 3;
// Margins around the content.
const int kTopMargin = kArrowSize + kCornerSize + 6;
const int kBottomMargin = kCornerSize + 6;
const int kLeftMargin = kCornerSize + 6;
const int kRightMargin = kCornerSize + 6;
const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xff, 0xff, 0xff);
const GdkColor kFrameColor = GDK_COLOR_RGB(0x63, 0x63, 0x63);
const gchar* kInfoBubbleToplevelKey = "__INFO_BUBBLE_TOPLEVEL__";
enum FrameType {
FRAME_MASK,
FRAME_STROKE,
};
// Make the points for our polygon frame, either for fill (the mask), or for
// when we stroke the border. NOTE: This seems a bit overcomplicated, but it
// requires a bunch of careful fudging to get the pixels rasterized exactly
// where we want them, the arrow to have a 1 pixel point, etc.
// TODO(deanm): Windows draws with Skia and uses some PNG images for the
// corners. This is a lot more work, but they get anti-aliasing.
std::vector<GdkPoint> MakeFramePolygonPoints(int width,
int height,
FrameType type) {
using gtk_util::MakeBidiGdkPoint;
std::vector<GdkPoint> points;
bool ltr = l10n_util::GetTextDirection() == l10n_util::LEFT_TO_RIGHT;
// If we have a stroke, we have to offset some of our points by 1 pixel.
// We have to inset by 1 pixel when we draw horizontal lines that are on the
// bottom or when we draw vertical lines that are closer to the end (end is
// right for ltr).
int y_off = (type == FRAME_MASK) ? 0 : -1;
// We use this one for LTR.
int x_off_l = ltr ? y_off : 0;
// We use this one for RTL.
int x_off_r = !ltr ? -y_off : 0;
// Top left corner.
points.push_back(MakeBidiGdkPoint(
x_off_r, kArrowSize + kCornerSize - 1, width, ltr));
points.push_back(MakeBidiGdkPoint(
kCornerSize + x_off_r - 1, kArrowSize, width, ltr));
// The arrow.
points.push_back(MakeBidiGdkPoint(
kArrowX - kArrowSize + x_off_r, kArrowSize, width, ltr));
points.push_back(MakeBidiGdkPoint(
kArrowX + x_off_r, 0, width, ltr));
points.push_back(MakeBidiGdkPoint(
kArrowX + 1 + x_off_l, 0, width, ltr));
points.push_back(MakeBidiGdkPoint(
kArrowX + kArrowSize + 1 + x_off_l, kArrowSize, width, ltr));
// Top right corner.
points.push_back(MakeBidiGdkPoint(
width - kCornerSize + 1 + x_off_l, kArrowSize, width, ltr));
points.push_back(MakeBidiGdkPoint(
width + x_off_l, kArrowSize + kCornerSize - 1, width, ltr));
// Bottom right corner.
points.push_back(MakeBidiGdkPoint(
width + x_off_l, height - kCornerSize, width, ltr));
points.push_back(MakeBidiGdkPoint(
width - kCornerSize + x_off_r, height + y_off, width, ltr));
// Bottom left corner.
points.push_back(MakeBidiGdkPoint(
kCornerSize + x_off_l, height + y_off, width, ltr));
points.push_back(MakeBidiGdkPoint(
x_off_r, height - kCornerSize, width, ltr));
return points;
}
gboolean HandleExpose(GtkWidget* widget,
GdkEventExpose* event,
gpointer unused) {
GdkDrawable* drawable = GDK_DRAWABLE(event->window);
GdkGC* gc = gdk_gc_new(drawable);
gdk_gc_set_rgb_fg_color(gc, &kFrameColor);
// Stroke the frame border.
std::vector<GdkPoint> points = MakeFramePolygonPoints(
widget->allocation.width, widget->allocation.height, FRAME_STROKE);
gdk_draw_polygon(drawable, gc, FALSE, &points[0], points.size());
g_object_unref(gc);
return FALSE; // Propagate so our children paint, etc.
}
} // namespace
// static
InfoBubbleGtk* InfoBubbleGtk::Show(GtkWindow* transient_toplevel,
const gfx::Rect& rect,
GtkWidget* content,
GtkThemeProvider* provider,
InfoBubbleGtkDelegate* delegate) {
InfoBubbleGtk* bubble = new InfoBubbleGtk(provider);
bubble->Init(transient_toplevel, rect, content);
bubble->set_delegate(delegate);
return bubble;
}
InfoBubbleGtk::InfoBubbleGtk(GtkThemeProvider* provider)
: delegate_(NULL),
window_(NULL),
theme_provider_(provider),
accel_group_(gtk_accel_group_new()),
screen_x_(0),
screen_y_(0) {
}
InfoBubbleGtk::~InfoBubbleGtk() {
g_object_unref(accel_group_);
}
void InfoBubbleGtk::Init(GtkWindow* transient_toplevel,
const gfx::Rect& rect,
GtkWidget* content) {
DCHECK(!window_);
rect_ = rect;
window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_transient_for(GTK_WINDOW(window_), transient_toplevel);
gtk_window_set_decorated(GTK_WINDOW(window_), FALSE);
gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
gtk_widget_set_app_paintable(window_, TRUE);
// Have GTK double buffer around the expose signal.
gtk_widget_set_double_buffered(window_, TRUE);
// Make sure that our window can be focused.
GTK_WIDGET_SET_FLAGS(window_, GTK_CAN_FOCUS);
// Attach our accelerator group to the window with an escape accelerator.
gtk_accel_group_connect(accel_group_, GDK_Escape,
static_cast<GdkModifierType>(0), static_cast<GtkAccelFlags>(0),
g_cclosure_new(G_CALLBACK(&HandleEscapeThunk), this, NULL));
gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group_);
GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(alignment),
kTopMargin, kBottomMargin,
kLeftMargin, kRightMargin);
gtk_container_add(GTK_CONTAINER(alignment), content);
gtk_container_add(GTK_CONTAINER(window_), alignment);
// GtkWidget only exposes the bitmap mask interface. Use GDK to more
// efficently mask a GdkRegion. Make sure the window is realized during
// HandleSizeAllocate, so the mask can be applied to the GdkWindow.
gtk_widget_realize(window_);
UpdateScreenX();
screen_y_ = rect.y() + rect.height() + kArrowToContentPadding;
// For RTL, we will have to move the window again when it is allocated, but
// this should be somewhat close to its final position.
gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_);
GtkRequisition req;
gtk_widget_size_request(window_, &req);
gtk_widget_add_events(window_, GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK);
g_signal_connect(window_, "expose-event",
G_CALLBACK(HandleExpose), NULL);
g_signal_connect(window_, "size-allocate",
G_CALLBACK(HandleSizeAllocateThunk), this);
g_signal_connect(window_, "configure-event",
G_CALLBACK(&HandleConfigureThunk), this);
g_signal_connect(window_, "button-press-event",
G_CALLBACK(&HandleButtonPressThunk), this);
g_signal_connect(window_, "destroy",
G_CALLBACK(&HandleDestroyThunk), this);
// Set some data which helps the browser know whether it should appear
// active.
g_object_set_data(G_OBJECT(window_->window), kInfoBubbleToplevelKey,
transient_toplevel);
gtk_widget_show_all(window_);
// Make sure our window has focus, is brought to the top, etc.
gtk_window_present(GTK_WINDOW(window_));
// We add a GTK (application level) grab. This means we will get all
// keyboard and mouse events for our application, even if they were delivered
// on another window. This allows us to close when the user clicks outside
// of the info bubble. We don't use an X grab since that would steal
// keystrokes from your window manager, prevent you from interacting with
// other applications, etc.
//
// Before adding the grab, we need to ensure that the bubble is added
// to the window group of the top level window. This ensures that the
// grab only affects the current browser window, and not all the open
// browser windows in the application.
gtk_window_group_add_window(gtk_window_get_group(transient_toplevel),
GTK_WINDOW(window_));
gtk_grab_add(window_);
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
theme_provider_->InitThemesFor(this);
}
void InfoBubbleGtk::UpdateScreenX() {
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
screen_x_ = rect_.x() + (rect_.width() / 2) - window_->allocation.width
+ kArrowX;
}
else {
screen_x_ = rect_.x() + (rect_.width() / 2) - kArrowX;
}
}
void InfoBubbleGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(type.value, NotificationType::BROWSER_THEME_CHANGED);
if (theme_provider_->UseGtkTheme()) {
gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, NULL);
} else {
// Set the background color, so we don't need to paint it manually.
gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, &kBackgroundColor);
}
}
// static
GtkWindow* InfoBubbleGtk::GetToplevelForInfoBubble(
const GdkWindow* bubble_window) {
if (!bubble_window)
return NULL;
return reinterpret_cast<GtkWindow*>(
g_object_get_data(G_OBJECT(bubble_window), kInfoBubbleToplevelKey));
}
void InfoBubbleGtk::Close(bool closed_by_escape) {
// Notify the delegate that we're about to close. This gives the chance
// to save state / etc from the hosted widget before it's destroyed.
if (delegate_)
delegate_->InfoBubbleClosing(this, closed_by_escape);
DCHECK(window_);
gtk_widget_destroy(window_);
// |this| has been deleted, see HandleDestroy.
}
gboolean InfoBubbleGtk::HandleEscape() {
Close(true); // Close by escape.
return TRUE;
}
// When our size is initially allocated or changed, we need to recompute
// and apply our shape mask region.
void InfoBubbleGtk::HandleSizeAllocate() {
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
UpdateScreenX();
gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_);
}
DCHECK(window_->allocation.x == 0 && window_->allocation.y == 0);
std::vector<GdkPoint> points = MakeFramePolygonPoints(
window_->allocation.width, window_->allocation.height, FRAME_MASK);
GdkRegion* mask_region = gdk_region_polygon(&points[0],
points.size(),
GDK_EVEN_ODD_RULE);
gdk_window_shape_combine_region(window_->window, mask_region, 0, 0);
gdk_region_destroy(mask_region);
}
gboolean InfoBubbleGtk::HandleConfigure(GdkEventConfigure* event) {
// If the window is moved someplace besides where we want it, move it back.
// TODO(deanm): In the end, I will probably remove this code and just let
// the user move around the bubble like a normal dialog. I want to try
// this for now and see if it causes problems when any window managers.
if (event->x != screen_x_ || event->y != screen_y_)
gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_);
return FALSE;
}
gboolean InfoBubbleGtk::HandleButtonPress(GdkEventButton* event) {
// If we got a click in our own window, that's ok.
if (event->window == window_->window)
return FALSE; // Propagate.
// Otherwise we had a click outside of our window, close ourself.
Close();
return TRUE;
}
gboolean InfoBubbleGtk::HandleDestroy() {
// We are self deleting, we have a destroy signal setup to catch when we
// destroy the widget manually, or the window was closed via X. This will
// delete the InfoBubbleGtk object.
delete this;
return FALSE; // Propagate.
}
<|endoftext|> |
<commit_before>//============================================================================
// Name : PinballBot.cpp
// Author : Nico Hauser, David Schmid
// Version : 0.1
// Description : A reinforcement learning agent that learns to play pinball
//============================================================================
#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
/**
* Contains all the information of a state
*/
class State{
};
/**
* Gets the expected reward based on a lookup table and the model of the environment
* @param s State The State of which the reward is calculated
* @return double The expected reward
*/
double reward(State s){
return 0.0;
}
/**
* Calculates the expected value the given state will in the next turn and in the future.
* Policies, the reward function and the model of the environment are used to do this calculation.
* @param s State The State of which the value is calculated
* @return double The expected value
*/
double value(State s){
return 0.0;
}
int main() {
boost::numeric::ublas::vector<double> v(3);
v[0] = 10;
std::cout << v[0] << std::endl;
return 0;
}
<commit_msg>Added "Ball" class<commit_after>//============================================================================
// Name : PinballBot.cpp
// Author : Nico Hauser, David Schmid
// Version : 0.1
// Description : A reinforcement learning agent that learns to play pinball
//============================================================================
#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
/**
* Stores information about a ball
*/
class Ball{
private:
boost::numeric::ublas::vector<double> ball_position;
boost::numeric::ublas::vector<double> ball_velocity;
boost::numeric::ublas::vector<double> ball_acceleration;
/**
* Checks if a given vector is valid to use
* @param vector boost::numeric::ublas::vector<double> The vector to check
* @return bool True if the vector is valid,
* false if it isn't
*/
bool is_vector_valid(boost::numeric::ublas::vector<double> vector){
if(vector.size() == 2 || vector.size() == 3){ /* Only 2 and 3 dimensional vectors make sense */
return true;
}
return false;
}
public:
/**
* Constructor without any arguments, defaults to 3-dimensional vector
*/
Ball(){
this->set_ball_position(boost::numeric::ublas::vector<double>(3));
this->set_ball_velocity(boost::numeric::ublas::vector<double>(3));
this->set_ball_acceleration(boost::numeric::ublas::vector<double>(3));
}
Ball(int dimensions){
if(this->is_vector_valid(boost::numeric::ublas::vector<double>(dimensions))){
this->set_ball_position(boost::numeric::ublas::vector<double>(dimensions));
this->set_ball_velocity(boost::numeric::ublas::vector<double>(dimensions));
this->set_ball_acceleration(boost::numeric::ublas::vector<double>(dimensions));
}
}
/**
* Updates the ball position
* @param ball_position boost::numeric::ublas::vector<double> The new ball position
* @return bool True if the variable was successfully updated,
* false if an error occurred
*/
bool set_ball_position(boost::numeric::ublas::vector<double> ball_position){
if(this->is_vector_valid(ball_position)){
this->ball_position = ball_position;
return true;
}
return false;
}
/**
* Retrieves the current ball position
* @return boost::numeric::ublas::vector<double> The current ball position
*/
boost::numeric::ublas::vector<double> get_ball_position(){
return this->ball_position;
}
/**
* Updates the ball velocity
* @param ball_velocity boost::numeric::ublas::vector<double> The new ball velocity
* @return bool True if the variable was successfully updated,
* false if an error occurred
*/
bool set_ball_velocity(boost::numeric::ublas::vector<double> ball_velocity){
if(this->is_vector_valid(ball_velocity)){
this->ball_velocity = ball_velocity;
return true;
}
return false;
}
/**
* Retrieves the current ball velocity
* @return boost::numeric::ublas::vector<double> The current ball velocity
*/
boost::numeric::ublas::vector<double> get_ball_velocity(){
return this->ball_velocity;
}
/**
* Updates the ball position
* @param ball_acceleration boost::numeric::ublas::vector<double> The new ball acceleration
* @return bool True if the variable was successfully updated,
* false if an error occurred
*/
bool set_ball_acceleration(boost::numeric::ublas::vector<double> ball_acceleration){
if(this->is_vector_valid(ball_acceleration)){
this->ball_acceleration = ball_acceleration;
return true;
}
return false;
}
/**
* Retrieves the current ball acceleration
* @return boost::numeric::ublas::vector<double> The current ball acceleration
*/
boost::numeric::ublas::vector<double> get_ball_acceleration(){
return this->ball_acceleration;
}
};
/**
* Contains all the information of a state
*/
class State{
};
/**
* Gets the expected reward based on a lookup table and the model of the environment
* @param s State The State of which the reward is calculated
* @return double The expected reward
*/
double reward(State s){
return 0.0;
}
/**
* Calculates the expected value the given state will in the next turn and in the future.
* Policies, the reward function and the model of the environment are used to do this calculation.
* @param s State The State of which the value is calculated
* @return double The expected value
*/
double value(State s){
return 0.0;
}
int main() {
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/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 <QBuffer>
#include <QXmlStreamWriter>
#ifndef QXMPP_NO_GUI
#include <QImage>
#include <QImageReader>
#endif
#include "QXmppVCard.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"
static QString getImageType(const QByteArray& image)
{
#ifndef QXMPP_NO_GUI
QBuffer buffer;
buffer.setData(image);
buffer.open(QIODevice::ReadOnly);
QString format = QImageReader::imageFormat(&buffer);
if(format.toUpper() == "PNG")
return "image/png";
else if(format.toUpper() == "MNG")
return "video/x-mng";
else if(format.toUpper() == "GIF")
return "image/gif";
else if(format.toUpper() == "BMP")
return "image/bmp";
else if(format.toUpper() == "XPM")
return "image/x-xpm";
else if(format.toUpper() == "SVG")
return "image/svg+xml";
else if(format.toUpper() == "JPEG")
return "image/jpeg";
#else
Q_UNUSED(image);
#endif
return "image/unknown";
}
QXmppVCard::QXmppVCard(const QString& jid) : QXmppIq(QXmppIq::Get)
{
// for self jid should be empty
setTo(jid);
}
/// Returns the date of birth of the individual associated with the vCard.
///
QDate QXmppVCard::birthday() const
{
return m_birthday;
}
/// Sets the date of birth of the individual associated with the vCard.
///
/// \param birthday
void QXmppVCard::setBirthday(const QDate &birthday)
{
m_birthday = birthday;
}
/// Returns the email address.
///
QString QXmppVCard::email() const
{
return m_email;
}
/// Sets the email address.
///
/// \param email
void QXmppVCard::setEmail(const QString &email)
{
m_email = email;
}
/// Returns the first name.
///
QString QXmppVCard::firstName() const
{
return m_firstName;
}
/// Sets the first name.
///
/// \param firstName
void QXmppVCard::setFirstName(const QString &firstName)
{
m_firstName = firstName;
}
/// Returns the full name.
///
QString QXmppVCard::fullName() const
{
return m_fullName;
}
/// Sets the full name.
///
/// \param fullName
void QXmppVCard::setFullName(const QString &fullName)
{
m_fullName = fullName;
}
/// Returns the last name.
///
QString QXmppVCard::lastName() const
{
return m_lastName;
}
/// Sets the last name.
///
/// \param lastName
void QXmppVCard::setLastName(const QString &lastName)
{
m_lastName = lastName;
}
/// Returns the middle name.
///
QString QXmppVCard::middleName() const
{
return m_middleName;
}
/// Sets the middle name.
///
/// \param middleName
void QXmppVCard::setMiddleName(const QString &middleName)
{
m_middleName = middleName;
}
/// Returns the nickname.
///
QString QXmppVCard::nickName() const
{
return m_nickName;
}
/// Sets the nickname.
///
/// \param nickName
void QXmppVCard::setNickName(const QString &nickName)
{
m_nickName = nickName;
}
/// Returns the URL associated with the vCard. It can represent the user's
/// homepage or a location at which you can find real-time information about
/// the vCard.
QString QXmppVCard::url() const
{
return m_url;
}
/// Sets the URL associated with the vCard. It can represent the user's
/// homepage or a location at which you can find real-time information about
/// the vCard.
///
/// \param vCard
void QXmppVCard::setUrl(const QString& url)
{
m_url = url;
}
/// Returns the photo's binary contents.
QByteArray QXmppVCard::photo() const
{
return m_photo;
}
/// Sets the photo's binary contents.
void QXmppVCard::setPhoto(const QByteArray& photo)
{
m_photo = photo;
}
/// Returns the photo's MIME type.
QString QXmppVCard::photoType() const
{
return m_photoType;
}
/// Sets the photo's MIME type.
void QXmppVCard::setPhotoType(const QString& photoType)
{
m_photoType = photoType;
}
bool QXmppVCard::isVCard(const QDomElement &nodeRecv)
{
return nodeRecv.firstChildElement("vCard").namespaceURI() == ns_vcard;
}
void QXmppVCard::parseElementFromChild(const QDomElement& nodeRecv)
{
// vCard
QDomElement cardElement = nodeRecv.firstChildElement("vCard");
m_birthday = QDate::fromString(cardElement.firstChildElement("BDAY").text(), "yyyy-MM-dd");
QDomElement emailElement = cardElement.firstChildElement("EMAIL");
m_email = emailElement.firstChildElement("USERID").text();
m_fullName = cardElement.firstChildElement("FN").text();
m_nickName = cardElement.firstChildElement("NICKNAME").text();
QDomElement nameElement = cardElement.firstChildElement("N");
m_firstName = nameElement.firstChildElement("GIVEN").text();
m_lastName = nameElement.firstChildElement("FAMILY").text();
m_middleName = nameElement.firstChildElement("MIDDLE").text();
m_url = cardElement.firstChildElement("URL").text();
QDomElement photoElement = cardElement.firstChildElement("PHOTO");
QByteArray base64data = photoElement.
firstChildElement("BINVAL").text().toAscii();
m_photo = QByteArray::fromBase64(base64data);
m_photoType = photoElement.firstChildElement("TYPE").text();
}
void QXmppVCard::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
writer->writeStartElement("vCard");
helperToXmlAddAttribute(writer,"xmlns", ns_vcard);
if (m_birthday.isValid())
helperToXmlAddTextElement(writer, "BDAY", m_birthday.toString("yyyy-MM-dd"));
if (!m_email.isEmpty())
{
writer->writeStartElement("EMAIL");
writer->writeEmptyElement("INTERNET");
helperToXmlAddTextElement(writer, "USERID", m_email);
writer->writeEndElement();
}
if (!m_fullName.isEmpty())
helperToXmlAddTextElement(writer, "FN", m_fullName);
if(!m_nickName.isEmpty())
helperToXmlAddTextElement(writer, "NICKNAME", m_nickName);
if (!m_firstName.isEmpty() ||
!m_lastName.isEmpty() ||
!m_middleName.isEmpty())
{
writer->writeStartElement("N");
if (!m_firstName.isEmpty())
helperToXmlAddTextElement(writer, "GIVEN", m_firstName);
if (!m_lastName.isEmpty())
helperToXmlAddTextElement(writer, "FAMILY", m_lastName);
if (!m_middleName.isEmpty())
helperToXmlAddTextElement(writer, "MIDDLE", m_middleName);
writer->writeEndElement();
}
if (!m_url.isEmpty())
helperToXmlAddTextElement(writer, "URL", m_url);
if(!photo().isEmpty())
{
writer->writeStartElement("PHOTO");
QString photoType = m_photoType;
if (photoType.isEmpty())
photoType = getImageType(m_photo);
helperToXmlAddTextElement(writer, "TYPE", photoType);
helperToXmlAddTextElement(writer, "BINVAL", m_photo.toBase64());
writer->writeEndElement();
}
writer->writeEndElement();
}
#ifndef QXMPP_NO_GUI
QImage QXmppVCard::photoAsImage() const
{
QBuffer buffer;
buffer.setData(m_photo);
buffer.open(QIODevice::ReadOnly);
QImageReader imageReader(&buffer);
return imageReader.read();
}
void QXmppVCard::setPhoto(const QImage& image)
{
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
m_photo = ba;
m_photoType = "image/png";
}
#endif
QString QXmppVCard::getFullName() const
{
return m_fullName;
}
QString QXmppVCard::getNickName() const
{
return m_nickName;
}
const QByteArray& QXmppVCard::getPhoto() const
{
return m_photo;
}
#ifndef QXMPP_NO_GUI
QImage QXmppVCard::getPhotoAsImage() const
{
return photoAsImage();
}
#endif
<commit_msg>add code for using getImageType without QtGui<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/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 <QBuffer>
#include <QXmlStreamWriter>
#ifndef QXMPP_NO_GUI
#include <QImage>
#include <QImageReader>
#endif
#include "QXmppVCard.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"
QString getImageType(const QByteArray &contents)
{
if (contents.startsWith("\x89PNG\x0d\x0a\x1a\x0a"))
return "image/png";
else if (contents.startsWith("\x8aMNG"))
return "video/x-mng";
else if (contents.startsWith("GIF8"))
return "image/gif";
else if (contents.startsWith("BM"))
return "image/bmp";
else if (contents.contains("/* XPM */"))
return "image/x-xpm";
else if (contents.contains("<?xml") && contents.contains("<svg"))
return "image/svg+xml";
else if (contents.startsWith("\xFF\xD8\xFF\xE0"))
return "image/jpeg";
return "image/unknown";
}
QXmppVCard::QXmppVCard(const QString& jid) : QXmppIq(QXmppIq::Get)
{
// for self jid should be empty
setTo(jid);
}
/// Returns the date of birth of the individual associated with the vCard.
///
QDate QXmppVCard::birthday() const
{
return m_birthday;
}
/// Sets the date of birth of the individual associated with the vCard.
///
/// \param birthday
void QXmppVCard::setBirthday(const QDate &birthday)
{
m_birthday = birthday;
}
/// Returns the email address.
///
QString QXmppVCard::email() const
{
return m_email;
}
/// Sets the email address.
///
/// \param email
void QXmppVCard::setEmail(const QString &email)
{
m_email = email;
}
/// Returns the first name.
///
QString QXmppVCard::firstName() const
{
return m_firstName;
}
/// Sets the first name.
///
/// \param firstName
void QXmppVCard::setFirstName(const QString &firstName)
{
m_firstName = firstName;
}
/// Returns the full name.
///
QString QXmppVCard::fullName() const
{
return m_fullName;
}
/// Sets the full name.
///
/// \param fullName
void QXmppVCard::setFullName(const QString &fullName)
{
m_fullName = fullName;
}
/// Returns the last name.
///
QString QXmppVCard::lastName() const
{
return m_lastName;
}
/// Sets the last name.
///
/// \param lastName
void QXmppVCard::setLastName(const QString &lastName)
{
m_lastName = lastName;
}
/// Returns the middle name.
///
QString QXmppVCard::middleName() const
{
return m_middleName;
}
/// Sets the middle name.
///
/// \param middleName
void QXmppVCard::setMiddleName(const QString &middleName)
{
m_middleName = middleName;
}
/// Returns the nickname.
///
QString QXmppVCard::nickName() const
{
return m_nickName;
}
/// Sets the nickname.
///
/// \param nickName
void QXmppVCard::setNickName(const QString &nickName)
{
m_nickName = nickName;
}
/// Returns the URL associated with the vCard. It can represent the user's
/// homepage or a location at which you can find real-time information about
/// the vCard.
QString QXmppVCard::url() const
{
return m_url;
}
/// Sets the URL associated with the vCard. It can represent the user's
/// homepage or a location at which you can find real-time information about
/// the vCard.
///
/// \param url
void QXmppVCard::setUrl(const QString& url)
{
m_url = url;
}
/// Returns the photo's binary contents.
QByteArray QXmppVCard::photo() const
{
return m_photo;
}
/// Sets the photo's binary contents.
void QXmppVCard::setPhoto(const QByteArray& photo)
{
m_photo = photo;
}
/// Returns the photo's MIME type.
QString QXmppVCard::photoType() const
{
return m_photoType;
}
/// Sets the photo's MIME type.
void QXmppVCard::setPhotoType(const QString& photoType)
{
m_photoType = photoType;
}
bool QXmppVCard::isVCard(const QDomElement &nodeRecv)
{
return nodeRecv.firstChildElement("vCard").namespaceURI() == ns_vcard;
}
void QXmppVCard::parseElementFromChild(const QDomElement& nodeRecv)
{
// vCard
QDomElement cardElement = nodeRecv.firstChildElement("vCard");
m_birthday = QDate::fromString(cardElement.firstChildElement("BDAY").text(), "yyyy-MM-dd");
QDomElement emailElement = cardElement.firstChildElement("EMAIL");
m_email = emailElement.firstChildElement("USERID").text();
m_fullName = cardElement.firstChildElement("FN").text();
m_nickName = cardElement.firstChildElement("NICKNAME").text();
QDomElement nameElement = cardElement.firstChildElement("N");
m_firstName = nameElement.firstChildElement("GIVEN").text();
m_lastName = nameElement.firstChildElement("FAMILY").text();
m_middleName = nameElement.firstChildElement("MIDDLE").text();
m_url = cardElement.firstChildElement("URL").text();
QDomElement photoElement = cardElement.firstChildElement("PHOTO");
QByteArray base64data = photoElement.
firstChildElement("BINVAL").text().toAscii();
m_photo = QByteArray::fromBase64(base64data);
m_photoType = photoElement.firstChildElement("TYPE").text();
}
void QXmppVCard::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
writer->writeStartElement("vCard");
helperToXmlAddAttribute(writer,"xmlns", ns_vcard);
if (m_birthday.isValid())
helperToXmlAddTextElement(writer, "BDAY", m_birthday.toString("yyyy-MM-dd"));
if (!m_email.isEmpty())
{
writer->writeStartElement("EMAIL");
writer->writeEmptyElement("INTERNET");
helperToXmlAddTextElement(writer, "USERID", m_email);
writer->writeEndElement();
}
if (!m_fullName.isEmpty())
helperToXmlAddTextElement(writer, "FN", m_fullName);
if(!m_nickName.isEmpty())
helperToXmlAddTextElement(writer, "NICKNAME", m_nickName);
if (!m_firstName.isEmpty() ||
!m_lastName.isEmpty() ||
!m_middleName.isEmpty())
{
writer->writeStartElement("N");
if (!m_firstName.isEmpty())
helperToXmlAddTextElement(writer, "GIVEN", m_firstName);
if (!m_lastName.isEmpty())
helperToXmlAddTextElement(writer, "FAMILY", m_lastName);
if (!m_middleName.isEmpty())
helperToXmlAddTextElement(writer, "MIDDLE", m_middleName);
writer->writeEndElement();
}
if (!m_url.isEmpty())
helperToXmlAddTextElement(writer, "URL", m_url);
if(!photo().isEmpty())
{
writer->writeStartElement("PHOTO");
QString photoType = m_photoType;
if (photoType.isEmpty())
photoType = getImageType(m_photo);
helperToXmlAddTextElement(writer, "TYPE", photoType);
helperToXmlAddTextElement(writer, "BINVAL", m_photo.toBase64());
writer->writeEndElement();
}
writer->writeEndElement();
}
#ifndef QXMPP_NO_GUI
QImage QXmppVCard::photoAsImage() const
{
QBuffer buffer;
buffer.setData(m_photo);
buffer.open(QIODevice::ReadOnly);
QImageReader imageReader(&buffer);
return imageReader.read();
}
void QXmppVCard::setPhoto(const QImage& image)
{
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
m_photo = ba;
m_photoType = "image/png";
}
#endif
QString QXmppVCard::getFullName() const
{
return m_fullName;
}
QString QXmppVCard::getNickName() const
{
return m_nickName;
}
const QByteArray& QXmppVCard::getPhoto() const
{
return m_photo;
}
#ifndef QXMPP_NO_GUI
QImage QXmppVCard::getPhotoAsImage() const
{
return photoAsImage();
}
#endif
<|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
#include "libmesh/diff_solver.h"
#include "libmesh/diff_system.h"
#include "libmesh/dof_map.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/unsteady_solver.h"
namespace libMesh
{
UnsteadySolver::UnsteadySolver (sys_type& s)
: TimeSolver(s),
old_local_nonlinear_solution (NumericVector<Number>::build()),
first_solve (true),
first_adjoint_step (true)
{
}
UnsteadySolver::~UnsteadySolver ()
{
}
void UnsteadySolver::init ()
{
TimeSolver::init();
_system.add_vector("_old_nonlinear_solution");
}
void UnsteadySolver::init_data()
{
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
}
void UnsteadySolver::reinit ()
{
TimeSolver::reinit();
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
// copy the system solution to the current vector
// this assumes that the syste vector has already been resized and projected
NumericVector<Number> &old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
NumericVector<Number> &nonlinear_solution =
*(_system.solution);
old_nonlinear_soln = nonlinear_solution;
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::solve ()
{
if (first_solve)
{
advance_timestep();
first_solve = false;
}
unsigned int solve_result = _diff_solver->solve();
// If we requested the UnsteadySolver to attempt reducing dt after a
// failed DiffSolver solve, check the results of the solve now.
if (reduce_deltat_on_diffsolver_failure)
{
bool backtracking_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (backtracking_failed || max_iterations)
{
// Cut timestep in half
for (unsigned int nr=0; nr<reduce_deltat_on_diffsolver_failure; ++nr)
{
_system.deltat *= 0.5;
libMesh::out << "Newton backtracking failed. Trying with smaller timestep, dt="
<< _system.deltat << std::endl;
solve_result = _diff_solver->solve();
// Check solve results with reduced timestep
bool backtracking_still_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool backtracking_max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (!backtracking_still_failed && !backtracking_max_iterations)
{
if (!quiet)
libMesh::out << "Reduced dt solve succeeded." << std::endl;
return;
}
}
// If we made it here, we still couldn't converge the solve after
// reducing deltat
libMesh::out << "DiffSolver::solve() did not succeed after "
<< reduce_deltat_on_diffsolver_failure
<< " attempts." << std::endl;
libmesh_convergence_failure();
} // end if (backtracking_failed || max_iterations)
} // end if (reduce_deltat_on_diffsolver_failure)
}
void UnsteadySolver::advance_timestep ()
{
if (!first_solve)
{
// Store the solution, does nothing by default
// User has to attach appropriate solution_history object for this to
// actually store anything anywhere
solution_history->store();
_system.time += _system.deltat;
}
NumericVector<Number> &old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
NumericVector<Number> &nonlinear_solution =
*(_system.solution);
old_nonlinear_soln = nonlinear_solution;
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::adjoint_advance_timestep ()
{
// On the first call of this function, we dont save the adjoint solution or
// decrement the time, we just call the retrieve function below
if(!first_adjoint_step)
{
// Call the store function to store the last adjoint before decrementing the time
solution_history->store();
// Decrement the system time
_system.time -= _system.deltat;
}
else
{
first_adjoint_step = false;
}
// Retrieve the primal solution vectors at this time using the
// solution_history object
solution_history->retrieve();
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::retrieve_timestep()
{
// Retrieve all the stored vectors at the current time
solution_history->retrieve();
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
Number UnsteadySolver::old_nonlinear_solution(const dof_id_type global_dof_number)
const
{
libmesh_assert_less (global_dof_number, _system.get_dof_map().n_dofs());
libmesh_assert_less (global_dof_number, old_local_nonlinear_solution->size());
return (*old_local_nonlinear_solution)(global_dof_number);
}
Real UnsteadySolver::du(const SystemNorm &norm) const
{
AutoPtr<NumericVector<Number> > solution_copy =
_system.solution->clone();
solution_copy->add(-1., _system.get_vector("_old_nonlinear_solution"));
solution_copy->close();
return _system.calculate_norm(*solution_copy, norm);
}
} // namespace libMesh
<commit_msg>Correct fix for UnsteadySolver::reinit()<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
#include "libmesh/diff_solver.h"
#include "libmesh/diff_system.h"
#include "libmesh/dof_map.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/unsteady_solver.h"
namespace libMesh
{
UnsteadySolver::UnsteadySolver (sys_type& s)
: TimeSolver(s),
old_local_nonlinear_solution (NumericVector<Number>::build()),
first_solve (true),
first_adjoint_step (true)
{
}
UnsteadySolver::~UnsteadySolver ()
{
}
void UnsteadySolver::init ()
{
TimeSolver::init();
_system.add_vector("_old_nonlinear_solution");
}
void UnsteadySolver::init_data()
{
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
}
void UnsteadySolver::reinit ()
{
TimeSolver::reinit();
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
// localize the old solution
NumericVector<Number> &old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::solve ()
{
if (first_solve)
{
advance_timestep();
first_solve = false;
}
unsigned int solve_result = _diff_solver->solve();
// If we requested the UnsteadySolver to attempt reducing dt after a
// failed DiffSolver solve, check the results of the solve now.
if (reduce_deltat_on_diffsolver_failure)
{
bool backtracking_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (backtracking_failed || max_iterations)
{
// Cut timestep in half
for (unsigned int nr=0; nr<reduce_deltat_on_diffsolver_failure; ++nr)
{
_system.deltat *= 0.5;
libMesh::out << "Newton backtracking failed. Trying with smaller timestep, dt="
<< _system.deltat << std::endl;
solve_result = _diff_solver->solve();
// Check solve results with reduced timestep
bool backtracking_still_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool backtracking_max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (!backtracking_still_failed && !backtracking_max_iterations)
{
if (!quiet)
libMesh::out << "Reduced dt solve succeeded." << std::endl;
return;
}
}
// If we made it here, we still couldn't converge the solve after
// reducing deltat
libMesh::out << "DiffSolver::solve() did not succeed after "
<< reduce_deltat_on_diffsolver_failure
<< " attempts." << std::endl;
libmesh_convergence_failure();
} // end if (backtracking_failed || max_iterations)
} // end if (reduce_deltat_on_diffsolver_failure)
}
void UnsteadySolver::advance_timestep ()
{
if (!first_solve)
{
// Store the solution, does nothing by default
// User has to attach appropriate solution_history object for this to
// actually store anything anywhere
solution_history->store();
_system.time += _system.deltat;
}
NumericVector<Number> &old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
NumericVector<Number> &nonlinear_solution =
*(_system.solution);
old_nonlinear_soln = nonlinear_solution;
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::adjoint_advance_timestep ()
{
// On the first call of this function, we dont save the adjoint solution or
// decrement the time, we just call the retrieve function below
if(!first_adjoint_step)
{
// Call the store function to store the last adjoint before decrementing the time
solution_history->store();
// Decrement the system time
_system.time -= _system.deltat;
}
else
{
first_adjoint_step = false;
}
// Retrieve the primal solution vectors at this time using the
// solution_history object
solution_history->retrieve();
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::retrieve_timestep()
{
// Retrieve all the stored vectors at the current time
solution_history->retrieve();
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
Number UnsteadySolver::old_nonlinear_solution(const dof_id_type global_dof_number)
const
{
libmesh_assert_less (global_dof_number, _system.get_dof_map().n_dofs());
libmesh_assert_less (global_dof_number, old_local_nonlinear_solution->size());
return (*old_local_nonlinear_solution)(global_dof_number);
}
Real UnsteadySolver::du(const SystemNorm &norm) const
{
AutoPtr<NumericVector<Number> > solution_copy =
_system.solution->clone();
solution_copy->add(-1., _system.get_vector("_old_nonlinear_solution"));
solution_copy->close();
return _system.calculate_norm(*solution_copy, norm);
}
} // namespace libMesh
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2022 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
#include "libmesh/unsteady_solver.h"
#include "libmesh/diff_solver.h"
#include "libmesh/diff_system.h"
#include "libmesh/dof_map.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/parameter_vector.h"
#include "libmesh/sensitivity_data.h"
#include "libmesh/solution_history.h"
#include "libmesh/adjoint_refinement_estimator.h"
#include "libmesh/error_vector.h"
namespace libMesh
{
UnsteadySolver::UnsteadySolver (sys_type & s)
: TimeSolver(s),
old_local_nonlinear_solution (NumericVector<Number>::build(s.comm()).release()),
first_solve (true),
first_adjoint_step (true)
{
old_adjoints.resize(s.n_qois());
// Set the old adjoint pointers to nullptrs
// We will use this nullness to skip the initial time instant,
// when there is no older adjoint.
for(auto j : make_range(s.n_qois()))
{
old_adjoints[j] = nullptr;
}
}
UnsteadySolver::~UnsteadySolver () = default;
void UnsteadySolver::init ()
{
TimeSolver::init();
_system.add_vector("_old_nonlinear_solution");
}
void UnsteadySolver::init_adjoints ()
{
TimeSolver::init_adjoints();
// Add old adjoint solutions
// To keep the number of vectors consistent between the primal and adjoint
// time loops, we will also add the adjoint rhs vector during initialization
for(auto i : make_range(_system.n_qois()))
{
std::string old_adjoint_solution_name = "_old_adjoint_solution";
old_adjoint_solution_name+= std::to_string(i);
_system.add_vector(old_adjoint_solution_name);
std::string adjoint_rhs_name = "adjoint_rhs";
adjoint_rhs_name+= std::to_string(i);
_system.add_vector(adjoint_rhs_name, false, GHOSTED);
}
}
void UnsteadySolver::init_data()
{
TimeSolver::init_data();
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
}
void UnsteadySolver::reinit ()
{
TimeSolver::reinit();
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
// localize the old solution
NumericVector<Number> & old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::solve ()
{
if (first_solve)
{
advance_timestep();
first_solve = false;
}
unsigned int solve_result = _diff_solver->solve();
// If we requested the UnsteadySolver to attempt reducing dt after a
// failed DiffSolver solve, check the results of the solve now.
if (reduce_deltat_on_diffsolver_failure)
{
bool backtracking_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (backtracking_failed || max_iterations)
{
// Cut timestep in half
for (unsigned int nr=0; nr<reduce_deltat_on_diffsolver_failure; ++nr)
{
_system.deltat *= 0.5;
libMesh::out << "Newton backtracking failed. Trying with smaller timestep, dt="
<< _system.deltat << std::endl;
solve_result = _diff_solver->solve();
// Check solve results with reduced timestep
bool backtracking_still_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool backtracking_max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (!backtracking_still_failed && !backtracking_max_iterations)
{
// Set the successful deltat as the last deltat
last_deltat = _system.deltat;
if (!quiet)
libMesh::out << "Reduced dt solve succeeded." << std::endl;
return;
}
}
// If we made it here, we still couldn't converge the solve after
// reducing deltat
libMesh::out << "DiffSolver::solve() did not succeed after "
<< reduce_deltat_on_diffsolver_failure
<< " attempts." << std::endl;
libmesh_convergence_failure();
} // end if (backtracking_failed || max_iterations)
} // end if (reduce_deltat_on_diffsolver_failure)
// Set the successful deltat as the last deltat
last_deltat = _system.deltat;
}
void UnsteadySolver::advance_timestep ()
{
// The first access of advance_timestep happens via solve, not user code
// It is used here to store any initial conditions data
if (!first_solve)
{
// We call advance_timestep in user code after solve, so any solutions
// we will be storing will be for the next time instance
_system.time += _system.deltat;
}
else
{
// We are here because of a call to advance_timestep that happens
// via solve, the very first solve. All we are doing here is storing
// the initial condition. The actual solution computed via this solve
// will be stored when we call advance_timestep in the user's timestep loop
first_solve = false;
}
// If the user has attached a memory or file solution history object
// to the solver, this will store the current solution indexed with
// the current time
solution_history->store(false, _system.time);
NumericVector<Number> & old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
NumericVector<Number> & nonlinear_solution =
*(_system.solution);
old_nonlinear_soln = nonlinear_solution;
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
std::pair<unsigned int, Real> UnsteadySolver::adjoint_solve(const QoISet & qoi_indices)
{
std::pair<unsigned int, Real> adjoint_output = _system.ImplicitSystem::adjoint_solve(qoi_indices);
// Record the deltat we used for this adjoint timestep. This was determined completely
// by SolutionHistory::retrieve methods. The adjoint_solve methods should never change deltat.
last_deltat = _system.deltat;
return adjoint_output;
}
void UnsteadySolver::adjoint_advance_timestep ()
{
// Call the store function to store the adjoint we have computed (or
// for first_adjoint_step, the adjoint initial condition) in this
// time step for the time instance.
solution_history->store(true, _system.time);
_system.time -= _system.deltat;
// Retrieve the primal solution vectors at this new (or for
// first_adjoint_step, initial) time instance. These provide the
// data to solve the adjoint problem for the next time instance.
solution_history->retrieve(true, _system.time);
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::retrieve_timestep()
{
// Retrieve all the stored vectors at the current time
solution_history->retrieve(false, _system.time);
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::integrate_adjoint_sensitivity(const QoISet & qois, const ParameterVector & parameter_vector, SensitivityData & sensitivities)
{
// CURRENTLY using the trapezoidal rule to integrate each timestep
// (f(t_j) + f(t_j+1))/2 (t_j+1 - t_j)
// Fix me: This function needs to be moved to the EulerSolver classes like the
// other integrate_timestep functions, and use an integration rule consistent with
// the theta method used for the time integration.
// Get t_j
Real time_left = _system.time;
// Left side sensitivities to hold f(t_j)
SensitivityData sensitivities_left(qois, _system, parameter_vector);
// Get f(t_j)
_system.adjoint_qoi_parameter_sensitivity(qois, parameter_vector, sensitivities_left);
// Advance to t_j+1
_system.time = _system.time + _system.deltat;
// Get t_j+1
Real time_right = _system.time;
// Right side sensitivities f(t_j+1)
SensitivityData sensitivities_right(qois, _system, parameter_vector);
// Remove the sensitivity rhs vector from system since we did not write it to file and it cannot be retrieved
_system.remove_vector("sensitivity_rhs0");
// Retrieve the primal and adjoint solutions at the current timestep
retrieve_timestep();
// Get f(t_j+1)
_system.adjoint_qoi_parameter_sensitivity(qois, parameter_vector, sensitivities_right);
// Remove the sensitivity rhs vector from system since we did not write it to file and it cannot be retrieved
_system.remove_vector("sensitivity_rhs0");
// Get the contributions for each sensitivity from this timestep
for(unsigned int i = 0; i != qois.size(_system); i++)
for(unsigned int j = 0; j != parameter_vector.size(); j++)
sensitivities[i][j] = ( (sensitivities_left[i][j] + sensitivities_right[i][j])/2. )*(time_right - time_left);
}
void UnsteadySolver::integrate_qoi_timestep()
{
libmesh_not_implemented();
}
#ifdef LIBMESH_ENABLE_AMR
void UnsteadySolver::integrate_adjoint_refinement_error_estimate(AdjointRefinementEstimator & /*adjoint_refinement_error_estimator*/, ErrorVector & /*QoI_elementwise_error*/)
{
libmesh_not_implemented();
}
#endif // LIBMESH_ENABLE_AMR
Number UnsteadySolver::old_nonlinear_solution(const dof_id_type global_dof_number)
const
{
libmesh_assert_less (global_dof_number, _system.get_dof_map().n_dofs());
libmesh_assert_less (global_dof_number, old_local_nonlinear_solution->size());
return (*old_local_nonlinear_solution)(global_dof_number);
}
Real UnsteadySolver::du(const SystemNorm & norm) const
{
std::unique_ptr<NumericVector<Number>> solution_copy =
_system.solution->clone();
solution_copy->add(-1., _system.get_vector("_old_nonlinear_solution"));
solution_copy->close();
return _system.calculate_norm(*solution_copy, norm);
}
void UnsteadySolver::update()
{
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
} // namespace libMesh
<commit_msg>Make old adjoint vectors GHOSTED.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2022 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
#include "libmesh/unsteady_solver.h"
#include "libmesh/diff_solver.h"
#include "libmesh/diff_system.h"
#include "libmesh/dof_map.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/parameter_vector.h"
#include "libmesh/sensitivity_data.h"
#include "libmesh/solution_history.h"
#include "libmesh/adjoint_refinement_estimator.h"
#include "libmesh/error_vector.h"
namespace libMesh
{
UnsteadySolver::UnsteadySolver (sys_type & s)
: TimeSolver(s),
old_local_nonlinear_solution (NumericVector<Number>::build(s.comm()).release()),
first_solve (true),
first_adjoint_step (true)
{
old_adjoints.resize(s.n_qois());
// Set the old adjoint pointers to nullptrs
// We will use this nullness to skip the initial time instant,
// when there is no older adjoint.
for(auto j : make_range(s.n_qois()))
{
old_adjoints[j] = nullptr;
}
}
UnsteadySolver::~UnsteadySolver () = default;
void UnsteadySolver::init ()
{
TimeSolver::init();
_system.add_vector("_old_nonlinear_solution");
}
void UnsteadySolver::init_adjoints ()
{
TimeSolver::init_adjoints();
// Add old adjoint solutions
// To keep the number of vectors consistent between the primal and adjoint
// time loops, we will also add the adjoint rhs vector during initialization
for(auto i : make_range(_system.n_qois()))
{
std::string old_adjoint_solution_name = "_old_adjoint_solution";
old_adjoint_solution_name+= std::to_string(i);
_system.add_vector(old_adjoint_solution_name, false, GHOSTED);
std::string adjoint_rhs_name = "adjoint_rhs";
adjoint_rhs_name+= std::to_string(i);
_system.add_vector(adjoint_rhs_name, false, GHOSTED);
}
}
void UnsteadySolver::init_data()
{
TimeSolver::init_data();
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
}
void UnsteadySolver::reinit ()
{
TimeSolver::reinit();
#ifdef LIBMESH_ENABLE_GHOSTED
old_local_nonlinear_solution->init (_system.n_dofs(), _system.n_local_dofs(),
_system.get_dof_map().get_send_list(), false,
GHOSTED);
#else
old_local_nonlinear_solution->init (_system.n_dofs(), false, SERIAL);
#endif
// localize the old solution
NumericVector<Number> & old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::solve ()
{
if (first_solve)
{
advance_timestep();
first_solve = false;
}
unsigned int solve_result = _diff_solver->solve();
// If we requested the UnsteadySolver to attempt reducing dt after a
// failed DiffSolver solve, check the results of the solve now.
if (reduce_deltat_on_diffsolver_failure)
{
bool backtracking_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (backtracking_failed || max_iterations)
{
// Cut timestep in half
for (unsigned int nr=0; nr<reduce_deltat_on_diffsolver_failure; ++nr)
{
_system.deltat *= 0.5;
libMesh::out << "Newton backtracking failed. Trying with smaller timestep, dt="
<< _system.deltat << std::endl;
solve_result = _diff_solver->solve();
// Check solve results with reduced timestep
bool backtracking_still_failed =
solve_result & DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
bool backtracking_max_iterations =
solve_result & DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
if (!backtracking_still_failed && !backtracking_max_iterations)
{
// Set the successful deltat as the last deltat
last_deltat = _system.deltat;
if (!quiet)
libMesh::out << "Reduced dt solve succeeded." << std::endl;
return;
}
}
// If we made it here, we still couldn't converge the solve after
// reducing deltat
libMesh::out << "DiffSolver::solve() did not succeed after "
<< reduce_deltat_on_diffsolver_failure
<< " attempts." << std::endl;
libmesh_convergence_failure();
} // end if (backtracking_failed || max_iterations)
} // end if (reduce_deltat_on_diffsolver_failure)
// Set the successful deltat as the last deltat
last_deltat = _system.deltat;
}
void UnsteadySolver::advance_timestep ()
{
// The first access of advance_timestep happens via solve, not user code
// It is used here to store any initial conditions data
if (!first_solve)
{
// We call advance_timestep in user code after solve, so any solutions
// we will be storing will be for the next time instance
_system.time += _system.deltat;
}
else
{
// We are here because of a call to advance_timestep that happens
// via solve, the very first solve. All we are doing here is storing
// the initial condition. The actual solution computed via this solve
// will be stored when we call advance_timestep in the user's timestep loop
first_solve = false;
}
// If the user has attached a memory or file solution history object
// to the solver, this will store the current solution indexed with
// the current time
solution_history->store(false, _system.time);
NumericVector<Number> & old_nonlinear_soln =
_system.get_vector("_old_nonlinear_solution");
NumericVector<Number> & nonlinear_solution =
*(_system.solution);
old_nonlinear_soln = nonlinear_solution;
old_nonlinear_soln.localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
std::pair<unsigned int, Real> UnsteadySolver::adjoint_solve(const QoISet & qoi_indices)
{
std::pair<unsigned int, Real> adjoint_output = _system.ImplicitSystem::adjoint_solve(qoi_indices);
// Record the deltat we used for this adjoint timestep. This was determined completely
// by SolutionHistory::retrieve methods. The adjoint_solve methods should never change deltat.
last_deltat = _system.deltat;
return adjoint_output;
}
void UnsteadySolver::adjoint_advance_timestep ()
{
// Call the store function to store the adjoint we have computed (or
// for first_adjoint_step, the adjoint initial condition) in this
// time step for the time instance.
solution_history->store(true, _system.time);
_system.time -= _system.deltat;
// Retrieve the primal solution vectors at this new (or for
// first_adjoint_step, initial) time instance. These provide the
// data to solve the adjoint problem for the next time instance.
solution_history->retrieve(true, _system.time);
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::retrieve_timestep()
{
// Retrieve all the stored vectors at the current time
solution_history->retrieve(false, _system.time);
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
void UnsteadySolver::integrate_adjoint_sensitivity(const QoISet & qois, const ParameterVector & parameter_vector, SensitivityData & sensitivities)
{
// CURRENTLY using the trapezoidal rule to integrate each timestep
// (f(t_j) + f(t_j+1))/2 (t_j+1 - t_j)
// Fix me: This function needs to be moved to the EulerSolver classes like the
// other integrate_timestep functions, and use an integration rule consistent with
// the theta method used for the time integration.
// Get t_j
Real time_left = _system.time;
// Left side sensitivities to hold f(t_j)
SensitivityData sensitivities_left(qois, _system, parameter_vector);
// Get f(t_j)
_system.adjoint_qoi_parameter_sensitivity(qois, parameter_vector, sensitivities_left);
// Advance to t_j+1
_system.time = _system.time + _system.deltat;
// Get t_j+1
Real time_right = _system.time;
// Right side sensitivities f(t_j+1)
SensitivityData sensitivities_right(qois, _system, parameter_vector);
// Remove the sensitivity rhs vector from system since we did not write it to file and it cannot be retrieved
_system.remove_vector("sensitivity_rhs0");
// Retrieve the primal and adjoint solutions at the current timestep
retrieve_timestep();
// Get f(t_j+1)
_system.adjoint_qoi_parameter_sensitivity(qois, parameter_vector, sensitivities_right);
// Remove the sensitivity rhs vector from system since we did not write it to file and it cannot be retrieved
_system.remove_vector("sensitivity_rhs0");
// Get the contributions for each sensitivity from this timestep
for(unsigned int i = 0; i != qois.size(_system); i++)
for(unsigned int j = 0; j != parameter_vector.size(); j++)
sensitivities[i][j] = ( (sensitivities_left[i][j] + sensitivities_right[i][j])/2. )*(time_right - time_left);
}
void UnsteadySolver::integrate_qoi_timestep()
{
libmesh_not_implemented();
}
#ifdef LIBMESH_ENABLE_AMR
void UnsteadySolver::integrate_adjoint_refinement_error_estimate(AdjointRefinementEstimator & /*adjoint_refinement_error_estimator*/, ErrorVector & /*QoI_elementwise_error*/)
{
libmesh_not_implemented();
}
#endif // LIBMESH_ENABLE_AMR
Number UnsteadySolver::old_nonlinear_solution(const dof_id_type global_dof_number)
const
{
libmesh_assert_less (global_dof_number, _system.get_dof_map().n_dofs());
libmesh_assert_less (global_dof_number, old_local_nonlinear_solution->size());
return (*old_local_nonlinear_solution)(global_dof_number);
}
Real UnsteadySolver::du(const SystemNorm & norm) const
{
std::unique_ptr<NumericVector<Number>> solution_copy =
_system.solution->clone();
solution_copy->add(-1., _system.get_vector("_old_nonlinear_solution"));
solution_copy->close();
return _system.calculate_norm(*solution_copy, norm);
}
void UnsteadySolver::update()
{
// Dont forget to localize the old_nonlinear_solution !
_system.get_vector("_old_nonlinear_solution").localize
(*old_local_nonlinear_solution,
_system.get_dof_map().get_send_list());
}
} // namespace libMesh
<|endoftext|> |
<commit_before>/**
* @file
* brief description, full stop.
*
* long description, many sentences.
*
*/
#include "angort.h"
#include "cycle.h"
#include <time.h>
using namespace angort;
namespace angort {
/// define a property to set and get the auto cycle detection interval.
/// It will be called "autogc".
class AutoGCProperty: public Property {
private:
Angort *a;
public:
AutoGCProperty(Angort *_a){
a = _a;
}
virtual void postSet(){
a->autoCycleInterval = v.toInt();
a->autoCycleCount = a->autoCycleInterval;
}
virtual void preGet(){
Types::tInteger->set(&v,a->autoCycleInterval);
}
};
/// a property to get and set the library search path,
/// called "searchpath".
class SearchPathProperty : public Property {
private:
Angort *a;
public:
SearchPathProperty(Angort *_a){
a = _a;
}
virtual void postSet(){
if(a->searchPath)
free((void *)a->searchPath);
a->searchPath = strdup(v.toString().get());
}
virtual void preGet(){
Types::tString->set(&v,
a->searchPath ? a->searchPath:DEFAULTSEARCHPATH);
}
};
static NamespaceEnt *getNSEnt(Angort *a){
const StringBuffer &s = a->popString();
Namespace *ns = a->names.getSpaceByIdx(a->popInt());
int idx = ns->get(s.get());
if(idx<0)
throw RUNT("ispriv: cannot find name in namespace");
return ns->getEnt(idx);
}
}// end namespace
%name std
%word version ( -- version ) version number
{
a->pushInt(a->getVersion());
}
%word barewords (v --) turn bare words on or off
{
a->barewords = a->popInt()?true:false;
}
%word dump ( title -- ) dump the stack
{
a->dumpStack(a->popString().get());
}
%word snark ( ) used during debugging; prints an autoincremented count
{
static int snarkct=0;
printf("SNARK %d\n",snarkct++);
}
%word none ( -- none ) stack a None value
{
Value *v = a->pushval();
v->clr();
}
%word ct (-- ct) push the current stack count
{
a->pushInt(a->stack.ct);
}
%word rct (gcv -- ct) push the GC count for a GC value
{
Value *v = a->popval();
GarbageCollected *gc = v->t->getGC(v);
if(gc){
a->pushInt(gc->refct);
}
}
%word p ( v -- ) print a value
{
fputs(a->popString().get(),stdout);
}
%word x (v -- ) print a value in hex
{
int x = a->popval()->toInt();
printf("%x",x);
}
%word rawp (v --) print a ptr value as raw hex
{
void *p = a->popval()->getRaw();
printf("%p",p);
}
%word nl ( -- ) print a new line
{
puts("");
}
%word quit ( -- ) exit with return code 0
{
a->shutdown();
exit(0);
}
%word debug ( v -- ) turn debugging on or off (value is 0 or 1)
{
a->debug = a->popInt();
}
%word disasm (name -- ) disassemble word
{
a->disasm(a->popString().get());
}
%word assertdebug (bool --) turn assertion printout on/off
{
a->assertDebug = a->popInt()!=0;
}
%word assert (bool desc --) throw exception with string 'desc' if bool is false
{
const StringBuffer &desc = a->popString();
bool cond = (a->popInt()==0);
if(a->assertNegated){
cond=!cond;
if(a->assertDebug)printf("Negated ");
}
if(cond){
if(a->assertDebug)printf("Assertion failed: %s\n",desc.get());
throw AssertException(desc.get(),a->getLineNumber());
} else if(a->assertDebug)
printf("Assertion passed: %s\n",desc.get());
}
%word assertmode (mode --) set to `negated or `normal, if negated assertion conditions are negated
{
const StringBuffer& sb = a->popString();
if(!strcmp(sb.get(),"negated"))
a->assertNegated=true;
else
a->assertNegated=false;
}
%word abs (x --) absolute value
{
Value *v = a->popval();
if(v->t == Types::tInteger){
int i;
i = v->toInt();
a->pushInt(i<0?-i:i);
} else if(v->t == Types::tFloat){
float f;
f = v->toFloat();
a->pushFloat(f<0?-f:f);
} else {
throw RUNT("bad type for 'abs'");
}
}
%word neg (x --) negate
{
Value *v = a->popval();
if(v->t == Types::tInteger){
int i;
i = v->toInt();
a->pushInt(-i);
} else if(v->t == Types::tFloat){
float f;
f = v->toFloat();
a->pushFloat(-f);
} else {
throw RUNT("bad type for 'neg'");
}
}
%word isnone (val -- bool) is a value NONE
{
Value *s = a->stack.peekptr();
Types::tInteger->set(s,s->isNone()?1:0);
}
%word iscallable (val -- bool) return true if is codeblock or closure
{
Value *s = a->stack.peekptr();
Types::tInteger->set(s,s->t->isCallable()?1:0);
}
%word gccount (-- val) return the number of GC objects
{
a->pushInt(GarbageCollected::getGlobalCount());
}
%word range (start end -- range) build a range object
{
int end = a->popInt();
int start = a->popInt();
Value *v = a->pushval();
Types::tIRange->set(v,start,end,end>=start?1:-1);
}
%word srange (start end step -- range) build a range object with step
{
int step = a->popInt();
int end = a->popInt();
int start = a->popInt();
Value *v = a->pushval();
Types::tIRange->set(v,start,end,step);
}
%word frange (start end step -- range) build a float range object with step size
{
float step = a->popFloat();
float end = a->popFloat();
float start = a->popFloat();
Value *v = a->pushval();
Types::tFRange->set(v,start,end,step);
}
%word frangesteps (start end stepcount -- range) build a float range object with step count
{
float steps = a->popFloat();
float end = a->popFloat();
float start = a->popFloat();
float step = (end-start)/steps;
end += step * 0.4f;
Value *v = a->pushval();
Types::tFRange->set(v,start,end,step);
}
%word i (-- current) get current iterator value
{
Value *p = a->pushval();
p->copy(a->getTopIterator()->current);
}
%word j (-- current) get nested iterator value
{
Value *p = a->pushval();
p->copy(a->getTopIterator(1)->current);
}
%word k (-- current) get nested iterator value
{
Value *p = a->pushval();
p->copy(a->getTopIterator(2)->current);
}
%word iter (-- iterable) get the iterable which is currently being looped over
{
Value *p = a->pushval();
IteratorObject *iterator = a->getTopIterator();
p->copy(iterator->iterable);
}
%word mkiter (iterable -- iterator) make an iterator object
{
Value *p = a->stack.peekptr();
p->t->createIterator(p,p);
}
%word icur (iterator -- item) get current item in iterator made with mkiter
{
Value *p = a->stack.peekptr();
Iterator<Value *>* i = Types::tIter->get(p);
if(i->isDone())
p->clr();
else
p->copy(i->current());
}
%word inext (iterator --) advance the iterator
{
Value *p = a->stack.popptr();
Iterator<Value *>* i = Types::tIter->get(p);
i->next();
}
%word ifirst (iterator --) reset the iterator to the start
{
Value *p = a->stack.popptr();
Iterator<Value *>* i = Types::tIter->get(p);
i->first();
}
%word idone (iterator -- boolean) true if iterator is done
{
Value *p = a->stack.peekptr();
Iterator<Value *>* i = Types::tIter->get(p);
Types::tInteger->set(p,i->isDone()?1:0);
}
%word reset (--) Clear everything
{
while(!a->stack.isempty()){
Value *v = a->popval();
v->clr();
}
a->clear();
}
%word clear (--) Clear the stack, and also set all values to None
{
while(!a->stack.isempty()){
Value *v = a->popval();
v->clr();
}
}
%word list (--) List everything
{
a->list();
}
%word help (s --) get help on a word or native function
{
const StringBuffer &name = a->popString();
const char *s = a->getSpec(name.get());
if(!s)s="no help found";
printf("%s: %s\n",name.get(),s);
}
%word listhelp (s --) list and show help for all public functions in the given namespace
{
Namespace *s = a->names.getSpaceByName(a->popString().get());
for(int i=0;i<s->count();i++){
NamespaceEnt *e = s->getEnt(i);
if(!e->isPriv){
const char *spec = e->spec?e->spec:"";
if(spec)
printf("%-20s : %s\n",s->getName(i),spec);
else
printf("%-20s\n",s->getName(i));
}
}
}
%word type (v -- symb) get the type of the item as a symbol
{
Value *v = a->stack.peekptr();
Types::tSymbol->set(v,v->t->nameSymb);
}
%word srand (i --) set the random number generator seed. If -1, use the timestamp.
{
int v = a->popInt();
if(v==-1){
long t;
time(&t);
srand(t);
} else
srand(v);
}
%word rand (-- i) stack an integer random number
{
a->pushInt(rand());
}
%word gc (--) perform a major garbage detect and cycle removal
{
a->gc();
}
%word nspace (name -- handle) get a namespace by name
{
const StringBuffer& name = a->popString();
Namespace *ns = a->names.getSpaceByName(name.get());
a->pushInt(ns->idx);
}
%word names (handle --) get a list of names from a namespace
{
int idx = a->popInt();
Namespace *ns = a->names.getSpaceByIdx(idx);
ArrayList<Value> *list=Types::tList->set(a->pushval());
ns->appendNamesToList(list);
}
%word ispriv (handle name -- bool) return true if the definition is private in the namespace
{
NamespaceEnt *ent = getNSEnt(a);
a->pushInt(ent->isPriv?1:0);
}
%word isconst (handle name -- bool) return true if the definition is constant in the namespace
{
NamespaceEnt *ent = getNSEnt(a);
a->pushInt(ent->isConst?1:0);
}
%word endpackage () mark end of package, only when used within a single script
{
a->endPackageInScript();
}
%word dumpframe () debugging - dump the frame variables
{
a->dumpFrame();
CycleDetector::getInstance()->dump();
}
%word showclosure (cl --)
{
Value *v = a->popval();
if(v->t == Types::tClosure)
v->v.closure->show("Show command");
}
%shared
%init
{
a->registerProperty("autogc",new angort::AutoGCProperty(a));
a->registerProperty("searchpath",new angort::SearchPathProperty(a));
}
<commit_msg>New word: tosymbol<commit_after>/**
* @file
* brief description, full stop.
*
* long description, many sentences.
*
*/
#include "angort.h"
#include "cycle.h"
#include <time.h>
using namespace angort;
namespace angort {
/// define a property to set and get the auto cycle detection interval.
/// It will be called "autogc".
class AutoGCProperty: public Property {
private:
Angort *a;
public:
AutoGCProperty(Angort *_a){
a = _a;
}
virtual void postSet(){
a->autoCycleInterval = v.toInt();
a->autoCycleCount = a->autoCycleInterval;
}
virtual void preGet(){
Types::tInteger->set(&v,a->autoCycleInterval);
}
};
/// a property to get and set the library search path,
/// called "searchpath".
class SearchPathProperty : public Property {
private:
Angort *a;
public:
SearchPathProperty(Angort *_a){
a = _a;
}
virtual void postSet(){
if(a->searchPath)
free((void *)a->searchPath);
a->searchPath = strdup(v.toString().get());
}
virtual void preGet(){
Types::tString->set(&v,
a->searchPath ? a->searchPath:DEFAULTSEARCHPATH);
}
};
static NamespaceEnt *getNSEnt(Angort *a){
const StringBuffer &s = a->popString();
Namespace *ns = a->names.getSpaceByIdx(a->popInt());
int idx = ns->get(s.get());
if(idx<0)
throw RUNT("ispriv: cannot find name in namespace");
return ns->getEnt(idx);
}
}// end namespace
%name std
%word version ( -- version ) version number
{
a->pushInt(a->getVersion());
}
%word barewords (v --) turn bare words on or off
{
a->barewords = a->popInt()?true:false;
}
%word dump ( title -- ) dump the stack
{
a->dumpStack(a->popString().get());
}
%word snark ( ) used during debugging; prints an autoincremented count
{
static int snarkct=0;
printf("SNARK %d\n",snarkct++);
}
%word none ( -- none ) stack a None value
{
Value *v = a->pushval();
v->clr();
}
%word ct (-- ct) push the current stack count
{
a->pushInt(a->stack.ct);
}
%word rct (gcv -- ct) push the GC count for a GC value
{
Value *v = a->popval();
GarbageCollected *gc = v->t->getGC(v);
if(gc){
a->pushInt(gc->refct);
}
}
%word p ( v -- ) print a value
{
fputs(a->popString().get(),stdout);
}
%word x (v -- ) print a value in hex
{
int x = a->popval()->toInt();
printf("%x",x);
}
%word rawp (v --) print a ptr value as raw hex
{
void *p = a->popval()->getRaw();
printf("%p",p);
}
%word nl ( -- ) print a new line
{
puts("");
}
%word quit ( -- ) exit with return code 0
{
a->shutdown();
exit(0);
}
%word debug ( v -- ) turn debugging on or off (value is 0 or 1)
{
a->debug = a->popInt();
}
%word disasm (name -- ) disassemble word
{
a->disasm(a->popString().get());
}
%word assertdebug (bool --) turn assertion printout on/off
{
a->assertDebug = a->popInt()!=0;
}
%word assert (bool desc --) throw exception with string 'desc' if bool is false
{
const StringBuffer &desc = a->popString();
bool cond = (a->popInt()==0);
if(a->assertNegated){
cond=!cond;
if(a->assertDebug)printf("Negated ");
}
if(cond){
if(a->assertDebug)printf("Assertion failed: %s\n",desc.get());
throw AssertException(desc.get(),a->getLineNumber());
} else if(a->assertDebug)
printf("Assertion passed: %s\n",desc.get());
}
%word assertmode (mode --) set to `negated or `normal, if negated assertion conditions are negated
{
const StringBuffer& sb = a->popString();
if(!strcmp(sb.get(),"negated"))
a->assertNegated=true;
else
a->assertNegated=false;
}
%word abs (x --) absolute value
{
Value *v = a->popval();
if(v->t == Types::tInteger){
int i;
i = v->toInt();
a->pushInt(i<0?-i:i);
} else if(v->t == Types::tFloat){
float f;
f = v->toFloat();
a->pushFloat(f<0?-f:f);
} else {
throw RUNT("bad type for 'abs'");
}
}
%word neg (x --) negate
{
Value *v = a->popval();
if(v->t == Types::tInteger){
int i;
i = v->toInt();
a->pushInt(-i);
} else if(v->t == Types::tFloat){
float f;
f = v->toFloat();
a->pushFloat(-f);
} else {
throw RUNT("bad type for 'neg'");
}
}
%word isnone (val -- bool) is a value NONE
{
Value *s = a->stack.peekptr();
Types::tInteger->set(s,s->isNone()?1:0);
}
%word iscallable (val -- bool) return true if is codeblock or closure
{
Value *s = a->stack.peekptr();
Types::tInteger->set(s,s->t->isCallable()?1:0);
}
%word gccount (-- val) return the number of GC objects
{
a->pushInt(GarbageCollected::getGlobalCount());
}
%word range (start end -- range) build a range object
{
int end = a->popInt();
int start = a->popInt();
Value *v = a->pushval();
Types::tIRange->set(v,start,end,end>=start?1:-1);
}
%word srange (start end step -- range) build a range object with step
{
int step = a->popInt();
int end = a->popInt();
int start = a->popInt();
Value *v = a->pushval();
Types::tIRange->set(v,start,end,step);
}
%word frange (start end step -- range) build a float range object with step size
{
float step = a->popFloat();
float end = a->popFloat();
float start = a->popFloat();
Value *v = a->pushval();
Types::tFRange->set(v,start,end,step);
}
%word frangesteps (start end stepcount -- range) build a float range object with step count
{
float steps = a->popFloat();
float end = a->popFloat();
float start = a->popFloat();
float step = (end-start)/steps;
end += step * 0.4f;
Value *v = a->pushval();
Types::tFRange->set(v,start,end,step);
}
%word i (-- current) get current iterator value
{
Value *p = a->pushval();
p->copy(a->getTopIterator()->current);
}
%word j (-- current) get nested iterator value
{
Value *p = a->pushval();
p->copy(a->getTopIterator(1)->current);
}
%word k (-- current) get nested iterator value
{
Value *p = a->pushval();
p->copy(a->getTopIterator(2)->current);
}
%word iter (-- iterable) get the iterable which is currently being looped over
{
Value *p = a->pushval();
IteratorObject *iterator = a->getTopIterator();
p->copy(iterator->iterable);
}
%word mkiter (iterable -- iterator) make an iterator object
{
Value *p = a->stack.peekptr();
p->t->createIterator(p,p);
}
%word icur (iterator -- item) get current item in iterator made with mkiter
{
Value *p = a->stack.peekptr();
Iterator<Value *>* i = Types::tIter->get(p);
if(i->isDone())
p->clr();
else
p->copy(i->current());
}
%word inext (iterator --) advance the iterator
{
Value *p = a->stack.popptr();
Iterator<Value *>* i = Types::tIter->get(p);
i->next();
}
%word ifirst (iterator --) reset the iterator to the start
{
Value *p = a->stack.popptr();
Iterator<Value *>* i = Types::tIter->get(p);
i->first();
}
%word idone (iterator -- boolean) true if iterator is done
{
Value *p = a->stack.peekptr();
Iterator<Value *>* i = Types::tIter->get(p);
Types::tInteger->set(p,i->isDone()?1:0);
}
%word reset (--) Clear everything
{
while(!a->stack.isempty()){
Value *v = a->popval();
v->clr();
}
a->clear();
}
%word clear (--) Clear the stack, and also set all values to None
{
while(!a->stack.isempty()){
Value *v = a->popval();
v->clr();
}
}
%word list (--) List everything
{
a->list();
}
%word help (s --) get help on a word or native function
{
const StringBuffer &name = a->popString();
const char *s = a->getSpec(name.get());
if(!s)s="no help found";
printf("%s: %s\n",name.get(),s);
}
%word listhelp (s --) list and show help for all public functions in the given namespace
{
Namespace *s = a->names.getSpaceByName(a->popString().get());
for(int i=0;i<s->count();i++){
NamespaceEnt *e = s->getEnt(i);
if(!e->isPriv){
const char *spec = e->spec?e->spec:"";
if(spec)
printf("%-20s : %s\n",s->getName(i),spec);
else
printf("%-20s\n",s->getName(i));
}
}
}
%word type (v -- symb) get the type of the item as a symbol
{
Value *v = a->stack.peekptr();
Types::tSymbol->set(v,v->t->nameSymb);
}
%word srand (i --) set the random number generator seed. If -1, use the timestamp.
{
int v = a->popInt();
if(v==-1){
long t;
time(&t);
srand(t);
} else
srand(v);
}
%word rand (-- i) stack an integer random number
{
a->pushInt(rand());
}
%word gc (--) perform a major garbage detect and cycle removal
{
a->gc();
}
%word nspace (name -- handle) get a namespace by name
{
const StringBuffer& name = a->popString();
Namespace *ns = a->names.getSpaceByName(name.get());
a->pushInt(ns->idx);
}
%word names (handle --) get a list of names from a namespace
{
int idx = a->popInt();
Namespace *ns = a->names.getSpaceByIdx(idx);
ArrayList<Value> *list=Types::tList->set(a->pushval());
ns->appendNamesToList(list);
}
%word ispriv (handle name -- bool) return true if the definition is private in the namespace
{
NamespaceEnt *ent = getNSEnt(a);
a->pushInt(ent->isPriv?1:0);
}
%word isconst (handle name -- bool) return true if the definition is constant in the namespace
{
NamespaceEnt *ent = getNSEnt(a);
a->pushInt(ent->isConst?1:0);
}
%word tosymbol (string -- symbol) convert string to symbol
{
const StringBuffer& name = a->popString();
int symb = SymbolType::getSymbol(name.get());
Types::tSymbol->set(a->pushval(),symb);
}
%word endpackage () mark end of package, only when used within a single script
{
a->endPackageInScript();
}
%word dumpframe () debugging - dump the frame variables
{
a->dumpFrame();
CycleDetector::getInstance()->dump();
}
%word showclosure (cl --)
{
Value *v = a->popval();
if(v->t == Types::tClosure)
v->v.closure->show("Show command");
}
%shared
%init
{
a->registerProperty("autogc",new angort::AutoGCProperty(a));
a->registerProperty("searchpath",new angort::SearchPathProperty(a));
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ScalarCoupleable.h"
// MOOSE includes
#include "FEProblem.h"
#include "MooseVariableFEBase.h"
#include "MooseVariableScalar.h"
#include "Problem.h"
#include "SubProblem.h"
ScalarCoupleable::ScalarCoupleable(const MooseObject * moose_object)
: _sc_parameters(moose_object->parameters()),
_sc_name(_sc_parameters.get<std::string>("_object_name")),
_sc_fe_problem(*_sc_parameters.getCheckedPointerParam<FEProblemBase *>("_fe_problem_base")),
_sc_is_implicit(_sc_parameters.have_parameter<bool>("implicit")
? _sc_parameters.get<bool>("implicit")
: true),
_coupleable_params(_sc_parameters),
_sc_tid(_sc_parameters.isParamValid("_tid") ? _sc_parameters.get<THREAD_ID>("_tid") : 0),
_real_zero(_sc_fe_problem._real_zero[_sc_tid]),
_scalar_zero(_sc_fe_problem._scalar_zero[_sc_tid]),
_point_zero(_sc_fe_problem._point_zero[_sc_tid])
{
SubProblem & problem = *_sc_parameters.getCheckedPointerParam<SubProblem *>("_subproblem");
// Coupling
for (std::set<std::string>::const_iterator iter = _sc_parameters.coupledVarsBegin();
iter != _sc_parameters.coupledVarsEnd();
++iter)
{
std::string name = *iter;
if (_sc_parameters.getVecMooseType(*iter) != std::vector<std::string>())
{
std::vector<std::string> vars = _sc_parameters.getVecMooseType(*iter);
for (const auto & coupled_var_name : vars)
{
if (problem.hasScalarVariable(coupled_var_name))
{
MooseVariableScalar * scalar_var = &problem.getScalarVariable(_sc_tid, coupled_var_name);
_coupled_scalar_vars[name].push_back(scalar_var);
_coupled_moose_scalar_vars.push_back(scalar_var);
}
else if (problem.hasVariable(coupled_var_name))
{
MooseVariableFEBase * moose_var =
&problem.getVariable(_sc_tid,
coupled_var_name,
Moose::VarKindType::VAR_ANY,
Moose::VarFieldType::VAR_FIELD_ANY);
_sc_coupled_vars[name].push_back(moose_var);
}
else
mooseError(_sc_name, "Coupled variable '", coupled_var_name, "' was not found");
}
}
}
}
ScalarCoupleable::~ScalarCoupleable()
{
for (auto & it : _default_value)
{
it.second->release();
delete it.second;
}
}
const std::vector<MooseVariableScalar *> &
ScalarCoupleable::getCoupledMooseScalarVars()
{
return _coupled_moose_scalar_vars;
}
bool
ScalarCoupleable::isCoupledScalar(const std::string & var_name, unsigned int i)
{
std::map<std::string, std::vector<MooseVariableScalar *>>::iterator it =
_coupled_scalar_vars.find(var_name);
if (it != _coupled_scalar_vars.end())
return (i < it->second.size());
else
{
// Make sure the user originally requested this value in the InputParameter syntax
if (!_coupleable_params.hasCoupledValue(var_name))
mooseError(_sc_name,
"The coupled scalar variable \"",
var_name,
"\" was never added to this objects's "
"InputParameters, please double-check "
"your spelling");
return false;
}
}
unsigned int
ScalarCoupleable::coupledScalar(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
return getScalarVar(var_name, comp)->number();
}
Order
ScalarCoupleable::coupledScalarOrder(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return _sc_fe_problem.getMaxScalarOrder();
return getScalarVar(var_name, comp)->order();
}
VariableValue *
ScalarCoupleable::getDefaultValue(const std::string & var_name)
{
std::map<std::string, VariableValue *>::iterator default_value_it = _default_value.find(var_name);
if (default_value_it == _default_value.end())
{
VariableValue * value = new VariableValue(_sc_fe_problem.getMaxScalarOrder(),
_coupleable_params.defaultCoupledValue(var_name));
default_value_it = _default_value.insert(std::make_pair(var_name, value)).first;
}
return default_value_it->second;
}
VariableValue &
ScalarCoupleable::coupledScalarValue(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
MooseVariableScalar * var = getScalarVar(var_name, comp);
return (_sc_is_implicit) ? var->sln() : var->slnOld();
}
VariableValue &
ScalarCoupleable::coupledVectorTagScalarValue(const std::string & var_name,
TagID tag,
unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
addScalarVariableCoupleableVectorTag(tag);
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->vectorTagSln(tag);
}
VariableValue &
ScalarCoupleable::coupledMatrixTagScalarValue(const std::string & var_name,
TagID tag,
unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
addScalarVariableCoupleableMatrixTag(tag);
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->matrixTagSln(tag);
}
VariableValue &
ScalarCoupleable::coupledScalarValueOld(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
validateExecutionerType(var_name, "coupledScalarValueOld");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return (_sc_is_implicit) ? var->slnOld() : var->slnOlder();
}
VariableValue &
ScalarCoupleable::coupledScalarValueOlder(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
validateExecutionerType(var_name, "coupledScalarValueOlder");
MooseVariableScalar * var = getScalarVar(var_name, comp);
if (_sc_is_implicit)
return var->slnOlder();
else
mooseError("Older values not available for explicit schemes");
}
VariableValue &
ScalarCoupleable::coupledScalarDot(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDot");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDot();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDot(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDot");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDotDot();
}
VariableValue &
ScalarCoupleable::coupledScalarDotOld(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotOld");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDotOld();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDotOld(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDotOld");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDotDotOld();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDu(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDu");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->duDotDu();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDotDu(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDotDu");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->duDotDotDu();
}
void
ScalarCoupleable::checkVar(const std::string & var_name)
{
auto it = _sc_coupled_vars.find(var_name);
if (it != _sc_coupled_vars.end())
{
std::string cvars;
for (auto jt : it->second)
cvars += " " + jt->name();
mooseError(_sc_name,
": Trying to couple a field variable where scalar variable is expected, '",
var_name,
" =",
cvars,
"'");
}
// NOTE: non-existent variables are handled in the constructor
}
MooseVariableScalar *
ScalarCoupleable::getScalarVar(const std::string & var_name, unsigned int comp)
{
if (_coupled_scalar_vars.find(var_name) != _coupled_scalar_vars.end())
{
if (comp < _coupled_scalar_vars[var_name].size())
return _coupled_scalar_vars[var_name][comp];
else
mooseError(_sc_name, "Trying to get a non-existent component of variable '", var_name, "'");
}
else
mooseError(_sc_name, "Trying to get a non-existent variable '", var_name, "'");
}
void
ScalarCoupleable::validateExecutionerType(const std::string & name,
const std::string & fn_name) const
{
if (!_sc_fe_problem.isTransient())
mooseError(_sc_name,
": Calling '",
fn_name,
"' on variable \"",
name,
"\" when using a \"Steady\" executioner is not allowed. This value is available "
"only in transient simulations.");
}
unsigned int
ScalarCoupleable::coupledScalarComponents(const std::string & var_name)
{
return _coupled_scalar_vars[var_name].size();
}
<commit_msg>Cleaned up ScalarCoupleable error messages<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ScalarCoupleable.h"
// MOOSE includes
#include "FEProblem.h"
#include "MooseVariableFEBase.h"
#include "MooseVariableScalar.h"
#include "Problem.h"
#include "SubProblem.h"
ScalarCoupleable::ScalarCoupleable(const MooseObject * moose_object)
: _sc_parameters(moose_object->parameters()),
_sc_name(_sc_parameters.get<std::string>("_object_name")),
_sc_fe_problem(*_sc_parameters.getCheckedPointerParam<FEProblemBase *>("_fe_problem_base")),
_sc_is_implicit(_sc_parameters.have_parameter<bool>("implicit")
? _sc_parameters.get<bool>("implicit")
: true),
_coupleable_params(_sc_parameters),
_sc_tid(_sc_parameters.isParamValid("_tid") ? _sc_parameters.get<THREAD_ID>("_tid") : 0),
_real_zero(_sc_fe_problem._real_zero[_sc_tid]),
_scalar_zero(_sc_fe_problem._scalar_zero[_sc_tid]),
_point_zero(_sc_fe_problem._point_zero[_sc_tid])
{
SubProblem & problem = *_sc_parameters.getCheckedPointerParam<SubProblem *>("_subproblem");
// Coupling
for (std::set<std::string>::const_iterator iter = _sc_parameters.coupledVarsBegin();
iter != _sc_parameters.coupledVarsEnd();
++iter)
{
std::string name = *iter;
if (_sc_parameters.getVecMooseType(*iter) != std::vector<std::string>())
{
std::vector<std::string> vars = _sc_parameters.getVecMooseType(*iter);
for (const auto & coupled_var_name : vars)
{
if (problem.hasScalarVariable(coupled_var_name))
{
MooseVariableScalar * scalar_var = &problem.getScalarVariable(_sc_tid, coupled_var_name);
_coupled_scalar_vars[name].push_back(scalar_var);
_coupled_moose_scalar_vars.push_back(scalar_var);
}
else if (problem.hasVariable(coupled_var_name))
{
MooseVariableFEBase * moose_var =
&problem.getVariable(_sc_tid,
coupled_var_name,
Moose::VarKindType::VAR_ANY,
Moose::VarFieldType::VAR_FIELD_ANY);
_sc_coupled_vars[name].push_back(moose_var);
}
else
mooseError(_sc_name, ": Coupled variable '", coupled_var_name, "' was not found");
}
}
}
}
ScalarCoupleable::~ScalarCoupleable()
{
for (auto & it : _default_value)
{
it.second->release();
delete it.second;
}
}
const std::vector<MooseVariableScalar *> &
ScalarCoupleable::getCoupledMooseScalarVars()
{
return _coupled_moose_scalar_vars;
}
bool
ScalarCoupleable::isCoupledScalar(const std::string & var_name, unsigned int i)
{
std::map<std::string, std::vector<MooseVariableScalar *>>::iterator it =
_coupled_scalar_vars.find(var_name);
if (it != _coupled_scalar_vars.end())
return (i < it->second.size());
else
{
// Make sure the user originally requested this value in the InputParameter syntax
if (!_coupleable_params.hasCoupledValue(var_name))
mooseError(_sc_name,
": The coupled scalar variable \"",
var_name,
"\" was never added to this objects's "
"InputParameters, please double-check "
"your spelling");
return false;
}
}
unsigned int
ScalarCoupleable::coupledScalar(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
return getScalarVar(var_name, comp)->number();
}
Order
ScalarCoupleable::coupledScalarOrder(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return _sc_fe_problem.getMaxScalarOrder();
return getScalarVar(var_name, comp)->order();
}
VariableValue *
ScalarCoupleable::getDefaultValue(const std::string & var_name)
{
std::map<std::string, VariableValue *>::iterator default_value_it = _default_value.find(var_name);
if (default_value_it == _default_value.end())
{
VariableValue * value = new VariableValue(_sc_fe_problem.getMaxScalarOrder(),
_coupleable_params.defaultCoupledValue(var_name));
default_value_it = _default_value.insert(std::make_pair(var_name, value)).first;
}
return default_value_it->second;
}
VariableValue &
ScalarCoupleable::coupledScalarValue(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
MooseVariableScalar * var = getScalarVar(var_name, comp);
return (_sc_is_implicit) ? var->sln() : var->slnOld();
}
VariableValue &
ScalarCoupleable::coupledVectorTagScalarValue(const std::string & var_name,
TagID tag,
unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
addScalarVariableCoupleableVectorTag(tag);
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->vectorTagSln(tag);
}
VariableValue &
ScalarCoupleable::coupledMatrixTagScalarValue(const std::string & var_name,
TagID tag,
unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
addScalarVariableCoupleableMatrixTag(tag);
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->matrixTagSln(tag);
}
VariableValue &
ScalarCoupleable::coupledScalarValueOld(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
validateExecutionerType(var_name, "coupledScalarValueOld");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return (_sc_is_implicit) ? var->slnOld() : var->slnOlder();
}
VariableValue &
ScalarCoupleable::coupledScalarValueOlder(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
if (!isCoupledScalar(var_name, comp))
return *getDefaultValue(var_name);
validateExecutionerType(var_name, "coupledScalarValueOlder");
MooseVariableScalar * var = getScalarVar(var_name, comp);
if (_sc_is_implicit)
return var->slnOlder();
else
mooseError("Older values not available for explicit schemes");
}
VariableValue &
ScalarCoupleable::coupledScalarDot(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDot");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDot();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDot(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDot");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDotDot();
}
VariableValue &
ScalarCoupleable::coupledScalarDotOld(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotOld");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDotOld();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDotOld(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDotOld");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->uDotDotOld();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDu(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDu");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->duDotDu();
}
VariableValue &
ScalarCoupleable::coupledScalarDotDotDu(const std::string & var_name, unsigned int comp)
{
checkVar(var_name);
validateExecutionerType(var_name, "coupledScalarDotDotDu");
MooseVariableScalar * var = getScalarVar(var_name, comp);
return var->duDotDotDu();
}
void
ScalarCoupleable::checkVar(const std::string & var_name)
{
auto it = _sc_coupled_vars.find(var_name);
if (it != _sc_coupled_vars.end())
{
std::string cvars;
for (auto jt : it->second)
cvars += " " + jt->name();
mooseError(_sc_name,
": Trying to couple a field variable where scalar variable is expected, '",
var_name,
" =",
cvars,
"'");
}
// NOTE: non-existent variables are handled in the constructor
}
MooseVariableScalar *
ScalarCoupleable::getScalarVar(const std::string & var_name, unsigned int comp)
{
if (_coupled_scalar_vars.find(var_name) != _coupled_scalar_vars.end())
{
if (comp < _coupled_scalar_vars[var_name].size())
return _coupled_scalar_vars[var_name][comp];
else
mooseError(_sc_name, ": Trying to get a non-existent component of variable '", var_name, "'");
}
else
mooseError(_sc_name, ": Trying to get a non-existent variable '", var_name, "'");
}
void
ScalarCoupleable::validateExecutionerType(const std::string & name,
const std::string & fn_name) const
{
if (!_sc_fe_problem.isTransient())
mooseError(_sc_name,
": Calling '",
fn_name,
"' on variable \"",
name,
"\" when using a \"Steady\" executioner is not allowed. This value is available "
"only in transient simulations.");
}
unsigned int
ScalarCoupleable::coupledScalarComponents(const std::string & var_name)
{
return _coupled_scalar_vars[var_name].size();
}
<|endoftext|> |
<commit_before>/*
* SampleSort.cpp
*
* Created on: 14.03.2016
* Author: s_sschmi
*/
#include "SampleSort.h"
#include <algorithm>
#include <iomanip>
using namespace std;
using namespace MPI;
const int CUSTOM_MPI_ROOT = 0;
SampleSort::SampleSort(int mpiRank, int mpiSize, bool presortLocalData, size_t sampleSize) :
presortLocalData(presortLocalData),
sampleSize(sampleSize),
mpiRank(mpiRank),
mpiSize(mpiSize)
{
splitter = 0;
}
void SampleSort::sort(vector<int> &data) {
if (presortLocalData) {
std::sort(data.begin(), data.end());
}
vector<int> samples;
vector<size_t> positions;
drawSamples(data, samples);
sortSamples(samples);
partitionData(data, positions);
cout << mpiRank << ": positions = ";
for (int i = 0; i < positions.size(); i++) {
cout << dec << positions[i] << ",";
}
shareData(data, positions);
cout << endl;
}
void SampleSort::drawSamples(vector<int> &data, vector<int> &samples) {
while (samples.size() < sampleSize) {
samples.push_back(data[rand() % data.size()]);
}
}
void SampleSort::sortSamples(vector<int> &samples) {
int sendBuffer[samples.size()];
int *receiveBuffer = 0;
size_t receiveSize = sampleSize * mpiSize;
if (mpiRank == CUSTOM_MPI_ROOT) {
receiveBuffer = new int[receiveSize];
for (int i = 0; i < receiveSize; i++) {
receiveBuffer[i] = 0;
}
cout << mpiRank << ": created receive buffer" << endl;
}
cout << mpiRank << ": receiveSize = " << receiveSize << endl;
cout << mpiRank << ": sizeof(MPI_INT) = " << sizeof(MPI::INT) << endl;
cout << mpiRank << ": MPI_INT = " << MPI::INT << endl;
for (size_t i = 0; i < samples.size(); i++) {
sendBuffer[i] = samples[i];
cout << hex << samples[i] << ",";
}
cout << endl;
if (mpiRank == CUSTOM_MPI_ROOT) {
cout << mpiRank << ": copy local data" << endl;
for (int i = 0; i < sampleSize; i++) {
receiveBuffer[i] = sendBuffer[i];
}
for (int i = 1; i < mpiSize; i++) {
cout << mpiRank << ": receiving from " << i << endl;
COMM_WORLD.Recv(receiveBuffer + (i * sampleSize), sampleSize, MPI::INT, i, MPI::ANY_TAG);
}
} else {
COMM_WORLD.Send(sendBuffer, sampleSize, MPI::INT, 0, 0);
}
//COMM_WORLD.Gather(sendBuffer, samples.size(), MPI::INT, receiveBuffer, receiveSize, MPI::INT, CUSTOM_MPI_ROOT);
cout << mpiRank << ": After gather" << endl;
COMM_WORLD.Barrier();
splitter = new int[mpiSize - 1];
if (mpiRank == CUSTOM_MPI_ROOT) {
cout << "all samples = ";
for (int i = 0; i < receiveSize; i++) {
cout << hex << receiveBuffer[i] << ",";
}
cout << endl;
std::sort(receiveBuffer, receiveBuffer + receiveSize);
cout << "all samples sorted = ";
for (int i = 0; i < receiveSize; i++) {
cout << hex << receiveBuffer[i] << ",";
}
cout << endl;
for (int i = 0; i < mpiSize - 1; i++) {
splitter[i] = receiveBuffer[(i + 1) * sampleSize - 1];
}
cout << "splitter = ";
for (int i = 0; i < mpiSize - 1; i++) {
cout << hex << splitter[i] << ",";
}
cout << endl;
delete receiveBuffer;
}
COMM_WORLD.Bcast(splitter, mpiSize - 1, MPI::INT, CUSTOM_MPI_ROOT);
COMM_WORLD.Barrier();
cout << mpiRank << ": Finished sorting samples" << endl;
}
void SampleSort::partitionData(vector<int> &data, vector<size_t> &positions) {
// BINARY SEARCH FOR SPLITTER POSITIONS
auto first = data.begin();
for (int i = 0; i < mpiSize - 1; i++) {
first = lower_bound(first, data.end(), splitter[i]);
positions.push_back(first - data.begin());
}
}
void SampleSort::shareData(vector<int> &data, vector<size_t> &positions) {
size_t *bucketSizes = new size_t[mpiSize];
size_t *recBucketSizes = new size_t[mpiSize];
bucketSizes[0] = positions[0];
for (int i = 1; i < mpiSize - 1; i++) {
bucketSizes[i] = positions[i] - positions[i-1];
}
bucketSizes[mpiSize - 1] = data.size() - positions[mpiSize - 2];
COMM_WORLD.Alltoall(bucketSizes, 1, MPI::UNSIGNED_LONG, recBucketSizes, 1, MPI::UNSIGNED_LONG);
size_t receiveSize = 0;
for (int i = 0; i < mpiSize; i++) {
receiveSize += recBucketSizes[i];
}
int *receivedData = new int[receiveSize];
COMM_WORLD.Alltoall
}
SampleSort::~SampleSort() {
// TODO Auto-generated destructor stub
}
<commit_msg>Worked on sorting<commit_after>/*
* SampleSort.cpp
*
* Created on: 14.03.2016
* Author: s_sschmi
*/
#include "SampleSort.h"
#include <algorithm>
#include <iomanip>
using namespace std;
using namespace MPI;
const int CUSTOM_MPI_ROOT = 0;
SampleSort::SampleSort(int mpiRank, int mpiSize, bool presortLocalData, size_t sampleSize) :
presortLocalData(presortLocalData),
sampleSize(sampleSize),
mpiRank(mpiRank),
mpiSize(mpiSize)
{
splitter = 0;
}
void SampleSort::sort(vector<int> &data) {
if (presortLocalData) {
std::sort(data.begin(), data.end());
}
vector<int> samples;
vector<size_t> positions;
drawSamples(data, samples);
sortSamples(samples);
partitionData(data, positions);
cout << mpiRank << ": positions = ";
for (int i = 0; i < positions.size(); i++) {
cout << dec << positions[i] << ",";
}
shareData(data, positions);
cout << endl;
}
void SampleSort::drawSamples(vector<int> &data, vector<int> &samples) {
while (samples.size() < sampleSize) {
samples.push_back(data[rand() % data.size()]);
}
}
void SampleSort::sortSamples(vector<int> &samples) {
int sendBuffer[samples.size()];
int *receiveBuffer = 0;
size_t receiveSize = sampleSize * mpiSize;
if (mpiRank == CUSTOM_MPI_ROOT) {
receiveBuffer = new int[receiveSize];
for (int i = 0; i < receiveSize; i++) {
receiveBuffer[i] = 0;
}
cout << mpiRank << ": created receive buffer" << endl;
}
cout << mpiRank << ": receiveSize = " << receiveSize << endl;
cout << mpiRank << ": sizeof(MPI_INT) = " << sizeof(MPI::INT) << endl;
cout << mpiRank << ": MPI_INT = " << MPI::INT << endl;
for (size_t i = 0; i < samples.size(); i++) {
sendBuffer[i] = samples[i];
cout << hex << samples[i] << ",";
}
cout << endl;
if (mpiRank == CUSTOM_MPI_ROOT) {
cout << mpiRank << ": copy local data" << endl;
for (int i = 0; i < sampleSize; i++) {
receiveBuffer[i] = sendBuffer[i];
}
for (int i = 1; i < mpiSize; i++) {
cout << mpiRank << ": receiving from " << i << endl;
COMM_WORLD.Recv(receiveBuffer + (i * sampleSize), sampleSize, MPI::INT, i, MPI::ANY_TAG);
}
} else {
COMM_WORLD.Send(sendBuffer, sampleSize, MPI::INT, 0, 0);
}
//COMM_WORLD.Gather(sendBuffer, samples.size(), MPI::INT, receiveBuffer, receiveSize, MPI::INT, CUSTOM_MPI_ROOT);
cout << mpiRank << ": After gather" << endl;
COMM_WORLD.Barrier();
splitter = new int[mpiSize - 1];
if (mpiRank == CUSTOM_MPI_ROOT) {
cout << "all samples = ";
for (int i = 0; i < receiveSize; i++) {
cout << hex << receiveBuffer[i] << ",";
}
cout << endl;
std::sort(receiveBuffer, receiveBuffer + receiveSize);
cout << "all samples sorted = ";
for (int i = 0; i < receiveSize; i++) {
cout << hex << receiveBuffer[i] << ",";
}
cout << endl;
for (int i = 0; i < mpiSize - 1; i++) {
splitter[i] = receiveBuffer[(i + 1) * sampleSize - 1];
}
cout << "splitter = ";
for (int i = 0; i < mpiSize - 1; i++) {
cout << hex << splitter[i] << ",";
}
cout << endl;
delete receiveBuffer;
}
COMM_WORLD.Bcast(splitter, mpiSize - 1, MPI::INT, CUSTOM_MPI_ROOT);
COMM_WORLD.Barrier();
cout << mpiRank << ": Finished sorting samples" << endl;
}
void SampleSort::partitionData(vector<int> &data, vector<size_t> &positions) {
// BINARY SEARCH FOR SPLITTER POSITIONS
auto first = data.begin();
positions.push_back(0);
for (int i = 0; i < mpiSize - 1; i++) {
first = lower_bound(first, data.end(), splitter[i]);
positions.push_back(first - data.begin());
}
}
void SampleSort::shareData(vector<int> &data, vector<size_t> &positions) {
size_t *bucketSizes = new size_t[mpiSize];
size_t *recBucketSizes = new size_t[mpiSize];
for (int i = 0; i < mpiSize - 1; i++) {
bucketSizes[i] = positions[i + 1] - positions[i];
}
bucketSizes[mpiSize - 1] = data.size() - positions[mpiSize - 1];
COMM_WORLD.Alltoall(bucketSizes, 1, MPI::UNSIGNED_LONG, recBucketSizes, 1, MPI::UNSIGNED_LONG);
size_t receiveSize = 0;
for (int i = 0; i < mpiSize; i++) {
receiveSize += recBucketSizes[i];
}
int *receivedData = new int[receiveSize];
//size
//COMM_WORLD.Alltoallv();
}
SampleSort::~SampleSort() {
// TODO Auto-generated destructor stub
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.