text
stringlengths 54
60.6k
|
---|
<commit_before>#include <fstream>
#include <iostream>
#include <glob.h>
#include <pdal/StageFactory.hpp>
#include <entwine/third/arbiter/arbiter.hpp>
#include <entwine/reader/query.hpp>
#include <entwine/reader/reader.hpp>
#include <entwine/third/json/json.hpp>
#include <entwine/tree/clipper.hpp>
#include <entwine/types/bounds.hpp>
#include <entwine/types/format.hpp>
#include <entwine/types/metadata.hpp>
#include <entwine/types/schema.hpp>
#include <entwine/types/structure.hpp>
#include <entwine/util/executor.hpp>
#include "read-queries/entwine.hpp"
#include "read-queries/unindexed.hpp"
#include "util/buffer-pool.hpp"
#include "session.hpp"
namespace
{
/*
std::vector<std::string> resolve(
const std::vector<std::string>& dirs,
const std::string& name)
{
glob_t buffer;
for (std::size_t i(0); i < dirs.size(); ++i)
{
auto flags(GLOB_NOSORT | GLOB_TILDE);
if (i) flags |= GLOB_APPEND;
glob((dirs[i] + "/" + name + ".*").c_str(), flags, 0, &buffer);
}
std::vector<std::string> results;
for (std::size_t i(0); i < buffer.gl_pathc; ++i)
{
results.push_back(buffer.gl_pathv[i]);
}
globfree(&buffer);
return results;
}
*/
std::string getTypeString(const entwine::Structure& structure)
{
if (structure.dimensions() == 2)
{
if (structure.tubular()) return "octree";
else return "quadtree";
}
else if (structure.dimensions() == 3 && !structure.tubular())
{
return "octree";
}
else
{
throw std::runtime_error("Invalid structure");
}
}
}
Session::Session(
pdal::StageFactory& stageFactory,
std::mutex& factoryMutex)
: m_stageFactory(stageFactory)
, m_factoryMutex(factoryMutex)
, m_initOnce()
, m_source()
, m_entwine()
{ }
Session::~Session()
{ }
bool Session::initialize(
const std::string& name,
std::vector<std::string> paths,
entwine::OuterScope& outerScope,
std::shared_ptr<entwine::Cache> cache)
{
m_initOnce.ensure([this, &name, &paths, &cache, &outerScope]()
{
std::cout << "Discovering " << name << std::endl;
if (resolveIndex(name, paths, outerScope, cache))
{
std::cout << "\tIndex for " << name << " found" << std::endl;
Json::Value json;
const entwine::Metadata& metadata(m_entwine->metadata());
const std::size_t numPoints(
metadata.manifest().pointStats().inserts());
json["type"] = getTypeString(metadata.structure());
json["numPoints"] = static_cast<Json::UInt64>(numPoints);
json["schema"] = metadata.schema().toJson();
json["bounds"] = metadata.bounds().toJson();
json["boundsConforming"] = metadata.boundsConforming().toJson();
json["srs"] = metadata.format().srs();
json["baseDepth"] = static_cast<Json::UInt64>(
metadata.structure().nullDepthEnd());
m_info = json.toStyledString();
}
else if (resolveSource(name, paths))
{
std::cout << "\tSource for " << name << " found" << std::endl;
const std::size_t numPoints(m_source->numPoints());
Json::Value json;
json["type"] = "unindexed";
json["numPoints"] = static_cast<Json::UInt64>(numPoints);
json["schema"] = m_source->schema().toJson();
json["bounds"] = m_source->bounds().toJson();
json["srs"] = m_source->srs();
m_info = json.toStyledString();
}
else
{
std::cout << "\tBacking for " << name << " NOT found" << std::endl;
}
});
return sourced() || indexed();
}
std::string Session::info() const
{
check();
return m_info;
}
std::string Session::hierarchy(
const entwine::Bounds& bounds,
const std::size_t depthBegin,
const std::size_t depthEnd) const
{
if (indexed())
{
Json::FastWriter writer;
return writer.write(
m_entwine->hierarchy(bounds, depthBegin, depthEnd));
}
else
{
throw std::runtime_error("Cannot get hierarchy from unindexed dataset");
}
}
std::shared_ptr<ReadQuery> Session::query(
const entwine::Schema& schema,
const bool compress)
{
if (sourced())
{
return std::shared_ptr<ReadQuery>(
new UnindexedReadQuery(
schema,
compress,
*m_source));
}
else
{
throw WrongQueryType();
}
}
std::shared_ptr<ReadQuery> Session::query(
const entwine::Schema& schema,
const bool compress,
const double scale,
const entwine::Point& offset,
const entwine::Bounds* bounds,
const std::size_t depthBegin,
const std::size_t depthEnd)
{
if (indexed())
{
return std::shared_ptr<ReadQuery>(
new EntwineReadQuery(
schema,
compress,
m_entwine->query(
schema,
bounds ? *bounds : m_entwine->metadata().bounds(),
depthBegin,
depthEnd,
scale,
offset)));
}
else
{
throw WrongQueryType();
}
}
const entwine::Schema& Session::schema() const
{
check();
if (indexed()) return m_entwine->metadata().schema();
else return m_source->schema();
}
bool Session::resolveIndex(
const std::string& name,
const std::vector<std::string>& paths,
entwine::OuterScope& outerScope,
std::shared_ptr<entwine::Cache> cache)
{
for (std::string path : paths)
{
std::string err;
try
{
if (path.size() && path.back() != '/') path.push_back('/');
entwine::arbiter::Endpoint endpoint(
outerScope.getArbiterPtr()->getEndpoint(path + name));
m_entwine.reset(
new entwine::Reader(
endpoint,
*outerScope.getArbiter(),
*cache));
}
catch (const std::runtime_error& e)
{
err = e.what();
}
catch (...)
{
err = "unknown error";
m_entwine.reset(0);
}
std::cout << "\tTried resolving index at " << path << ": ";
if (m_entwine)
{
std::cout << "SUCCESS" << std::endl;
break;
}
else
{
std::cout << "fail - " << err << std::endl;
}
}
return indexed();
}
bool Session::resolveSource(
const std::string& name,
const std::vector<std::string>& paths)
{
return false;
/*
const auto sources(resolve(paths, name));
if (sources.size() > 1)
{
std::cout << "\tFound competing unindexed sources for " << name <<
std::endl;
}
if (sources.size())
{
std::size_t i(0);
while (!m_source && i < sources.size())
{
const std::string path(sources[i++]);
std::unique_lock<std::mutex> lock(m_factoryMutex);
const std::string driver(
m_stageFactory.inferReaderDriver(path));
lock.unlock();
if (driver.size())
{
try
{
m_source.reset(
new SourceManager(
m_stageFactory,
m_factoryMutex,
path,
driver));
}
catch (...)
{
m_source.reset(0);
}
}
std::cout << "\tTried resolving unindexed at " << path << ": ";
if (m_source) std::cout << "SUCCESS" << std::endl;
else std::cout << "failed" << std::endl;
}
}
return sourced();
*/
}
<commit_msg>Entwine API catch up.<commit_after>#include <fstream>
#include <iostream>
#include <glob.h>
#include <pdal/StageFactory.hpp>
#include <entwine/third/arbiter/arbiter.hpp>
#include <entwine/reader/query.hpp>
#include <entwine/reader/reader.hpp>
#include <entwine/third/json/json.hpp>
#include <entwine/tree/clipper.hpp>
#include <entwine/types/bounds.hpp>
#include <entwine/types/format.hpp>
#include <entwine/types/metadata.hpp>
#include <entwine/types/schema.hpp>
#include <entwine/types/structure.hpp>
#include <entwine/util/executor.hpp>
#include "read-queries/entwine.hpp"
#include "read-queries/unindexed.hpp"
#include "util/buffer-pool.hpp"
#include "session.hpp"
namespace
{
/*
std::vector<std::string> resolve(
const std::vector<std::string>& dirs,
const std::string& name)
{
glob_t buffer;
for (std::size_t i(0); i < dirs.size(); ++i)
{
auto flags(GLOB_NOSORT | GLOB_TILDE);
if (i) flags |= GLOB_APPEND;
glob((dirs[i] + "/" + name + ".*").c_str(), flags, 0, &buffer);
}
std::vector<std::string> results;
for (std::size_t i(0); i < buffer.gl_pathc; ++i)
{
results.push_back(buffer.gl_pathv[i]);
}
globfree(&buffer);
return results;
}
*/
std::string getTypeString(const entwine::Structure& structure)
{
if (structure.dimensions() == 2)
{
if (structure.tubular()) return "octree";
else return "quadtree";
}
else if (structure.dimensions() == 3 && !structure.tubular())
{
return "octree";
}
else
{
throw std::runtime_error("Invalid structure");
}
}
}
Session::Session(
pdal::StageFactory& stageFactory,
std::mutex& factoryMutex)
: m_stageFactory(stageFactory)
, m_factoryMutex(factoryMutex)
, m_initOnce()
, m_source()
, m_entwine()
{ }
Session::~Session()
{ }
bool Session::initialize(
const std::string& name,
std::vector<std::string> paths,
entwine::OuterScope& outerScope,
std::shared_ptr<entwine::Cache> cache)
{
m_initOnce.ensure([this, &name, &paths, &cache, &outerScope]()
{
std::cout << "Discovering " << name << std::endl;
if (resolveIndex(name, paths, outerScope, cache))
{
std::cout << "\tIndex for " << name << " found" << std::endl;
Json::Value json;
const entwine::Metadata& metadata(m_entwine->metadata());
const std::size_t numPoints(
metadata.manifest().pointStats().inserts());
json["type"] = getTypeString(metadata.structure());
json["numPoints"] = static_cast<Json::UInt64>(numPoints);
json["schema"] = metadata.schema().toJson();
json["bounds"] = metadata.bounds().toJson();
json["boundsConforming"] = metadata.boundsConforming().toJson();
json["srs"] = metadata.format().srs();
json["baseDepth"] = static_cast<Json::UInt64>(
metadata.structure().nullDepthEnd());
m_info = json.toStyledString();
}
else if (resolveSource(name, paths))
{
std::cout << "\tSource for " << name << " found" << std::endl;
const std::size_t numPoints(m_source->numPoints());
Json::Value json;
json["type"] = "unindexed";
json["numPoints"] = static_cast<Json::UInt64>(numPoints);
json["schema"] = m_source->schema().toJson();
json["bounds"] = m_source->bounds().toJson();
json["srs"] = m_source->srs();
m_info = json.toStyledString();
}
else
{
std::cout << "\tBacking for " << name << " NOT found" << std::endl;
}
});
return sourced() || indexed();
}
std::string Session::info() const
{
check();
return m_info;
}
std::string Session::hierarchy(
const entwine::Bounds& bounds,
const std::size_t depthBegin,
const std::size_t depthEnd) const
{
if (indexed())
{
Json::FastWriter writer;
return writer.write(
m_entwine->hierarchy(bounds, depthBegin, depthEnd));
}
else
{
throw std::runtime_error("Cannot get hierarchy from unindexed dataset");
}
}
std::shared_ptr<ReadQuery> Session::query(
const entwine::Schema& schema,
const bool compress)
{
if (sourced())
{
return std::shared_ptr<ReadQuery>(
new UnindexedReadQuery(
schema,
compress,
*m_source));
}
else
{
throw WrongQueryType();
}
}
std::shared_ptr<ReadQuery> Session::query(
const entwine::Schema& schema,
const bool compress,
const double scale,
const entwine::Point& offset,
const entwine::Bounds* bounds,
const std::size_t depthBegin,
const std::size_t depthEnd)
{
if (indexed())
{
return std::shared_ptr<ReadQuery>(
new EntwineReadQuery(
schema,
compress,
m_entwine->query(
schema,
bounds ? *bounds : m_entwine->metadata().bounds(),
depthBegin,
depthEnd,
scale,
offset)));
}
else
{
throw WrongQueryType();
}
}
const entwine::Schema& Session::schema() const
{
check();
if (indexed()) return m_entwine->metadata().schema();
else return m_source->schema();
}
bool Session::resolveIndex(
const std::string& name,
const std::vector<std::string>& paths,
entwine::OuterScope& outerScope,
std::shared_ptr<entwine::Cache> cache)
{
for (std::string path : paths)
{
std::string err;
try
{
if (path.size() && path.back() != '/') path.push_back('/');
entwine::arbiter::Endpoint endpoint(
outerScope.getArbiterPtr()->getEndpoint(path + name));
m_entwine.reset(new entwine::Reader(endpoint, *cache));
}
catch (const std::runtime_error& e)
{
err = e.what();
}
catch (...)
{
err = "unknown error";
m_entwine.reset(0);
}
std::cout << "\tTried resolving index at " << path << ": ";
if (m_entwine)
{
std::cout << "SUCCESS" << std::endl;
break;
}
else
{
std::cout << "fail - " << err << std::endl;
}
}
return indexed();
}
bool Session::resolveSource(
const std::string& name,
const std::vector<std::string>& paths)
{
return false;
/*
const auto sources(resolve(paths, name));
if (sources.size() > 1)
{
std::cout << "\tFound competing unindexed sources for " << name <<
std::endl;
}
if (sources.size())
{
std::size_t i(0);
while (!m_source && i < sources.size())
{
const std::string path(sources[i++]);
std::unique_lock<std::mutex> lock(m_factoryMutex);
const std::string driver(
m_stageFactory.inferReaderDriver(path));
lock.unlock();
if (driver.size())
{
try
{
m_source.reset(
new SourceManager(
m_stageFactory,
m_factoryMutex,
path,
driver));
}
catch (...)
{
m_source.reset(0);
}
}
std::cout << "\tTried resolving unindexed at " << path << ": ";
if (m_source) std::cout << "SUCCESS" << std::endl;
else std::cout << "failed" << std::endl;
}
}
return sourced();
*/
}
<|endoftext|> |
<commit_before>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Hunspell, based on MySpell.
*
* The Initial Developers of the Original Code are
* Kevin Hendricks (MySpell) and Nmeth Lszl (Hunspell).
* Portions created by the Initial Developers are Copyright (C) 2002-2005
* the Initial Developers. All Rights Reserved.
*
* Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
* Gianluca Turconi, Simon Brouwer, Noll Jnos, Br rpd,
* Goldman Eleonra, Sarls Tams, Bencsth Boldizsr, Halcsy Pter,
* Dvornik Lszl, Gefferth Andrs, Nagy Viktor, Varga Dniel, Chris Halls,
* Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitknen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include "textparser.hxx"
#include "htmlparser.hxx"
#include "latexparser.hxx"
#include "xmlparser.hxx"
#ifndef W32
using namespace std;
#endif
int main(int argc, char** argv) {
FILE* f;
/* first parse the command line options */
if (argc < 2) {
fprintf(stderr, "correct syntax is:\n");
fprintf(stderr, "testparser file\n");
fprintf(stderr, "example: testparser /dev/stdin\n");
exit(1);
}
/* open the words to check list */
f = fopen(argv[1], "r");
if (!f) {
fprintf(stderr, "Error - could not open file of words to check\n");
exit(1);
}
TextParser* p = new TextParser(
"qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM");
char buf[MAXLNLEN];
while (fgets(buf, MAXLNLEN, f)) {
p->put_line(buf);
p->set_url_checking(1);
std::string next;
while (p->next_token(next)) {
fprintf(stdout, "token: %s\n", next.c_str());
}
}
delete p;
fclose(f);
return 0;
}
<commit_msg>drop this to pass -Winvalid-source-encoding<commit_after>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Hunspell, based on MySpell.
*
* The Initial Developers of the Original Code are
* Kevin Hendricks (MySpell) and Nmeth Lszl (Hunspell).
* Portions created by the Initial Developers are Copyright (C) 2002-2005
* the Initial Developers. All Rights Reserved.
*
* Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
* Gianluca Turconi, Simon Brouwer, Noll Jnos, Br rpd,
* Goldman Eleonra, Sarls Tams, Bencsth Boldizsr, Halcsy Pter,
* Dvornik Lszl, Gefferth Andrs, Nagy Viktor, Varga Dniel, Chris Halls,
* Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitknen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include "textparser.hxx"
#include "htmlparser.hxx"
#include "latexparser.hxx"
#include "xmlparser.hxx"
#ifndef W32
using namespace std;
#endif
int main(int argc, char** argv) {
FILE* f;
/* first parse the command line options */
if (argc < 2) {
fprintf(stderr, "correct syntax is:\n");
fprintf(stderr, "testparser file\n");
fprintf(stderr, "example: testparser /dev/stdin\n");
exit(1);
}
/* open the words to check list */
f = fopen(argv[1], "r");
if (!f) {
fprintf(stderr, "Error - could not open file of words to check\n");
exit(1);
}
TextParser* p = new TextParser(
"qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM");
char buf[MAXLNLEN];
while (fgets(buf, MAXLNLEN, f)) {
p->put_line(buf);
p->set_url_checking(1);
std::string next;
while (p->next_token(next)) {
fprintf(stdout, "token: %s\n", next.c_str());
}
}
delete p;
fclose(f);
return 0;
}
<|endoftext|> |
<commit_before>/*
c++ xapiand.cc server.cc threadpool.cc ../../net/length.cc -lev `xapian-config-1.3 --libs` `xapian-config-1.3 --cxxflags` -I../../ -I../../common -DXAPIAN_LIB_BUILD -oxapiand
*/
#include <stdlib.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h> /* for TCP_NODELAY */
#include <sys/socket.h>
#include "utils.h"
#include "config.h"
#include "server.h"
int bind_http(int http_port)
{
int error;
int optval = 1;
struct sockaddr_in addr;
struct linger ling = {0, 0};
int http_sock = socket(PF_INET, SOCK_STREAM, 0);
setsockopt(http_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval));
error = setsockopt(http_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno));
error = setsockopt(http_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno));
error = setsockopt(http_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno));
addr.sin_family = AF_INET;
addr.sin_port = htons(http_port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(http_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
LOG_CONN((void *)NULL, "ERROR: http bind error (sock=%d): %s\n", http_sock, strerror(errno));
close(http_sock);
http_sock = -1;
} else {
LOG_CONN((void *)NULL, "Listening http protocol on port %d\n", http_port);
fcntl(http_sock, F_SETFL, fcntl(http_sock, F_GETFL, 0) | O_NONBLOCK);
listen(http_sock, 5);
}
return http_sock;
}
int bind_binary(int binary_port)
{
int error;
int optval = 1;
struct sockaddr_in addr;
struct linger ling = {0, 0};
int binary_sock = socket(PF_INET, SOCK_STREAM, 0);
setsockopt(binary_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval));
error = setsockopt(binary_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno));
error = setsockopt(binary_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno));
error = setsockopt(binary_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno));
addr.sin_family = AF_INET;
addr.sin_port = htons(binary_port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(binary_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
LOG_CONN((void *)NULL, "ERROR: binary bind error (sock=%d): %s\n", binary_sock, strerror(errno));
close(binary_sock);
binary_sock = -1;
} else {
LOG_CONN((void *)NULL, "Listening binary protocol on port %d\n", binary_port);
fcntl(binary_sock, F_SETFL, fcntl(binary_sock, F_GETFL, 0) | O_NONBLOCK);
listen(binary_sock, 5);
}
return binary_sock;
}
int main(int argc, char **argv)
{
int http_port = XAPIAND_HTTP_PORT_DEFAULT;
int binary_port = XAPIAND_BINARY_PORT_DEFAULT;
if (argc > 2) {
http_port = atoi(argv[1]);
binary_port = atoi(argv[2]);
}
LOG((void *)NULL, "Starting Xapiand.\n");
int http_sock = bind_http(http_port);
int binary_sock = bind_binary(binary_port);
int tasks = 0;
if (http_sock != -1 && binary_sock != -1) {
ev::default_loop loop;
if (tasks) {
ThreadPool thread_pool(tasks);
for (int i = 0; i < tasks; i++) {
thread_pool.addTask(new XapiandServer(NULL, http_sock, binary_sock));
}
loop.run();
LOG_OBJ((void *)NULL, "Waiting for threads...\n");
thread_pool.finish();
thread_pool.join();
} else {
XapiandServer * server = new XapiandServer(&loop, http_sock, binary_sock);
server->run();
}
}
if (http_sock != -1) {
close(http_sock);
}
if (binary_sock != -1) {
close(binary_sock);
}
LOG((void *)NULL, "Done with all work!\n");
return 0;
}
<commit_msg>Allocate memory for ThreadPool object<commit_after>/*
c++ xapiand.cc server.cc threadpool.cc ../../net/length.cc -lev `xapian-config-1.3 --libs` `xapian-config-1.3 --cxxflags` -I../../ -I../../common -DXAPIAN_LIB_BUILD -oxapiand
*/
#include <stdlib.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h> /* for TCP_NODELAY */
#include <sys/socket.h>
#include "utils.h"
#include "config.h"
#include "server.h"
int bind_http(int http_port)
{
int error;
int optval = 1;
struct sockaddr_in addr;
struct linger ling = {0, 0};
int http_sock = socket(PF_INET, SOCK_STREAM, 0);
setsockopt(http_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval));
error = setsockopt(http_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno));
error = setsockopt(http_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno));
error = setsockopt(http_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno));
addr.sin_family = AF_INET;
addr.sin_port = htons(http_port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(http_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
LOG_CONN((void *)NULL, "ERROR: http bind error (sock=%d): %s\n", http_sock, strerror(errno));
close(http_sock);
http_sock = -1;
} else {
LOG_CONN((void *)NULL, "Listening http protocol on port %d\n", http_port);
fcntl(http_sock, F_SETFL, fcntl(http_sock, F_GETFL, 0) | O_NONBLOCK);
listen(http_sock, 5);
}
return http_sock;
}
int bind_binary(int binary_port)
{
int error;
int optval = 1;
struct sockaddr_in addr;
struct linger ling = {0, 0};
int binary_sock = socket(PF_INET, SOCK_STREAM, 0);
setsockopt(binary_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval));
error = setsockopt(binary_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno));
error = setsockopt(binary_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno));
error = setsockopt(binary_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval));
if (error != 0)
LOG_CONN((void *)NULL, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno));
addr.sin_family = AF_INET;
addr.sin_port = htons(binary_port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(binary_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
LOG_CONN((void *)NULL, "ERROR: binary bind error (sock=%d): %s\n", binary_sock, strerror(errno));
close(binary_sock);
binary_sock = -1;
} else {
LOG_CONN((void *)NULL, "Listening binary protocol on port %d\n", binary_port);
fcntl(binary_sock, F_SETFL, fcntl(binary_sock, F_GETFL, 0) | O_NONBLOCK);
listen(binary_sock, 5);
}
return binary_sock;
}
int main(int argc, char **argv)
{
int http_port = XAPIAND_HTTP_PORT_DEFAULT;
int binary_port = XAPIAND_BINARY_PORT_DEFAULT;
if (argc > 2) {
http_port = atoi(argv[1]);
binary_port = atoi(argv[2]);
}
LOG((void *)NULL, "Starting Xapiand.\n");
int http_sock = bind_http(http_port);
int binary_sock = bind_binary(binary_port);
int tasks = 0;
if (http_sock != -1 && binary_sock != -1) {
ev::default_loop loop;
if (tasks) {
ThreadPool *thread_pool = new ThreadPool(tasks);
for (int i = 0; i < tasks; i++) {
XapiandServer * server = new XapiandServer(NULL, http_sock, binary_sock);
thread_pool->addTask(server);
}
loop.run();
LOG_OBJ((void *)NULL, "Waiting for threads...\n");
thread_pool->finish();
thread_pool->join();
delete thread_pool;
} else {
XapiandServer * server = new XapiandServer(&loop, http_sock, binary_sock);
server->run();
}
}
if (http_sock != -1) {
close(http_sock);
}
if (binary_sock != -1) {
close(binary_sock);
}
LOG((void *)NULL, "Done with all work!\n");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Patterns.cpp
*
* Created on: April 21, 2010
* Author: Marian Anghel and Craig Rasmussen
*/
#include "Patterns.hpp"
#include <src/include/pv_common.h> // for PI
#include <src/utils/pv_random.h>
#define MAXVAL 1.0f
namespace PV {
// CER-new
FILE * fp;
int start = 0;
Patterns::Patterns(const char * name, HyPerCol * hc, PatternType type) :
Image(name, hc)
{
// CER-new
fp = fopen("bar-pos.txt", "w");
this->type = type;
// set default params
// set reference position of bars
this->prefPosition = 3;
this->position = this->prefPosition;
this->lastPosition = this->prefPosition;
// set bars orientation to default values
this->orientation = vertical;
this->lastOrientation = orientation;
const PVLayerLoc * loc = getLayerLoc();
// check for explicit parameters in params.stdp
//
PVParams * params = hc->parameters();
minWidth = 4.0;
minHeight = 4.0;
maxWidth = params->value(name, "width", loc->nx);
maxHeight = params->value(name, "height", loc->ny);
pMove = params->value(name, "pMove", 0.0);
pSwitch = params->value(name, "pSwitch", 0.0);
// set parameters that controls writing of new images
writeImages = params->value(name, "writeImages", 0.0);
initPattern(MAXVAL);
// make sure initialization is finished
updateState(0.0, 0.0);
}
Patterns::~Patterns()
{
// CER-new
fclose(fp);
}
int Patterns::tag()
{
if (orientation == vertical) return position;
else return 10*position;
}
int Patterns::initPattern(float val)
{
int width, height;
const int interval = 4;
// extended frame
const PVLayerLoc * loc = getLayerLoc();
const int nx = loc->nx + 2 * loc->nb;
const int ny = loc->ny + 2 * loc->nb;
const int sx = 1;
const int sy = sx * nx;
// reset data buffer
const int nk = nx * ny;
for (int k = 0; k < nk; k++) {
data[k] = 0.0;
}
if (type == RECTANGLES) {
width = minWidth + (maxWidth - minWidth) * pv_random_prob();
height = minHeight + (maxHeight - minHeight) * pv_random_prob();
const int half_w = width/2;
const int half_h = height/2;
// random center location
const int xc = (nx-1) * pv_random_prob();
const int yc = (ny-1) * pv_random_prob();
const int x0 = (xc - half_w < 0) ? 0 : xc - half_w;
const int y0 = (yc - half_h < 0) ? 0 : yc - half_h;
const int x1 = (xc + half_w > nx) ? nx : xc + half_w;
const int y1 = (yc + half_h > ny) ? ny : yc + half_h;
for (int iy = y0; iy < y1; iy++) {
for (int ix = x0; ix < x1; ix++) {
data[ix * sx + iy * sy] = val;
}
}
position = x0 + y0*nx;
return 0;
}
// type is bars
if (orientation == vertical) { // vertical bars
width = maxWidth;
for (int iy = 0; iy < ny; iy++) {
for (int ix = 0; ix < nx; ix++) {
int m = (ix + position) % (2*width);
data[ix * sx + iy * sy] = (m < width) ? val : 0;
}
}
}
else { // horizontal bars
height = maxHeight;
for (int iy = 0; iy < ny; iy++) {
int m = (iy + position) % (2*height);
for (int ix = 0; ix < nx; ix++) {
data[ix * sx + iy * sy] = (m < height) ? val : 0;
}
}
}
return 0;
}
/**
* update the image buffers
*/
int Patterns::updateState(float time, float dt)
{
int size = 0;
// alternate between vertical and horizontal bars
double p = pv_random_prob();
if (orientation == vertical) { // current vertical gratings
size = maxWidth;
if (p < pSwitch) { // switch with probability pSwitch
orientation = horizontal;
initPattern(MAXVAL);
}
}
else {
size = maxHeight;
if (p < pSwitch) { // current horizontal gratings
orientation = vertical;
initPattern(MAXVAL);
}
}
// moving probability
double p_move = pv_random_prob();
if (p_move < pMove) {
position = calcPosition(position, 2*size);
//position = (start++) % 4;
//position = prefPosition;
initPattern(MAXVAL);
//fprintf(fp, "%d %d %d\n", 2*(int)time, position, lastPosition);
}
else {
position = lastPosition;
}
if (lastPosition != position || lastOrientation != orientation) {
lastPosition = position;
lastOrientation = orientation;
lastUpdateTime = time;
if (writeImages) {
char basicfilename[PV_PATH_MAX+1]; // is +1 needed?
snprintf(basicfilename, PV_PATH_MAX, "Bars_%.2f.tif", time);
write(basicfilename);
}
return 1;
}
else {
return 0;
}
}
/**
*
* Return an integer between 0 and (step-1)
*/
int Patterns::calcPosition(int pos, int step)
{
float dp = 1.0 / step;
double p = pv_random_prob();
int random_walk = 1;
int move_forward = 0;
int move_backward = 0;
int random_jump = 0;
if (random_walk) {
if (p < 0.5){
pos = (pos+1) % step;
} else {
pos = (pos-1+step) % step;
}
//printf("pos = %f\n",position);
} else if (move_forward){
pos = (pos+1) % step;
} else if (move_backward){
pos = (pos-1+step) % step;
}
else if (random_jump) {
pos = int(p * step) % step;
}
return pos;
}
} // namespace PV
<commit_msg>commented out bar-pos<commit_after>/*
* Patterns.cpp
*
* Created on: April 21, 2010
* Author: Marian Anghel and Craig Rasmussen
*/
#include "Patterns.hpp"
#include <src/include/pv_common.h> // for PI
#include <src/utils/pv_random.h>
#define MAXVAL 1.0f
namespace PV {
// CER-new
FILE * fp;
int start = 0;
Patterns::Patterns(const char * name, HyPerCol * hc, PatternType type) :
Image(name, hc)
{
// CER-new
//fp = fopen("bar-pos.txt", "w");
this->type = type;
// set default params
// set reference position of bars
this->prefPosition = 3;
this->position = this->prefPosition;
this->lastPosition = this->prefPosition;
// set bars orientation to default values
this->orientation = vertical;
this->lastOrientation = orientation;
const PVLayerLoc * loc = getLayerLoc();
// check for explicit parameters in params.stdp
//
PVParams * params = hc->parameters();
minWidth = 4.0;
minHeight = 4.0;
maxWidth = params->value(name, "width", loc->nx);
maxHeight = params->value(name, "height", loc->ny);
pMove = params->value(name, "pMove", 0.0);
pSwitch = params->value(name, "pSwitch", 0.0);
// set parameters that controls writing of new images
writeImages = params->value(name, "writeImages", 0.0);
initPattern(MAXVAL);
// make sure initialization is finished
updateState(0.0, 0.0);
}
Patterns::~Patterns()
{
// CER-new
//fclose(fp);
}
int Patterns::tag()
{
if (orientation == vertical) return position;
else return 10*position;
}
int Patterns::initPattern(float val)
{
int width, height;
const int interval = 4;
// extended frame
const PVLayerLoc * loc = getLayerLoc();
const int nx = loc->nx + 2 * loc->nb;
const int ny = loc->ny + 2 * loc->nb;
const int sx = 1;
const int sy = sx * nx;
// reset data buffer
const int nk = nx * ny;
for (int k = 0; k < nk; k++) {
data[k] = 0.0;
}
if (type == RECTANGLES) {
width = minWidth + (maxWidth - minWidth) * pv_random_prob();
height = minHeight + (maxHeight - minHeight) * pv_random_prob();
const int half_w = width/2;
const int half_h = height/2;
// random center location
const int xc = (nx-1) * pv_random_prob();
const int yc = (ny-1) * pv_random_prob();
const int x0 = (xc - half_w < 0) ? 0 : xc - half_w;
const int y0 = (yc - half_h < 0) ? 0 : yc - half_h;
const int x1 = (xc + half_w > nx) ? nx : xc + half_w;
const int y1 = (yc + half_h > ny) ? ny : yc + half_h;
for (int iy = y0; iy < y1; iy++) {
for (int ix = x0; ix < x1; ix++) {
data[ix * sx + iy * sy] = val;
}
}
position = x0 + y0*nx;
return 0;
}
// type is bars
if (orientation == vertical) { // vertical bars
width = maxWidth;
for (int iy = 0; iy < ny; iy++) {
for (int ix = 0; ix < nx; ix++) {
int m = (ix + position) % (2*width);
data[ix * sx + iy * sy] = (m < width) ? val : 0;
}
}
}
else { // horizontal bars
height = maxHeight;
for (int iy = 0; iy < ny; iy++) {
int m = (iy + position) % (2*height);
for (int ix = 0; ix < nx; ix++) {
data[ix * sx + iy * sy] = (m < height) ? val : 0;
}
}
}
return 0;
}
/**
* update the image buffers
*/
int Patterns::updateState(float time, float dt)
{
int size = 0;
// alternate between vertical and horizontal bars
double p = pv_random_prob();
if (orientation == vertical) { // current vertical gratings
size = maxWidth;
if (p < pSwitch) { // switch with probability pSwitch
orientation = horizontal;
initPattern(MAXVAL);
}
}
else {
size = maxHeight;
if (p < pSwitch) { // current horizontal gratings
orientation = vertical;
initPattern(MAXVAL);
}
}
// moving probability
double p_move = pv_random_prob();
if (p_move < pMove) {
position = calcPosition(position, 2*size);
//position = (start++) % 4;
//position = prefPosition;
initPattern(MAXVAL);
//fprintf(fp, "%d %d %d\n", 2*(int)time, position, lastPosition);
}
else {
position = lastPosition;
}
if (lastPosition != position || lastOrientation != orientation) {
lastPosition = position;
lastOrientation = orientation;
lastUpdateTime = time;
if (writeImages) {
char basicfilename[PV_PATH_MAX+1]; // is +1 needed?
snprintf(basicfilename, PV_PATH_MAX, "Bars_%.2f.tif", time);
write(basicfilename);
}
return 1;
}
else {
return 0;
}
}
/**
*
* Return an integer between 0 and (step-1)
*/
int Patterns::calcPosition(int pos, int step)
{
float dp = 1.0 / step;
double p = pv_random_prob();
int random_walk = 1;
int move_forward = 0;
int move_backward = 0;
int random_jump = 0;
if (random_walk) {
if (p < 0.5){
pos = (pos+1) % step;
} else {
pos = (pos-1+step) % step;
}
//printf("pos = %f\n",position);
} else if (move_forward){
pos = (pos+1) % step;
} else if (move_backward){
pos = (pos-1+step) % step;
}
else if (random_jump) {
pos = int(p * step) % step;
}
return pos;
}
} // namespace PV
<|endoftext|> |
<commit_before>
#include "lcio.h"
#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "DATA/LCFloatVec.h"
#include "DATA/LCIntVec.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/SimCalorimeterHitImpl.h"
#include "IMPL/SimTrackerHitImpl.h"
#include "IMPL/MCParticleImpl.h"
#include "IMPL/LCFlagImpl.h"
#include "IMPL/LCTOOLS.h"
#include "IMPL/TPCHitImpl.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std ;
using namespace lcio ;
static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NMCPART = 10 ; // mc particles per event
static const int NHITS = 50 ; // calorimeter hits per event
static string FILEN = "simjob.slcio" ;
/** Simple test program to demonstrate writing of data with lcio.
*/
int main(int argc, char** argv ){
try{
// loop over runs
for(int rn=0;rn<NRUN;rn++){
// create sio writer
LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;
if( argc > 1 ) { FILEN = argv[1] ; }
if( rn==0 )
lcWrt->open( FILEN , LCIO::WRITE_NEW ) ;
else
lcWrt->open( FILEN , LCIO::WRITE_APPEND ) ;
// NB: in order to test writing multiple files we create a new LCWriter
// for every run even though we are in fact writing to one file only;
// so for a simple job writing one file the
// 'createLCWriter/open' and 'close/delete' will be outside the run loop...
LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ;
runHdr->setRunNumber( rn ) ;
string detName("D09TileHcal") ;
runHdr->setDetectorName( detName ) ;
stringstream description ;
description << " run: " << rn <<" just for testing lcio - no physics !" ;
runHdr->setDescription( description.str() ) ;
string ecalName("ECAL007") ;
runHdr->addActiveSubdetector( ecalName ) ;
string tpcName("TPC4711") ;
runHdr->addActiveSubdetector( tpcName ) ;
lcWrt->writeRunHeader( runHdr ) ;
// EventLoop - create some events and write them to the file
for(int i=0;i<NEVENT;i++){
// we need to use the implementation classes here
LCEventImpl* evt = new LCEventImpl() ;
evt->setRunNumber( rn ) ;
evt->setEventNumber( i ) ;
evt->setDetectorName( detName ) ;
// create and add some mc particles
LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;
// debug only - add the same particle to more than one collection
//LCCollectionVec* mcVec2 = new LCCollectionVec( LCIO::MCPARTICLE ) ;
MCParticleImpl* mom = new MCParticleImpl ;
mom->setPDG( 1 ) ;
float p0[3] = { 0. , 0. , 1000. } ;
mom->setMomentum( p0 ) ;
mom->setMass( 3.01 ) ;
for(int j=0;j<NMCPART;j++){
MCParticleImpl* mcp = new MCParticleImpl ;
mcp->setPDG( 1000 * (j+1) ) ;
float p[3] = { j*1. , 4./1024. , 8./1024. } ;
mcp->setMomentum( p ) ;
mcp->setMass( .135 ) ;
// create and add some daughters
for(int k=0;k<3;k++){
MCParticleImpl* d1 = new MCParticleImpl ;
d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;
float pd1[3] = { k*1. , 4.1 , 8.1 } ;
d1->setMomentum( pd1 ) ;
d1->setMass( .135 ) ;
for(int l=0;l<2;l++){
MCParticleImpl* d2 = new MCParticleImpl ;
d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;
float pd2[3] = { l*1. , 0.41 , 4.1 } ;
d2->setMomentum( pd2 ) ;
d2->setMass( .135 ) ;
double ep[3] = { 1.111111 , 2.2222222, 3.3333333 } ;
d2->setEndpoint( ep ) ;
// d2->setSimulatorStatus( 1234 ) ;
d2->setCreatedInSimulation(true) ;
d2->setBackscatter(true) ;
d2->setDecayedInTracker(true) ;
d2->setDecayedInCalorimeter(false);
d2->setHasLeftDetector(false) ;
d2->setStopped(true) ;
d2->addParent( d1 );
mcVec->push_back( d2 ) ;
// debug only - add the same particle to more than one collection
//mcVec2->push_back( d2 ) ;
}
d1->addParent( mcp );
mcVec->push_back( d1 ) ;
}
mcp->addParent( mom );
mcVec->push_back( mcp ) ;
}
mcVec->push_back( mom ) ;
// now add some calorimeter hits
LCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;
// set flag for long format (including position )
// and PDG and cellid1
LCFlagImpl chFlag(0) ;
chFlag.setBit( LCIO::CHBIT_LONG ) ;
chFlag.setBit( LCIO::CHBIT_PDG ) ;
chFlag.setBit( LCIO::CHBIT_ID1 ) ;
calVec->setFlag( chFlag.getFlag() ) ;
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;
hit->setEnergy( 3.1415 * rand()/RAND_MAX ) ;
float pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setCellID0( 1024 ) ;
hit->setCellID1( 65535 ) ;
hit->setPosition( pos ) ;
calVec->push_back( hit ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
// in order to access a MCParticle, we need a dynamic cast as the
// LCCollection returns an LCIOObject - this is like vectors in Java
hit->addMCParticleContribution( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx )) ,
0.314159, 0.1155 ) ; // no pdg
}
// -------- data can be modified as long as is not not made persistent --------
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* existingHit
= dynamic_cast<SimCalorimeterHitImpl*>( calVec->getElementAt(j) ) ; // << Ok now
// = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ; // << not needed
existingHit->addMCParticleContribution( dynamic_cast<MCParticle*>
(mcVec->getElementAt(0)),
0.1, 0. ) ;
}
// and finally some tracker hits
// with some user extensions (4 floats and 2 ints) per track:
// we just need to create parallel collections of float and int vectors
LCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;
LCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;
for(int j=0;j<NHITS;j++){
SimTrackerHitImpl* hit = new SimTrackerHitImpl ;
LCFloatVec* extF = new LCFloatVec ;
LCIntVec* extI = new LCIntVec ;
hit->setdEdx( 30e-9 ) ;
double pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setPosition( pos ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
hit->setMCParticle( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;
// fill the extension vectors (4 floats, 2 ints)
extF->push_back( 3.14159 ) ;
for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;
extI->push_back( 123456789 ) ;
extI->push_back( mcIndx ) ;
// add the hit and the extensions to their corresponding collections
trkVec->push_back( hit ) ;
extFVec->push_back( extF ) ;
extIVec->push_back( extI ) ;
}
// add all collections to the event
evt->addCollection( mcVec , "MCParticle" ) ;
//deubg only
//evt->addCollection( mcVec2, "MCParticle2" ) ;
evt->addCollection( calVec , ecalName ) ;
evt->addCollection( trkVec , tpcName ) ;
evt->addCollection( extFVec , tpcName+"UserFloatExtension" ) ;
evt->addCollection( extIVec , tpcName+"UserIntExtension" ) ;
// test: add a collection for one event only:
// if( rn == NRUN-1 && i == 0 ) { // first event o last run
if( rn == 1 && i == 0 ) { // first event o last run
LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCFloatVec* addExt = new LCFloatVec ;
addExt->push_back( 1. );
addExt->push_back( 2. );
addExt->push_back( 3. );
addExt->push_back( 4. );
addExtVec->push_back( addExt ) ;
evt->addCollection( addExtVec , "AdditionalExtension" ) ;
}
// even though this is a simjob we can store 'real data' objects :)
// --- for example we can store TPC hits ------------
LCCollectionVec* TPCVec = new LCCollectionVec( LCIO::TPCHIT ) ;
bool storeRawData = true ;
LCFlagImpl tpcFlag(0) ;
if( storeRawData ) // if we want to store the raw data we need to set the flag
tpcFlag.setBit( LCIO::TPCBIT_RAW ) ;
TPCVec->setFlag( tpcFlag.getFlag() ) ;
for(int j=0;j<NHITS;j++){
TPCHitImpl* tpcHit = new TPCHitImpl ;
tpcHit->setCellID( j ) ;
tpcHit->setTime( 0.1234567 ) ;
tpcHit->setCharge( 3.14159 ) ;
tpcHit->setQuality( 0xbad ) ;
if( storeRawData ) {
int rawData[10] ;
// fill some random numbers
int size = int( (double(rand()) / RAND_MAX ) * 10 ) ;
for(int k=0;k<size;k++){
rawData[k] = int( (double(rand()) / RAND_MAX ) * INT_MAX ) ;
}
tpcHit->setRawData( rawData , size ) ;
}
TPCVec->push_back( tpcHit ) ;
}
evt->addCollection( TPCVec , "TPCRawFADC" ) ;
//-------------- all for TPC --------------------
// write the event to the file
lcWrt->writeEvent( evt ) ;
// dump the event to the screen
LCTOOLS::dumpEvent( evt ) ;
// ------------ IMPORTANT ------------- !
// we created the event so we need to delete it ...
delete evt ;
// -------------------------------------
if( ! (i%100) ) cout << ". " << flush ;
} // evt loop
delete runHdr ;
lcWrt->close() ;
delete lcWrt ;
} // run loop
cout << endl
<< " created " << NRUN << " runs with " << NRUN*NEVENT << " events"
<< endl << endl ;
} catch( Exception& ex){
cout << " an excpetion occured: " << endl ;
cout << " " << ex.what() << endl ;
return 1 ;
}
return 0 ;
}
<commit_msg>small correction for output<commit_after>
#include "lcio.h"
#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "DATA/LCFloatVec.h"
#include "DATA/LCIntVec.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/SimCalorimeterHitImpl.h"
#include "IMPL/SimTrackerHitImpl.h"
#include "IMPL/MCParticleImpl.h"
#include "IMPL/LCFlagImpl.h"
#include "IMPL/LCTOOLS.h"
#include "IMPL/TPCHitImpl.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std ;
using namespace lcio ;
static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NMCPART = 10 ; // mc particles per event
static const int NHITS = 50 ; // calorimeter hits per event
static string FILEN = "simjob.slcio" ;
/** Simple test program to demonstrate writing of data with lcio.
*/
int main(int argc, char** argv ){
try{
// loop over runs
for(int rn=0;rn<NRUN;rn++){
// create sio writer
LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;
if( argc > 1 ) { FILEN = argv[1] ; }
if( rn==0 )
lcWrt->open( FILEN , LCIO::WRITE_NEW ) ;
else
lcWrt->open( FILEN , LCIO::WRITE_APPEND ) ;
// NB: in order to test writing multiple files we create a new LCWriter
// for every run even though we are in fact writing to one file only;
// so for a simple job writing one file the
// 'createLCWriter/open' and 'close/delete' will be outside the run loop...
LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ;
runHdr->setRunNumber( rn ) ;
string detName("D09TileHcal") ;
runHdr->setDetectorName( detName ) ;
stringstream description ;
description << " run: " << rn <<" just for testing lcio - no physics !" ;
runHdr->setDescription( description.str() ) ;
string ecalName("ECAL007") ;
runHdr->addActiveSubdetector( ecalName ) ;
string tpcName("TPC4711") ;
runHdr->addActiveSubdetector( tpcName ) ;
lcWrt->writeRunHeader( runHdr ) ;
// EventLoop - create some events and write them to the file
for(int i=0;i<NEVENT;i++){
// we need to use the implementation classes here
LCEventImpl* evt = new LCEventImpl() ;
evt->setRunNumber( rn ) ;
evt->setEventNumber( i ) ;
evt->setDetectorName( detName ) ;
// create and add some mc particles
LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;
// debug only - add the same particle to more than one collection
//LCCollectionVec* mcVec2 = new LCCollectionVec( LCIO::MCPARTICLE ) ;
MCParticleImpl* mom = new MCParticleImpl ;
mom->setPDG( 1 ) ;
float p0[3] = { 0. , 0. , 1000. } ;
mom->setMomentum( p0 ) ;
mom->setMass( 3.01 ) ;
for(int j=0;j<NMCPART;j++){
MCParticleImpl* mcp = new MCParticleImpl ;
mcp->setPDG( 1000 * (j+1) ) ;
float p[3] = { j*1. , 4./1024. , 8./1024. } ;
mcp->setMomentum( p ) ;
mcp->setMass( .135 ) ;
// create and add some daughters
for(int k=0;k<3;k++){
MCParticleImpl* d1 = new MCParticleImpl ;
d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;
float pd1[3] = { k*1. , 4.1 , 8.1 } ;
d1->setMomentum( pd1 ) ;
d1->setMass( .135 ) ;
for(int l=0;l<2;l++){
MCParticleImpl* d2 = new MCParticleImpl ;
d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;
float pd2[3] = { l*1. , 0.41 , 4.1 } ;
d2->setMomentum( pd2 ) ;
d2->setMass( .135 ) ;
double ep[3] = { 1.111111 , 2.2222222, 3.3333333 } ;
d2->setEndpoint( ep ) ;
// d2->setSimulatorStatus( 1234 ) ;
d2->setCreatedInSimulation(true) ;
d2->setBackscatter(true) ;
d2->setDecayedInTracker(true) ;
d2->setDecayedInCalorimeter(false);
d2->setHasLeftDetector(false) ;
d2->setStopped(true) ;
d2->addParent( d1 );
mcVec->push_back( d2 ) ;
// debug only - add the same particle to more than one collection
//mcVec2->push_back( d2 ) ;
}
d1->addParent( mcp );
mcVec->push_back( d1 ) ;
}
mcp->addParent( mom );
mcVec->push_back( mcp ) ;
}
mcVec->push_back( mom ) ;
// now add some calorimeter hits
LCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;
// set flag for long format (including position )
// and PDG and cellid1
LCFlagImpl chFlag(0) ;
chFlag.setBit( LCIO::CHBIT_LONG ) ;
chFlag.setBit( LCIO::CHBIT_PDG ) ;
chFlag.setBit( LCIO::CHBIT_ID1 ) ;
calVec->setFlag( chFlag.getFlag() ) ;
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;
hit->setEnergy( 3.1415 * rand()/RAND_MAX ) ;
float pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setCellID0( 1024 ) ;
hit->setCellID1( 65535 ) ;
hit->setPosition( pos ) ;
calVec->push_back( hit ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
// in order to access a MCParticle, we need a dynamic cast as the
// LCCollection returns an LCIOObject - this is like vectors in Java
hit->addMCParticleContribution( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx )) ,
0.314159, 0.1155 ) ; // no pdg
}
// -------- data can be modified as long as is not not made persistent --------
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* existingHit
= dynamic_cast<SimCalorimeterHitImpl*>( calVec->getElementAt(j) ) ; // << Ok now
// = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ; // << not needed
existingHit->addMCParticleContribution( dynamic_cast<MCParticle*>
(mcVec->getElementAt(0)),
0.1, 0. ) ;
}
// and finally some tracker hits
// with some user extensions (4 floats and 2 ints) per track:
// we just need to create parallel collections of float and int vectors
LCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;
LCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;
for(int j=0;j<NHITS;j++){
SimTrackerHitImpl* hit = new SimTrackerHitImpl ;
LCFloatVec* extF = new LCFloatVec ;
LCIntVec* extI = new LCIntVec ;
hit->setdEdx( 30e-9 ) ;
double pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setPosition( pos ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
hit->setMCParticle( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;
// fill the extension vectors (4 floats, 2 ints)
extF->push_back( 3.14159 ) ;
for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;
extI->push_back( 123456789 ) ;
extI->push_back( mcIndx ) ;
// add the hit and the extensions to their corresponding collections
trkVec->push_back( hit ) ;
extFVec->push_back( extF ) ;
extIVec->push_back( extI ) ;
}
// add all collections to the event
evt->addCollection( mcVec , "MCParticle" ) ;
//deubg only
//evt->addCollection( mcVec2, "MCParticle2" ) ;
evt->addCollection( calVec , ecalName ) ;
evt->addCollection( trkVec , tpcName ) ;
evt->addCollection( extFVec , tpcName+"UserFloatExtension" ) ;
evt->addCollection( extIVec , tpcName+"UserIntExtension" ) ;
// test: add a collection for one event only:
// if( rn == NRUN-1 && i == 0 ) { // first event o last run
if( rn == 1 && i == 0 ) { // first event o last run
LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCFloatVec* addExt = new LCFloatVec ;
addExt->push_back( 1. );
addExt->push_back( 2. );
addExt->push_back( 3. );
addExt->push_back( 4. );
addExtVec->push_back( addExt ) ;
evt->addCollection( addExtVec , "AdditionalExtension" ) ;
}
// even though this is a simjob we can store 'real data' objects :)
// --- for example we can store TPC hits ------------
LCCollectionVec* TPCVec = new LCCollectionVec( LCIO::TPCHIT ) ;
bool storeRawData = true ;
LCFlagImpl tpcFlag(0) ;
if( storeRawData ) // if we want to store the raw data we need to set the flag
tpcFlag.setBit( LCIO::TPCBIT_RAW ) ;
TPCVec->setFlag( tpcFlag.getFlag() ) ;
for(int j=0;j<NHITS;j++){
TPCHitImpl* tpcHit = new TPCHitImpl ;
tpcHit->setCellID( j ) ;
tpcHit->setTime( 0.1234567 ) ;
tpcHit->setCharge( 3.14159 ) ;
tpcHit->setQuality( 0xbad ) ;
if( storeRawData ) {
int rawData[10] ;
// fill some random numbers
int size = int( (double(rand()) / RAND_MAX ) * 10 ) ;
for(int k=0;k<size;k++){
rawData[k] = int( (double(rand()) / RAND_MAX ) * INT_MAX ) ;
}
tpcHit->setRawData( rawData , size ) ;
}
TPCVec->push_back( tpcHit ) ;
}
evt->addCollection( TPCVec , "TPCRawFADC" ) ;
//-------------- all for TPC --------------------
// write the event to the file
lcWrt->writeEvent( evt ) ;
// dump the event to the screen
LCTOOLS::dumpEvent( evt ) ;
// ------------ IMPORTANT ------------- !
// we created the event so we need to delete it ...
delete evt ;
// -------------------------------------
// dont use this (compatibility with Fortran simjob.F)
// if( ! (i%100) ) cout << ". " << flush ;
} // evt loop
delete runHdr ;
lcWrt->close() ;
delete lcWrt ;
} // run loop
cout << endl
<< " created " << NRUN << " runs with " << NRUN*NEVENT << " events"
<< endl << endl ;
} catch( Exception& ex){
cout << " an excpetion occured: " << endl ;
cout << " " << ex.what() << endl ;
return 1 ;
}
return 0 ;
}
<|endoftext|> |
<commit_before>#include "customfilesystemmodel.h"
CustomFileSystemModel::CustomFileSystemModel()
{
}
CustomFileSystemModel::~CustomFileSystemModel()
{
}
QList<QPersistentModelIndex> CustomFileSystemModel::checkedIndexes()
{
return _checklist.toList();
}
Qt::ItemFlags CustomFileSystemModel::flags(const QModelIndex &index) const
{
return QFileSystemModel::flags(index) | Qt::ItemIsUserCheckable;
}
QVariant CustomFileSystemModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::CheckStateRole && index.column() == 0)
{
if(_checklist.contains(index))
{
return Qt::Checked;
}
else if(_partialChecklist.contains(index))
{
return Qt::PartiallyChecked;
}
else
{
QModelIndex parent = index.parent();
while(parent.isValid())
{
if(_checklist.contains(parent))
return Qt::PartiallyChecked;
parent = parent.parent();
}
}
return Qt::Unchecked;
}
return QFileSystemModel::data(index, role);
}
void CustomFileSystemModel::setIndexCheckState(const QModelIndex &index,
const Qt::CheckState state)
{
if(index.data(Qt::CheckStateRole) != state)
setData(index, state, Qt::CheckStateRole);
}
bool CustomFileSystemModel::hasCheckedSibling(const QModelIndex &index)
{
for(int i = 0; i < rowCount(index.parent()); i++)
{
QModelIndex sibling = index.sibling(i, index.column());
if(sibling.isValid())
{
if(sibling == index)
continue;
if(data(sibling, Qt::CheckStateRole) != Qt::Unchecked)
return true;
}
}
return false;
}
bool CustomFileSystemModel::setData(const QModelIndex &index,
const QVariant &value, int role)
{
QVector<int> selectionChangedRole;
selectionChangedRole << SELECTION_CHANGED_ROLE;
if(role == Qt::CheckStateRole)
{
if(value == Qt::Checked)
{
_partialChecklist.remove(index);
_checklist.insert(index);
emit dataChanged(index, index, selectionChangedRole);
if(index.parent().isValid())
{
if(index.parent().data(Qt::CheckStateRole) == Qt::Checked)
{
for(int i = 0; i < rowCount(index.parent()); i++)
{
if(index.sibling(i, index.column()).isValid())
{
if(index.sibling(i, index.column()) == index)
continue;
if(data(index.sibling(i, index.column()),
Qt::CheckStateRole) == Qt::PartiallyChecked)
setData(index.sibling(i, index.column()),
Qt::Unchecked, Qt::CheckStateRole);
}
}
}
setIndexCheckState(index.parent(), Qt::PartiallyChecked);
}
if(isDir(index))
{
for(int i = 0; i < rowCount(index); i++)
{
if(index.child(i, index.column()).isValid())
setData(index.child(i, index.column()),
Qt::PartiallyChecked, Qt::CheckStateRole);
}
}
}
else if(value == Qt::PartiallyChecked)
{
if(_checklist.remove(index))
emit dataChanged(index, index, selectionChangedRole);
_partialChecklist.insert(index);
if(index.parent().isValid() &&
(index.parent().data(Qt::CheckStateRole) == Qt::Unchecked))
setIndexCheckState(index.parent(), Qt::PartiallyChecked);
}
else if(value == Qt::Unchecked)
{
if(_checklist.remove(index))
emit dataChanged(index, index, selectionChangedRole);
_partialChecklist.remove(index);
if(isDir(index))
{
for(int i = 0; i < rowCount(index); i++)
{
if(index.child(i, index.column()).isValid())
setData(index.child(i, index.column()), Qt::Unchecked,
Qt::CheckStateRole);
}
}
QModelIndex parent = index.parent();
if(parent.isValid())
{
if(hasCheckedSibling(index))
setIndexCheckState(parent, Qt::PartiallyChecked);
else
setIndexCheckState(parent, Qt::Unchecked);
}
}
QVector<int> roles;
roles << Qt::CheckStateRole;
emit dataChanged(index, index, roles);
return true;
}
return QFileSystemModel::setData(index, value, role);
}
void CustomFileSystemModel::reset()
{
_checklist.clear();
_partialChecklist.clear();
}
<commit_msg>CustomFileSystemModel: add some comments<commit_after>#include "customfilesystemmodel.h"
CustomFileSystemModel::CustomFileSystemModel()
{
}
CustomFileSystemModel::~CustomFileSystemModel()
{
}
QList<QPersistentModelIndex> CustomFileSystemModel::checkedIndexes()
{
return _checklist.toList();
}
Qt::ItemFlags CustomFileSystemModel::flags(const QModelIndex &index) const
{
return QFileSystemModel::flags(index) | Qt::ItemIsUserCheckable;
}
QVariant CustomFileSystemModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::CheckStateRole && index.column() == 0)
{
if(_checklist.contains(index))
{
return Qt::Checked;
}
else if(_partialChecklist.contains(index))
{
return Qt::PartiallyChecked;
}
else
{
// Return PartiallyChecked if any ancestor is checked.
QModelIndex parent = index.parent();
while(parent.isValid())
{
if(_checklist.contains(parent))
return Qt::PartiallyChecked;
parent = parent.parent();
}
}
return Qt::Unchecked;
}
return QFileSystemModel::data(index, role);
}
void CustomFileSystemModel::setIndexCheckState(const QModelIndex &index,
const Qt::CheckState state)
{
if(index.data(Qt::CheckStateRole) != state)
setData(index, state, Qt::CheckStateRole);
}
bool CustomFileSystemModel::hasCheckedSibling(const QModelIndex &index)
{
for(int i = 0; i < rowCount(index.parent()); i++)
{
QModelIndex sibling = index.sibling(i, index.column());
if(sibling.isValid())
{
if(sibling == index)
continue;
if(data(sibling, Qt::CheckStateRole) != Qt::Unchecked)
return true;
}
}
return false;
}
bool CustomFileSystemModel::setData(const QModelIndex &index,
const QVariant &value, int role)
{
QVector<int> selectionChangedRole;
selectionChangedRole << SELECTION_CHANGED_ROLE;
if(role == Qt::CheckStateRole)
{
if(value == Qt::Checked)
{
_partialChecklist.remove(index);
_checklist.insert(index);
emit dataChanged(index, index, selectionChangedRole);
if(index.parent().isValid())
{
if(index.parent().data(Qt::CheckStateRole) == Qt::Checked)
{
// Set any partially-selected siblings to be unchecked.
for(int i = 0; i < rowCount(index.parent()); i++)
{
if(index.sibling(i, index.column()).isValid())
{
if(index.sibling(i, index.column()) == index)
continue;
if(data(index.sibling(i, index.column()),
Qt::CheckStateRole) == Qt::PartiallyChecked)
setData(index.sibling(i, index.column()),
Qt::Unchecked, Qt::CheckStateRole);
}
}
}
// Set parent to be PartiallyChecked.
setIndexCheckState(index.parent(), Qt::PartiallyChecked);
}
if(isDir(index))
{
// Set all children to be PartiallyChecked.
for(int i = 0; i < rowCount(index); i++)
{
if(index.child(i, index.column()).isValid())
setData(index.child(i, index.column()),
Qt::PartiallyChecked, Qt::CheckStateRole);
}
}
}
else if(value == Qt::PartiallyChecked)
{
if(_checklist.remove(index))
emit dataChanged(index, index, selectionChangedRole);
_partialChecklist.insert(index);
if(index.parent().isValid() &&
(index.parent().data(Qt::CheckStateRole) == Qt::Unchecked))
setIndexCheckState(index.parent(), Qt::PartiallyChecked);
}
else if(value == Qt::Unchecked)
{
if(_checklist.remove(index))
emit dataChanged(index, index, selectionChangedRole);
_partialChecklist.remove(index);
if(isDir(index))
{
// Set all children to be unchecked.
for(int i = 0; i < rowCount(index); i++)
{
if(index.child(i, index.column()).isValid())
setData(index.child(i, index.column()), Qt::Unchecked,
Qt::CheckStateRole);
}
}
QModelIndex parent = index.parent();
if(parent.isValid())
{
if(hasCheckedSibling(index))
setIndexCheckState(parent, Qt::PartiallyChecked);
else
setIndexCheckState(parent, Qt::Unchecked);
}
}
QVector<int> roles;
roles << Qt::CheckStateRole;
emit dataChanged(index, index, roles);
return true;
}
return QFileSystemModel::setData(index, value, role);
}
void CustomFileSystemModel::reset()
{
_checklist.clear();
_partialChecklist.clear();
}
<|endoftext|> |
<commit_before>#include "ClassLoader.hpp"
#include <boost/algorithm/string.hpp>
using namespace envire;
using namespace std;
const std::vector<std::string> ClassLoader::plugin_paths = ClassLoader::loadLibraryPath();
constexpr char ClassLoader::envire_item_suffix[];
constexpr char ClassLoader::envire_collision_suffix[];
vector<string> ClassLoader::loadLibraryPath()
{
const string path(std::getenv("LD_LIBRARY_PATH"));
vector<string> paths;
//":" is the separator in LD_LIBRARY_PATH
boost::split(paths, path, boost::is_any_of(":"));
//trim ":" and " " from the beginning and end of the string
for(string& path : paths)
{
boost::trim_if(path, boost::is_any_of(": "));
}
return paths;
}
ClassLoader::ClassLoader()
{
}
ClassLoader::~ClassLoader()
{
try
{
loaders.clear();
}
catch(class_loader::LibraryUnloadException& e)
{
std::cerr << "got exception: " << e.what() << std::endl;
}
}
ClassLoader* ClassLoader::getInstance()
{
return base::Singleton<ClassLoader>::getInstance();
}
bool ClassLoader::hasValidPluginPath()
{
return !plugin_paths.empty();
}
bool ClassLoader::hasItem(const std::string& class_name)
{
LoaderMap::iterator it = loaders.find(class_name);
if(it != loaders.end())
{
return it->second->isClassAvailable<ItemBaseClass>(class_name);
}
return false;
}
ClassLoader::ItemBaseClassPtr ClassLoader::createItem(const std::string& class_name)
{
return createItemIntern(class_name);
}
ClassLoader::ItemBaseClassPtr ClassLoader::createItemIntern(const std::string& class_name)
{
LoaderMap::iterator it = loaders.find(class_name);
if(it == loaders.end())
{
loadLibrary(class_name);
it = loaders.find(class_name);
}
if(it == loaders.end())
{
std::string error_msg = "Could not fing plugin library ";
error_msg += class_name;
throw std::runtime_error(error_msg);
}
else
return it->second->createInstance<ItemBaseClass>(class_name);
}
void ClassLoader::loadLibrary(const std::string& class_name)
{
if(hasValidPluginPath())
{
const string lib_name = "lib" + class_name + envire_item_suffix + ".so";
//try to load the plugin from all available paths
bool loaded = false;
for(string path : plugin_paths)
{
path += "/" + lib_name;
boost::shared_ptr<class_loader::ClassLoader> loader(new class_loader::ClassLoader(path, false));
if(loader->isLibraryLoaded() && loader->isClassAvailable<ItemBaseClass>(class_name))
{
loaders.insert(std::make_pair(class_name, loader));
loaded = true;
break;
}
}
if(!loaded)
{
std::string error_msg = "Failed to load plugin library " + lib_name;
throw std::runtime_error(error_msg);
}
}
else
throw std::runtime_error("Have no valid path in environment variable. Please set LD_LIBRARY_PATH");
}
<commit_msg>class loader: check if getenv returned null<commit_after>#include "ClassLoader.hpp"
#include <boost/algorithm/string.hpp>
using namespace envire;
using namespace std;
const std::vector<std::string> ClassLoader::plugin_paths = ClassLoader::loadLibraryPath();
constexpr char ClassLoader::envire_item_suffix[];
constexpr char ClassLoader::envire_collision_suffix[];
vector<string> ClassLoader::loadLibraryPath()
{
const char* lib_path = std::getenv("LD_LIBRARY_PATH");
vector<string> paths;
if(lib_path != NULL)
{
const string path(lib_path);
//":" is the separator in LD_LIBRARY_PATH
boost::split(paths, path, boost::is_any_of(":"));
//trim ":" and " " from the beginning and end of the string
for(string& path : paths)
{
boost::trim_if(path, boost::is_any_of(": "));
}
}
return paths;
}
ClassLoader::ClassLoader()
{
}
ClassLoader::~ClassLoader()
{
try
{
loaders.clear();
}
catch(class_loader::LibraryUnloadException& e)
{
std::cerr << "got exception: " << e.what() << std::endl;
}
}
ClassLoader* ClassLoader::getInstance()
{
return base::Singleton<ClassLoader>::getInstance();
}
bool ClassLoader::hasValidPluginPath()
{
return !plugin_paths.empty();
}
bool ClassLoader::hasItem(const std::string& class_name)
{
LoaderMap::iterator it = loaders.find(class_name);
if(it != loaders.end())
{
return it->second->isClassAvailable<ItemBaseClass>(class_name);
}
return false;
}
ClassLoader::ItemBaseClassPtr ClassLoader::createItem(const std::string& class_name)
{
return createItemIntern(class_name);
}
ClassLoader::ItemBaseClassPtr ClassLoader::createItemIntern(const std::string& class_name)
{
LoaderMap::iterator it = loaders.find(class_name);
if(it == loaders.end())
{
loadLibrary(class_name);
it = loaders.find(class_name);
}
if(it == loaders.end())
{
std::string error_msg = "Could not fing plugin library ";
error_msg += class_name;
throw std::runtime_error(error_msg);
}
else
return it->second->createInstance<ItemBaseClass>(class_name);
}
void ClassLoader::loadLibrary(const std::string& class_name)
{
if(hasValidPluginPath())
{
const string lib_name = "lib" + class_name + envire_item_suffix + ".so";
//try to load the plugin from all available paths
bool loaded = false;
for(string path : plugin_paths)
{
path += "/" + lib_name;
boost::shared_ptr<class_loader::ClassLoader> loader(new class_loader::ClassLoader(path, false));
if(loader->isLibraryLoaded() && loader->isClassAvailable<ItemBaseClass>(class_name))
{
loaders.insert(std::make_pair(class_name, loader));
loaded = true;
break;
}
}
if(!loaded)
{
std::string error_msg = "Failed to load plugin library " + lib_name;
throw std::runtime_error(error_msg);
}
}
else
throw std::runtime_error("Have no valid path in environment variable. Please set LD_LIBRARY_PATH");
}
<|endoftext|> |
<commit_before>#include "api/plugin_instance.h"
#include "core/core.h"
#include "core/log.h"
#include "core/math.h"
#include "core/plugin_handler.h"
#include "session/session.h"
#include "settings.h"
//#include <imgui.h>
#include "ui/imgui_setup.h"
#include "ui/ui_layout.h"
#include "ui/menu.h"
#include "ui/dialogs.h"
#include <bgfx.h>
#include <bgfxplatform.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef PRODBG_WIN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
// TODO: Fix me
int Window_buildPluginMenu(PluginData** plugins, int count);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Context
{
int width;
int height;
float mouseX;
float mouseY;
int mouseLmb;
int keyDown;
int keyMod;
Session* session; // one session right now
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static Context s_context;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static const char* s_plugins[] =
{
"sourcecode_plugin",
"disassembly_plugin",
"locals_plugin",
"callstack_plugin",
"registers_plugin",
"breakpoints_plugin",
"hex_memory_plugin",
#ifdef PRODBG_MAC
"lldb_plugin",
#endif
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setLayout(UILayout* layout)
{
Context* context = &s_context;
IMGUI_preUpdate(context->mouseX, context->mouseY, context->mouseLmb, context->keyDown, context->keyMod);
Session_setLayout(context->session, layout, (float)context->width, (float)context->height);
IMGUI_postUpdate();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loadLayout()
{
UILayout layout;
if (UILayout_loadLayout(&layout, "data/current_layout.json"))
{
setLayout(&layout);
return;
}
if (UILayout_loadLayout(&layout, "data/default_layout.json"))
setLayout(&layout);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_create(void* window, int width, int height)
{
Context* context = &s_context;
//Rect settingsRect;
context->session = Session_create();
//Settings_getWindowRect(&settingsRect);
//width = settingsRect.width;
//height = settingsRect.height;
(void)window;
for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)
{
PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]);
}
#if BX_PLATFORM_OSX
bgfx::osxSetNSWindow(window);
#elif BX_PLATFORM_WINDOWS
bgfx::winSetHwnd((HWND)window);
#else
//bgfx::winSetHwnd(0);
#endif
bgfx::init();
bgfx::reset(width, height);
bgfx::setViewSeq(0, true);
context->width = width;
context->height = height;
IMGUI_setup(width, height);
//loadLayout();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_update()
{
Context* context = &s_context;
bgfx::setViewRect(0, 0, 0, (uint16_t)context->width, (uint16_t)context->height);
bgfx::setViewClear(0, BGFX_CLEAR_COLOR_BIT | BGFX_CLEAR_DEPTH_BIT, 0x101010ff, 1.0f, 0);
bgfx::submit(0);
IMGUI_preUpdate(context->mouseX, context->mouseY, context->mouseLmb, context->keyDown, context->keyMod);
// TODO: Support multiple sessions
Session_update(context->session);
/*
bool show = true;
ImGui::Begin("ImGui Test", &show, ImVec2(550, 480), true, ImGuiWindowFlags_ShowBorders);
if (ImGui::Button("Test0r testing!"))
{
printf("test\n");
}
ImGui::End();
*/
IMGUI_postUpdate();
bgfx::frame();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_setWindowSize(int width, int height)
{
Context* context = &s_context;
context->width = width;
context->height = height;
//bgfx::reset(width, height);
//IMGUI_setup(width, height);
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_applicationLaunched()
{
int pluginCount = 0;
printf("building menu!\n");
Window_buildPluginMenu(PluginHandler_getPlugins(&pluginCount), pluginCount);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_destroy()
{
UILayout layout;
Context* context = &s_context;
Session_getLayout(context->session, &layout, (float)context->width, (float)context->height);
UILayout_saveLayout(&layout, "data/current_layout.json");
Settings_save();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_timedUpdate()
{
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void onLoadRunExec(Session* session, const char* filename)
{
PluginData* pluginData = PluginHandler_findPlugin(0, "lldb_plugin", "LLDB Mac", true);
if (!pluginData)
{
log_error("Unable to find LLDB Mac backend\n");
return;
}
Session_startLocal(session, (PDBackendPlugin*)pluginData->plugin, filename);
// Temp test
// Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, "t2-output/macosx-clang-debug-default/ProDBG.app/Contents/MacOS/prodbg");
// Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, OBJECT_DIR "/crashing_native");
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Events
void ProDBG_event(int eventId)
{
Context* context = &s_context;
int count;
PluginData** pluginsData = PluginHandler_getPlugins(&count);
// TODO: This code really needs to be made more robust.
if (eventId >= PRODBG_MENU_PLUGIN_START && eventId < PRODBG_MENU_PLUGIN_START + 9)
{
ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId - PRODBG_MENU_PLUGIN_START]);
Session_addViewPlugin(context->session, instance);
return;
}
switch (eventId)
{
case PRODBG_MENU_FILE_OPEN_AND_RUN_EXE:
{
char filename[4096];
if (Dialog_open(filename))
{
onLoadRunExec(context->session, filename);
}
break;
}
case PRODBG_MENU_FILE_OPEN_SOURCE:
{
char filename[4096];
if (Dialog_open(filename))
{
Session_loadSourceFile(context->session, filename);
}
break;
}
case PRODBG_MENU_DEBUG_BREAK:
{
Session_action(context->session, PDAction_break);
log_info("trying to break...\n");
break;
}
case PRODBG_MENU_DEBUG_ATTACH_TO_REMOTE:
{
Session_startRemote(context->session, "127.0.0.1", 1340);
break;
}
case PRODBG_MENU_DEBUG_TOGGLE_BREAKPOINT:
{
Session_toggleBreakpointCurrentLine(context->session);
break;
}
case PRODBG_MENU_DEBUG_STEP_OVER:
{
Session_stepOver(context->session);
break;
}
case PRODBG_MENU_DEBUG_STEP_IN:
{
Session_stepIn(context->session);
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_scroll(float deltaX, float deltaY, int flags)
{
(void)deltaX;
(void)deltaY;
(void)flags;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_setMousePos(float x, float y)
{
Context* context = &s_context;
context->mouseX = x;
context->mouseY = y;
IMGUI_setMouse(x, y, context->mouseLmb);
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_setMouseState(int button, int state)
{
Context* context = &s_context;
(void)button;
context->mouseLmb = state;
IMGUI_setMouse(context->mouseX, context->mouseY, state);
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_keyDown(int key, int modifier)
{
IMGUI_setKeyDown(key, modifier);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_keyUp(int key, int modifier)
{
IMGUI_setKeyUp(key, modifier);
}
<commit_msg>Load layout again<commit_after>#include "api/plugin_instance.h"
#include "core/core.h"
#include "core/log.h"
#include "core/math.h"
#include "core/plugin_handler.h"
#include "session/session.h"
#include "settings.h"
//#include <imgui.h>
#include "ui/imgui_setup.h"
#include "ui/ui_layout.h"
#include "ui/menu.h"
#include "ui/dialogs.h"
#include <bgfx.h>
#include <bgfxplatform.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef PRODBG_WIN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
// TODO: Fix me
int Window_buildPluginMenu(PluginData** plugins, int count);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Context
{
int width;
int height;
float mouseX;
float mouseY;
int mouseLmb;
int keyDown;
int keyMod;
Session* session; // one session right now
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static Context s_context;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static const char* s_plugins[] =
{
"sourcecode_plugin",
"disassembly_plugin",
"locals_plugin",
"callstack_plugin",
"registers_plugin",
"breakpoints_plugin",
"hex_memory_plugin",
#ifdef PRODBG_MAC
"lldb_plugin",
#endif
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setLayout(UILayout* layout)
{
Context* context = &s_context;
IMGUI_preUpdate(context->mouseX, context->mouseY, context->mouseLmb, context->keyDown, context->keyMod);
Session_setLayout(context->session, layout, (float)context->width, (float)context->height);
IMGUI_postUpdate();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loadLayout()
{
UILayout layout;
if (UILayout_loadLayout(&layout, "data/current_layout.json"))
{
setLayout(&layout);
return;
}
if (UILayout_loadLayout(&layout, "data/default_layout.json"))
setLayout(&layout);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_create(void* window, int width, int height)
{
Context* context = &s_context;
//Rect settingsRect;
context->session = Session_create();
//Settings_getWindowRect(&settingsRect);
//width = settingsRect.width;
//height = settingsRect.height;
(void)window;
for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)
{
PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]);
}
#if BX_PLATFORM_OSX
bgfx::osxSetNSWindow(window);
#elif BX_PLATFORM_WINDOWS
bgfx::winSetHwnd((HWND)window);
#else
//bgfx::winSetHwnd(0);
#endif
bgfx::init();
bgfx::reset(width, height);
bgfx::setViewSeq(0, true);
context->width = width;
context->height = height;
IMGUI_setup(width, height);
loadLayout();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_update()
{
Context* context = &s_context;
bgfx::setViewRect(0, 0, 0, (uint16_t)context->width, (uint16_t)context->height);
bgfx::setViewClear(0, BGFX_CLEAR_COLOR_BIT | BGFX_CLEAR_DEPTH_BIT, 0x101010ff, 1.0f, 0);
bgfx::submit(0);
IMGUI_preUpdate(context->mouseX, context->mouseY, context->mouseLmb, context->keyDown, context->keyMod);
// TODO: Support multiple sessions
Session_update(context->session);
/*
bool show = true;
ImGui::Begin("ImGui Test", &show, ImVec2(550, 480), true, ImGuiWindowFlags_ShowBorders);
if (ImGui::Button("Test0r testing!"))
{
printf("test\n");
}
ImGui::End();
*/
IMGUI_postUpdate();
bgfx::frame();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_setWindowSize(int width, int height)
{
Context* context = &s_context;
context->width = width;
context->height = height;
//bgfx::reset(width, height);
//IMGUI_setup(width, height);
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_applicationLaunched()
{
int pluginCount = 0;
printf("building menu!\n");
Window_buildPluginMenu(PluginHandler_getPlugins(&pluginCount), pluginCount);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_destroy()
{
UILayout layout;
Context* context = &s_context;
Session_getLayout(context->session, &layout, (float)context->width, (float)context->height);
UILayout_saveLayout(&layout, "data/current_layout.json");
Settings_save();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_timedUpdate()
{
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void onLoadRunExec(Session* session, const char* filename)
{
PluginData* pluginData = PluginHandler_findPlugin(0, "lldb_plugin", "LLDB Mac", true);
if (!pluginData)
{
log_error("Unable to find LLDB Mac backend\n");
return;
}
Session_startLocal(session, (PDBackendPlugin*)pluginData->plugin, filename);
// Temp test
// Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, "t2-output/macosx-clang-debug-default/ProDBG.app/Contents/MacOS/prodbg");
// Session_startLocal(context->session, (PDBackendPlugin*)pluginData->plugin, OBJECT_DIR "/crashing_native");
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Events
void ProDBG_event(int eventId)
{
Context* context = &s_context;
int count;
PluginData** pluginsData = PluginHandler_getPlugins(&count);
// TODO: This code really needs to be made more robust.
if (eventId >= PRODBG_MENU_PLUGIN_START && eventId < PRODBG_MENU_PLUGIN_START + 9)
{
ViewPluginInstance* instance = PluginInstance_createViewPlugin(pluginsData[eventId - PRODBG_MENU_PLUGIN_START]);
Session_addViewPlugin(context->session, instance);
return;
}
switch (eventId)
{
case PRODBG_MENU_FILE_OPEN_AND_RUN_EXE:
{
char filename[4096];
if (Dialog_open(filename))
{
onLoadRunExec(context->session, filename);
}
break;
}
case PRODBG_MENU_FILE_OPEN_SOURCE:
{
char filename[4096];
if (Dialog_open(filename))
{
Session_loadSourceFile(context->session, filename);
}
break;
}
case PRODBG_MENU_DEBUG_BREAK:
{
Session_action(context->session, PDAction_break);
log_info("trying to break...\n");
break;
}
case PRODBG_MENU_DEBUG_ATTACH_TO_REMOTE:
{
Session_startRemote(context->session, "127.0.0.1", 1340);
break;
}
case PRODBG_MENU_DEBUG_TOGGLE_BREAKPOINT:
{
Session_toggleBreakpointCurrentLine(context->session);
break;
}
case PRODBG_MENU_DEBUG_STEP_OVER:
{
Session_stepOver(context->session);
break;
}
case PRODBG_MENU_DEBUG_STEP_IN:
{
Session_stepIn(context->session);
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_scroll(float deltaX, float deltaY, int flags)
{
(void)deltaX;
(void)deltaY;
(void)flags;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_setMousePos(float x, float y)
{
Context* context = &s_context;
context->mouseX = x;
context->mouseY = y;
IMGUI_setMouse(x, y, context->mouseLmb);
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_setMouseState(int button, int state)
{
Context* context = &s_context;
(void)button;
context->mouseLmb = state;
IMGUI_setMouse(context->mouseX, context->mouseY, state);
ProDBG_update();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_keyDown(int key, int modifier)
{
IMGUI_setKeyDown(key, modifier);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ProDBG_keyUp(int key, int modifier)
{
IMGUI_setKeyUp(key, modifier);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2002-2010 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.
*/
/*
* XSEC
*
* DSIGTransformXSL := Class that Handles DSIG XSLT Transforms
*
* $Id$
*
*/
// XSEC
#include <xsec/dsig/DSIGTransformXSL.hpp>
#include <xsec/dsig/DSIGSignature.hpp>
#include <xsec/transformers/TXFMXSL.hpp>
#include <xsec/transformers/TXFMC14n.hpp>
#include <xsec/transformers/TXFMChain.hpp>
#include <xsec/framework/XSECException.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
XERCES_CPP_NAMESPACE_USE
class XSECDomToSafeBuffer {
public:
XSECDomToSafeBuffer::XSECDomToSafeBuffer(DOMNode *node);
virtual ~XSECDomToSafeBuffer() {}
operator const safeBuffer&() const {
return m_buffer;
}
private:
safeBuffer m_buffer;
};
XSECDomToSafeBuffer::XSECDomToSafeBuffer(DOMNode* node)
{
static const XMLCh _LS[] = {chLatin_L, chLatin_S, chNull};
DOMImplementationLS* impl = DOMImplementationRegistry::getDOMImplementation(_LS);
MemBufFormatTarget* target = new MemBufFormatTarget;
Janitor<MemBufFormatTarget> j_target(target);
#if defined (XSEC_XERCES_DOMLSSERIALIZER)
// DOM L3 version as per Xerces 3.0 API
DOMLSSerializer* theSerializer = impl->createLSSerializer();
Janitor<DOMLSSerializer> j_theSerializer(theSerializer);
DOMLSOutput *theOutput = impl->createLSOutput();
Janitor<DOMLSOutput> j_theOutput(theOutput);
theOutput->setByteStream(target);
#else
DOMWriter* theSerializer = impl->createDOMWriter();
Janitor<DOMWriter> j_theSerializer(theSerializer);
#endif
try
{
#if defined (XSEC_XERCES_DOMLSSERIALIZER)
theSerializer->write(node, theOutput);
#else
theSerializer->writeNode(target, *node);
#endif
m_buffer.sbMemcpyIn(0, target->getRawBuffer(), target->getLen());
}
catch(const XMLException&)
{
throw XSECException(XSECException::UnknownError);
}
catch(const DOMException&)
{
throw XSECException(XSECException::UnknownError);
}
}
// --------------------------------------------------------------------------------
// Constructors and Destructors
// --------------------------------------------------------------------------------
DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env, DOMNode * node) :
DSIGTransform(env, node),
mp_stylesheetNode(NULL) {};
DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env) :
DSIGTransform(env),
mp_stylesheetNode(NULL) {};
DSIGTransformXSL::~DSIGTransformXSL() {};
// --------------------------------------------------------------------------------
// Interface Methods
// --------------------------------------------------------------------------------
transformType DSIGTransformXSL::getTransformType() {
return TRANSFORM_XSLT;
}
void DSIGTransformXSL::appendTransformer(TXFMChain * input) {
#ifdef XSEC_NO_XSLT
throw XSECException(XSECException::UnsupportedFunction,
"XSLT Transforms not supported in this compilation of the library");
#else
if (mp_stylesheetNode == 0)
throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");
TXFMBase * nextInput;
// XSLT Transform - requires a byte stream input
if (input->getLastTxfm()->getOutputType() == TXFMBase::DOM_NODES) {
// Use c14n to translate to BYTES
XSECnew(nextInput, TXFMC14n(mp_txfmNode->getOwnerDocument()));
input->appendTxfm(nextInput);
}
TXFMXSL * x;
// Create the XSLT transform
XSECnew(x, TXFMXSL(mp_txfmNode->getOwnerDocument()));
input->appendTxfm(x);
// Patch to avoid c14n of stylesheet
XSECDomToSafeBuffer sbStyleSheet(mp_stylesheetNode);
x->evaluateStyleSheet(sbStyleSheet);
#endif /* NO_XSLT */
}
DOMElement * DSIGTransformXSL::createBlankTransform(DOMDocument * parentDoc) {
safeBuffer str;
const XMLCh * prefix;
DOMElement *ret;
DOMDocument *doc = mp_env->getParentDocument();
prefix = mp_env->getDSIGNSPrefix();
// Create the transform node
makeQName(str, prefix, "Transform");
ret = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer());
ret->setAttributeNS(NULL,DSIGConstants::s_unicodeStrAlgorithm, DSIGConstants::s_unicodeStrURIXSLT);
mp_txfmNode = ret;
mp_stylesheetNode = NULL;
return ret;
}
void DSIGTransformXSL::load(void) {
// find the style sheet
mp_stylesheetNode = mp_txfmNode->getFirstChild();
while (mp_stylesheetNode != 0 &&
mp_stylesheetNode->getNodeType() != DOMNode::ELEMENT_NODE && !strEquals(mp_stylesheetNode->getNodeName(), "xsl:stylesheet"))
mp_stylesheetNode = mp_stylesheetNode->getNextSibling();
if (mp_stylesheetNode == 0)
throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");
}
// --------------------------------------------------------------------------------
// XSLT Specific Methods
// --------------------------------------------------------------------------------
DOMNode * DSIGTransformXSL::setStylesheet(DOMNode * stylesheet) {
DOMNode * ret = mp_stylesheetNode;
if (mp_stylesheetNode) {
if (stylesheet)
mp_txfmNode->insertBefore(stylesheet, mp_stylesheetNode);
mp_txfmNode->removeChild(mp_stylesheetNode);
}
else if (stylesheet) {
mp_txfmNode->appendChild(stylesheet);
}
mp_stylesheetNode = stylesheet;
return ret;
}
DOMNode * DSIGTransformXSL::getStylesheet(void) {
return mp_stylesheetNode;
}
<commit_msg>Syntax bug in constructor.<commit_after>/*
* Copyright 2002-2010 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.
*/
/*
* XSEC
*
* DSIGTransformXSL := Class that Handles DSIG XSLT Transforms
*
* $Id$
*
*/
// XSEC
#include <xsec/dsig/DSIGTransformXSL.hpp>
#include <xsec/dsig/DSIGSignature.hpp>
#include <xsec/transformers/TXFMXSL.hpp>
#include <xsec/transformers/TXFMC14n.hpp>
#include <xsec/transformers/TXFMChain.hpp>
#include <xsec/framework/XSECException.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
XERCES_CPP_NAMESPACE_USE
class XSECDomToSafeBuffer {
public:
XSECDomToSafeBuffer(DOMNode *node);
virtual ~XSECDomToSafeBuffer() {}
operator const safeBuffer&() const {
return m_buffer;
}
private:
safeBuffer m_buffer;
};
XSECDomToSafeBuffer::XSECDomToSafeBuffer(DOMNode* node)
{
static const XMLCh _LS[] = {chLatin_L, chLatin_S, chNull};
DOMImplementationLS* impl = DOMImplementationRegistry::getDOMImplementation(_LS);
MemBufFormatTarget* target = new MemBufFormatTarget;
Janitor<MemBufFormatTarget> j_target(target);
#if defined (XSEC_XERCES_DOMLSSERIALIZER)
// DOM L3 version as per Xerces 3.0 API
DOMLSSerializer* theSerializer = impl->createLSSerializer();
Janitor<DOMLSSerializer> j_theSerializer(theSerializer);
DOMLSOutput *theOutput = impl->createLSOutput();
Janitor<DOMLSOutput> j_theOutput(theOutput);
theOutput->setByteStream(target);
#else
DOMWriter* theSerializer = impl->createDOMWriter();
Janitor<DOMWriter> j_theSerializer(theSerializer);
#endif
try
{
#if defined (XSEC_XERCES_DOMLSSERIALIZER)
theSerializer->write(node, theOutput);
#else
theSerializer->writeNode(target, *node);
#endif
m_buffer.sbMemcpyIn(0, target->getRawBuffer(), target->getLen());
}
catch(const XMLException&)
{
throw XSECException(XSECException::UnknownError);
}
catch(const DOMException&)
{
throw XSECException(XSECException::UnknownError);
}
}
// --------------------------------------------------------------------------------
// Constructors and Destructors
// --------------------------------------------------------------------------------
DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env, DOMNode * node) :
DSIGTransform(env, node),
mp_stylesheetNode(NULL) {};
DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env) :
DSIGTransform(env),
mp_stylesheetNode(NULL) {};
DSIGTransformXSL::~DSIGTransformXSL() {};
// --------------------------------------------------------------------------------
// Interface Methods
// --------------------------------------------------------------------------------
transformType DSIGTransformXSL::getTransformType() {
return TRANSFORM_XSLT;
}
void DSIGTransformXSL::appendTransformer(TXFMChain * input) {
#ifdef XSEC_NO_XSLT
throw XSECException(XSECException::UnsupportedFunction,
"XSLT Transforms not supported in this compilation of the library");
#else
if (mp_stylesheetNode == 0)
throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");
TXFMBase * nextInput;
// XSLT Transform - requires a byte stream input
if (input->getLastTxfm()->getOutputType() == TXFMBase::DOM_NODES) {
// Use c14n to translate to BYTES
XSECnew(nextInput, TXFMC14n(mp_txfmNode->getOwnerDocument()));
input->appendTxfm(nextInput);
}
TXFMXSL * x;
// Create the XSLT transform
XSECnew(x, TXFMXSL(mp_txfmNode->getOwnerDocument()));
input->appendTxfm(x);
// Patch to avoid c14n of stylesheet
XSECDomToSafeBuffer sbStyleSheet(mp_stylesheetNode);
x->evaluateStyleSheet(sbStyleSheet);
#endif /* NO_XSLT */
}
DOMElement * DSIGTransformXSL::createBlankTransform(DOMDocument * parentDoc) {
safeBuffer str;
const XMLCh * prefix;
DOMElement *ret;
DOMDocument *doc = mp_env->getParentDocument();
prefix = mp_env->getDSIGNSPrefix();
// Create the transform node
makeQName(str, prefix, "Transform");
ret = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer());
ret->setAttributeNS(NULL,DSIGConstants::s_unicodeStrAlgorithm, DSIGConstants::s_unicodeStrURIXSLT);
mp_txfmNode = ret;
mp_stylesheetNode = NULL;
return ret;
}
void DSIGTransformXSL::load(void) {
// find the style sheet
mp_stylesheetNode = mp_txfmNode->getFirstChild();
while (mp_stylesheetNode != 0 &&
mp_stylesheetNode->getNodeType() != DOMNode::ELEMENT_NODE && !strEquals(mp_stylesheetNode->getNodeName(), "xsl:stylesheet"))
mp_stylesheetNode = mp_stylesheetNode->getNextSibling();
if (mp_stylesheetNode == 0)
throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");
}
// --------------------------------------------------------------------------------
// XSLT Specific Methods
// --------------------------------------------------------------------------------
DOMNode * DSIGTransformXSL::setStylesheet(DOMNode * stylesheet) {
DOMNode * ret = mp_stylesheetNode;
if (mp_stylesheetNode) {
if (stylesheet)
mp_txfmNode->insertBefore(stylesheet, mp_stylesheetNode);
mp_txfmNode->removeChild(mp_stylesheetNode);
}
else if (stylesheet) {
mp_txfmNode->appendChild(stylesheet);
}
mp_stylesheetNode = stylesheet;
return ret;
}
DOMNode * DSIGTransformXSL::getStylesheet(void) {
return mp_stylesheetNode;
}
<|endoftext|> |
<commit_before>/*
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "SkBitmapCache.h"
struct SkBitmapCache::Entry {
Entry* fPrev;
Entry* fNext;
void* fBuffer;
size_t fSize;
SkBitmap fBitmap;
Entry(const void* buffer, size_t size, const SkBitmap& bm) : fBitmap(bm) {
fBuffer = sk_malloc_throw(size);
fSize = size;
memcpy(fBuffer, buffer, size);
}
~Entry() { sk_free(fBuffer); }
bool equals(const void* buffer, size_t size) const {
return (fSize == size) && !memcmp(fBuffer, buffer, size);
}
};
SkBitmapCache::SkBitmapCache(int max) : fMaxEntries(max) {
fEntryCount = 0;
fHead = fTail = NULL;
this->validate();
}
SkBitmapCache::~SkBitmapCache() {
this->validate();
Entry* entry = fHead;
while (entry) {
Entry* next = entry->fNext;
delete entry;
entry = next;
}
}
SkBitmapCache::Entry* SkBitmapCache::detach(Entry* entry) const {
if (entry->fPrev) {
SkASSERT(fHead != entry);
entry->fPrev->fNext = entry->fNext;
} else {
SkASSERT(fHead == entry);
fHead = entry->fNext;
}
if (entry->fNext) {
SkASSERT(fTail != entry);
entry->fNext->fPrev = entry->fPrev;
} else {
SkASSERT(fTail == entry);
fTail = entry->fPrev;
}
return entry;
}
void SkBitmapCache::attachToHead(Entry* entry) const {
entry->fPrev = NULL;
entry->fNext = fHead;
if (fHead) {
fHead->fPrev = entry;
} else {
fTail = entry;
}
fHead = entry;
}
bool SkBitmapCache::find(const void* buffer, size_t size, SkBitmap* bm) const {
AutoValidate av(this);
Entry* entry = fHead;
while (entry) {
if (entry->equals(buffer, size)) {
if (bm) {
*bm = entry->fBitmap;
}
// move to the head of our list, so we purge it last
this->detach(entry);
this->attachToHead(entry);
return true;
}
entry = entry->fNext;
}
return false;
}
void SkBitmapCache::add(const void* buffer, size_t len, const SkBitmap& bm) {
AutoValidate av(this);
if (fEntryCount == fMaxEntries) {
if (fTail) {
delete this->detach(fTail);
}
}
Entry* entry = new Entry(buffer, len, bm);
this->attachToHead(entry);
fEntryCount += 1;
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_DEBUG
void SkBitmapCache::validate() const {
SkASSERT(fEntryCount >= 0 && fEntryCount <= fMaxEntries);
if (fEntryCount > 0) {
SkASSERT(NULL == fHead->fPrev);
SkASSERT(NULL == fTail->fNext);
if (fEntryCount == 1) {
SkASSERT(fHead == fTail);
} else {
SkASSERT(fHead != fTail);
}
Entry* entry = fHead;
int count = 0;
while (entry) {
count += 1;
entry = entry->fNext;
}
SkASSERT(count == fEntryCount);
entry = fTail;
while (entry) {
count -= 1;
entry = entry->fPrev;
}
SkASSERT(0 == count);
} else {
SkASSERT(NULL == fHead);
SkASSERT(NULL == fTail);
}
}
#endif
<commit_msg>fix fEntryCount when we purge a cache entry (bug caught by our validate())<commit_after>/*
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "SkBitmapCache.h"
struct SkBitmapCache::Entry {
Entry* fPrev;
Entry* fNext;
void* fBuffer;
size_t fSize;
SkBitmap fBitmap;
Entry(const void* buffer, size_t size, const SkBitmap& bm) : fBitmap(bm) {
fBuffer = sk_malloc_throw(size);
fSize = size;
memcpy(fBuffer, buffer, size);
}
~Entry() { sk_free(fBuffer); }
bool equals(const void* buffer, size_t size) const {
return (fSize == size) && !memcmp(fBuffer, buffer, size);
}
};
SkBitmapCache::SkBitmapCache(int max) : fMaxEntries(max) {
fEntryCount = 0;
fHead = fTail = NULL;
this->validate();
}
SkBitmapCache::~SkBitmapCache() {
this->validate();
Entry* entry = fHead;
while (entry) {
Entry* next = entry->fNext;
delete entry;
entry = next;
}
}
SkBitmapCache::Entry* SkBitmapCache::detach(Entry* entry) const {
if (entry->fPrev) {
SkASSERT(fHead != entry);
entry->fPrev->fNext = entry->fNext;
} else {
SkASSERT(fHead == entry);
fHead = entry->fNext;
}
if (entry->fNext) {
SkASSERT(fTail != entry);
entry->fNext->fPrev = entry->fPrev;
} else {
SkASSERT(fTail == entry);
fTail = entry->fPrev;
}
return entry;
}
void SkBitmapCache::attachToHead(Entry* entry) const {
entry->fPrev = NULL;
entry->fNext = fHead;
if (fHead) {
fHead->fPrev = entry;
} else {
fTail = entry;
}
fHead = entry;
}
bool SkBitmapCache::find(const void* buffer, size_t size, SkBitmap* bm) const {
AutoValidate av(this);
Entry* entry = fHead;
while (entry) {
if (entry->equals(buffer, size)) {
if (bm) {
*bm = entry->fBitmap;
}
// move to the head of our list, so we purge it last
this->detach(entry);
this->attachToHead(entry);
return true;
}
entry = entry->fNext;
}
return false;
}
void SkBitmapCache::add(const void* buffer, size_t len, const SkBitmap& bm) {
AutoValidate av(this);
if (fEntryCount == fMaxEntries) {
SkASSERT(fTail);
delete this->detach(fTail);
fEntryCount -= 1;
}
Entry* entry = new Entry(buffer, len, bm);
this->attachToHead(entry);
fEntryCount += 1;
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_DEBUG
void SkBitmapCache::validate() const {
SkASSERT(fEntryCount >= 0 && fEntryCount <= fMaxEntries);
if (fEntryCount > 0) {
SkASSERT(NULL == fHead->fPrev);
SkASSERT(NULL == fTail->fNext);
if (fEntryCount == 1) {
SkASSERT(fHead == fTail);
} else {
SkASSERT(fHead != fTail);
}
Entry* entry = fHead;
int count = 0;
while (entry) {
count += 1;
entry = entry->fNext;
}
SkASSERT(count == fEntryCount);
entry = fTail;
while (entry) {
count -= 1;
entry = entry->fPrev;
}
SkASSERT(0 == count);
} else {
SkASSERT(NULL == fHead);
SkASSERT(NULL == fTail);
}
}
#endif
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <map>
#include "transcript.h"
transcript::transcript()
{
RPKM = 0;
}
transcript::~transcript()
{
}
bool transcript::operator< (const transcript &t) const
{
int b = seqname.compare(t.seqname);
if(b < 0) return true;
if(b > 0) return false;
if(exons.size() == 0) return true;
if(t.exons.size() == 0) return false;
if(exons[0].first < t.exons[0].first) return true;
else return false;
}
int transcript::add_exon(int s, int t)
{
exons.push_back(PI32(s, t));
return 0;
}
int transcript::add_exon(const exon &e)
{
seqname = e.seqname;
source = e.source;
feature = e.feature;
transcript_id = e.transcript_id;
gene_id = e.gene_id;
expression = e.expression;
coverage = e.coverage;
strand = e.strand;
RPKM = e.RPKM;
exons.push_back(PI32(e.start, e.end));
return 0;
}
int transcript::sort()
{
std::sort(exons.begin(), exons.end());
return 0;
}
int transcript::assign_RPKM(double factor)
{
RPKM = coverage * factor / length();
return 0;
}
int transcript::length() const
{
int s = 0;
for(int i = 0; i < exons.size(); i++)
{
assert(exons[i].second > exons[i].first);
s += exons[i].second - exons[i].first;
}
return s;
}
PI32 transcript::get_bounds() const
{
if(exons.size() == 0) return PI32(-1, -1);
int32_t p = exons[0].first;
int32_t q = exons[exons.size() - 1].second;
return PI32(p, q);
}
string transcript::label() const
{
char buf[10240];
PI32 p = get_bounds();
sprintf(buf, "%s:%d-%d", seqname.c_str(), p.first, p.second);
return string(buf);
}
int transcript::write(ofstream &fout) const
{
fout.precision(4);
fout<<fixed;
if(exons.size() == 0) return 0;
int lpos = exons[0].first;
int rpos = exons[exons.size() - 1].second;
fout<<seqname.c_str()<<"\t"; // chromosome name
fout<<source.c_str()<<"\t"; // source
fout<<"transcript\t"; // feature
fout<<lpos + 1<<"\t"; // left position
fout<<rpos<<"\t"; // right position
fout<<1000<<"\t"; // score, now as expression
fout<<strand<<"\t"; // strand
fout<<".\t"; // frame
fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
fout<<"RPKM \""<<RPKM<<"\"; ";
fout<<"coverage \""<<coverage<<"\"; ";
fout<<"covratio \""<<covratio<<"\"; ";
fout<<"expression \""<<expression<<"\";"<<endl;
for(int k = 0; k < exons.size(); k++)
{
fout<<seqname.c_str()<<"\t"; // chromosome name
fout<<source.c_str()<<"\t"; // source
fout<<"exon\t"; // feature
fout<<exons[k].first + 1<<"\t"; // left position
fout<<exons[k].second<<"\t"; // right position
fout<<1000<<"\t"; // score, now as expression
fout<<strand<<"\t"; // strand
fout<<".\t"; // frame
fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
fout<<"exon \""<<k + 1<<"\"; ";
fout<<"RPKM \""<<RPKM<<"\"; ";
fout<<"coverage \""<<coverage<<"\"; ";
fout<<"covratio\""<<covratio<<"\"; ";
fout<<"expression \""<<expression<<"\";"<<endl;
}
return 0;
}
<commit_msg>fix space in outputing covratio<commit_after>#include <cstdio>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <map>
#include "transcript.h"
transcript::transcript()
{
RPKM = 0;
}
transcript::~transcript()
{
}
bool transcript::operator< (const transcript &t) const
{
int b = seqname.compare(t.seqname);
if(b < 0) return true;
if(b > 0) return false;
if(exons.size() == 0) return true;
if(t.exons.size() == 0) return false;
if(exons[0].first < t.exons[0].first) return true;
else return false;
}
int transcript::add_exon(int s, int t)
{
exons.push_back(PI32(s, t));
return 0;
}
int transcript::add_exon(const exon &e)
{
seqname = e.seqname;
source = e.source;
feature = e.feature;
transcript_id = e.transcript_id;
gene_id = e.gene_id;
expression = e.expression;
coverage = e.coverage;
strand = e.strand;
RPKM = e.RPKM;
exons.push_back(PI32(e.start, e.end));
return 0;
}
int transcript::sort()
{
std::sort(exons.begin(), exons.end());
return 0;
}
int transcript::assign_RPKM(double factor)
{
RPKM = coverage * factor / length();
return 0;
}
int transcript::length() const
{
int s = 0;
for(int i = 0; i < exons.size(); i++)
{
assert(exons[i].second > exons[i].first);
s += exons[i].second - exons[i].first;
}
return s;
}
PI32 transcript::get_bounds() const
{
if(exons.size() == 0) return PI32(-1, -1);
int32_t p = exons[0].first;
int32_t q = exons[exons.size() - 1].second;
return PI32(p, q);
}
string transcript::label() const
{
char buf[10240];
PI32 p = get_bounds();
sprintf(buf, "%s:%d-%d", seqname.c_str(), p.first, p.second);
return string(buf);
}
int transcript::write(ofstream &fout) const
{
fout.precision(4);
fout<<fixed;
if(exons.size() == 0) return 0;
int lpos = exons[0].first;
int rpos = exons[exons.size() - 1].second;
fout<<seqname.c_str()<<"\t"; // chromosome name
fout<<source.c_str()<<"\t"; // source
fout<<"transcript\t"; // feature
fout<<lpos + 1<<"\t"; // left position
fout<<rpos<<"\t"; // right position
fout<<1000<<"\t"; // score, now as expression
fout<<strand<<"\t"; // strand
fout<<".\t"; // frame
fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
fout<<"RPKM \""<<RPKM<<"\"; ";
fout<<"coverage \""<<coverage<<"\"; ";
fout<<"covratio \""<<covratio<<"\"; ";
fout<<"expression \""<<expression<<"\";"<<endl;
for(int k = 0; k < exons.size(); k++)
{
fout<<seqname.c_str()<<"\t"; // chromosome name
fout<<source.c_str()<<"\t"; // source
fout<<"exon\t"; // feature
fout<<exons[k].first + 1<<"\t"; // left position
fout<<exons[k].second<<"\t"; // right position
fout<<1000<<"\t"; // score, now as expression
fout<<strand<<"\t"; // strand
fout<<".\t"; // frame
fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
fout<<"exon \""<<k + 1<<"\"; ";
fout<<"RPKM \""<<RPKM<<"\"; ";
fout<<"coverage \""<<coverage<<"\"; ";
fout<<"covratio \""<<covratio<<"\"; ";
fout<<"expression \""<<expression<<"\";"<<endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiondesc.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "paymentserver.h"
#include "transactionrecord.h"
#include "base58.h"
#include "db.h"
#include "main.h"
#include "script/script.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet.h"
#include <stdint.h>
#include <string>
using namespace std;
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
if (!IsFinalTx(wtx, chainActive.Height() + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.nLockTime - chainActive.Height());
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth < 6)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
{
QString strHTML;
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64_t nTime = wtx.GetTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase())
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
if (CBitcoinAddress(rec->address).IsValid())
{
CTxDestination address = CBitcoinAddress(rec->address).Get();
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only");
if (!wallet->mapAddressBook[address].name.empty())
strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")";
else
strHTML += " (" + addressOwned + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = CBitcoinAddress(strAddress).Get();
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
CAmount nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>";
}
else
{
isminetype fAllFromMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
isminetype mine = wallet->IsMine(txin);
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
isminetype mine = wallet->IsMine(txout);
if(fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMe)
{
if(fAllFromMe == ISMINE_WATCH_ONLY)
strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>";
//
// Debit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
// Ignore change
isminetype toSelf = wallet->IsMine(txout);
if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
if(toSelf == ISMINE_SPENDABLE)
strHTML += " (own address)";
else if(toSelf == ISMINE_WATCH_ONLY)
strHTML += " (watch-only)";
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>";
if(toSelf)
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
CAmount nChange = wtx.GetChange();
CAmount nValue = nCredit - nChange;
strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>";
}
CAmount nTxFee = nDebit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + TransactionRecord::formatSubTxId(wtx.GetHash(), rec->idx) + "<br>";
// Message from normal bitcoin:URI (bitcoin:123...?message=example)
foreach (const PAIRTYPE(string, string)& r, wtx.vOrderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
foreach (const PAIRTYPE(string, string)& r, wtx.vOrderForm)
{
if (r.first == "PaymentRequest")
{
PaymentRequestPlus req;
req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));
QString merchant;
if (req.getMerchant(PaymentServer::getCertStore(), merchant))
strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>";
}
}
if (wtx.IsCoinBase())
{
quint32 numBlocksToMaturity = COINBASE_MATURITY + 1;
strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>";
}
//
// Debug view
//
if (fDebug)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if(wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if(wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
CCoins prev;
if(pcoinsTip->GetCoins(prevout.hash, prev))
{
if (prevout.n < prev.vout.size())
{
strHTML += "<li>";
const CTxOut &vout = prev.vout[prevout.n];
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>";
strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>";
}
}
}
strHTML += "</ul>";
}
strHTML += "</font></html>";
return strHTML;
}
<commit_msg>Add transaction comment to transaction description<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiondesc.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "paymentserver.h"
#include "transactionrecord.h"
#include "base58.h"
#include "db.h"
#include "main.h"
#include "script/script.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet.h"
#include <stdint.h>
#include <string>
using namespace std;
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
if (!IsFinalTx(wtx, chainActive.Height() + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.nLockTime - chainActive.Height());
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth < 6)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
{
QString strHTML;
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64_t nTime = wtx.GetTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase())
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
if (CBitcoinAddress(rec->address).IsValid())
{
CTxDestination address = CBitcoinAddress(rec->address).Get();
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only");
if (!wallet->mapAddressBook[address].name.empty())
strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")";
else
strHTML += " (" + addressOwned + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = CBitcoinAddress(strAddress).Get();
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
CAmount nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>";
}
else
{
isminetype fAllFromMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
isminetype mine = wallet->IsMine(txin);
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
isminetype mine = wallet->IsMine(txout);
if(fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMe)
{
if(fAllFromMe == ISMINE_WATCH_ONLY)
strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>";
//
// Debit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
// Ignore change
isminetype toSelf = wallet->IsMine(txout);
if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
if(toSelf == ISMINE_SPENDABLE)
strHTML += " (own address)";
else if(toSelf == ISMINE_WATCH_ONLY)
strHTML += " (watch-only)";
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>";
if(toSelf)
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
CAmount nChange = wtx.GetChange();
CAmount nValue = nCredit - nChange;
strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>";
}
CAmount nTxFee = nDebit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
//
// Transaction comment
//
if (!wtx.strTxComment.empty())
strHTML += "<b>" + tr("Transaction comment") + ":</b><br>" + wtx.strTxComment.c_str() + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + TransactionRecord::formatSubTxId(wtx.GetHash(), rec->idx) + "<br>";
// Message from normal bitcoin:URI (bitcoin:123...?message=example)
foreach (const PAIRTYPE(string, string)& r, wtx.vOrderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
foreach (const PAIRTYPE(string, string)& r, wtx.vOrderForm)
{
if (r.first == "PaymentRequest")
{
PaymentRequestPlus req;
req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));
QString merchant;
if (req.getMerchant(PaymentServer::getCertStore(), merchant))
strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>";
}
}
if (wtx.IsCoinBase())
{
quint32 numBlocksToMaturity = COINBASE_MATURITY + 1;
strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>";
}
//
// Debug view
//
if (fDebug)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if(wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if(wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
CCoins prev;
if(pcoinsTip->GetCoins(prevout.hash, prev))
{
if (prevout.n < prev.vout.size())
{
strHTML += "<li>";
const CTxOut &vout = prev.vout[prevout.n];
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>";
strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>";
}
}
}
strHTML += "</ul>";
}
strHTML += "</font></html>";
return strHTML;
}
<|endoftext|> |
<commit_before>#include "plugin_manager.h"
#include "core/library.h"
#include "core/log.h"
#include "core/array.h"
#include "engine.h"
#include "iplugin.h"
namespace Lumix
{
class PluginManagerImpl : public PluginManager
{
private:
typedef Array<IPlugin*> PluginList;
typedef Array<Library*> LibraryList;
public:
PluginManagerImpl(Engine& engine, IAllocator& allocator)
: m_plugins(allocator)
, m_libraries(allocator)
, m_allocator(allocator)
, m_engine(engine)
, m_library_loaded(allocator)
{ }
~PluginManagerImpl()
{
for (int i = 0; i < m_plugins.size(); ++i)
{
m_plugins[i]->destroy();
m_engine.getAllocator().deleteObject(m_plugins[i]);
}
for (int i = 0; i < m_libraries.size(); ++i)
{
Library::destroy(m_libraries[i]);
}
}
void update(float dt) override
{
for (int i = 0, c = m_plugins.size(); i < c; ++i)
{
m_plugins[i]->update(dt);
}
}
void serialize(OutputBlob& serializer) override
{
for (int i = 0, c = m_plugins.size(); i < c; ++i)
{
m_plugins[i]->serialize(serializer);
}
}
void deserialize(InputBlob& serializer) override
{
for (int i = 0, c = m_plugins.size(); i < c; ++i)
{
m_plugins[i]->deserialize(serializer);
}
}
virtual const Array<Library*>& getLibraries() const override
{
return m_libraries;
}
const Array<IPlugin*>& getPlugins() const override
{
return m_plugins;
}
IPlugin* getPlugin(const char* name) override
{
for (int i = 0; i < m_plugins.size(); ++i)
{
if (strcmp(m_plugins[i]->getName(), name) == 0)
{
return m_plugins[i];
}
}
return 0;
}
virtual DelegateList<void(Library&)>& libraryLoaded() override
{
return m_library_loaded;
}
IPlugin* load(const char* path) override
{
g_log_info.log("plugins") << "loading plugin " << path;
typedef IPlugin* (*PluginCreator)(Engine&);
Library* lib = Library::create(Path(path), m_engine.getAllocator());
if (lib->load())
{
PluginCreator creator = (PluginCreator)lib->resolve("createPlugin");
if (creator)
{
IPlugin* plugin = creator(m_engine);
if (!plugin->create())
{
m_engine.getAllocator().deleteObject(plugin);
ASSERT(false);
return nullptr;
}
m_plugins.push(plugin);
m_libraries.push(lib);
m_library_loaded.invoke(*lib);
g_log_info.log("plugins") << "plugin loaded";
return plugin;
}
}
Library::destroy(lib);
return 0;
}
IAllocator& getAllocator() { return m_allocator; }
void addPlugin(IPlugin* plugin) override
{
m_plugins.push(plugin);
}
private:
Engine& m_engine;
DelegateList<void(Library&)> m_library_loaded;
LibraryList m_libraries;
PluginList m_plugins;
IAllocator& m_allocator;
};
PluginManager* PluginManager::create(Engine& engine)
{
return engine.getAllocator().newObject<PluginManagerImpl>(engine, engine.getAllocator());
}
void PluginManager::destroy(PluginManager* manager)
{
static_cast<PluginManagerImpl*>(manager)->getAllocator().deleteObject(manager);
}
} // ~namespace Lumix
<commit_msg>plugins are loaded/unloaded in LIFO order - fixes #588<commit_after>#include "plugin_manager.h"
#include "core/library.h"
#include "core/log.h"
#include "core/array.h"
#include "engine.h"
#include "iplugin.h"
namespace Lumix
{
class PluginManagerImpl : public PluginManager
{
private:
typedef Array<IPlugin*> PluginList;
typedef Array<Library*> LibraryList;
public:
PluginManagerImpl(Engine& engine, IAllocator& allocator)
: m_plugins(allocator)
, m_libraries(allocator)
, m_allocator(allocator)
, m_engine(engine)
, m_library_loaded(allocator)
{ }
~PluginManagerImpl()
{
for (int i = m_plugins.size() - 1; i >= 0; --i)
{
m_plugins[i]->destroy();
m_engine.getAllocator().deleteObject(m_plugins[i]);
}
for (int i = 0; i < m_libraries.size(); ++i)
{
Library::destroy(m_libraries[i]);
}
}
void update(float dt) override
{
for (int i = 0, c = m_plugins.size(); i < c; ++i)
{
m_plugins[i]->update(dt);
}
}
void serialize(OutputBlob& serializer) override
{
for (int i = 0, c = m_plugins.size(); i < c; ++i)
{
m_plugins[i]->serialize(serializer);
}
}
void deserialize(InputBlob& serializer) override
{
for (int i = 0, c = m_plugins.size(); i < c; ++i)
{
m_plugins[i]->deserialize(serializer);
}
}
virtual const Array<Library*>& getLibraries() const override
{
return m_libraries;
}
const Array<IPlugin*>& getPlugins() const override
{
return m_plugins;
}
IPlugin* getPlugin(const char* name) override
{
for (int i = 0; i < m_plugins.size(); ++i)
{
if (strcmp(m_plugins[i]->getName(), name) == 0)
{
return m_plugins[i];
}
}
return 0;
}
virtual DelegateList<void(Library&)>& libraryLoaded() override
{
return m_library_loaded;
}
IPlugin* load(const char* path) override
{
g_log_info.log("plugins") << "loading plugin " << path;
typedef IPlugin* (*PluginCreator)(Engine&);
Library* lib = Library::create(Path(path), m_engine.getAllocator());
if (lib->load())
{
PluginCreator creator = (PluginCreator)lib->resolve("createPlugin");
if (creator)
{
IPlugin* plugin = creator(m_engine);
if (!plugin->create())
{
m_engine.getAllocator().deleteObject(plugin);
ASSERT(false);
return nullptr;
}
m_plugins.push(plugin);
m_libraries.push(lib);
m_library_loaded.invoke(*lib);
g_log_info.log("plugins") << "plugin loaded";
return plugin;
}
}
Library::destroy(lib);
return 0;
}
IAllocator& getAllocator() { return m_allocator; }
void addPlugin(IPlugin* plugin) override
{
m_plugins.push(plugin);
}
private:
Engine& m_engine;
DelegateList<void(Library&)> m_library_loaded;
LibraryList m_libraries;
PluginList m_plugins;
IAllocator& m_allocator;
};
PluginManager* PluginManager::create(Engine& engine)
{
return engine.getAllocator().newObject<PluginManagerImpl>(engine, engine.getAllocator());
}
void PluginManager::destroy(PluginManager* manager)
{
static_cast<PluginManagerImpl*>(manager)->getAllocator().deleteObject(manager);
}
} // ~namespace Lumix
<|endoftext|> |
<commit_before>//
// Programmer: Tom M. <tom.mbrt@gmail.com>
// Creation Date: Sat Nov 05 14:51:00 PST 2016
// Last Modified: Sat Nov 05 14:51:00 PST 2016
// Filename: midifile/src-programs/mid2beep.cpp
// Web Address: https://github.com/craigsapp/midifile/blob/master/src-programs/mid2beep.cpp
// Syntax: C++
//
// Description: Linux-only: Play a monophonic midi file on the PC Speaker (i.e. the midi file contains only a single track
// on a single channel playing a single note at a time)
//
#include <iostream>
#include <cmath>
#include <unistd.h> // usleep()
#include <sys/io.h>
#include "MidiFile.h"
#include "Options.h"
#include <signal.h>
using namespace std;
using namespace smf;
void beepOff(int)
{
int r = inb(0x61);
outb(r|3, 0x61);
outb(r & 0xFC, 0x61);
exit(0);
}
void beep(int fre, int usDuration)
{
int r, ff;
if(fre > 0) {
ff = 1193180/fre;
outb( 0xB6, 0x43);
outb( ff & 0xff, 0x42);
outb((ff >> 8) & 0xff, 0x42);
}
r = inb(0x61);
if(fre > 0) outb(r|3, 0x61);
usleep(usDuration);
outb(r & 0xFC, 0x61);
}
int main(int argc, char** argv)
{
signal(SIGINT, beepOff);
Options options;
options.process(argc, argv);
MidiFile midifile;
if (options.getArgCount() == 1) {
midifile.read(options.getArg(1));
}
else
{
cout << "usage: " << argv[0] << " file.mid" << endl;
return -1;
}
int k= iopl(3);
printf("\n Result iopl: %d \n", k);
if (k<0)
{
cerr << " iopl() " << endl;
return k;
}
midifile.linkNotePairs();
midifile.joinTracks();
midifile.doTimeAnalysis();
midifile.absoluteTicks();
double lastNoteFinished = 0.0;
for (int track=0; track < midifile.getTrackCount(); track++) {
for (int i=0; i<midifile[track].size(); i++) {
MidiEvent* mev = &midifile[track][i];
if (!mev->isNoteOn() || mev->getLinkedEvent() == NULL) {
continue;
}
// pause, silence
int silence = static_cast<int>((midifile.getTimeInSeconds(mev->tick) - lastNoteFinished) * 1000 * 1000);
if(silence >0)
{
usleep(silence);
}
double duration = mev->getDurationInSeconds();
int halfTonesFromA4 = mev->getKeyNumber() - 69; // 69 == A4 == 440Hz
int frq = 440 * pow(2, halfTonesFromA4/12.0);
// play note
beep(frq, static_cast<int>(duration*1000*1000));
MidiEvent* off = mev->getLinkedEvent();
lastNoteFinished = midifile.getTimeInSeconds(off->tick);
}
}
return 0;
}
<commit_msg>Update example program for location of apple-specific files (program still does not compile on MacOS).<commit_after>//
// Programmer: Tom M. <tom.mbrt@gmail.com>
// Creation Date: Sat Nov 05 14:51:00 PST 2016
// Last Modified: Sat Nov 05 14:51:00 PST 2016
// Filename: midifile/src-programs/mid2beep.cpp
// Web Address: https://github.com/craigsapp/midifile/blob/master/src-programs/mid2beep.cpp
// Syntax: C++
//
// Description: Linux-only: Play a monophonic midi file on the PC Speaker (i.e. the midi file contains only a single track
// on a single channel playing a single note at a time)
//
#include "MidiFile.h"
#include "Options.h"
#include <iostream>
#include <cmath>
#include <unistd.h> // usleep()
#include <signal.h>
#ifdef __APPLE__
#include <sys/uio.h>
#else
#include <sys/io.h>
#endif
using namespace std;
using namespace smf;
void beepOff(int)
{
int r = inb(0x61);
outb(r|3, 0x61);
outb(r & 0xFC, 0x61);
exit(0);
}
void beep(int fre, int usDuration)
{
int r, ff;
if(fre > 0) {
ff = 1193180/fre;
outb( 0xB6, 0x43);
outb( ff & 0xff, 0x42);
outb((ff >> 8) & 0xff, 0x42);
}
r = inb(0x61);
if(fre > 0) outb(r|3, 0x61);
usleep(usDuration);
outb(r & 0xFC, 0x61);
}
int main(int argc, char** argv)
{
signal(SIGINT, beepOff);
Options options;
options.process(argc, argv);
MidiFile midifile;
if (options.getArgCount() == 1) {
midifile.read(options.getArg(1));
}
else
{
cout << "usage: " << argv[0] << " file.mid" << endl;
return -1;
}
int k= iopl(3);
printf("\n Result iopl: %d \n", k);
if (k<0)
{
cerr << " iopl() " << endl;
return k;
}
midifile.linkNotePairs();
midifile.joinTracks();
midifile.doTimeAnalysis();
midifile.absoluteTicks();
double lastNoteFinished = 0.0;
for (int track=0; track < midifile.getTrackCount(); track++) {
for (int i=0; i<midifile[track].size(); i++) {
MidiEvent* mev = &midifile[track][i];
if (!mev->isNoteOn() || mev->getLinkedEvent() == NULL) {
continue;
}
// pause, silence
int silence = static_cast<int>((midifile.getTimeInSeconds(mev->tick) - lastNoteFinished) * 1000 * 1000);
if(silence >0)
{
usleep(silence);
}
double duration = mev->getDurationInSeconds();
int halfTonesFromA4 = mev->getKeyNumber() - 69; // 69 == A4 == 440Hz
int frq = 440 * pow(2, halfTonesFromA4/12.0);
// play note
beep(frq, static_cast<int>(duration*1000*1000));
MidiEvent* off = mev->getLinkedEvent();
lastNoteFinished = midifile.getTimeInSeconds(off->tick);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <interactive_markers/interactive_marker_server.h>
#include <interactive_markers/menu_handler.h>
#include <visualization_msgs/InteractiveMarkerInit.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>
#include <math.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/shared_array.hpp>
#include <boost/program_options.hpp>
#include <boost/date_time.hpp>
bool compareInteractiveMarker(visualization_msgs::InteractiveMarker left,
visualization_msgs::InteractiveMarker right)
{
return std::stoi(left.name) < std::stoi(right.name);
}
std::string timeToStr()
{
std::stringstream msg;
const boost::posix_time::ptime now=
boost::posix_time::second_clock::local_time();
boost::posix_time::time_facet *const f=
new boost::posix_time::time_facet("%Y-%m-%d-%H-%M-%S");
msg.imbue(std::locale(msg.getloc(),f));
msg << now;
return msg.str();
}
class WaypointSaver
{
public:
WaypointSaver(const std::string& waypoints_file):
waypoints_file_(waypoints_file), saved_waypoints_(false)
{
ros::NodeHandle n;
ROS_INFO("Waiting for waypoints");
waypoints_sub_ = n.subscribe("/cube/update_full", 1, &WaypointSaver::pointsCallback, this);
}
void pointsCallback(visualization_msgs::InteractiveMarkerInit all_markers)
{
ROS_INFO("Received markers : %d", (int)all_markers.markers.size());
std::ofstream savefile(waypoints_file_.c_str(), std::ios::out);
std::sort(all_markers.markers.begin(), all_markers.markers.end(), compareInteractiveMarker);
size_t size = all_markers.markers.size();
for(unsigned int i = 0; i < size; i++){
//3次元の位置の指定
int is_searching_area = 0;
if (all_markers.markers[i].controls[2].markers[0].color.r > 1.0) {
is_searching_area = 1;
}
savefile << all_markers.markers[i].pose.position.x << ","
<< all_markers.markers[i].pose.position.y << ","
<< 0 << ","
<< all_markers.markers[i].pose.orientation.x << ","
<< all_markers.markers[i].pose.orientation.y << ","
<< all_markers.markers[i].pose.orientation.z << ","
<< all_markers.markers[i].pose.orientation.w << ","
<< is_searching_area << std::endl;
}
saved_waypoints_ = true;
}
std::string waypoints_file_;
ros::Subscriber waypoints_sub_;
bool saved_waypoints_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "waypoint_saver");
std::string waypoints_name = timeToStr() + ".csv";
ROS_INFO_STREAM("Saved to : " << waypoints_name);
WaypointSaver saver(waypoints_name);
while(!saver.saved_waypoints_ && ros::ok())
{
ros::spinOnce();
}
return 0;
}
<commit_msg>waypoint reach thresholdに対応<commit_after>#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <interactive_markers/interactive_marker_server.h>
#include <interactive_markers/menu_handler.h>
#include <visualization_msgs/InteractiveMarkerInit.h>
#include <visualization_msgs/MarkerArray.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>
#include <math.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/shared_array.hpp>
#include <boost/program_options.hpp>
#include <boost/date_time.hpp>
bool compareInteractiveMarker(visualization_msgs::InteractiveMarker left,
visualization_msgs::InteractiveMarker right)
{
return std::stoi(left.name) < std::stoi(right.name);
}
std::string timeToStr()
{
std::stringstream msg;
const boost::posix_time::ptime now=
boost::posix_time::second_clock::local_time();
boost::posix_time::time_facet *const f=
new boost::posix_time::time_facet("%Y-%m-%d-%H-%M-%S");
msg.imbue(std::locale(msg.getloc(),f));
msg << now;
return msg.str();
}
class WaypointSaver
{
public:
WaypointSaver(const std::string& waypoints_file):
waypoints_file_(waypoints_file), saved_waypoints_(false)
{
ros::NodeHandle n;
waypoints_sub_ = n.subscribe("/cube/update_full", 1, &WaypointSaver::pointsCallback, this);
reached_markers_sub_ = n.subscribe("/reach_threshold_markers", 1, &WaypointSaver::reachedMarkerCallback, this);
is_reached_markers_ = false;
}
void pointsCallback(visualization_msgs::InteractiveMarkerInit all_markers)
{
ROS_INFO("Waiting for reach_markers");
if (! is_reached_markers_) {
return;
}
ROS_INFO("Received markers : %d", (int)all_markers.markers.size());
if(all_markers.markers.size() != reached_markers_.markers.size())
{
ROS_ERROR("markers size is mismatch!!!");
}
std::ofstream savefile(waypoints_file_.c_str(), std::ios::out);
std::sort(all_markers.markers.begin(), all_markers.markers.end(), compareInteractiveMarker);
size_t size = all_markers.markers.size();
for(unsigned int i = 0; i < size; i++){
//3次元の位置の指定
int is_searching_area = 0;
if (all_markers.markers[i].controls[2].markers[0].color.r > 1.0) {
is_searching_area = 1;
}
savefile << all_markers.markers[i].pose.position.x << ","
<< all_markers.markers[i].pose.position.y << ","
<< 0 << ","
<< all_markers.markers[i].pose.orientation.x << ","
<< all_markers.markers[i].pose.orientation.y << ","
<< all_markers.markers[i].pose.orientation.z << ","
<< all_markers.markers[i].pose.orientation.w << ","
<< is_searching_area << ","
<< 2.0*reached_markers_.markers[i].scale.x << std::endl;
}
saved_waypoints_ = true;
ROS_INFO_STREAM("Saved to : " << waypoints_file_);
}
void reachedMarkerCallback(visualization_msgs::MarkerArray reached_markers)
{
ROS_INFO("Received Reach threshold markers : %d", (int)reached_markers.markers.size());
reached_markers_ = reached_markers;
is_reached_markers_ = true;
}
std::string waypoints_file_;
ros::Subscriber waypoints_sub_;
bool saved_waypoints_;
bool is_reached_markers_;
ros::Subscriber reached_markers_sub_;
visualization_msgs::MarkerArray reached_markers_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "waypoint_saver");
std::string waypoints_name = timeToStr() + ".csv";
WaypointSaver saver(waypoints_name);
while(!saver.saved_waypoints_ && ros::ok())
{
ros::spinOnce();
}
return 0;
}
<|endoftext|> |
<commit_before>
#include "rust_sched_loop.h"
#include "rust_util.h"
#include "rust_scheduler.h"
#ifndef _WIN32
pthread_key_t rust_sched_loop::task_key;
#else
DWORD rust_sched_loop::task_key;
#endif
const size_t C_STACK_SIZE = 1024*1024;
bool rust_sched_loop::tls_initialized = false;
rust_sched_loop::rust_sched_loop(rust_scheduler *sched,int id) :
_log(this),
id(id),
should_exit(false),
cached_c_stack(NULL),
dead_task(NULL),
pump_signal(NULL),
kernel(sched->kernel),
sched(sched),
log_lvl(log_debug),
min_stack_size(kernel->env->min_stack_size),
local_region(kernel->env, false),
// TODO: calculate a per scheduler name.
name("main")
{
LOGPTR(this, "new dom", (uintptr_t)this);
isaac_init(kernel, &rctx, NULL);
if (!tls_initialized)
init_tls();
}
void
rust_sched_loop::activate(rust_task *task) {
lock.must_have_lock();
task->ctx.next = &c_context;
DLOG(this, task, "descheduling...");
lock.unlock();
prepare_c_stack(task);
task->ctx.swap(c_context);
task->cleanup_after_turn();
unprepare_c_stack();
lock.lock();
DLOG(this, task, "task has returned");
}
void
rust_sched_loop::fail() {
_log.log(NULL, log_err, "domain %s @0x%" PRIxPTR " root task failed",
name, this);
kernel->fail();
}
void
rust_sched_loop::kill_all_tasks() {
std::vector<rust_task*> all_tasks;
{
scoped_lock with(lock);
for (size_t i = 0; i < running_tasks.length(); i++) {
all_tasks.push_back(running_tasks[i]);
}
for (size_t i = 0; i < blocked_tasks.length(); i++) {
all_tasks.push_back(blocked_tasks[i]);
}
}
while (!all_tasks.empty()) {
rust_task *task = all_tasks.back();
all_tasks.pop_back();
// We don't want the failure of these tasks to propagate back
// to the kernel again since we're already failing everything
task->unsupervise();
task->kill();
}
}
size_t
rust_sched_loop::number_of_live_tasks() {
return running_tasks.length() + blocked_tasks.length();
}
/**
* Delete any dead tasks.
*/
void
rust_sched_loop::reap_dead_tasks() {
lock.must_have_lock();
if (dead_task == NULL) {
return;
}
// Dereferencing the task will probably cause it to be released
// from the scheduler, which may end up trying to take this lock
lock.unlock();
dead_task->delete_all_stacks();
// Deref the task, which may cause it to request us to release it
dead_task->deref();
dead_task = NULL;
lock.lock();
}
void
rust_sched_loop::release_task(rust_task *task) {
// Nobody should have a ref to the task at this point
assert(task->get_ref_count() == 0);
// Now delete the task, which will require using this thread's
// memory region.
delete task;
// Now release the task from the scheduler, which may trigger this
// thread to exit
sched->release_task();
}
/**
* Schedules a running task for execution. Only running tasks can be
* activated. Blocked tasks have to be unblocked before they can be
* activated.
*
* Returns NULL if no tasks can be scheduled.
*/
rust_task *
rust_sched_loop::schedule_task() {
lock.must_have_lock();
assert(this);
// FIXME: in the face of failing tasks, this is not always right. (#2695)
// assert(n_live_tasks() > 0);
if (running_tasks.length() > 0) {
size_t k = isaac_rand(&rctx);
// Look around for a runnable task, starting at k.
for(size_t j = 0; j < running_tasks.length(); ++j) {
size_t i = (j + k) % running_tasks.length();
return (rust_task *)running_tasks[i];
}
}
return NULL;
}
void
rust_sched_loop::log_state() {
if (log_rt_task < log_debug) return;
if (!running_tasks.is_empty()) {
_log.log(NULL, log_debug, "running tasks:");
for (size_t i = 0; i < running_tasks.length(); i++) {
_log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR,
running_tasks[i]->name,
running_tasks[i]);
}
}
if (!blocked_tasks.is_empty()) {
_log.log(NULL, log_debug, "blocked tasks:");
for (size_t i = 0; i < blocked_tasks.length(); i++) {
_log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR
", blocked on: 0x%" PRIxPTR " '%s'",
blocked_tasks[i]->name, blocked_tasks[i],
blocked_tasks[i]->get_cond(),
blocked_tasks[i]->get_cond_name());
}
}
}
void
rust_sched_loop::on_pump_loop(rust_signal *signal) {
assert(pump_signal == NULL);
assert(signal != NULL);
pump_signal = signal;
}
void
rust_sched_loop::pump_loop() {
assert(pump_signal != NULL);
pump_signal->signal();
}
rust_sched_loop_state
rust_sched_loop::run_single_turn() {
DLOG(this, task,
"scheduler %d resuming ...", id);
lock.lock();
if (!should_exit) {
assert(dead_task == NULL && "Tasks should only die after running");
DLOG(this, dom, "worker %d, number_of_live_tasks = %d",
id, number_of_live_tasks());
rust_task *scheduled_task = schedule_task();
if (scheduled_task == NULL) {
log_state();
DLOG(this, task,
"all tasks are blocked, scheduler id %d yielding ...",
id);
lock.unlock();
return sched_loop_state_block;
}
assert(scheduled_task->running());
DLOG(this, task,
"activating task %s 0x%" PRIxPTR
", state: %s",
scheduled_task->name,
(uintptr_t)scheduled_task,
state_name(scheduled_task->get_state()));
place_task_in_tls(scheduled_task);
DLOG(this, task,
"Running task %p on worker %d",
scheduled_task, id);
activate(scheduled_task);
DLOG(this, task,
"returned from task %s @0x%" PRIxPTR
" in state '%s', worker id=%d" PRIxPTR,
scheduled_task->name,
(uintptr_t)scheduled_task,
state_name(scheduled_task->get_state()),
id);
reap_dead_tasks();
lock.unlock();
return sched_loop_state_keep_going;
} else {
assert(running_tasks.is_empty() && "Should have no running tasks");
assert(blocked_tasks.is_empty() && "Should have no blocked tasks");
assert(dead_task == NULL && "Should have no dead tasks");
DLOG(this, dom, "finished main-loop %d", id);
lock.unlock();
assert(!extra_c_stack);
if (cached_c_stack) {
destroy_stack(kernel->region(), cached_c_stack);
cached_c_stack = NULL;
}
sched->release_task_thread();
return sched_loop_state_exit;
}
}
rust_task *
rust_sched_loop::create_task(rust_task *spawner, const char *name) {
rust_task *task =
new (this->kernel, "rust_task")
rust_task (this, task_state_newborn,
spawner, name, kernel->env->min_stack_size);
DLOG(this, task, "created task: " PTR ", spawner: %s, name: %s",
task, spawner ? spawner->name : "null", name);
task->id = kernel->generate_task_id();
return task;
}
rust_task_list *
rust_sched_loop::state_list(rust_task_state state) {
switch (state) {
case task_state_running:
return &running_tasks;
case task_state_blocked:
return &blocked_tasks;
default:
return NULL;
}
}
const char *
rust_sched_loop::state_name(rust_task_state state) {
switch (state) {
case task_state_newborn:
return "newborn";
case task_state_running:
return "running";
case task_state_blocked:
return "blocked";
case task_state_dead:
return "dead";
default:
assert(false);
return "";
}
}
void
rust_sched_loop::transition(rust_task *task,
rust_task_state src, rust_task_state dst,
rust_cond *cond, const char* cond_name) {
scoped_lock with(lock);
DLOG(this, task,
"task %s " PTR " state change '%s' -> '%s' while in '%s'",
name, (uintptr_t)this, state_name(src), state_name(dst),
state_name(task->get_state()));
assert(task->get_state() == src);
rust_task_list *src_list = state_list(src);
if (src_list) {
src_list->remove(task);
}
rust_task_list *dst_list = state_list(dst);
if (dst_list) {
dst_list->append(task);
}
if (dst == task_state_dead) {
assert(dead_task == NULL);
dead_task = task;
}
task->set_state(dst, cond, cond_name);
pump_loop();
}
#ifndef _WIN32
void
rust_sched_loop::init_tls() {
int result = pthread_key_create(&task_key, NULL);
assert(!result && "Couldn't create the TLS key!");
tls_initialized = true;
}
void
rust_sched_loop::place_task_in_tls(rust_task *task) {
int result = pthread_setspecific(task_key, task);
assert(!result && "Couldn't place the task in TLS!");
task->record_stack_limit();
}
#else
void
rust_sched_loop::init_tls() {
task_key = TlsAlloc();
assert(task_key != TLS_OUT_OF_INDEXES && "Couldn't create the TLS key!");
tls_initialized = true;
}
void
rust_sched_loop::place_task_in_tls(rust_task *task) {
BOOL result = TlsSetValue(task_key, task);
assert(result && "Couldn't place the task in TLS!");
task->record_stack_limit();
}
#endif
void
rust_sched_loop::exit() {
scoped_lock with(lock);
DLOG(this, dom, "Requesting exit for thread %d", id);
should_exit = true;
pump_loop();
}
// Before activating each task, make sure we have a C stack available.
// It needs to be allocated ahead of time (while we're on our own
// stack), because once we're on the Rust stack we won't have enough
// room to do the allocation
void
rust_sched_loop::prepare_c_stack(rust_task *task) {
assert(!extra_c_stack);
if (!cached_c_stack && !task->have_c_stack()) {
cached_c_stack = create_stack(kernel->region(), C_STACK_SIZE);
}
}
void
rust_sched_loop::unprepare_c_stack() {
if (extra_c_stack) {
destroy_stack(kernel->region(), extra_c_stack);
extra_c_stack = NULL;
}
}
//
// Local Variables:
// mode: C++
// fill-column: 70;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
<commit_msg>Remove obsolete FIXME<commit_after>
#include "rust_sched_loop.h"
#include "rust_util.h"
#include "rust_scheduler.h"
#ifndef _WIN32
pthread_key_t rust_sched_loop::task_key;
#else
DWORD rust_sched_loop::task_key;
#endif
const size_t C_STACK_SIZE = 1024*1024;
bool rust_sched_loop::tls_initialized = false;
rust_sched_loop::rust_sched_loop(rust_scheduler *sched,int id) :
_log(this),
id(id),
should_exit(false),
cached_c_stack(NULL),
dead_task(NULL),
pump_signal(NULL),
kernel(sched->kernel),
sched(sched),
log_lvl(log_debug),
min_stack_size(kernel->env->min_stack_size),
local_region(kernel->env, false),
// TODO: calculate a per scheduler name.
name("main")
{
LOGPTR(this, "new dom", (uintptr_t)this);
isaac_init(kernel, &rctx, NULL);
if (!tls_initialized)
init_tls();
}
void
rust_sched_loop::activate(rust_task *task) {
lock.must_have_lock();
task->ctx.next = &c_context;
DLOG(this, task, "descheduling...");
lock.unlock();
prepare_c_stack(task);
task->ctx.swap(c_context);
task->cleanup_after_turn();
unprepare_c_stack();
lock.lock();
DLOG(this, task, "task has returned");
}
void
rust_sched_loop::fail() {
_log.log(NULL, log_err, "domain %s @0x%" PRIxPTR " root task failed",
name, this);
kernel->fail();
}
void
rust_sched_loop::kill_all_tasks() {
std::vector<rust_task*> all_tasks;
{
scoped_lock with(lock);
for (size_t i = 0; i < running_tasks.length(); i++) {
all_tasks.push_back(running_tasks[i]);
}
for (size_t i = 0; i < blocked_tasks.length(); i++) {
all_tasks.push_back(blocked_tasks[i]);
}
}
while (!all_tasks.empty()) {
rust_task *task = all_tasks.back();
all_tasks.pop_back();
// We don't want the failure of these tasks to propagate back
// to the kernel again since we're already failing everything
task->unsupervise();
task->kill();
}
}
size_t
rust_sched_loop::number_of_live_tasks() {
return running_tasks.length() + blocked_tasks.length();
}
/**
* Delete any dead tasks.
*/
void
rust_sched_loop::reap_dead_tasks() {
lock.must_have_lock();
if (dead_task == NULL) {
return;
}
// Dereferencing the task will probably cause it to be released
// from the scheduler, which may end up trying to take this lock
lock.unlock();
dead_task->delete_all_stacks();
// Deref the task, which may cause it to request us to release it
dead_task->deref();
dead_task = NULL;
lock.lock();
}
void
rust_sched_loop::release_task(rust_task *task) {
// Nobody should have a ref to the task at this point
assert(task->get_ref_count() == 0);
// Now delete the task, which will require using this thread's
// memory region.
delete task;
// Now release the task from the scheduler, which may trigger this
// thread to exit
sched->release_task();
}
/**
* Schedules a running task for execution. Only running tasks can be
* activated. Blocked tasks have to be unblocked before they can be
* activated.
*
* Returns NULL if no tasks can be scheduled.
*/
rust_task *
rust_sched_loop::schedule_task() {
lock.must_have_lock();
assert(this);
if (running_tasks.length() > 0) {
size_t k = isaac_rand(&rctx);
// Look around for a runnable task, starting at k.
for(size_t j = 0; j < running_tasks.length(); ++j) {
size_t i = (j + k) % running_tasks.length();
return (rust_task *)running_tasks[i];
}
}
return NULL;
}
void
rust_sched_loop::log_state() {
if (log_rt_task < log_debug) return;
if (!running_tasks.is_empty()) {
_log.log(NULL, log_debug, "running tasks:");
for (size_t i = 0; i < running_tasks.length(); i++) {
_log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR,
running_tasks[i]->name,
running_tasks[i]);
}
}
if (!blocked_tasks.is_empty()) {
_log.log(NULL, log_debug, "blocked tasks:");
for (size_t i = 0; i < blocked_tasks.length(); i++) {
_log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR
", blocked on: 0x%" PRIxPTR " '%s'",
blocked_tasks[i]->name, blocked_tasks[i],
blocked_tasks[i]->get_cond(),
blocked_tasks[i]->get_cond_name());
}
}
}
void
rust_sched_loop::on_pump_loop(rust_signal *signal) {
assert(pump_signal == NULL);
assert(signal != NULL);
pump_signal = signal;
}
void
rust_sched_loop::pump_loop() {
assert(pump_signal != NULL);
pump_signal->signal();
}
rust_sched_loop_state
rust_sched_loop::run_single_turn() {
DLOG(this, task,
"scheduler %d resuming ...", id);
lock.lock();
if (!should_exit) {
assert(dead_task == NULL && "Tasks should only die after running");
DLOG(this, dom, "worker %d, number_of_live_tasks = %d",
id, number_of_live_tasks());
rust_task *scheduled_task = schedule_task();
if (scheduled_task == NULL) {
log_state();
DLOG(this, task,
"all tasks are blocked, scheduler id %d yielding ...",
id);
lock.unlock();
return sched_loop_state_block;
}
assert(scheduled_task->running());
DLOG(this, task,
"activating task %s 0x%" PRIxPTR
", state: %s",
scheduled_task->name,
(uintptr_t)scheduled_task,
state_name(scheduled_task->get_state()));
place_task_in_tls(scheduled_task);
DLOG(this, task,
"Running task %p on worker %d",
scheduled_task, id);
activate(scheduled_task);
DLOG(this, task,
"returned from task %s @0x%" PRIxPTR
" in state '%s', worker id=%d" PRIxPTR,
scheduled_task->name,
(uintptr_t)scheduled_task,
state_name(scheduled_task->get_state()),
id);
reap_dead_tasks();
lock.unlock();
return sched_loop_state_keep_going;
} else {
assert(running_tasks.is_empty() && "Should have no running tasks");
assert(blocked_tasks.is_empty() && "Should have no blocked tasks");
assert(dead_task == NULL && "Should have no dead tasks");
DLOG(this, dom, "finished main-loop %d", id);
lock.unlock();
assert(!extra_c_stack);
if (cached_c_stack) {
destroy_stack(kernel->region(), cached_c_stack);
cached_c_stack = NULL;
}
sched->release_task_thread();
return sched_loop_state_exit;
}
}
rust_task *
rust_sched_loop::create_task(rust_task *spawner, const char *name) {
rust_task *task =
new (this->kernel, "rust_task")
rust_task (this, task_state_newborn,
spawner, name, kernel->env->min_stack_size);
DLOG(this, task, "created task: " PTR ", spawner: %s, name: %s",
task, spawner ? spawner->name : "null", name);
task->id = kernel->generate_task_id();
return task;
}
rust_task_list *
rust_sched_loop::state_list(rust_task_state state) {
switch (state) {
case task_state_running:
return &running_tasks;
case task_state_blocked:
return &blocked_tasks;
default:
return NULL;
}
}
const char *
rust_sched_loop::state_name(rust_task_state state) {
switch (state) {
case task_state_newborn:
return "newborn";
case task_state_running:
return "running";
case task_state_blocked:
return "blocked";
case task_state_dead:
return "dead";
default:
assert(false);
return "";
}
}
void
rust_sched_loop::transition(rust_task *task,
rust_task_state src, rust_task_state dst,
rust_cond *cond, const char* cond_name) {
scoped_lock with(lock);
DLOG(this, task,
"task %s " PTR " state change '%s' -> '%s' while in '%s'",
name, (uintptr_t)this, state_name(src), state_name(dst),
state_name(task->get_state()));
assert(task->get_state() == src);
rust_task_list *src_list = state_list(src);
if (src_list) {
src_list->remove(task);
}
rust_task_list *dst_list = state_list(dst);
if (dst_list) {
dst_list->append(task);
}
if (dst == task_state_dead) {
assert(dead_task == NULL);
dead_task = task;
}
task->set_state(dst, cond, cond_name);
pump_loop();
}
#ifndef _WIN32
void
rust_sched_loop::init_tls() {
int result = pthread_key_create(&task_key, NULL);
assert(!result && "Couldn't create the TLS key!");
tls_initialized = true;
}
void
rust_sched_loop::place_task_in_tls(rust_task *task) {
int result = pthread_setspecific(task_key, task);
assert(!result && "Couldn't place the task in TLS!");
task->record_stack_limit();
}
#else
void
rust_sched_loop::init_tls() {
task_key = TlsAlloc();
assert(task_key != TLS_OUT_OF_INDEXES && "Couldn't create the TLS key!");
tls_initialized = true;
}
void
rust_sched_loop::place_task_in_tls(rust_task *task) {
BOOL result = TlsSetValue(task_key, task);
assert(result && "Couldn't place the task in TLS!");
task->record_stack_limit();
}
#endif
void
rust_sched_loop::exit() {
scoped_lock with(lock);
DLOG(this, dom, "Requesting exit for thread %d", id);
should_exit = true;
pump_loop();
}
// Before activating each task, make sure we have a C stack available.
// It needs to be allocated ahead of time (while we're on our own
// stack), because once we're on the Rust stack we won't have enough
// room to do the allocation
void
rust_sched_loop::prepare_c_stack(rust_task *task) {
assert(!extra_c_stack);
if (!cached_c_stack && !task->have_c_stack()) {
cached_c_stack = create_stack(kernel->region(), C_STACK_SIZE);
}
}
void
rust_sched_loop::unprepare_c_stack() {
if (extra_c_stack) {
destroy_stack(kernel->region(), extra_c_stack);
extra_c_stack = NULL;
}
}
//
// Local Variables:
// mode: C++
// fill-column: 70;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "filtermanager.h"
#include "filters.h"
#include "../daemon/strigilogging.h"
#include <fstream>
using namespace std;
FilterManager::FilterManager()
{
pthread_mutex_init(&m_mutex, NULL);
}
FilterManager::~ FilterManager()
{
saveFilter();
clearRules();
pthread_mutex_destroy (&m_mutex);
}
void FilterManager::clearRules()
{
for (unsigned int i = 0; i < m_rules.size(); i++)
delete m_rules[i];
m_rules.clear();
}
void FilterManager::setConfFile (string& patternRules, string& pathRules)
{
m_patternFile = patternRules;
m_pathFile = pathRules;
// clear old rules
// TODO: remove when weì'll have a single configuration file
clearRules();
loadFilter(patternRules, PatternFilter::RTTI);
loadFilter(pathRules, PathFilter::RTTI);
}
void FilterManager::loadFilter(string& file, unsigned int filterRTTI)
{
fstream confFile;
string rule;
char buffer [500];
confFile.open(file.c_str(), ios::in);
// clear old rules
// TODO: restore when weì'll have a single configuration file
//clearRules();
if (confFile.is_open())
{
pthread_mutex_lock (&m_mutex);
// read filter rules
while (!confFile.eof())
{
confFile.getline(buffer, 500);
rule = buffer;
if (rule.size() > 0)
{
switch (filterRTTI)
{
case PathFilter::RTTI:
m_rules.push_back (new PathFilter (string(buffer)));
STRIGI_LOG_DEBUG ("strigi.filtermanager.loadFilter", "added path filter: |" + string(buffer) + "|")
break;
case PatternFilter::RTTI:
m_rules.push_back (new PatternFilter (string(buffer)));
STRIGI_LOG_DEBUG ("strigi.filtermanager.loadFilter", "added pattern filter: |" + string(buffer) + "|")
break;
default:
STRIGI_LOG_ERROR ("strigi.filtermanager.loadFilter", "unknown rule RTTI")
break;
}
}
}
pthread_mutex_unlock (&m_mutex);
confFile.close();
}
snprintf (buffer, 500*sizeof (char), "%i", m_rules.size());
STRIGI_LOG_INFO ("strigi.filtermanager", "added " + string(buffer) + " filtering rules")
}
void FilterManager::saveFilter()
{
if (m_patternFile.empty() || m_pathFile.empty())
return;
fstream pathFile;
fstream patternFile;
pathFile.open(m_pathFile.c_str(), ios::out | ios::trunc);
patternFile.open(m_patternFile.c_str(), ios::out | ios::trunc);
pthread_mutex_lock (&m_mutex);
// TODO: fix when we'll use a single conf file
if (pathFile.is_open() && patternFile.is_open())
{
for (vector<Filter*>::iterator iter = m_rules.begin(); iter != m_rules.end(); iter++)
{
Filter* filter = *iter;
switch (filter->rtti())
{
case PathFilter::RTTI:
pathFile << filter->rule() << endl;
break;
case PatternFilter::RTTI:
patternFile << filter->rule() << endl;
break;
default:
STRIGI_LOG_ERROR ("strigi.filtermanager.saveFilter", "unknown rule RTTI")
break;
}
}
patternFile.close();
pathFile.close();
STRIGI_LOG_DEBUG ("strigi.filtermanager", "successfully saved filtering rules")
}
else
STRIGI_LOG_ERROR ("strigi.filtermanager.saveFilter", "unable to save filtering rules");
pthread_mutex_unlock (&m_mutex);
}
bool FilterManager::findMatch(const char* text)
{
string t (text);
return findMatch (t);
}
bool FilterManager::findMatch (string& text)
{
pthread_mutex_lock (&m_mutex);
for (vector<Filter*>::iterator iter = m_rules.begin(); iter != m_rules.end(); iter++)
{
Filter* filter = *iter;
if (filter->match (text))
{
pthread_mutex_unlock (&m_mutex);
return true;
}
}
pthread_mutex_unlock (&m_mutex);
STRIGI_LOG_DEBUG ("strigi.filtermanager", text + " didn't match any pattern")
return false;
}
multimap<int,string> FilterManager::getFilteringRules()
{
multimap<int,string> rules;
for (vector<Filter*>::iterator iter = m_rules.begin(); iter != m_rules.end(); iter++)
{
Filter* filter = *iter;
rules.insert(make_pair (int(filter->rtti()),filter->rule()));
}
return rules;
}
void FilterManager::setFilteringRules(const multimap<int, string>& rules)
{
clearRules();
map<int,string>::const_iterator iter;
for (iter = rules.begin(); iter != rules.end(); iter++)
{
switch (iter->first)
{
case PathFilter::RTTI:
m_rules.push_back (new PathFilter (iter->second));
break;
case PatternFilter::RTTI:
m_rules.push_back (new PatternFilter (iter->second));
break;
default:
STRIGI_LOG_ERROR ("strigi.filtermanager.setFilteringRules", "unknown rule RTTI")
}
}
}
<commit_msg>made filtermanager less verbose<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "filtermanager.h"
#include "filters.h"
#include "../daemon/strigilogging.h"
#include <fstream>
using namespace std;
FilterManager::FilterManager()
{
pthread_mutex_init(&m_mutex, NULL);
}
FilterManager::~ FilterManager()
{
saveFilter();
clearRules();
pthread_mutex_destroy (&m_mutex);
}
void FilterManager::clearRules()
{
for (unsigned int i = 0; i < m_rules.size(); i++)
delete m_rules[i];
m_rules.clear();
}
void FilterManager::setConfFile (string& patternRules, string& pathRules)
{
m_patternFile = patternRules;
m_pathFile = pathRules;
// clear old rules
// TODO: remove when weì'll have a single configuration file
clearRules();
loadFilter(patternRules, PatternFilter::RTTI);
loadFilter(pathRules, PathFilter::RTTI);
}
void FilterManager::loadFilter(string& file, unsigned int filterRTTI)
{
fstream confFile;
string rule;
char buffer [500];
confFile.open(file.c_str(), ios::in);
// clear old rules
// TODO: restore when weì'll have a single configuration file
//clearRules();
if (confFile.is_open())
{
pthread_mutex_lock (&m_mutex);
// read filter rules
while (!confFile.eof())
{
confFile.getline(buffer, 500);
rule = buffer;
if (rule.size() > 0)
{
switch (filterRTTI)
{
case PathFilter::RTTI:
m_rules.push_back (new PathFilter (string(buffer)));
STRIGI_LOG_DEBUG ("strigi.filtermanager.loadFilter", "added path filter: |" + string(buffer) + "|")
break;
case PatternFilter::RTTI:
m_rules.push_back (new PatternFilter (string(buffer)));
STRIGI_LOG_DEBUG ("strigi.filtermanager.loadFilter", "added pattern filter: |" + string(buffer) + "|")
break;
default:
STRIGI_LOG_ERROR ("strigi.filtermanager.loadFilter", "unknown rule RTTI")
break;
}
}
}
pthread_mutex_unlock (&m_mutex);
confFile.close();
}
snprintf (buffer, 500*sizeof (char), "%i", m_rules.size());
STRIGI_LOG_INFO ("strigi.filtermanager", "added " + string(buffer) + " filtering rules")
}
void FilterManager::saveFilter()
{
if (m_patternFile.empty() || m_pathFile.empty())
return;
fstream pathFile;
fstream patternFile;
pathFile.open(m_pathFile.c_str(), ios::out | ios::trunc);
patternFile.open(m_patternFile.c_str(), ios::out | ios::trunc);
pthread_mutex_lock (&m_mutex);
// TODO: fix when we'll use a single conf file
if (pathFile.is_open() && patternFile.is_open())
{
for (vector<Filter*>::iterator iter = m_rules.begin(); iter != m_rules.end(); iter++)
{
Filter* filter = *iter;
switch (filter->rtti())
{
case PathFilter::RTTI:
pathFile << filter->rule() << endl;
break;
case PatternFilter::RTTI:
patternFile << filter->rule() << endl;
break;
default:
STRIGI_LOG_ERROR ("strigi.filtermanager.saveFilter", "unknown rule RTTI")
break;
}
}
patternFile.close();
pathFile.close();
STRIGI_LOG_DEBUG ("strigi.filtermanager", "successfully saved filtering rules")
}
else
STRIGI_LOG_ERROR ("strigi.filtermanager.saveFilter", "unable to save filtering rules");
pthread_mutex_unlock (&m_mutex);
}
bool FilterManager::findMatch(const char* text)
{
string t (text);
return findMatch (t);
}
bool FilterManager::findMatch (string& text)
{
pthread_mutex_lock (&m_mutex);
for (vector<Filter*>::iterator iter = m_rules.begin(); iter != m_rules.end(); iter++)
{
Filter* filter = *iter;
if (filter->match (text))
{
pthread_mutex_unlock (&m_mutex);
return true;
}
}
pthread_mutex_unlock (&m_mutex);
//STRIGI_LOG_DEBUG ("strigi.filtermanager", text + " didn't match any pattern")
return false;
}
multimap<int,string> FilterManager::getFilteringRules()
{
multimap<int,string> rules;
for (vector<Filter*>::iterator iter = m_rules.begin(); iter != m_rules.end(); iter++)
{
Filter* filter = *iter;
rules.insert(make_pair (int(filter->rtti()),filter->rule()));
}
return rules;
}
void FilterManager::setFilteringRules(const multimap<int, string>& rules)
{
clearRules();
map<int,string>::const_iterator iter;
for (iter = rules.begin(); iter != rules.end(); iter++)
{
switch (iter->first)
{
case PathFilter::RTTI:
m_rules.push_back (new PathFilter (iter->second));
break;
case PatternFilter::RTTI:
m_rules.push_back (new PatternFilter (iter->second));
break;
default:
STRIGI_LOG_ERROR ("strigi.filtermanager.setFilteringRules", "unknown rule RTTI")
}
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 Damien Tardy-Panis
*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
**/
#include "CommitStrip.h"
#include <QDebug>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
CommitStrip::CommitStrip(QObject *parent) :
Comic(parent)
{
m_info.id = QString("commitstrip");
m_info.name = QString("CommitStrip");
m_info.color = QColor(43, 63, 107);
m_info.authors = QStringList() << "Etienne Issartial" << "Thomas Gx";
m_info.homepage = QUrl("http://www.commitstrip.com/");
m_info.country = QLocale::France;
m_info.language = QLocale::English;
m_info.startDate = QDate::fromString("2012-02", "yyyy-MM");
m_info.endDate = QDate::currentDate();
m_info.stripSourceUrl = QUrl("http://www.commitstrip.com/en/");
}
QUrl CommitStrip::extractStripImageUrl(QByteArray data)
{
QString html(data);
QRegularExpression reg("<img[^>]*src=\"([^\"]*/wp-content/uploads/[^\"]*)\"");
QRegularExpressionMatch match = reg.match(html);
if (!match.hasMatch()) {
return QUrl();
}
QString src = match.captured(1);
return QUrl(src);
}
<commit_msg>fix CommitStrip comic<commit_after>/**
* Copyright (c) 2015 Damien Tardy-Panis
*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
**/
#include "CommitStrip.h"
#include <QDebug>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
CommitStrip::CommitStrip(QObject *parent) :
Comic(parent)
{
m_info.id = QString("commitstrip");
m_info.name = QString("CommitStrip");
m_info.color = QColor(43, 63, 107);
m_info.authors = QStringList() << "Etienne Issartial" << "Thomas Gx";
m_info.homepage = QUrl("http://www.commitstrip.com/");
m_info.country = QLocale::France;
m_info.language = QLocale::English;
m_info.startDate = QDate::fromString("2012-02", "yyyy-MM");
m_info.endDate = QDate::currentDate();
m_info.stripSourceUrl = QUrl("http://www.commitstrip.com/en/feed/");
}
QUrl CommitStrip::extractStripImageUrl(QByteArray data)
{
QString html(data);
QRegularExpression reg("<img[^>]*src=\"([^\"]*/wp-content/uploads/[^\"]*)\"");
QRegularExpressionMatch match = reg.match(html);
if (!match.hasMatch()) {
return QUrl();
}
QString src = match.captured(1);
return QUrl(src);
}
<|endoftext|> |
<commit_before>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
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/>.
*/
/*}}}*/
// INCLUDES/*{{{*/
#ifdef HAVE_CONFIG_H
# include <config.hxx>
#endif
#include <deque>
#include <string>
#include <exception>
#include <print.hxx>
#include <Control/Control.hxx>
#include <Contact/Contact.hxx>
#include <Contact/File/Input.hxx>
#include <Contact/Command.hxx>
#include <Exception/InputException.hxx>
#include <libsxc/Exception/Exception.hxx>
/*}}}*/
namespace Contact
{
namespace File
{
Input::Input(Control::Control &control, Contact &contact)/*{{{*/
: _control(control),
_contact(contact)
{
}
/*}}}*/
std::string Input::_createPath() const/*{{{*/
{
return _control.getJid().bare() + _contact.getJid().bare() + "/in";
}
/*}}}*/
void Input::_handleInput(const std::string &input)/*{{{*/
{
/* // TODO
try {
Command::Command command(_contact, input);
command.execute();
} catch (Exception::InputException &e) {
// Just an invalid input, nothing serious.
_contact.handleError(e);
} catch (libsxc::Exception::Exception &e) {
// This may be something more serious.
// TODO: Fix handleError() to make use of stderr
_contact.handleError(e);
} catch (std::exception &e) {
// This is *really* unexpected.
printErr(e.what());
_contact.print(e.what());
}
*/
}
/*}}}*/
}
}
// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<commit_msg>Contact::File::Input: Fixed bad path.<commit_after>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
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/>.
*/
/*}}}*/
// INCLUDES/*{{{*/
#ifdef HAVE_CONFIG_H
# include <config.hxx>
#endif
#include <deque>
#include <string>
#include <exception>
#include <print.hxx>
#include <Control/Control.hxx>
#include <Contact/Contact.hxx>
#include <Contact/File/Input.hxx>
#include <Contact/Command.hxx>
#include <Exception/InputException.hxx>
#include <libsxc/Exception/Exception.hxx>
/*}}}*/
namespace Contact
{
namespace File
{
Input::Input(Control::Control &control, Contact &contact)/*{{{*/
: _control(control),
_contact(contact)
{
}
/*}}}*/
std::string Input::_createPath() const/*{{{*/
{
return _control.getJid().bare() + "/"
+ _contact.getJid().bare() + "/in";
}
/*}}}*/
void Input::_handleInput(const std::string &input)/*{{{*/
{
/* // TODO
try {
Command::Command command(_contact, input);
command.execute();
} catch (Exception::InputException &e) {
// Just an invalid input, nothing serious.
_contact.handleError(e);
} catch (libsxc::Exception::Exception &e) {
// This may be something more serious.
// TODO: Fix handleError() to make use of stderr
_contact.handleError(e);
} catch (std::exception &e) {
// This is *really* unexpected.
printErr(e.what());
_contact.print(e.what());
}
*/
}
/*}}}*/
}
}
// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
typedef float dataType;
std::string typeName("float");
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);
int main(int argc, char * argv[]) {
bool reInit = false;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreads = 0;
unsigned int maxRows = 0;
unsigned int maxColumns = 0;
unsigned int threadUnit = 0;
unsigned int threadIncrement = 0;
unsigned int maxItems = 0;
unsigned int maxUnroll = 0;
unsigned int maxLoopBodySize = 0;
AstroData::Observation observation;
PulsarSearch::DedispersionConf conf;
cl::Event event;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
conf.setLocalMem(args.getSwitch("-local"));
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment");
maxItems = args.getSwitchArgument< unsigned int >("-max_items");
maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll");
maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize");
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Allocate host memory
std::vector< float > * shifts = PulsarSearch::getShifts(observation);
observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >((shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))) * observation.getNrSamplesPerSecond()));
// Initialize OpenCL
cl::Context clContext;
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
// Allocate device memory
cl::Buffer shifts_d;
cl::Buffer dispersedData_d;
cl::Buffer dedispersedData_d;
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} catch ( cl::Error & err ) {
return -1;
}
// Find the parameters
std::vector< unsigned int > samplesPerBlock;
for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {
if ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {
samplesPerBlock.push_back(samples);
}
}
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {
if ( (observation.getNrDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrChannels nrSamples local unroll samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread GFLOP/s time stdDeviation COV" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {
conf.setNrSamplesPerBlock(*samples);
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
conf.setNrDMsPerBlock(*DMs);
if ( conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock() > maxThreads ) {
break;
} else if ( (conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock()) % threadUnit != 0 ) {
continue;
}
for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {
conf.setNrSamplesPerThread(samplesPerThread);
if ( (observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 && (observation.getNrSamplesPerPaddedSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 ) {
continue;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {
conf.setNrDMsPerThread(DMsPerThread);
if ( (observation.getNrDMs() % (conf.getNrDMsPerBlock() * conf.getNrDMsPerThread())) != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread()) + conf.getNrDMsPerThread() > maxItems ) {
break;
}
for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {
conf.setUnroll(unroll);
if ( (observation.getNrChannels() - 1) % conf.getUnroll() != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread() * conf.getUnroll()) > maxLoopBodySize ) {
break;
}
// Generate kernel
double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());
isa::utils::Timer timer;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getDedispersionOpenCL(conf, typeName, observation, *shifts);
if ( reInit ) {
delete clQueues;
clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} catch ( cl::Error & err ) {
return -1;
}
reInit = false;
}
try {
kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
delete code;
break;
}
delete code;
unsigned int nrThreads = 0;
if ( observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) == 0 ) {
nrThreads = observation.getNrSamplesPerSecond() / conf.getNrSamplesPerThread();
} else {
nrThreads = observation.getNrSamplesPerPaddedSecond() / conf.getNrSamplesPerThread();
}
cl::NDRange global(nrThreads, observation.getNrDMs() / conf.getNrDMsPerThread());
cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());
kernel->setArg(0, dispersedData_d);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, shifts_d);
try {
// Warm-up run
clQueues->at(clDeviceID)[0].finish();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
// Tuning runs
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution (";
std::cerr << conf.print() << "): ";
std::cerr << isa::utils::toString(err.err()) << "." << std::endl;
delete kernel;
if ( err.err() == -4 || err.err() == -61 ) {
return -1;
}
reInit = true;
break;
}
delete kernel;
std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " ";
std::cout << conf.print() << " ";
std::cout << std::setprecision(3);
std::cout << gflops / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " ";
std::cout << timer.getCoefficientOfVariation() << std::endl;
}
}
}
}
}
std::cout << std::endl;
return 0;
}
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {
try {
*shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);
*dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0);
*dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0);
clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()));
clQueue->finish();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl;
throw;
}
}
<commit_msg>Revert "Fixed a bug in computing the number of samples per dispersed second."<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
typedef float dataType;
std::string typeName("float");
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);
int main(int argc, char * argv[]) {
bool reInit = false;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreads = 0;
unsigned int maxRows = 0;
unsigned int maxColumns = 0;
unsigned int threadUnit = 0;
unsigned int threadIncrement = 0;
unsigned int maxItems = 0;
unsigned int maxUnroll = 0;
unsigned int maxLoopBodySize = 0;
AstroData::Observation observation;
PulsarSearch::DedispersionConf conf;
cl::Event event;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
conf.setLocalMem(args.getSwitch("-local"));
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment");
maxItems = args.getSwitchArgument< unsigned int >("-max_items");
maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll");
maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize");
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Allocate host memory
std::vector< float > * shifts = PulsarSearch::getShifts(observation);
observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));
// Initialize OpenCL
cl::Context clContext;
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
// Allocate device memory
cl::Buffer shifts_d;
cl::Buffer dispersedData_d;
cl::Buffer dedispersedData_d;
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} catch ( cl::Error & err ) {
return -1;
}
// Find the parameters
std::vector< unsigned int > samplesPerBlock;
for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {
if ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {
samplesPerBlock.push_back(samples);
}
}
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {
if ( (observation.getNrDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrChannels nrSamples local unroll samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread GFLOP/s time stdDeviation COV" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {
conf.setNrSamplesPerBlock(*samples);
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
conf.setNrDMsPerBlock(*DMs);
if ( conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock() > maxThreads ) {
break;
} else if ( (conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock()) % threadUnit != 0 ) {
continue;
}
for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {
conf.setNrSamplesPerThread(samplesPerThread);
if ( (observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 && (observation.getNrSamplesPerPaddedSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 ) {
continue;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {
conf.setNrDMsPerThread(DMsPerThread);
if ( (observation.getNrDMs() % (conf.getNrDMsPerBlock() * conf.getNrDMsPerThread())) != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread()) + conf.getNrDMsPerThread() > maxItems ) {
break;
}
for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {
conf.setUnroll(unroll);
if ( (observation.getNrChannels() - 1) % conf.getUnroll() != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread() * conf.getUnroll()) > maxLoopBodySize ) {
break;
}
// Generate kernel
double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());
isa::utils::Timer timer;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getDedispersionOpenCL(conf, typeName, observation, *shifts);
if ( reInit ) {
delete clQueues;
clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} catch ( cl::Error & err ) {
return -1;
}
reInit = false;
}
try {
kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
delete code;
break;
}
delete code;
unsigned int nrThreads = 0;
if ( observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) == 0 ) {
nrThreads = observation.getNrSamplesPerSecond() / conf.getNrSamplesPerThread();
} else {
nrThreads = observation.getNrSamplesPerPaddedSecond() / conf.getNrSamplesPerThread();
}
cl::NDRange global(nrThreads, observation.getNrDMs() / conf.getNrDMsPerThread());
cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());
kernel->setArg(0, dispersedData_d);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, shifts_d);
try {
// Warm-up run
clQueues->at(clDeviceID)[0].finish();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
// Tuning runs
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution (";
std::cerr << conf.print() << "): ";
std::cerr << isa::utils::toString(err.err()) << "." << std::endl;
delete kernel;
if ( err.err() == -4 || err.err() == -61 ) {
return -1;
}
reInit = true;
break;
}
delete kernel;
std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " ";
std::cout << conf.print() << " ";
std::cout << std::setprecision(3);
std::cout << gflops / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " ";
std::cout << timer.getCoefficientOfVariation() << std::endl;
}
}
}
}
}
std::cout << std::endl;
return 0;
}
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {
try {
*shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);
*dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0);
*dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0);
clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()));
clQueue->finish();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl;
throw;
}
}
<|endoftext|> |
<commit_before>#include "Plater/Plate2D.hpp"
// libslic3r includes
#include "Geometry.hpp"
#include "Point.hpp"
#include "Log.hpp"
#include "ClipperUtils.hpp"
// wx includes
#include <wx/colour.h>
#include <wx/dcbuffer.h>
namespace Slic3r { namespace GUI {
Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :
wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)
{
this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });
this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });
this->Bind(wxEVT_LEFT_DOWN, [=](wxMouseEvent &e) { this->mouse_down(e); });
this->Bind(wxEVT_LEFT_UP, [=](wxMouseEvent &e) { this->mouse_up(e); });
this->Bind(wxEVT_LEFT_DCLICK, [=](wxMouseEvent &e) { this->mouse_dclick(e); });
if (user_drawn_background) {
this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });
}
this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });
// Bind the varying mouse events
// Set the brushes
set_colors();
this->SetBackgroundStyle(wxBG_STYLE_PAINT);
}
void Plate2D::repaint(wxPaintEvent& e) {
// Need focus to catch keyboard events.
this->SetFocus();
auto dc {new wxAutoBufferedPaintDC(this)};
const auto& size {wxSize(this->GetSize().GetWidth(), this->GetSize().GetHeight())};
if (this->user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux/GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux/GTK.
const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};
const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};
dc->SetPen(pen_background);
dc->SetBrush(brush_background);
const auto& rect {this->GetUpdateRegion().GetBox()};
dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// Draw bed
{
dc->SetPen(this->print_center_pen);
dc->SetBrush(this->bed_brush);
auto tmp {scaled_points_to_pixel(this->bed_polygon, true)};
dc->DrawPolygon(this->bed_polygon.points.size(), tmp.data(), 0, 0);
}
// draw print center
{
if (this->objects.size() > 0 && settings->autocenter) {
const auto center = this->unscaled_point_to_pixel(this->print_center);
dc->SetPen(print_center_pen);
dc->DrawLine(center.x, 0, center.x, size.y);
dc->DrawLine(0, center.y, size.x, center.y);
dc->SetTextForeground(wxColor(0,0,0));
dc->SetFont(wxFont(10, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(wxString::Format("X = %.0f", this->print_center.x), wxRect(0,0, center.x*2, this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM);
dc->DrawRotatedText(wxString::Format("Y = %.0f", this->print_center.y), 0, center.y + 15, 90);
}
}
// draw text if plate is empty
if (this->objects.size() == 0) {
dc->SetTextForeground(settings->color->BED_OBJECTS());
dc->SetFont(wxFont(14, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(CANVAS_TEXT, wxRect(0,0, this->GetSize().GetWidth(), this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL);
} else {
// draw grid
dc->SetPen(grid_pen);
// Assumption: grid of lines is arranged
// as adjacent pairs of wxPoints
for (auto i = 0U; i < grid.size(); i+=2) {
dc->DrawLine(grid[i], grid[i+1]);
}
}
// Draw thumbnails
dc->SetPen(dark_pen);
this->clean_instance_thumbnails();
for (auto& obj : this->objects) {
auto model_object {this->model->objects.at(obj.identifier)};
if (obj.thumbnail.expolygons.size() == 0)
continue; // if there's no thumbnail move on
for (size_t instance_idx = 0U; instance_idx < model_object->instances.size(); instance_idx++) {
auto& instance {model_object->instances.at(instance_idx)};
if (obj.transformed_thumbnail.expolygons.size() == 0) continue;
auto thumbnail {obj.transformed_thumbnail}; // starts in unscaled model coords
thumbnail.translate(Point::new_scale(instance->offset));
obj.instance_thumbnails.emplace_back(thumbnail);
if (0) { // object is dragged
dc->SetBrush(dragged_brush);
} else if (0) {
dc->SetBrush(instance_brush);
} else if (0) {
dc->SetBrush(selected_brush);
} else {
dc->SetBrush(objects_brush);
}
// porting notes: perl here seems to be making a single-item array of the
// thumbnail set.
// no idea why. It doesn't look necessary, so skip the outer layer
// and draw the contained expolygons
for (const auto& points : obj.instance_thumbnails.back().expolygons) {
auto poly { this->scaled_points_to_pixel(Polygon(points), true) };
dc->DrawPolygon(poly.size(), poly.data(), 0, 0);
}
}
}
e.Skip();
}
void Plate2D::clean_instance_thumbnails() {
for (auto& obj : this->objects) {
obj.instance_thumbnails.clear();
}
}
void Plate2D::mouse_drag(wxMouseEvent& e) {
const auto pos {e.GetPosition()};
const auto& point {this->point_to_model_units(e.GetPosition())};
if (e.Dragging()) {
Slic3r::Log::info(LogChannel, L"Mouse dragging");
} else {
auto cursor = wxSTANDARD_CURSOR;
/*
if (find_first_of(this->objects.begin(), this->objects.end(); [=](const PlaterObject& o) { return o.contour->contains_point(point);} ) == this->object.end()) {
cursor = wxCursor(wxCURSOR_HAND);
}
*/
this->SetCursor(*cursor);
}
}
void Plate2D::mouse_down(wxMouseEvent& e) {
}
void Plate2D::mouse_up(wxMouseEvent& e) {
}
void Plate2D::mouse_dclick(wxMouseEvent& e) {
}
void Plate2D::set_colors() {
this->SetBackgroundColour(settings->color->BACKGROUND255());
this->objects_brush.SetColour(settings->color->BED_OBJECTS());
this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->instance_brush.SetColour(settings->color->BED_INSTANCE());
this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->selected_brush.SetColour(settings->color->BED_SELECTED());
this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->dragged_brush.SetColour(settings->color->BED_DRAGGED());
this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->bed_brush.SetColour(settings->color->BED_COLOR());
this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->transparent_brush.SetColour(wxColour(0,0,0));
this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
this->grid_pen.SetColour(settings->color->BED_GRID());
this->grid_pen.SetWidth(1);
this->grid_pen.SetStyle(wxPENSTYLE_SOLID);
this->print_center_pen.SetColour(settings->color->BED_CENTER());
this->print_center_pen.SetWidth(1);
this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);
this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());
this->clearance_pen.SetWidth(1);
this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);
this->skirt_pen.SetColour(settings->color->BED_SKIRT());
this->skirt_pen.SetWidth(1);
this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);
this->dark_pen.SetColour(settings->color->BED_DARK());
this->dark_pen.SetWidth(1);
this->dark_pen.SetStyle(wxPENSTYLE_SOLID);
}
void Plate2D::nudge_key(wxKeyEvent& e) {
const auto key = e.GetKeyCode();
switch( key ) {
case WXK_LEFT:
this->nudge(MoveDirection::Left);
case WXK_RIGHT:
this->nudge(MoveDirection::Right);
case WXK_DOWN:
this->nudge(MoveDirection::Down);
case WXK_UP:
this->nudge(MoveDirection::Up);
default:
break; // do nothing
}
}
void Plate2D::nudge(MoveDirection dir) {
if (this->selected_instance < this->objects.size()) {
auto i = 0U;
for (auto& obj : this->objects) {
if (obj.selected) {
if (obj.selected_instance != -1) {
}
}
i++;
}
}
if (selected_instance >= this->objects.size()) {
Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance.");
return; // Abort
}
}
void Plate2D::update_bed_size() {
const auto& canvas_size {this->GetSize()};
const auto& canvas_w {canvas_size.GetWidth()};
const auto& canvas_h {canvas_size.GetHeight()};
if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet.
this->bed_polygon = Slic3r::Polygon(scale(dynamic_cast<ConfigOptionPoints*>(config->optptr("bed_shape"))->values));
const auto& polygon = bed_polygon;
const auto& bb = bed_polygon.bounding_box();
const auto& size = bb.size();
this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y));
this->bed_origin = wxPoint(
canvas_w / 2.0 - (unscale(bb.max.x + bb.min.x)/2.0 * this->scaling_factor),
canvas_h - (canvas_h / 2.0 - (unscale(bb.max.y + bb.min.y)/2.0 * this->scaling_factor))
);
const auto& center = bb.center();
this->print_center = wxPoint(unscale(center.x), unscale(center.y));
// Cache bed contours and grid
{
const auto& step { scale_(10.0) }; // want a 10mm step for the lines
auto grid {Polylines()};
for (coord_t x = (bb.min.x - (bb.min.x % step) + step); x < bb.max.x; x += step) {
grid.push_back(Polyline());
grid.back().append(Point(x, bb.min.y));
grid.back().append(Point(x, bb.max.y));
};
for (coord_t y = (bb.min.y - (bb.min.y % step) + step); y < bb.max.y; y += step) {
grid.push_back(Polyline());
grid.back().append(Point(bb.min.x, y));
grid.back().append(Point(bb.max.x, y));
};
grid = intersection_pl(grid, polygon);
for (auto& i : grid) {
const auto& tmpline { this->scaled_points_to_pixel(i, 1) };
this->grid.insert(this->grid.end(), tmpline.begin(), tmpline.end());
}
}
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {
return this->scaled_points_to_pixel(Polyline(poly), unscale);
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool _unscale) {
std::vector<wxPoint> result;
for (const auto& pt : poly.points) {
const auto x {_unscale ? Slic3r::unscale(pt.x) : pt.x};
const auto y {_unscale ? Slic3r::unscale(pt.y) : pt.y};
result.push_back(wxPoint(x, y));
}
return result;
}
wxPoint Plate2D::unscaled_point_to_pixel(const wxPoint& in) {
const auto& canvas_height {this->GetSize().GetHeight()};
const auto& zero = this->bed_origin;
return wxPoint(in.x * this->scaling_factor + zero.x,
in.y * this->scaling_factor + (zero.y - canvas_height));
}
} } // Namespace Slic3r::GUI
<commit_msg>Get access to LOG_WSTRING.<commit_after>#include "Plater/Plate2D.hpp"
// libslic3r includes
#include "Geometry.hpp"
#include "Point.hpp"
#include "Log.hpp"
#include "ClipperUtils.hpp"
#include "misc_ui.hpp"
// wx includes
#include <wx/colour.h>
#include <wx/dcbuffer.h>
namespace Slic3r { namespace GUI {
Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :
wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)
{
this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });
this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });
this->Bind(wxEVT_LEFT_DOWN, [=](wxMouseEvent &e) { this->mouse_down(e); });
this->Bind(wxEVT_LEFT_UP, [=](wxMouseEvent &e) { this->mouse_up(e); });
this->Bind(wxEVT_LEFT_DCLICK, [=](wxMouseEvent &e) { this->mouse_dclick(e); });
if (user_drawn_background) {
this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });
}
this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });
// Bind the varying mouse events
// Set the brushes
set_colors();
this->SetBackgroundStyle(wxBG_STYLE_PAINT);
}
void Plate2D::repaint(wxPaintEvent& e) {
// Need focus to catch keyboard events.
this->SetFocus();
auto dc {new wxAutoBufferedPaintDC(this)};
const auto& size {wxSize(this->GetSize().GetWidth(), this->GetSize().GetHeight())};
if (this->user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux/GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux/GTK.
const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};
const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};
dc->SetPen(pen_background);
dc->SetBrush(brush_background);
const auto& rect {this->GetUpdateRegion().GetBox()};
dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// Draw bed
{
dc->SetPen(this->print_center_pen);
dc->SetBrush(this->bed_brush);
auto tmp {scaled_points_to_pixel(this->bed_polygon, true)};
dc->DrawPolygon(this->bed_polygon.points.size(), tmp.data(), 0, 0);
}
// draw print center
{
if (this->objects.size() > 0 && settings->autocenter) {
const auto center = this->unscaled_point_to_pixel(this->print_center);
dc->SetPen(print_center_pen);
dc->DrawLine(center.x, 0, center.x, size.y);
dc->DrawLine(0, center.y, size.x, center.y);
dc->SetTextForeground(wxColor(0,0,0));
dc->SetFont(wxFont(10, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(wxString::Format("X = %.0f", this->print_center.x), wxRect(0,0, center.x*2, this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM);
dc->DrawRotatedText(wxString::Format("Y = %.0f", this->print_center.y), 0, center.y + 15, 90);
}
}
// draw text if plate is empty
if (this->objects.size() == 0) {
dc->SetTextForeground(settings->color->BED_OBJECTS());
dc->SetFont(wxFont(14, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(CANVAS_TEXT, wxRect(0,0, this->GetSize().GetWidth(), this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL);
} else {
// draw grid
dc->SetPen(grid_pen);
// Assumption: grid of lines is arranged
// as adjacent pairs of wxPoints
for (auto i = 0U; i < grid.size(); i+=2) {
dc->DrawLine(grid[i], grid[i+1]);
}
}
// Draw thumbnails
dc->SetPen(dark_pen);
this->clean_instance_thumbnails();
for (auto& obj : this->objects) {
auto model_object {this->model->objects.at(obj.identifier)};
if (obj.thumbnail.expolygons.size() == 0)
continue; // if there's no thumbnail move on
for (size_t instance_idx = 0U; instance_idx < model_object->instances.size(); instance_idx++) {
auto& instance {model_object->instances.at(instance_idx)};
if (obj.transformed_thumbnail.expolygons.size() == 0) continue;
auto thumbnail {obj.transformed_thumbnail}; // starts in unscaled model coords
thumbnail.translate(Point::new_scale(instance->offset));
obj.instance_thumbnails.emplace_back(thumbnail);
if (0) { // object is dragged
dc->SetBrush(dragged_brush);
} else if (0) {
dc->SetBrush(instance_brush);
} else if (0) {
dc->SetBrush(selected_brush);
} else {
dc->SetBrush(objects_brush);
}
// porting notes: perl here seems to be making a single-item array of the
// thumbnail set.
// no idea why. It doesn't look necessary, so skip the outer layer
// and draw the contained expolygons
for (const auto& points : obj.instance_thumbnails.back().expolygons) {
auto poly { this->scaled_points_to_pixel(Polygon(points), true) };
dc->DrawPolygon(poly.size(), poly.data(), 0, 0);
}
}
}
e.Skip();
}
void Plate2D::clean_instance_thumbnails() {
for (auto& obj : this->objects) {
obj.instance_thumbnails.clear();
}
}
void Plate2D::mouse_drag(wxMouseEvent& e) {
const auto pos {e.GetPosition()};
const auto& point {this->point_to_model_units(e.GetPosition())};
if (e.Dragging()) {
Slic3r::Log::info(LogChannel, L"Mouse dragging");
} else {
auto cursor = wxSTANDARD_CURSOR;
/*
if (find_first_of(this->objects.begin(), this->objects.end(); [=](const PlaterObject& o) { return o.contour->contains_point(point);} ) == this->object.end()) {
cursor = wxCursor(wxCURSOR_HAND);
}
*/
this->SetCursor(*cursor);
}
}
void Plate2D::mouse_down(wxMouseEvent& e) {
}
void Plate2D::mouse_up(wxMouseEvent& e) {
}
void Plate2D::mouse_dclick(wxMouseEvent& e) {
}
void Plate2D::set_colors() {
this->SetBackgroundColour(settings->color->BACKGROUND255());
this->objects_brush.SetColour(settings->color->BED_OBJECTS());
this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->instance_brush.SetColour(settings->color->BED_INSTANCE());
this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->selected_brush.SetColour(settings->color->BED_SELECTED());
this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->dragged_brush.SetColour(settings->color->BED_DRAGGED());
this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->bed_brush.SetColour(settings->color->BED_COLOR());
this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->transparent_brush.SetColour(wxColour(0,0,0));
this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
this->grid_pen.SetColour(settings->color->BED_GRID());
this->grid_pen.SetWidth(1);
this->grid_pen.SetStyle(wxPENSTYLE_SOLID);
this->print_center_pen.SetColour(settings->color->BED_CENTER());
this->print_center_pen.SetWidth(1);
this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);
this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());
this->clearance_pen.SetWidth(1);
this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);
this->skirt_pen.SetColour(settings->color->BED_SKIRT());
this->skirt_pen.SetWidth(1);
this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);
this->dark_pen.SetColour(settings->color->BED_DARK());
this->dark_pen.SetWidth(1);
this->dark_pen.SetStyle(wxPENSTYLE_SOLID);
}
void Plate2D::nudge_key(wxKeyEvent& e) {
const auto key = e.GetKeyCode();
switch( key ) {
case WXK_LEFT:
this->nudge(MoveDirection::Left);
case WXK_RIGHT:
this->nudge(MoveDirection::Right);
case WXK_DOWN:
this->nudge(MoveDirection::Down);
case WXK_UP:
this->nudge(MoveDirection::Up);
default:
break; // do nothing
}
}
void Plate2D::nudge(MoveDirection dir) {
if (this->selected_instance < this->objects.size()) {
auto i = 0U;
for (auto& obj : this->objects) {
if (obj.selected) {
if (obj.selected_instance != -1) {
}
}
i++;
}
}
if (selected_instance >= this->objects.size()) {
Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance.");
return; // Abort
}
}
void Plate2D::update_bed_size() {
const auto& canvas_size {this->GetSize()};
const auto& canvas_w {canvas_size.GetWidth()};
const auto& canvas_h {canvas_size.GetHeight()};
if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet.
this->bed_polygon = Slic3r::Polygon(scale(dynamic_cast<ConfigOptionPoints*>(config->optptr("bed_shape"))->values));
const auto& polygon = bed_polygon;
const auto& bb = bed_polygon.bounding_box();
const auto& size = bb.size();
this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y));
this->bed_origin = wxPoint(
canvas_w / 2.0 - (unscale(bb.max.x + bb.min.x)/2.0 * this->scaling_factor),
canvas_h - (canvas_h / 2.0 - (unscale(bb.max.y + bb.min.y)/2.0 * this->scaling_factor))
);
const auto& center = bb.center();
this->print_center = wxPoint(unscale(center.x), unscale(center.y));
// Cache bed contours and grid
{
const auto& step { scale_(10.0) }; // want a 10mm step for the lines
auto grid {Polylines()};
for (coord_t x = (bb.min.x - (bb.min.x % step) + step); x < bb.max.x; x += step) {
grid.push_back(Polyline());
grid.back().append(Point(x, bb.min.y));
grid.back().append(Point(x, bb.max.y));
};
for (coord_t y = (bb.min.y - (bb.min.y % step) + step); y < bb.max.y; y += step) {
grid.push_back(Polyline());
grid.back().append(Point(bb.min.x, y));
grid.back().append(Point(bb.max.x, y));
};
grid = intersection_pl(grid, polygon);
for (auto& i : grid) {
const auto& tmpline { this->scaled_points_to_pixel(i, 1) };
this->grid.insert(this->grid.end(), tmpline.begin(), tmpline.end());
}
}
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {
return this->scaled_points_to_pixel(Polyline(poly), unscale);
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool _unscale) {
std::vector<wxPoint> result;
for (const auto& pt : poly.points) {
const auto x {_unscale ? Slic3r::unscale(pt.x) : pt.x};
const auto y {_unscale ? Slic3r::unscale(pt.y) : pt.y};
result.push_back(wxPoint(x, y));
}
return result;
}
wxPoint Plate2D::unscaled_point_to_pixel(const wxPoint& in) {
const auto& canvas_height {this->GetSize().GetHeight()};
const auto& zero = this->bed_origin;
return wxPoint(in.x * this->scaling_factor + zero.x,
in.y * this->scaling_factor + (zero.y - canvas_height));
}
} } // Namespace Slic3r::GUI
<|endoftext|> |
<commit_before>//
// LuaFunctionWrapper.cpp
// integral
//
// Copyright (C) 2016 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral 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.
//
// integral 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 integral. If not, see <http://www.gnu.org/licenses/>.
//
#include "LuaFunctionWrapper.hpp"
namespace integral {
namespace detail {
namespace exchanger {
const char * const Exchanger<LuaFunctionWrapper>::kMetatableName_ = "integral_LuaFunctionWrapperMetatableName";
LuaFunctionWrapper Exchanger<LuaFunctionWrapper>::get(lua_State *luaState, int index) {
if (lua_iscfunction(luaState, index) == 0) {
if (lua_getupvalue(luaState, index, 1) != nullptr) {
// stack: upvalue
const LuaFunctionWrapper *luaFunctionWrapperPointer = static_cast<LuaFunctionWrapper *>(lua_compatibility::testudata(luaState, -1, kMetatableName_));
if (luaFunctionWrapperPointer != nullptr) {
LuaFunctionWrapper luaFunctionWrapper = *luaFunctionWrapperPointer;
lua_pop(luaState, 1);
// stack:
return std::move(luaFunctionWrapper);
} else {
const ArgumentException argumentException = ArgumentException::createTypeErrorException(luaState, index, "LuaFunctionWrapper");
lua_pop(luaState, 1);
// stack:
throw argumentException;
}
} else {
throw ArgumentException::createTypeErrorException(luaState, index, "LuaFunctionWrapper (no upvalue)");
}
} else {
throw ArgumentException::createTypeErrorException(luaState, index, "lua_CFuntion");
}
}
}
}
}
<commit_msg>removed std::move that could prevent return value optimization<commit_after>//
// LuaFunctionWrapper.cpp
// integral
//
// Copyright (C) 2016 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral 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.
//
// integral 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 integral. If not, see <http://www.gnu.org/licenses/>.
//
#include "LuaFunctionWrapper.hpp"
namespace integral {
namespace detail {
namespace exchanger {
const char * const Exchanger<LuaFunctionWrapper>::kMetatableName_ = "integral_LuaFunctionWrapperMetatableName";
LuaFunctionWrapper Exchanger<LuaFunctionWrapper>::get(lua_State *luaState, int index) {
if (lua_iscfunction(luaState, index) == 0) {
if (lua_getupvalue(luaState, index, 1) != nullptr) {
// stack: upvalue
const LuaFunctionWrapper *luaFunctionWrapperPointer = static_cast<LuaFunctionWrapper *>(lua_compatibility::testudata(luaState, -1, kMetatableName_));
if (luaFunctionWrapperPointer != nullptr) {
LuaFunctionWrapper luaFunctionWrapper = *luaFunctionWrapperPointer;
lua_pop(luaState, 1);
// stack:
return luaFunctionWrapper;
} else {
const ArgumentException argumentException = ArgumentException::createTypeErrorException(luaState, index, "LuaFunctionWrapper");
lua_pop(luaState, 1);
// stack:
throw argumentException;
}
} else {
throw ArgumentException::createTypeErrorException(luaState, index, "LuaFunctionWrapper (no upvalue)");
}
} else {
throw ArgumentException::createTypeErrorException(luaState, index, "lua_CFuntion");
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* 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 "HLSMaker.h"
#include "Util/File.h"
#include "Util/uv_errno.h"
using namespace ZL::Util;
namespace ZL {
namespace MediaFile {
HLSMaker::HLSMaker(const string& strM3u8File,
uint32_t ui32BufSize,
uint32_t ui32Duration,
uint32_t ui32Num) {
if (ui32BufSize < 16 * 1024) {
ui32BufSize = 16 * 1024;
}
if(ui32Num < 1){
ui32Num = 1;
}
m_ui32BufSize = ui32BufSize;
m_ui64TsCnt = 0;
m_strM3u8File = strM3u8File;
m_ui32NumSegments = ui32Num;
m_ui32SegmentDuration = ui32Duration;
m_strOutputPrefix = strM3u8File.substr(0, strM3u8File.find_last_of('.'));
m_strFileName = m_strOutputPrefix.substr(m_strOutputPrefix.find_last_of('/') + 1);
m_ts.init(m_strOutputPrefix + "-0.ts", m_ui32BufSize);
}
HLSMaker::~HLSMaker() {
m_ts.clear();
string strDir = m_strOutputPrefix.substr(0,m_strOutputPrefix.find_last_of('/'));
File::delete_file(strDir.data());
}
bool HLSMaker::write_index_file(int iFirstSegment, unsigned int uiLastSegment, int iEnd) {
char acWriteBuf[1024];
std::shared_ptr<FILE> pM3u8File(File::createfile_file(m_strM3u8File.data(), "w"),[](FILE *fp){
fclose(fp);
});
if (!pM3u8File) {
WarnL << "Could not open temporary m3u8 index file (" << m_strM3u8File << "), no index file will be created";
return false;
}
if (iFirstSegment < 0) {
iFirstSegment = 0;
}
//最少1秒
int maxSegmentDuration = 1;
for (auto dur : m_iDurations) {
dur /=1000;
if(dur > maxSegmentDuration){
maxSegmentDuration = dur;
}
}
if (m_ui32NumSegments) {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTM3U\n"
"#EXT-X-VERSION:3\n"
"#EXT-X-TARGETDURATION:%u\n"
"#EXT-X-MEDIA-SEQUENCE:%u\n",
maxSegmentDuration,
iFirstSegment);
} else {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTM3U\n"
"#EXT-X-VERSION:3\n"
"#EXT-X-TARGETDURATION:%u\n",
maxSegmentDuration);
}
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write to m3u8 index file, will not continue writing to index file";
return false;
}
for (unsigned int i = iFirstSegment; i < uiLastSegment; i++) {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTINF:%.3f,\n%s-%u.ts\n",
m_iDurations[i-iFirstSegment]/1000.0,
m_strFileName.c_str(),
i);
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write to m3u8 index file, will not continue writing to index file";
return false;
}
}
if (iEnd) {
snprintf(acWriteBuf, sizeof(acWriteBuf), "#EXT-X-ENDLIST\n");
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write last file and endlist tag to m3u8 index file";
return false;
}
}
return true;
}
void HLSMaker::inputH264(void *data, uint32_t length, uint32_t timeStamp, int type) {
if(m_ui32LastStamp == 0){
m_ui32LastStamp = timeStamp;
}
int stampInc = timeStamp - m_ui32LastStamp;
switch (type) {
case 7: //SPS
if (stampInc >= m_ui32SegmentDuration * 1000) {
m_ui32LastStamp = timeStamp;
//关闭文件
m_ts.clear();
auto strTmpFileName = StrPrinter << m_strOutputPrefix << '-' << (++m_ui64TsCnt) << ".ts" << endl;
if (!m_ts.init(strTmpFileName, m_ui32BufSize)) {
//创建文件失败
return;
}
//记录切片时间
m_iDurations.push_back(stampInc);
if(removets()){
//删除老的时间戳
m_iDurations.pop_front();
}
write_index_file(m_ui64TsCnt - m_ui32NumSegments, m_ui64TsCnt, 0);
}
case 1: //P
//insert aud frame before p and SPS frame
m_ts.inputH264("\x0\x0\x0\x1\x9\xf0", 6, timeStamp * 90);
case 5: //IDR
case 8: //PPS
m_ts.inputH264((char *) data, length, timeStamp * 90);
break;
default:
break;
}
}
void HLSMaker::inputAAC(void *data, uint32_t length, uint32_t timeStamp) {
m_ts.inputAAC((char *) data, length, timeStamp * 90);
}
bool HLSMaker::removets() {
if (m_ui64TsCnt < m_ui32NumSegments + 2) {
return false;
}
File::delete_file((StrPrinter << m_strOutputPrefix << "-"
<< m_ui64TsCnt - m_ui32NumSegments - 2
<< ".ts" << endl).data());
return true;
}
} /* namespace MediaFile */
} /* namespace ZL */
<commit_msg>优化hls<commit_after>/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* 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 "HLSMaker.h"
#include "Util/File.h"
#include "Util/uv_errno.h"
using namespace ZL::Util;
namespace ZL {
namespace MediaFile {
HLSMaker::HLSMaker(const string& strM3u8File,
uint32_t ui32BufSize,
uint32_t ui32Duration,
uint32_t ui32Num) {
if (ui32BufSize < 16 * 1024) {
ui32BufSize = 16 * 1024;
}
if(ui32Num < 1){
ui32Num = 1;
}
m_ui32BufSize = ui32BufSize;
m_ui64TsCnt = 0;
m_strM3u8File = strM3u8File;
m_ui32NumSegments = ui32Num;
m_ui32SegmentDuration = ui32Duration;
m_strOutputPrefix = strM3u8File.substr(0, strM3u8File.find_last_of('.'));
m_strFileName = m_strOutputPrefix.substr(m_strOutputPrefix.find_last_of('/') + 1);
m_ts.init(m_strOutputPrefix + "-0.ts", m_ui32BufSize);
}
HLSMaker::~HLSMaker() {
m_ts.clear();
string strDir = m_strOutputPrefix.substr(0,m_strOutputPrefix.find_last_of('/'));
File::delete_file(strDir.data());
}
bool HLSMaker::write_index_file(int iFirstSegment, unsigned int uiLastSegment, int iEnd) {
char acWriteBuf[1024];
std::shared_ptr<FILE> pM3u8File(File::createfile_file(m_strM3u8File.data(), "w"),[](FILE *fp){
if(fp){
fflush(fp);
fclose(fp);
}
});
if (!pM3u8File) {
WarnL << "Could not open temporary m3u8 index file (" << m_strM3u8File << "), no index file will be created";
return false;
}
if (iFirstSegment < 0) {
iFirstSegment = 0;
}
//最少1秒
int maxSegmentDuration = 0;
for (auto dur : m_iDurations) {
dur /=1000;
if(dur > maxSegmentDuration){
maxSegmentDuration = dur;
}
}
if (m_ui32NumSegments) {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTM3U\n"
"#EXT-X-VERSION:3\n"
"#EXT-X-ALLOW-CACHE:NO\n"
"#EXT-X-TARGETDURATION:%u\n"
"#EXT-X-MEDIA-SEQUENCE:%u\n",
maxSegmentDuration + 1,
iFirstSegment);
} else {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTM3U\n"
"#EXT-X-VERSION:3\n"
"#EXT-X-ALLOW-CACHE:NO\n"
"#EXT-X-TARGETDURATION:%u\n",
maxSegmentDuration);
}
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write to m3u8 index file, will not continue writing to index file";
return false;
}
for (unsigned int i = iFirstSegment; i < uiLastSegment; i++) {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTINF:%.3f,\n%s-%u.ts\n",
m_iDurations[i-iFirstSegment]/1000.0,
m_strFileName.c_str(),
i);
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write to m3u8 index file, will not continue writing to index file";
return false;
}
}
if (iEnd) {
snprintf(acWriteBuf, sizeof(acWriteBuf), "#EXT-X-ENDLIST\n");
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write last file and endlist tag to m3u8 index file";
return false;
}
}
return true;
}
void HLSMaker::inputH264(void *data, uint32_t length, uint32_t timeStamp, int type) {
if(m_ui32LastStamp == 0){
m_ui32LastStamp = timeStamp;
}
int stampInc = timeStamp - m_ui32LastStamp;
switch (type) {
case 7: //SPS
if (stampInc >= m_ui32SegmentDuration * 1000) {
m_ui32LastStamp = timeStamp;
//关闭文件
m_ts.clear();
auto strTmpFileName = StrPrinter << m_strOutputPrefix << '-' << (++m_ui64TsCnt) << ".ts" << endl;
if (!m_ts.init(strTmpFileName, m_ui32BufSize)) {
//创建文件失败
return;
}
//记录切片时间
m_iDurations.push_back(stampInc);
if(removets()){
//删除老的时间戳
m_iDurations.pop_front();
}
write_index_file(m_ui64TsCnt - m_ui32NumSegments, m_ui64TsCnt, 0);
}
case 1: //P
//insert aud frame before p and SPS frame
m_ts.inputH264("\x0\x0\x0\x1\x9\xf0", 6, timeStamp * 90);
case 5: //IDR
case 8: //PPS
m_ts.inputH264((char *) data, length, timeStamp * 90);
break;
default:
break;
}
}
void HLSMaker::inputAAC(void *data, uint32_t length, uint32_t timeStamp) {
m_ts.inputAAC((char *) data, length, timeStamp * 90);
}
bool HLSMaker::removets() {
if (m_ui64TsCnt < m_ui32NumSegments + 2) {
return false;
}
File::delete_file((StrPrinter << m_strOutputPrefix << "-"
<< m_ui64TsCnt - m_ui32NumSegments - 2
<< ".ts" << endl).data());
return true;
}
} /* namespace MediaFile */
} /* namespace ZL */
<|endoftext|> |
<commit_before>/** \file TranslationUtil.cc
* \brief Implementation of the DbConnection class.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016-2020 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 "TranslationUtil.h"
#include <map>
#include "Compiler.h"
#include "File.h"
#include "StringUtil.h"
#include "util.h"
namespace TranslationUtil {
std::string GetId(DbConnection * const connection, const std::string &german_text) {
const std::string SELECT_EXISTING("SELECT id FROM translations WHERE text=\""
+ connection->escapeString(german_text) + "\" AND language_code=\"deu\"");
if (not connection->query(SELECT_EXISTING))
LOG_ERROR("SELECT failed: " + SELECT_EXISTING + " (" + connection->getLastErrorMessage() + ")");
DbResultSet id_result_set(connection->getLastResultSet());
std::string id;
if (not id_result_set.empty())
return id_result_set.getNextRow()["id"];
else { // We don't have any entries for this German term yet.
const std::string SELECT_MAX_ID("SELECT MAX(id) FROM translations");
if (not connection->query(SELECT_MAX_ID))
logger->error("in TranslationUtil::GetId: SELECT failed: " + SELECT_MAX_ID + " ("
+ connection->getLastErrorMessage() + ")");
DbResultSet max_id_result_set(connection->getLastResultSet());
if (max_id_result_set.empty())
return "1";
const std::string max_id(max_id_result_set.getNextRow()["MAX(id)"]); // Apparently SQL NULL can be returned
// which leads to an empty string here.
return std::to_string(max_id.empty() ? 1 : StringUtil::ToUnsigned(max_id) + 1);
}
}
const std::map<std::string, std::string> international_2letter_code_to_german_3or4letter_code{
{ "af", "afr" },
{ "ar", "ara" },
{ "da", "dan" },
{ "de", "deu" },
{ "el", "gre" },
{ "en", "eng" },
{ "es", "spa" },
{ "fr", "fra" },
{ "it", "ita" },
{ "ms", "may" },
{ "nl", "nld" },
{ "pt", "por" },
{ "ro", "rum" },
{ "ru", "rus" },
{ "sr", "srp" },
{ "tr", "tur" },
};
std::string MapInternational2LetterCodeToGerman3Or4LetterCode(const std::string &international_2letter_code) {
const auto _2letter_and_3letter_codes(
international_2letter_code_to_german_3or4letter_code.find(international_2letter_code));
if (unlikely(_2letter_and_3letter_codes == international_2letter_code_to_german_3or4letter_code.cend()))
logger->error("in TranslationUtil::MapInternational2LetterCodeToGerman3LetterCode: unknown international "
"2-letter code \"" + international_2letter_code + "\"!");
return _2letter_and_3letter_codes->second;
}
bool IsValidInternational2LetterCode(const std::string &international_2letter_code_candidate) {
if (international_2letter_code_candidate.length() != 2)
return false;
for (const auto &_2letter_and_3letter_codes : international_2letter_code_to_german_3or4letter_code) {
if (_2letter_and_3letter_codes.first == international_2letter_code_candidate)
return true;
}
return false;
}
std::string MapGerman3Or4LetterCodeToInternational2LetterCode(const std::string &german_3or4letter_code) {
for (const auto &_2letter_and_3letter_codes : international_2letter_code_to_german_3or4letter_code) {
if (_2letter_and_3letter_codes.second == german_3or4letter_code)
return _2letter_and_3letter_codes.first;
}
LOG_ERROR("unknown German 3-letter code \"" + german_3or4letter_code + "\"!");
}
bool IsValidGerman3Or4LetterCode(const std::string &german_3or4letter_code_candidate) {
if (german_3or4letter_code_candidate.length() != 3 and german_3or4letter_code_candidate.length() != 4)
return false;
for (const auto &_2letter_and_3letter_codes : international_2letter_code_to_german_3or4letter_code) {
if (_2letter_and_3letter_codes.second == german_3or4letter_code_candidate)
return true;
}
return false;
}
void ReadIniFile(
const std::string &ini_filename,
std::unordered_map<std::string, std::pair<unsigned, std::string>> * const token_to_line_no_and_other_map)
{
File input(ini_filename, "r");
if (not input)
throw std::runtime_error("can't open \"" + ini_filename + "\" for reading!");
unsigned line_no(0);
while (not input.eof()) {
++line_no;
std::string line;
if (input.getline(&line) == 0 or line.empty())
continue;
const std::string::size_type first_equal_pos(line.find('='));
if (unlikely(first_equal_pos == std::string::npos))
throw std::runtime_error("missing equal-sign in \"" + ini_filename + "\" on line "
+ std::to_string(line_no) + "!");
const std::string key(StringUtil::Trim(line.substr(0, first_equal_pos)));
if (unlikely(key.empty()))
throw std::runtime_error("missing token or English key in \"" + ini_filename + "\" on line "
+ std::to_string(line_no) + "!");
const std::string rest(StringUtil::Trim(StringUtil::Trim(line.substr(first_equal_pos + 1)), '"'));
if (unlikely(rest.empty()))
throw std::runtime_error("missing translation in \"" + ini_filename + "\" on line "
+ std::to_string(line_no) + "!");
(*token_to_line_no_and_other_map)[key] = std::make_pair(line_no, rest);
}
}
static std::map<std::string, std::string> german_to_3or4letter_english_codes {
{ "afr", "afr" },
{ "ara", "ara" },
{ "dan", "dan" },
{ "deu", "ger" },
{ "eng", "eng" },
{ "fra", "fre" },
{ "gre", "gre" },
{ "ita", "ita" },
{ "may", "msa" },
{ "nld", "dut" },
{ "por", "por" },
{ "rum", "ron" },
{ "rus", "rus" },
{ "spa", "spa" },
{ "srp", "srp" },
{ "tur", "tur" },
{ "hans", "hans" },
{ "hant", "hant" }
};
std::string MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(const std::string &german_code) {
const auto ger_and_eng_code(german_to_3or4letter_english_codes.find(german_code));
if (ger_and_eng_code == german_to_3or4letter_english_codes.cend())
return "???";
return ger_and_eng_code->second;
}
std::string MapFake3LetterEnglishLanguagesCodesToGermanLanguageCodes(const std::string &english_3or4letter_code) {
for (const auto &ger_and_eng_code : german_to_3or4letter_english_codes) {
if (ger_and_eng_code.second == english_3or4letter_code)
return ger_and_eng_code.first;
}
return "???";
}
bool IsValidFake3Or4LetterEnglishLanguagesCode(const std::string &english_3or4letter_code_candidate) {
if (english_3or4letter_code_candidate.length() != 3 and english_3or4letter_code_candidate.length() != 4)
return false;
for (const auto &german_and_english_codes: german_to_3or4letter_english_codes) {
if (german_and_english_codes.second == english_3or4letter_code_candidate)
return true;
}
return false;
}
} // namespace TranslationUtil
<commit_msg>TranslationUtil.cc: Swap values for msa+may<commit_after>/** \file TranslationUtil.cc
* \brief Implementation of the DbConnection class.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016-2020 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 "TranslationUtil.h"
#include <map>
#include "Compiler.h"
#include "File.h"
#include "StringUtil.h"
#include "util.h"
namespace TranslationUtil {
std::string GetId(DbConnection * const connection, const std::string &german_text) {
const std::string SELECT_EXISTING("SELECT id FROM translations WHERE text=\""
+ connection->escapeString(german_text) + "\" AND language_code=\"deu\"");
if (not connection->query(SELECT_EXISTING))
LOG_ERROR("SELECT failed: " + SELECT_EXISTING + " (" + connection->getLastErrorMessage() + ")");
DbResultSet id_result_set(connection->getLastResultSet());
std::string id;
if (not id_result_set.empty())
return id_result_set.getNextRow()["id"];
else { // We don't have any entries for this German term yet.
const std::string SELECT_MAX_ID("SELECT MAX(id) FROM translations");
if (not connection->query(SELECT_MAX_ID))
logger->error("in TranslationUtil::GetId: SELECT failed: " + SELECT_MAX_ID + " ("
+ connection->getLastErrorMessage() + ")");
DbResultSet max_id_result_set(connection->getLastResultSet());
if (max_id_result_set.empty())
return "1";
const std::string max_id(max_id_result_set.getNextRow()["MAX(id)"]); // Apparently SQL NULL can be returned
// which leads to an empty string here.
return std::to_string(max_id.empty() ? 1 : StringUtil::ToUnsigned(max_id) + 1);
}
}
const std::map<std::string, std::string> international_2letter_code_to_german_3or4letter_code{
{ "af", "afr" },
{ "ar", "ara" },
{ "da", "dan" },
{ "de", "deu" },
{ "el", "gre" },
{ "en", "eng" },
{ "es", "spa" },
{ "fr", "fra" },
{ "it", "ita" },
{ "ms", "may" },
{ "nl", "nld" },
{ "pt", "por" },
{ "ro", "rum" },
{ "ru", "rus" },
{ "sr", "srp" },
{ "tr", "tur" },
};
std::string MapInternational2LetterCodeToGerman3Or4LetterCode(const std::string &international_2letter_code) {
const auto _2letter_and_3letter_codes(
international_2letter_code_to_german_3or4letter_code.find(international_2letter_code));
if (unlikely(_2letter_and_3letter_codes == international_2letter_code_to_german_3or4letter_code.cend()))
logger->error("in TranslationUtil::MapInternational2LetterCodeToGerman3LetterCode: unknown international "
"2-letter code \"" + international_2letter_code + "\"!");
return _2letter_and_3letter_codes->second;
}
bool IsValidInternational2LetterCode(const std::string &international_2letter_code_candidate) {
if (international_2letter_code_candidate.length() != 2)
return false;
for (const auto &_2letter_and_3letter_codes : international_2letter_code_to_german_3or4letter_code) {
if (_2letter_and_3letter_codes.first == international_2letter_code_candidate)
return true;
}
return false;
}
std::string MapGerman3Or4LetterCodeToInternational2LetterCode(const std::string &german_3or4letter_code) {
for (const auto &_2letter_and_3letter_codes : international_2letter_code_to_german_3or4letter_code) {
if (_2letter_and_3letter_codes.second == german_3or4letter_code)
return _2letter_and_3letter_codes.first;
}
LOG_ERROR("unknown German 3-letter code \"" + german_3or4letter_code + "\"!");
}
bool IsValidGerman3Or4LetterCode(const std::string &german_3or4letter_code_candidate) {
if (german_3or4letter_code_candidate.length() != 3 and german_3or4letter_code_candidate.length() != 4)
return false;
for (const auto &_2letter_and_3letter_codes : international_2letter_code_to_german_3or4letter_code) {
if (_2letter_and_3letter_codes.second == german_3or4letter_code_candidate)
return true;
}
return false;
}
void ReadIniFile(
const std::string &ini_filename,
std::unordered_map<std::string, std::pair<unsigned, std::string>> * const token_to_line_no_and_other_map)
{
File input(ini_filename, "r");
if (not input)
throw std::runtime_error("can't open \"" + ini_filename + "\" for reading!");
unsigned line_no(0);
while (not input.eof()) {
++line_no;
std::string line;
if (input.getline(&line) == 0 or line.empty())
continue;
const std::string::size_type first_equal_pos(line.find('='));
if (unlikely(first_equal_pos == std::string::npos))
throw std::runtime_error("missing equal-sign in \"" + ini_filename + "\" on line "
+ std::to_string(line_no) + "!");
const std::string key(StringUtil::Trim(line.substr(0, first_equal_pos)));
if (unlikely(key.empty()))
throw std::runtime_error("missing token or English key in \"" + ini_filename + "\" on line "
+ std::to_string(line_no) + "!");
const std::string rest(StringUtil::Trim(StringUtil::Trim(line.substr(first_equal_pos + 1)), '"'));
if (unlikely(rest.empty()))
throw std::runtime_error("missing translation in \"" + ini_filename + "\" on line "
+ std::to_string(line_no) + "!");
(*token_to_line_no_and_other_map)[key] = std::make_pair(line_no, rest);
}
}
static std::map<std::string, std::string> german_to_3or4letter_english_codes {
{ "afr", "afr" },
{ "ara", "ara" },
{ "dan", "dan" },
{ "deu", "ger" },
{ "eng", "eng" },
{ "fra", "fre" },
{ "gre", "gre" },
{ "ita", "ita" },
{ "msa", "may" },
{ "nld", "dut" },
{ "por", "por" },
{ "rum", "ron" },
{ "rus", "rus" },
{ "spa", "spa" },
{ "srp", "srp" },
{ "tur", "tur" },
{ "hans", "hans" },
{ "hant", "hant" }
};
std::string MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(const std::string &german_code) {
const auto ger_and_eng_code(german_to_3or4letter_english_codes.find(german_code));
if (ger_and_eng_code == german_to_3or4letter_english_codes.cend())
return "???";
return ger_and_eng_code->second;
}
std::string MapFake3LetterEnglishLanguagesCodesToGermanLanguageCodes(const std::string &english_3or4letter_code) {
for (const auto &ger_and_eng_code : german_to_3or4letter_english_codes) {
if (ger_and_eng_code.second == english_3or4letter_code)
return ger_and_eng_code.first;
}
return "???";
}
bool IsValidFake3Or4LetterEnglishLanguagesCode(const std::string &english_3or4letter_code_candidate) {
if (english_3or4letter_code_candidate.length() != 3 and english_3or4letter_code_candidate.length() != 4)
return false;
for (const auto &german_and_english_codes: german_to_3or4letter_english_codes) {
if (german_and_english_codes.second == english_3or4letter_code_candidate)
return true;
}
return false;
}
} // namespace TranslationUtil
<|endoftext|> |
<commit_before>#include "session.h"
#include <iostream>
#include <QtCore/QProcess>
#include <QtCore/QFile>
#include <QTcpSocket>
#include "PJobFileError.h"
#include "dataconnectionthread.h"
#include <QtCore/QDateTime>
#include <QtServiceBase>
#include <QHostAddress>
#include "pjobrunnerservice.h"
#include <QtNetwork/QHostInfo>
Session::Session(QTcpSocket* socket) : m_pjob_file(0), m_script_engine(0), m_wants_shutdown(false), m_socket(socket), m_data_to_send(0), m_data_receive_connection(0), m_data_push_connection(0), m_has_turn(false), m_has_running_process(false)
{
QDir temp = QDir::temp();
QString random = QDateTime::currentDateTime().toString("yyyyMMdd_hhmm_ss_zzz");;
while(temp.exists(random)) random.append("_");
temp.mkdir(random);
temp.cd(random);
m_temp_dir = temp.absolutePath();
if(m_socket) QtServiceBase::instance()->logMessage(QString("Opening new session for peer %1 over port %2 with temporary directory %3.").arg(socket->peerAddress().toString()).arg(socket->localPort()).arg(m_temp_dir));
connect(&m_turn_timeout, SIGNAL(timeout()), this, SLOT(turn_timeout()));
}
Session::~Session(){
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
if(service){
TicketDispatcher* ticket_dispatcher = service->ticket_dispatcher();
if(ticket_dispatcher) ticket_dispatcher->remove_session(this);
}
delete m_script_engine;
delete m_pjob_file;
delete m_data_receive_connection;
}
Session& Session::global_instance(){
static Session c;
return c;
}
ScriptEngine& Session::script_engine(){
if(m_script_engine == 0) m_script_engine = new ScriptEngine(this);
return *m_script_engine;
}
bool Session::wants_shutdown(){
return m_wants_shutdown;
}
QString Session::hello(){
return QString("This is %1 (%3) version %2 running on %4 (%5).\nNice to meet you.").arg(QCoreApplication::applicationName()).arg(QCoreApplication::applicationVersion()).arg(PJobRunnerService::instance()->serviceDescription()).arg(QHostInfo::localHostName()).arg(platform());
}
QString Session::platform(){
#ifdef Q_OS_WIN32
return "Windows";
#endif
#ifdef Q_OS_MAC
return "MacOSX";
#endif
#ifdef Q_OS_UNIX
return "Unix";
#endif
}
void Session::give_turn(){
m_has_turn = true;
output("It's your turn now! Go!");
m_turn_timeout.start(6000);
}
void Session::finish_turn(){
output("Your turn has ended.");
m_has_turn = false;
dynamic_cast<PJobRunnerService*>(QtServiceBase::instance())->ticket_dispatcher()->finished_turn(this);
}
void Session::turn_timeout(){
m_turn_timeout.stop();
if(!m_has_running_process && m_has_turn) finish_turn();
}
QHostAddress Session::peer(){
return m_socket->peerAddress();
}
void Session::open_local_pjob_file(QString filename){
if(m_pjob_file) delete m_pjob_file;
try{
m_pjob_file = new PJobFile(filename);
}catch(PJobFileError &e){
m_pjob_file = 0;
output(e.msg());
return;
}
output(QString("File %1 opened!").arg(filename));
QtServiceBase::instance()->logMessage(QString("Opened local pjob file %1 for peer %2.").arg(filename).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
m_application = m_pjob_file->defaultApplication();
foreach(PJobFileParameterDefinition d, m_pjob_file->parameterDefinitions()){
m_parameters[d.name()] = d.defaultValue();
}
}
quint32 Session::prepare_push_connection(){
if(m_data_receive_connection) delete m_data_receive_connection;
m_received_data.clear();
m_data_receive_connection = new DataReceiveConnection(m_received_data,this);
quint32 port = m_data_receive_connection->open_data_port();
m_data_receive_connection->start();
QtServiceBase::instance()->logMessage(QString("Prepared push connection on port %1 for peer %2.").arg(port).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
return port;
}
quint32 Session::prepare_pull_connection_for_results(){
if(!m_pjob_file){
output("Can't prepare pull connection! No PJob file openend!");
return 0;
}
if(m_data_push_connection) delete m_data_push_connection;
if(m_data_to_send) delete m_data_to_send;
m_data_to_send = m_pjob_file->get_result_files_raw();
m_data_push_connection = new DataPushConnection(*m_data_to_send,this);
quint32 port = m_data_push_connection->open_data_port();
m_data_push_connection->start();
QtServiceBase::instance()->logMessage(QString("Prepared pull connection on port %1 for peer %2.").arg(port).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
return port;
}
void Session::open_pjob_from_received_data(){
if(!m_data_receive_connection || !m_data_receive_connection->data_received()){
output("No data received! Can't open pjob file!");
return;
}
try{
m_pjob_file = new PJobFile(m_received_data);
}catch(PJobFileError &e){
m_pjob_file = 0;
output(e.msg());
}
m_application = m_pjob_file->defaultApplication();
foreach(PJobFileParameterDefinition d, m_pjob_file->parameterDefinitions()){
m_parameters[d.name()] = d.defaultValue();
}
output("pjob file opened from received data.");
QtServiceBase::instance()->logMessage(QString("Opened received pjob for peer %1.").arg(m_socket->peerAddress().toString()));
}
void Session::set_temp_dir(QString path){
m_temp_dir = path;
}
void Session::set_parameter(QString name, double value){
m_parameters[name] = value;
}
void Session::set_application(QString app_name){
m_application = app_name;
}
bool removeDir(const QString &dirName)
{
bool result = true;
QDir dir(dirName);
if (dir.exists(dirName)) {
Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
if (info.isDir()) {
result = removeDir(info.absoluteFilePath());
}
else {
result = QFile::remove(info.absoluteFilePath());
}
if (!result) {
return result;
}
}
result = dir.rmdir(dirName);
}
return result;
}
void Session::run_job(){
if(m_pjob_file == 0){
output("Can't run job! No pjob file opened!");
return;
}
if(!m_has_turn){
output("Can't run job! It's not your turn! Use enqueue() first and wait till it's your turn!");
return;
}
PJobFileApplication::Platform this_platform;
#ifdef Q_OS_WIN32
#ifdef _WIN64
this_platform = PJobFileApplication::Win64;
#else
this_platform = PJobFileApplication::Win32;
#endif
#endif
#ifdef Q_OS_MAC
this_platform = PJobFileApplication::MacOSX;
#endif
#ifdef Q_OS_UNIX
this_platform = PJobFileApplication::Linux;
#endif
PJobFileApplication app;
if(m_application == "auto"){
QList<PJobFileApplication> apps = m_pjob_file->applications();
QStringList names;
foreach(PJobFileApplication current_app, apps){
names.append(current_app.name);
}
names.sort();
foreach(QString name, names){
PJobFileApplication current_app = m_pjob_file->applicationByName(name);
if(current_app.platform == this_platform){
app = current_app;
break;
}
}
}else{
app = m_pjob_file->applicationByName(m_application);
}
#ifdef Q_OS_WIN32
if(app.platform != PJobFileApplication::Win32 && app.platform != PJobFileApplication::Win64){
output(QString("Can't run %1. No Application build for Windows!").arg(app.name));
return;
}
#endif
#ifdef Q_OS_MAC
if(app.platform != PJobFileApplication::MacOSX){
output(QString("Can't run %1. No Application build for MacOSX!").arg(app.name));
return;
}
#endif
#ifdef Q_OS_UNIX
if(app.platform != PJobFileApplication::Linux){
output(QString("Can't run %1. No Application build for Unix-like Systems!").arg(app.name));
return;
}
#endif
m_has_running_process = true;
QtServiceBase::instance()->logMessage(QString("Running job for peer %1 in temp dir %2.").arg(m_socket->peerAddress().toString()).arg(m_temp_dir));
QString temp_dir = QFileInfo(m_temp_dir).absoluteFilePath();
output(QString("Clearing temporary directory %1").arg(temp_dir));
removeDir(temp_dir);
QString resources_directory = QString("%1/Resources/").arg(temp_dir);
m_pjob_file->export_application(app.name, temp_dir);
m_pjob_file->export_resources(temp_dir);
QString executable = temp_dir + "/" + app.name + "/" + app.executable;
QFile::setPermissions(executable, QFile::ExeUser);
QProcess process;
process.setWorkingDirectory(resources_directory);
output(QString("Starting process: %1").arg(executable));
output(QString("With arguments:"));
foreach(QString arg, create_commandline_arguments_for_app(app)){
output(arg);
}
process.start(executable, create_commandline_arguments_for_app(app));
process.waitForStarted(-1);
output("-------------------");
output("Process std output:");
output("-------------------");
do{
output(process.readAllStandardOutput());
}while(!process.waitForFinished(100));
switch(process.exitStatus()){
case QProcess::NormalExit:
output("Process exited normally.");
m_pjob_file->import_run_directory(resources_directory);
output("Created files imported into run directory.");
break;
case QProcess::CrashExit:
output("Process crashed!");
switch(process.error()){
case QProcess::FailedToStart:
output("Process failed to start!");
break;
case QProcess::Crashed:
output("Process crashed some time after starting successfully!");
break;
default:
break;
}
output("---------------------");
output("Process error output:");
output("---------------------");
output(process.readAllStandardError());
}
m_pjob_file->save();
m_has_running_process = false;
finish_turn();
}
QStringList Session::create_commandline_arguments_for_app(const PJobFileApplication& app){
QStringList params;
QMapIterator<QString, double> it(m_parameters);
while(it.hasNext()){
it.next();
QString arguments = app.parameter_pattern;
arguments.replace(QString("<param>"), it.key());
arguments.replace(QString("<value>"), QString::number(it.value()));
params.append(arguments);
}
QStringList result = app.arguments.split(" ");
int params_index = result.indexOf("<parameters>");
result.removeAt(params_index);
while(!params.empty())
result.insert(params_index, params.takeLast());
return result;
}
void Session::exit(){
m_wants_shutdown = true;
}
QStringList Session::run_directories(){
return m_pjob_file->runDirectoryEntries();
}
void Session::output(const QString& msg){
if(m_socket){
m_socket->write((msg + "\n").toAscii());
m_socket->flush();
}
else std::cout << msg.toStdString() << std::endl;
}
const QByteArray& Session::received_data(){
return m_received_data;
}
void Session::write_received_data_to_file(QString path){
QFile file(path);
if(!file.open(QIODevice::WriteOnly)){
output(QString("Could not open %1 for writing!"));
return;
}
file.write(m_received_data);
file.close();
QtServiceBase::instance()->logMessage(QString("Wrote received data to file %1 for peer %2.").arg(path).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
}
void Session::enqueue(){
if(m_has_turn){
output("It's already your turn! Did not enqueue.");
return;
}
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
if(service->ticket_dispatcher()->number_queue_entries_for_peer(peer()) < service->ticket_dispatcher()->max_process_count()){
if(service->ticket_dispatcher()->enqueue(this))
output("Successfully added to queue.");
else
output("Not added to queue! You are already waiting.");
}
else output(QString("Not added to queue! You already have %1 session(s) enqueued and that is the allowed maximum.").arg(service->ticket_dispatcher()->max_process_count()));
}
unsigned int Session::max_process_count(){
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
return service->ticket_dispatcher()->max_process_count();
}
unsigned int Session::process_count(){
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
return service->ticket_dispatcher()->running_processes();
}
<commit_msg>Bugfixes: PJobRunner: abort if process could not be started.<commit_after>#include "session.h"
#include <iostream>
#include <QtCore/QProcess>
#include <QtCore/QFile>
#include <QTcpSocket>
#include "PJobFileError.h"
#include "dataconnectionthread.h"
#include <QtCore/QDateTime>
#include <QtServiceBase>
#include <QHostAddress>
#include "pjobrunnerservice.h"
#include <QtNetwork/QHostInfo>
Session::Session(QTcpSocket* socket) : m_pjob_file(0), m_script_engine(0), m_wants_shutdown(false), m_socket(socket), m_data_to_send(0), m_data_receive_connection(0), m_data_push_connection(0), m_has_turn(false), m_has_running_process(false)
{
QDir temp = QDir::temp();
QString random = QDateTime::currentDateTime().toString("yyyyMMdd_hhmm_ss_zzz");;
while(temp.exists(random)) random.append("_");
temp.mkdir(random);
temp.cd(random);
m_temp_dir = temp.absolutePath();
if(m_socket) QtServiceBase::instance()->logMessage(QString("Opening new session for peer %1 over port %2 with temporary directory %3.").arg(socket->peerAddress().toString()).arg(socket->localPort()).arg(m_temp_dir));
connect(&m_turn_timeout, SIGNAL(timeout()), this, SLOT(turn_timeout()));
}
Session::~Session(){
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
if(service){
TicketDispatcher* ticket_dispatcher = service->ticket_dispatcher();
if(ticket_dispatcher) ticket_dispatcher->remove_session(this);
}
delete m_script_engine;
delete m_pjob_file;
delete m_data_receive_connection;
}
Session& Session::global_instance(){
static Session c;
return c;
}
ScriptEngine& Session::script_engine(){
if(m_script_engine == 0) m_script_engine = new ScriptEngine(this);
return *m_script_engine;
}
bool Session::wants_shutdown(){
return m_wants_shutdown;
}
QString Session::hello(){
return QString("This is %1 (%3) version %2 running on %4 (%5).\nNice to meet you.").arg(QCoreApplication::applicationName()).arg(QCoreApplication::applicationVersion()).arg(PJobRunnerService::instance()->serviceDescription()).arg(QHostInfo::localHostName()).arg(platform());
}
QString Session::platform(){
#ifdef Q_OS_WIN32
return "Windows";
#endif
#ifdef Q_OS_MAC
return "MacOSX";
#endif
#ifdef Q_OS_UNIX
return "Unix";
#endif
}
void Session::give_turn(){
m_has_turn = true;
output("It's your turn now! Go!");
m_turn_timeout.start(6000);
}
void Session::finish_turn(){
output("Your turn has ended.");
m_has_turn = false;
dynamic_cast<PJobRunnerService*>(QtServiceBase::instance())->ticket_dispatcher()->finished_turn(this);
}
void Session::turn_timeout(){
m_turn_timeout.stop();
if(!m_has_running_process && m_has_turn) finish_turn();
}
QHostAddress Session::peer(){
return m_socket->peerAddress();
}
void Session::open_local_pjob_file(QString filename){
if(m_pjob_file) delete m_pjob_file;
try{
m_pjob_file = new PJobFile(filename);
}catch(PJobFileError &e){
m_pjob_file = 0;
output(e.msg());
return;
}
output(QString("File %1 opened!").arg(filename));
QtServiceBase::instance()->logMessage(QString("Opened local pjob file %1 for peer %2.").arg(filename).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
m_application = m_pjob_file->defaultApplication();
foreach(PJobFileParameterDefinition d, m_pjob_file->parameterDefinitions()){
m_parameters[d.name()] = d.defaultValue();
}
}
quint32 Session::prepare_push_connection(){
if(m_data_receive_connection) delete m_data_receive_connection;
m_received_data.clear();
m_data_receive_connection = new DataReceiveConnection(m_received_data,this);
quint32 port = m_data_receive_connection->open_data_port();
m_data_receive_connection->start();
QtServiceBase::instance()->logMessage(QString("Prepared push connection on port %1 for peer %2.").arg(port).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
return port;
}
quint32 Session::prepare_pull_connection_for_results(){
if(!m_pjob_file){
output("Can't prepare pull connection! No PJob file openend!");
return 0;
}
if(m_data_push_connection) delete m_data_push_connection;
if(m_data_to_send) delete m_data_to_send;
m_data_to_send = m_pjob_file->get_result_files_raw();
m_data_push_connection = new DataPushConnection(*m_data_to_send,this);
quint32 port = m_data_push_connection->open_data_port();
m_data_push_connection->start();
QtServiceBase::instance()->logMessage(QString("Prepared pull connection on port %1 for peer %2.").arg(port).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
return port;
}
void Session::open_pjob_from_received_data(){
if(!m_data_receive_connection || !m_data_receive_connection->data_received()){
output("No data received! Can't open pjob file!");
return;
}
try{
m_pjob_file = new PJobFile(m_received_data);
}catch(PJobFileError &e){
m_pjob_file = 0;
output(e.msg());
}
m_application = m_pjob_file->defaultApplication();
foreach(PJobFileParameterDefinition d, m_pjob_file->parameterDefinitions()){
m_parameters[d.name()] = d.defaultValue();
}
output("pjob file opened from received data.");
QtServiceBase::instance()->logMessage(QString("Opened received pjob for peer %1.").arg(m_socket->peerAddress().toString()));
}
void Session::set_temp_dir(QString path){
m_temp_dir = path;
}
void Session::set_parameter(QString name, double value){
m_parameters[name] = value;
}
void Session::set_application(QString app_name){
m_application = app_name;
}
bool removeDir(const QString &dirName)
{
bool result = true;
QDir dir(dirName);
if (dir.exists(dirName)) {
Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
if (info.isDir()) {
result = removeDir(info.absoluteFilePath());
}
else {
result = QFile::remove(info.absoluteFilePath());
}
if (!result) {
return result;
}
}
result = dir.rmdir(dirName);
}
return result;
}
void Session::run_job(){
if(m_pjob_file == 0){
output("Can't run job! No pjob file opened!");
return;
}
if(!m_has_turn){
output("Can't run job! It's not your turn! Use enqueue() first and wait till it's your turn!");
return;
}
PJobFileApplication::Platform this_platform;
#ifdef Q_OS_WIN32
#ifdef _WIN64
this_platform = PJobFileApplication::Win64;
#else
this_platform = PJobFileApplication::Win32;
#endif
#endif
#ifdef Q_OS_MAC
this_platform = PJobFileApplication::MacOSX;
#endif
#ifdef Q_OS_UNIX
this_platform = PJobFileApplication::Linux;
#endif
PJobFileApplication app;
if(m_application == "auto"){
QList<PJobFileApplication> apps = m_pjob_file->applications();
QStringList names;
foreach(PJobFileApplication current_app, apps){
names.append(current_app.name);
}
names.sort();
foreach(QString name, names){
PJobFileApplication current_app = m_pjob_file->applicationByName(name);
if(current_app.platform == this_platform){
app = current_app;
break;
}
}
}else{
app = m_pjob_file->applicationByName(m_application);
}
#ifdef Q_OS_WIN32
if(app.platform != PJobFileApplication::Win32 && app.platform != PJobFileApplication::Win64){
output(QString("Can't run %1. No Application build for Windows!").arg(app.name));
return;
}
#endif
#ifdef Q_OS_MAC
if(app.platform != PJobFileApplication::MacOSX){
output(QString("Can't run %1. No Application build for MacOSX!").arg(app.name));
return;
}
#endif
#ifdef Q_OS_UNIX
if(app.platform != PJobFileApplication::Linux){
output(QString("Can't run %1. No Application build for Unix-like Systems!").arg(app.name));
return;
}
#endif
m_has_running_process = true;
QtServiceBase::instance()->logMessage(QString("Running job for peer %1 in temp dir %2.").arg(m_socket->peerAddress().toString()).arg(m_temp_dir));
QString temp_dir = QFileInfo(m_temp_dir).absoluteFilePath();
output(QString("Clearing temporary directory %1").arg(temp_dir));
removeDir(temp_dir);
QString resources_directory = QString("%1/Resources/").arg(temp_dir);
m_pjob_file->export_application(app.name, temp_dir);
m_pjob_file->export_resources(temp_dir);
QString executable = temp_dir + "/" + app.name + "/" + app.executable;
QFile::setPermissions(executable, QFile::ExeUser);
QProcess process;
process.setWorkingDirectory(resources_directory);
output(QString("Starting process: %1").arg(executable));
output(QString("With arguments:"));
foreach(QString arg, create_commandline_arguments_for_app(app)){
output(arg);
}
process.start(executable, create_commandline_arguments_for_app(app));
if(process.waitForStarted(-1)){
output("-------------------");
output("Process std output:");
output("-------------------");
do{
output(process.readAllStandardOutput());
}while(!process.waitForFinished(100) && process.isOpen());
switch(process.exitStatus()){
case QProcess::NormalExit:
output("Process exited normally.");
m_pjob_file->import_run_directory(resources_directory);
output("Created files imported into run directory.");
break;
case QProcess::CrashExit:
output("Process crashed!");
switch(process.error()){
case QProcess::FailedToStart:
output("Process failed to start!");
break;
case QProcess::Crashed:
output("Process crashed some time after starting successfully!");
break;
default:
break;
}
output("---------------------");
output("Process error output:");
output("---------------------");
output(process.readAllStandardError());
}
m_pjob_file->save();
}else{
output("-----------------------------");
output("ERORR!");
output("Process could not be started!");
output("Problem within pjob file?");
output("-----------------------------");
}
m_has_running_process = false;
finish_turn();
}
QStringList Session::create_commandline_arguments_for_app(const PJobFileApplication& app){
QStringList params;
QMapIterator<QString, double> it(m_parameters);
while(it.hasNext()){
it.next();
QString arguments = app.parameter_pattern;
arguments.replace(QString("<param>"), it.key());
arguments.replace(QString("<value>"), QString::number(it.value()));
params.append(arguments);
}
QStringList result = app.arguments.split(" ");
int params_index = result.indexOf("<parameters>");
result.removeAt(params_index);
while(!params.empty())
result.insert(params_index, params.takeLast());
return result;
}
void Session::exit(){
m_wants_shutdown = true;
}
QStringList Session::run_directories(){
return m_pjob_file->runDirectoryEntries();
}
void Session::output(const QString& msg){
if(m_socket && m_socket->state() == QTcpSocket::ConnectedState){
m_socket->write((msg + "\n").toAscii());
m_socket->flush();
}
}
const QByteArray& Session::received_data(){
return m_received_data;
}
void Session::write_received_data_to_file(QString path){
QFile file(path);
if(!file.open(QIODevice::WriteOnly)){
output(QString("Could not open %1 for writing!"));
return;
}
file.write(m_received_data);
file.close();
QtServiceBase::instance()->logMessage(QString("Wrote received data to file %1 for peer %2.").arg(path).arg(m_socket->peerAddress().toString()), QtServiceBase::Information);
}
void Session::enqueue(){
if(m_has_turn){
output("It's already your turn! Did not enqueue.");
return;
}
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
if(service->ticket_dispatcher()->number_queue_entries_for_peer(peer()) < service->ticket_dispatcher()->max_process_count()){
if(service->ticket_dispatcher()->enqueue(this))
output("Successfully added to queue.");
else
output("Not added to queue! You are already waiting.");
}
else output(QString("Not added to queue! You already have %1 session(s) enqueued and that is the allowed maximum.").arg(service->ticket_dispatcher()->max_process_count()));
}
unsigned int Session::max_process_count(){
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
return service->ticket_dispatcher()->max_process_count();
}
unsigned int Session::process_count(){
PJobRunnerService* service = dynamic_cast<PJobRunnerService*>(QtServiceBase::instance());
return service->ticket_dispatcher()->running_processes();
}
<|endoftext|> |
<commit_before>#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "media/lirc.h"
#ifndef __u32
#define __u32 uint32_t
#endif
#include "irpipe.h"
static const char* const help =
"Write data to irpipe kernel device, applying conversions\n"
"and ioctls.\n\n"
"Usage: irpipe [options] <file\n"
" irpipe --read [options] >file\n"
" irpipe --filter [options] <infile >outfile\n\n"
"Options:\n"
"\t -F --features=bitmask\tSet kernel device features set\n"
"\t -l --length=bits\tSet kernel device signal length\n"
"\t -d --device=driver\tSet kernel device, default /dev/irpipe0\n"
"\t -b --bin2text\t\tConvert binary data to text\n"
"\t -t --text2bin\t\tConvert text data to binary\n"
"\t -r --read\t\tSend data from kernel device to stdout\n"
"\t -f --filter\t\tSend data from stdin to stdout\n"
"\t -s --add-sync\t\tAdd long initial sync on converted output\n"
"\t -h --help\t\tDisplay this message\n"
"\t -v --version\t\tDisplay version\n";
static const struct option options[] = {
{ "features", required_argument, NULL, 'F' },
{ "length", required_argument, NULL, 'l' },
{ "bin2text", no_argument, NULL, 't' },
{ "text2bin", no_argument, NULL, 'b' },
{ "write", no_argument, NULL, 'w' },
{ "filter", no_argument, NULL, 'f' },
{ "add-sync", no_argument, NULL, 's' },
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
static enum {MODE_READ, MODE_WRITE, MODE_FILTER} opt_mode = MODE_WRITE;
static const char* opt_device = "/dev/irpipe0";
static unsigned long opt_features = LONG_MAX;
static int opt_length = -1;
static bool opt_totext = false;
static bool opt_tobin = false;
static bool opt_add_sync = false;
static void parse_options(int argc, char* argv[])
{
int c;
long l;
const char* const optstring = "F:l:btrfd:hsv";
while (1) {
c = getopt_long(argc, argv, optstring, options, NULL);
if (c == -1)
break;
switch (c) {
case 'F':
l = strtol(optarg, NULL, 10);
if (l >= INT_MAX || l <= INT_MIN) {
fprintf(stderr, "Bad numeric: %s\n", optarg);
exit(1);
}
opt_features = (int)l;
case 'l':
l = strtol(optarg, NULL, 10);
if (l >= INT_MAX || l <= INT_MIN) {
fprintf(stderr, "Bad numeric: %s\n", optarg);
exit(1);
}
opt_length = l;
case 'b':
opt_tobin = true;
break;
case 's':
opt_add_sync = true;
break;
case 't':
opt_totext = true;
break;
case 'r':
opt_mode = MODE_READ;
break;
case 'f':
opt_mode = MODE_FILTER;
break;
case 'd':
opt_device = strdup(optarg);
break;
case 'h':
fputs(help, stdout);
exit(0);
case 'v':
fputs("irpipe " VERSION "\n", stdout);
exit(0);
default:
return;
}
}
}
/** Redirect newfd to the kernel irpipe device using mode. */
static void irpipe_setup(int newfd, const char* device, int mode)
{
int fd;
fd = open(device, mode);
if (fd == -1) {
perror("Cannot open kernel device");
exit(1);
}
fd = dup2(fd, newfd);
if (fd == -1) {
perror("Cannot dup2 kernel device");
exit(1);
}
}
/** Parse a pulse/space text line, return duration. */
static uint32_t process_line(const char* token1, const char* token2)
{
long value;
if (token1 == NULL || token2 == NULL)
return (uint32_t)-1;
value = strtol(token2, NULL, 10);
if (value == LONG_MIN || value >= PULSE_BIT || value == 0)
return (uint32_t)-1;
if (strcmp("pulse", token1) == 0)
value |= PULSE_BIT;
else if (strcmp("space", token1) != 0)
return (uint32_t)-1;
return (uint32_t)value;
}
/** Copy stdin to stdout, converting ascii data to binary. */
static void write_tobin(void)
{
char line[128];
char buff[128];
char* token1;
char* token2;
int32_t value;
if (opt_add_sync) {
value = 1000000;
if (write(1, &value, sizeof(uint32_t)) != sizeof(uint32_t))
perror("write() failed.");
}
while (fgets(line, sizeof(line), stdin) != NULL) {
strncpy(buff, line, sizeof(buff) - 1);
token1 = strtok(buff, "\n ");
token2 = strtok(NULL, "\n ");
value = process_line(token1, token2);
if (value == -1)
fprintf(stderr,
"Illegal data (ignored):\"%s\"\n", line);
else
if (write(1, &value, sizeof(uint32_t))
!= sizeof(uint32_t))
perror("write() failed");
}
}
/** Copy stdin to stdout, converting binary data to text. */
static void write_totext(void)
{
char buff[2048 * sizeof(int)];
int r;
int i;
const uint32_t* data;
if (opt_add_sync)
puts("space 1000000\n");
while ((r = read(0, buff, sizeof(buff))) > 0) {
for (i = 0; i < r; i += sizeof(int)) {
data = (uint32_t*)(&buff[i]);
printf("%s %u\n",
(*data & PULSE_BIT) ? "pulse" : "space",
*data & PULSE_MASK);
}
}
if (r == -1) {
perror("irpipe: Cannot read stdin");
exit(1);
}
}
/** Send verbatim copy of stdin to stdout. */
static void write_raw(void)
{
char buff[2048 * sizeof(int)];
int r;
int written;
while ((r = read(0, buff, sizeof(buff))) > 0) {
written = write(1, buff, r);
if (written != r) {
perror("irpipe: Cannot write in raw copy");
exit(1);
}
}
if (r == -1) {
perror("irpipe: Cannot read stdin");
exit(1);
}
}
static void run_ioctl(int cmd, unsigned long arg)
{
int fd = (opt_mode == MODE_WRITE) ? 1 : 0;
int r = ioctl(fd, cmd, arg);
if (r == -1) {
perror("Cannot run ioctl");
exit(1);
}
}
int main(int argc, char**argv)
{
parse_options(argc, argv);
if (opt_mode == MODE_WRITE)
irpipe_setup(1, opt_device, O_WRONLY);
else if (opt_mode == MODE_READ)
irpipe_setup(0, opt_device, O_RDONLY);
if (opt_features != LONG_MAX)
run_ioctl(LIRC_SET_FEATURES, opt_features);
if (opt_length != -1)
run_ioctl(LIRC_SET_LENGTH, opt_length);
if (opt_tobin)
write_tobin();
else if (opt_totext)
write_totext();
else
write_raw();
}
<commit_msg>tools: Teach irpipe to handle LIRCCODE drivers.<commit_after>#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "media/lirc.h"
#ifndef __u32
#define __u32 uint32_t
#endif
#include "irpipe.h"
static const char* const help =
"Write data to irpipe kernel device, applying conversions\n"
"and ioctls.\n\n"
"Usage: irpipe [options] <file\n"
" irpipe --read [options] >file\n"
" irpipe --filter [options] <infile >outfile\n\n"
"Options:\n"
"\t -F --features=bitmask\tSet kernel device features set\n"
"\t -l --length=bits\tSet kernel device signal length\n"
"\t -d --device=driver\tSet kernel device, default /dev/irpipe0\n"
"\t -b --bin2text\t\tConvert binary data to text\n"
"\t -t --text2bin\t\tConvert text data to binary\n"
"\t -r --read\t\tSend data from kernel device to stdout\n"
"\t -f --filter\t\tSend data from stdin to stdout\n"
"\t -B --bits=bits\t\tConvert bits wide LIRCCODE data\n"
"\t -s --add-sync\t\tAdd long initial sync on converted output\n"
"\t -h --help\t\tDisplay this message\n"
"\t -v --version\t\tDisplay version\n";
static const struct option options[] = {
{ "features", required_argument, NULL, 'F' },
{ "length", required_argument, NULL, 'l' },
{ "bin2text", no_argument, NULL, 't' },
{ "text2bin", no_argument, NULL, 'b' },
{ "bits", required_argument, NULL, 'B' },
{ "write", no_argument, NULL, 'w' },
{ "filter", no_argument, NULL, 'f' },
{ "add-sync", no_argument, NULL, 's' },
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
static enum {MODE_READ, MODE_WRITE, MODE_FILTER} opt_mode = MODE_WRITE;
static const char* opt_device = "/dev/irpipe0";
static unsigned long opt_features = LONG_MAX;
static int opt_length = -1;
static bool opt_totext = false;
static bool opt_tobin = false;
static bool opt_add_sync = false;
static int opt_bits = 0;
static void parse_options(int argc, char* argv[])
{
int c;
long l;
const char* const optstring = "F:l:bB:trfd:hsv";
while (1) {
c = getopt_long(argc, argv, optstring, options, NULL);
if (c == -1)
break;
switch (c) {
case 'F':
l = strtol(optarg, NULL, 10);
if (l >= INT_MAX || l <= INT_MIN) {
fprintf(stderr, "Bad numeric: %s\n", optarg);
exit(1);
}
opt_features = (int)l;
case 'l':
l = strtol(optarg, NULL, 10);
if (l >= INT_MAX || l <= INT_MIN) {
fprintf(stderr, "Bad numeric: %s\n", optarg);
exit(1);
}
opt_length = l;
case 'B':
l = strtol(optarg, NULL, 10);
if (l >= INT_MAX || l <= INT_MIN) {
fprintf(stderr, "Bad numeric: %s\n", optarg);
exit(1);
}
opt_bits = l;
case 'b':
opt_tobin = true;
break;
case 's':
opt_add_sync = true;
break;
case 't':
opt_totext = true;
break;
case 'r':
opt_mode = MODE_READ;
break;
case 'f':
opt_mode = MODE_FILTER;
break;
case 'd':
opt_device = strdup(optarg);
break;
case 'h':
fputs(help, stdout);
exit(0);
case 'v':
fputs("irpipe " VERSION "\n", stdout);
exit(0);
default:
return;
}
}
}
/** Redirect newfd to the kernel irpipe device using mode. */
static void irpipe_setup(int newfd, const char* device, int mode)
{
int fd;
fd = open(device, mode);
if (fd == -1) {
perror("Cannot open kernel device");
exit(1);
}
fd = dup2(fd, newfd);
if (fd == -1) {
perror("Cannot dup2 kernel device");
exit(1);
}
}
/** Parse a pulse/space text line, return duration. */
static uint32_t process_line(const char* token1, const char* token2)
{
long value;
if (token1 == NULL || token2 == NULL)
return (uint32_t)-1;
value = strtol(token2, NULL, 10);
if (value == LONG_MIN || value >= PULSE_BIT || value == 0)
return (uint32_t)-1;
if (strcmp("pulse", token1) == 0)
value |= PULSE_BIT;
else if (strcmp("space", token1) == 0)
return (uint32_t)value;
else if (strcmp("code", token1) == 0)
return (uint32_t)value;
return (uint32_t)-1;
}
/** Copy stdin to stdout, converting ascii data to binary. */
static void write_tobin(void)
{
char line[128];
char buff[128];
char* token1;
char* token2;
int32_t value;
const int len = opt_bits == 0 ? sizeof(uint32_t) : opt_bits/8;
if (opt_add_sync) {
value = 1000000;
if (write(1, &value, sizeof(uint32_t)) != sizeof(uint32_t))
perror("write() failed.");
}
while (fgets(line, sizeof(line), stdin) != NULL) {
strncpy(buff, line, sizeof(buff) - 1);
token1 = strtok(buff, "\n ");
token2 = strtok(NULL, "\n ");
value = process_line(token1, token2);
if (value == -1) {
fprintf(stderr,
"Illegal data (ignored):\"%s\"\n", line);
} else {
if (write(1, &value,len) != len)
perror("write() failed");
}
}
}
/** Copy stdin to stdout, converting binary data to text. */
static void write_totext(void)
{
char buff[2048 * sizeof(int)];
int r;
int i;
const uint32_t* data;
if (opt_add_sync)
puts("space 1000000\n");
while ((r = read(0, buff, sizeof(buff))) > 0) {
for (i = 0; i < r; i += sizeof(int)) {
data = (uint32_t*)(&buff[i]);
printf("%s %u\n",
(*data & PULSE_BIT) ? "pulse" : "space",
*data & PULSE_MASK);
}
}
if (r == -1) {
perror("irpipe: Cannot read stdin");
exit(1);
}
}
/** Send verbatim copy of stdin to stdout. */
static void write_raw(void)
{
char buff[2048 * sizeof(int)];
int r;
int written;
while ((r = read(0, buff, sizeof(buff))) > 0) {
written = write(1, buff, r);
if (written != r) {
perror("irpipe: Cannot write in raw copy");
exit(1);
}
}
if (r == -1) {
perror("irpipe: Cannot read stdin");
exit(1);
}
}
static void run_ioctl(int cmd, unsigned long arg)
{
int fd = (opt_mode == MODE_WRITE) ? 1 : 0;
int r = ioctl(fd, cmd, arg);
if (r == -1) {
perror("Cannot run ioctl");
exit(1);
}
}
int main(int argc, char**argv)
{
parse_options(argc, argv);
if (opt_mode == MODE_WRITE)
irpipe_setup(1, opt_device, O_WRONLY);
else if (opt_mode == MODE_READ)
irpipe_setup(0, opt_device, O_RDONLY);
if (opt_features != LONG_MAX)
run_ioctl(LIRC_SET_FEATURES, opt_features);
if (opt_length != -1)
run_ioctl(LIRC_SET_LENGTH, opt_length);
if (opt_bits > 0 && opt_mode != MODE_FILTER) {
run_ioctl(LIRC_SET_REC_MODE, LIRC_MODE_LIRCCODE);
run_ioctl(LIRC_SET_SEND_MODE, LIRC_MODE_LIRCCODE);
}
if (opt_tobin)
write_tobin();
else if (opt_totext)
write_totext();
else
write_raw();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtscreenutil_p.h"
#include <qt_windows.h>
void QxtScreenUtilPrivate::init_sys()
{
DISPLAY_DEVICE displayDevice;
::ZeroMemory(&displayDevice, sizeof(displayDevice));
displayDevice.cb = sizeof(displayDevice);
if (::EnumDisplayDevices(NULL, screen, &displayDevice, 0))
{
DEVMODE devMode;
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
// current resolution & rate
if (!currReso.isValid() || currRate < 0)
{
if (::EnumDisplaySettings(displayDevice.DeviceName, ENUM_CURRENT_SETTINGS, &devMode))
{
currReso = QSize(devMode.dmPelsWidth, devMode.dmPelsHeight);
currRate = devMode.dmDisplayFrequency;
}
}
// available resolutions & rates
if (availResos.isEmpty() || availRates.isEmpty())
{
availResos.clear();
availRates.clear();
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
DWORD i = 0;
while (::EnumDisplaySettings(displayDevice.DeviceName, i++, &devMode))
{
QSize reso(devMode.dmPelsWidth, devMode.dmPelsHeight);
if (!availResos.contains(reso))
availResos += reso;
availRates.insertMulti(reso, devMode.dmDisplayFrequency);
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
}
}
}
}
bool QxtScreenUtilPrivate::set(const QSize& reso, int rate)
{
bool result = false;
DISPLAY_DEVICE displayDevice;
::ZeroMemory(&displayDevice, sizeof(displayDevice));
displayDevice.cb = sizeof(displayDevice);
if (::EnumDisplayDevices(NULL, screen, &displayDevice, 0))
{
DEVMODE devMode;
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
if (reso.isValid())
{
devMode.dmPelsWidth = reso.width();
devMode.dmPelsHeight = reso.height();
devMode.dmFields |= DM_PELSWIDTH | DM_PELSHEIGHT;
}
if (rate != -1)
{
devMode.dmDisplayFrequency = rate;
devMode.dmFields |= DM_DISPLAYFREQUENCY;
}
//TODO:
//if (depth != -1)
//{
// devMode.dmBitsPerPel = depth;
// devMode.dmFields |= DM_BITSPERPEL;;
//}
result = ::ChangeDisplaySettingsEx(displayDevice.DeviceName, &devMode, NULL, 0, NULL) == DISP_CHANGE_SUCCESSFUL;
}
return result;
}
<commit_msg>Prevent double refresh rates on windows.<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtscreenutil_p.h"
#include <qt_windows.h>
void QxtScreenUtilPrivate::init_sys()
{
DISPLAY_DEVICE displayDevice;
::ZeroMemory(&displayDevice, sizeof(displayDevice));
displayDevice.cb = sizeof(displayDevice);
if (::EnumDisplayDevices(NULL, screen, &displayDevice, 0))
{
DEVMODE devMode;
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
// current resolution & rate
if (!currReso.isValid() || currRate < 0)
{
if (::EnumDisplaySettings(displayDevice.DeviceName, ENUM_CURRENT_SETTINGS, &devMode))
{
currReso = QSize(devMode.dmPelsWidth, devMode.dmPelsHeight);
currRate = devMode.dmDisplayFrequency;
}
}
// available resolutions & rates
if (availResos.isEmpty() || availRates.isEmpty())
{
availResos.clear();
availRates.clear();
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
DWORD i = 0;
while (::EnumDisplaySettings(displayDevice.DeviceName, i++, &devMode))
{
const QSize reso(devMode.dmPelsWidth, devMode.dmPelsHeight);
if (!availResos.contains(reso))
availResos += reso;
if (!availRates.contains(reso, devMode.dmDisplayFrequency))
availRates.insertMulti(reso, devMode.dmDisplayFrequency);
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
}
}
}
}
bool QxtScreenUtilPrivate::set(const QSize& reso, int rate)
{
bool result = false;
DISPLAY_DEVICE displayDevice;
::ZeroMemory(&displayDevice, sizeof(displayDevice));
displayDevice.cb = sizeof(displayDevice);
if (::EnumDisplayDevices(NULL, screen, &displayDevice, 0))
{
DEVMODE devMode;
::ZeroMemory(&devMode, sizeof(devMode));
devMode.dmSize = sizeof(devMode);
if (reso.isValid())
{
devMode.dmPelsWidth = reso.width();
devMode.dmPelsHeight = reso.height();
devMode.dmFields |= DM_PELSWIDTH | DM_PELSHEIGHT;
}
if (rate != -1)
{
devMode.dmDisplayFrequency = rate;
devMode.dmFields |= DM_DISPLAYFREQUENCY;
}
//TODO:
//if (depth != -1)
//{
// devMode.dmBitsPerPel = depth;
// devMode.dmFields |= DM_BITSPERPEL;;
//}
result = ::ChangeDisplaySettingsEx(displayDevice.DeviceName, &devMode, NULL, 0, NULL) == DISP_CHANGE_SUCCESSFUL;
}
return result;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 J-P Nurmi <jpnurmi@gmail.com>
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "sessiontreewidget.h"
#include "sessiontreedelegate.h"
#include "sessiontreeitem.h"
#include "messageview.h"
#include "menufactory.h"
#include "sharedtimer.h"
#include "session.h"
#include <QContextMenuEvent>
#include <QHeaderView>
#include <QTimer>
SessionTreeWidget::SessionTreeWidget(QWidget* parent) : QTreeWidget(parent)
{
setAnimated(true);
setColumnCount(2);
setIndentation(0);
setHeaderHidden(true);
setRootIsDecorated(false);
setFrameStyle(QFrame::NoFrame);
header()->setStretchLastSection(false);
header()->setResizeMode(0, QHeaderView::Stretch);
header()->setResizeMode(1, QHeaderView::Fixed);
header()->resizeSection(1, 22);
setItemDelegate(new SessionTreeDelegate(this));
setDragEnabled(true);
setDropIndicatorShown(true);
setDragDropMode(InternalMove);
d.dropParent = 0;
d.menuFactory = 0;
d.colors[Active] = palette().color(QPalette::WindowText);
d.colors[Inactive] = palette().color(QPalette::Disabled, QPalette::Highlight);
d.colors[Highlight] = palette().color(QPalette::Highlight);
connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)),
this, SLOT(onItemExpanded(QTreeWidgetItem*)));
connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)),
this, SLOT(onItemCollapsed(QTreeWidgetItem*)));
connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(onCurrentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
d.prevShortcut = new QShortcut(this);
connect(d.prevShortcut, SIGNAL(activated()), this, SLOT(moveToPrevItem()));
d.nextShortcut = new QShortcut(this);
connect(d.nextShortcut, SIGNAL(activated()), this, SLOT(moveToNextItem()));
d.prevUnreadShortcut = new QShortcut(this);
connect(d.prevUnreadShortcut, SIGNAL(activated()), this, SLOT(moveToPrevUnreadItem()));
d.nextUnreadShortcut = new QShortcut(this);
connect(d.nextUnreadShortcut, SIGNAL(activated()), this, SLOT(moveToNextUnreadItem()));
d.expandShortcut = new QShortcut(this);
connect(d.expandShortcut, SIGNAL(activated()), this, SLOT(expandCurrentSession()));
d.collapseShortcut = new QShortcut(this);
connect(d.collapseShortcut, SIGNAL(activated()), this, SLOT(collapseCurrentSession()));
d.mostActiveShortcut = new QShortcut(this);
connect(d.mostActiveShortcut, SIGNAL(activated()), this, SLOT(moveToMostActiveItem()));
applySettings(d.settings);
}
QSize SessionTreeWidget::sizeHint() const
{
return QSize(20 * fontMetrics().width('#'), QTreeWidget::sizeHint().height());
}
QByteArray SessionTreeWidget::saveState() const
{
QByteArray state;
QDataStream out(&state, QIODevice::WriteOnly);
QVariantHash hash;
for (int i = 0; i < topLevelItemCount(); ++i) {
QTreeWidgetItem* parent = topLevelItem(i);
QStringList receivers;
for (int j = 0; j < parent->childCount(); ++j)
receivers += parent->child(j)->text(0);
hash.insert(parent->text(0), receivers);
}
out << hash;
return state;
}
void SessionTreeWidget::restoreState(const QByteArray& state)
{
QDataStream in(state);
in >> d.state;
for (int i = 0; i < topLevelItemCount(); ++i)
topLevelItem(i)->sortChildren(0, Qt::AscendingOrder);
}
MenuFactory* SessionTreeWidget::menuFactory() const
{
if (!d.menuFactory) {
SessionTreeWidget* that = const_cast<SessionTreeWidget*>(this);
that->d.menuFactory = new MenuFactory(that);
}
return d.menuFactory;
}
void SessionTreeWidget::setMenuFactory(MenuFactory* factory)
{
if (d.menuFactory && d.menuFactory->parent() == this)
delete d.menuFactory;
d.menuFactory = factory;
}
QColor SessionTreeWidget::statusColor(SessionTreeWidget::ItemStatus status) const
{
return d.colors.value(status);
}
void SessionTreeWidget::setStatusColor(SessionTreeWidget::ItemStatus status, const QColor& color)
{
d.colors[status] = color;
}
SessionTreeItem* SessionTreeWidget::viewItem(MessageView* view) const
{
return d.viewItems.value(view);
}
SessionTreeItem* SessionTreeWidget::sessionItem(Session* session) const
{
return d.sessionItems.value(session);
}
void SessionTreeWidget::addView(MessageView* view)
{
SessionTreeItem* item = 0;
if (view->viewType() == MessageView::ServerView) {
item = new SessionTreeItem(view, this);
Session* session = view->session();
connect(session, SIGNAL(nameChanged(QString)), this, SLOT(updateSession()));
connect(session, SIGNAL(networkChanged(QString)), this, SLOT(updateSession()));
d.sessionItems.insert(session, item);
} else {
SessionTreeItem* parent = d.sessionItems.value(view->session());
item = new SessionTreeItem(view, parent);
}
connect(view, SIGNAL(activeChanged()), this, SLOT(updateView()));
connect(view, SIGNAL(receiverChanged(QString)), this, SLOT(updateView()));
d.viewItems.insert(view, item);
updateView(view);
}
void SessionTreeWidget::removeView(MessageView* view)
{
if (view->viewType() == MessageView::ServerView)
d.sessionItems.remove(view->session());
delete d.viewItems.take(view);
}
void SessionTreeWidget::renameView(MessageView* view)
{
SessionTreeItem* item = d.viewItems.value(view);
if (item)
item->setText(0, view->receiver());
}
void SessionTreeWidget::setCurrentView(MessageView* view)
{
SessionTreeItem* item = d.viewItems.value(view);
if (item)
setCurrentItem(item);
}
void SessionTreeWidget::moveToNextItem()
{
QTreeWidgetItem* item = nextItem(currentItem());
if (!item)
item = topLevelItem(0);
setCurrentItem(item);
}
void SessionTreeWidget::moveToPrevItem()
{
QTreeWidgetItem* item = previousItem(currentItem());
if (!item)
item = lastItem();
setCurrentItem(item);
}
void SessionTreeWidget::moveToNextUnreadItem()
{
QTreeWidgetItem* current = currentItem();
if (current) {
QTreeWidgetItemIterator it(current);
while (*++it && *it != current) {
SessionTreeItem* item = static_cast<SessionTreeItem*>(*it);
if (item->badge() > 0) {
setCurrentItem(item);
break;
}
}
}
}
void SessionTreeWidget::moveToPrevUnreadItem()
{
QTreeWidgetItem* current = currentItem();
if (current) {
QTreeWidgetItemIterator it(current);
while (*--it && *it != current) {
SessionTreeItem* item = static_cast<SessionTreeItem*>(*it);
if (item->badge() > 0) {
setCurrentItem(item);
break;
}
}
}
}
void SessionTreeWidget::moveToMostActiveItem()
{
QTreeWidgetItem *firstHighlight = 0;
QTreeWidgetItemIterator it(this);
while (*it) {
SessionTreeItem* item = static_cast<SessionTreeItem*>(*it);
if (item->isHighlighted()) {
// we found a channel hilight or PM to us
setCurrentItem(item);
return;
}
// as a backup, also store the first window with any sort of activity
if (!firstHighlight && item->badge()) {
firstHighlight = item;
// can't break in case we find an alerted item
}
it++;
}
if (firstHighlight)
setCurrentItem(firstHighlight);
}
void SessionTreeWidget::expandCurrentSession()
{
QTreeWidgetItem* item = currentItem();
if (item && item->parent())
item = item->parent();
if (item)
expandItem(item);
}
void SessionTreeWidget::collapseCurrentSession()
{
QTreeWidgetItem* item = currentItem();
if (item && item->parent())
item = item->parent();
if (item) {
collapseItem(item);
setCurrentItem(item);
}
}
void SessionTreeWidget::applySettings(const Settings& settings)
{
QColor color(settings.colors.value(Settings::Highlight));
setStatusColor(Highlight, color);
d.prevShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateUp)));
d.nextShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateDown)));
d.prevUnreadShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NextUnreadUp)));
d.nextUnreadShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NextUnreadDown)));
d.expandShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateRight)));
d.collapseShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateLeft)));
d.mostActiveShortcut->setKey(QKeySequence("Ctrl+S"));
d.settings = settings;
}
void SessionTreeWidget::contextMenuEvent(QContextMenuEvent* event)
{
SessionTreeItem* item = static_cast<SessionTreeItem*>(itemAt(event->pos()));
if (item) {
QMenu* menu = menuFactory()->createSessionTreeMenu(item, this);
menu->exec(event->globalPos());
menu->deleteLater();
}
}
void SessionTreeWidget::dragMoveEvent(QDragMoveEvent* event)
{
QTreeWidgetItem* item = itemAt(event->pos());
if (!item || !item->parent() || item->parent() != d.dropParent)
event->ignore();
else
QTreeWidget::dragMoveEvent(event);
}
bool SessionTreeWidget::event(QEvent* event)
{
if (event->type() == QEvent::WindowActivate)
delayedItemReset();
return QTreeWidget::event(event);
}
QMimeData* SessionTreeWidget::mimeData(const QList<QTreeWidgetItem*> items) const
{
QTreeWidgetItem* item = items.value(0);
d.dropParent = item ? item->parent() : 0;
return QTreeWidget::mimeData(items);
}
void SessionTreeWidget::updateView(MessageView* view)
{
if (!view)
view = qobject_cast<MessageView*>(sender());
SessionTreeItem* item = d.viewItems.value(view);
if (item) {
if (!item->parent())
item->setText(0, item->session()->name().isEmpty() ? item->session()->host() : item->session()->name());
else
item->setText(0, view->receiver());
// re-read MessageView::isActive()
item->emitDataChanged();
}
}
void SessionTreeWidget::updateSession(Session* session)
{
if (!session)
session = qobject_cast<Session*>(sender());
SessionTreeItem* item = d.sessionItems.value(session);
if (item)
item->setText(0, session->name().isEmpty() ? session->host() : session->name());
}
void SessionTreeWidget::onItemExpanded(QTreeWidgetItem* item)
{
static_cast<SessionTreeItem*>(item)->emitDataChanged();
}
void SessionTreeWidget::onItemCollapsed(QTreeWidgetItem* item)
{
static_cast<SessionTreeItem*>(item)->emitDataChanged();
}
void SessionTreeWidget::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (previous)
resetItem(static_cast<SessionTreeItem*>(previous));
delayedItemReset();
SessionTreeItem* item = static_cast<SessionTreeItem*>(current);
emit currentViewChanged(item->session(), item->parent() ? item->text(0) : QString());
}
void SessionTreeWidget::delayedItemReset()
{
SessionTreeItem* item = static_cast<SessionTreeItem*>(currentItem());
if (item) {
d.resetedItems.insert(item);
QTimer::singleShot(500, this, SLOT(delayedItemResetTimeout()));
}
}
void SessionTreeWidget::delayedItemResetTimeout()
{
if (!d.resetedItems.isEmpty()) {
foreach (SessionTreeItem* item, d.resetedItems)
resetItem(item);
d.resetedItems.clear();
}
}
void SessionTreeWidget::resetItem(SessionTreeItem* item)
{
item->setBadge(0);
item->setHighlighted(false);
}
QTreeWidgetItem* SessionTreeWidget::lastItem() const
{
QTreeWidgetItem* item = topLevelItem(topLevelItemCount() - 1);
if (item->childCount() > 0)
item = item->child(item->childCount() - 1);
return item;
}
QTreeWidgetItem* SessionTreeWidget::nextItem(QTreeWidgetItem* from) const
{
if (!from)
return 0;
QTreeWidgetItemIterator it(from);
while (*++it) {
if (!(*it)->parent() || (*it)->parent()->isExpanded())
break;
}
return *it;
}
QTreeWidgetItem* SessionTreeWidget::previousItem(QTreeWidgetItem* from) const
{
if (!from)
return 0;
QTreeWidgetItemIterator it(from);
while (*--it) {
if (!(*it)->parent() || (*it)->parent()->isExpanded())
break;
}
return *it;
}
<commit_msg>Fix SessionTreeWidget::moveToMostActiveItem() slowness<commit_after>/*
* Copyright (C) 2008-2013 J-P Nurmi <jpnurmi@gmail.com>
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "sessiontreewidget.h"
#include "sessiontreedelegate.h"
#include "sessiontreeitem.h"
#include "messageview.h"
#include "menufactory.h"
#include "sharedtimer.h"
#include "session.h"
#include <QContextMenuEvent>
#include <QHeaderView>
#include <QTimer>
SessionTreeWidget::SessionTreeWidget(QWidget* parent) : QTreeWidget(parent)
{
setAnimated(true);
setColumnCount(2);
setIndentation(0);
setHeaderHidden(true);
setRootIsDecorated(false);
setFrameStyle(QFrame::NoFrame);
header()->setStretchLastSection(false);
header()->setResizeMode(0, QHeaderView::Stretch);
header()->setResizeMode(1, QHeaderView::Fixed);
header()->resizeSection(1, 22);
setItemDelegate(new SessionTreeDelegate(this));
setDragEnabled(true);
setDropIndicatorShown(true);
setDragDropMode(InternalMove);
d.dropParent = 0;
d.menuFactory = 0;
d.colors[Active] = palette().color(QPalette::WindowText);
d.colors[Inactive] = palette().color(QPalette::Disabled, QPalette::Highlight);
d.colors[Highlight] = palette().color(QPalette::Highlight);
connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)),
this, SLOT(onItemExpanded(QTreeWidgetItem*)));
connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)),
this, SLOT(onItemCollapsed(QTreeWidgetItem*)));
connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(onCurrentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
d.prevShortcut = new QShortcut(this);
connect(d.prevShortcut, SIGNAL(activated()), this, SLOT(moveToPrevItem()));
d.nextShortcut = new QShortcut(this);
connect(d.nextShortcut, SIGNAL(activated()), this, SLOT(moveToNextItem()));
d.prevUnreadShortcut = new QShortcut(this);
connect(d.prevUnreadShortcut, SIGNAL(activated()), this, SLOT(moveToPrevUnreadItem()));
d.nextUnreadShortcut = new QShortcut(this);
connect(d.nextUnreadShortcut, SIGNAL(activated()), this, SLOT(moveToNextUnreadItem()));
d.expandShortcut = new QShortcut(this);
connect(d.expandShortcut, SIGNAL(activated()), this, SLOT(expandCurrentSession()));
d.collapseShortcut = new QShortcut(this);
connect(d.collapseShortcut, SIGNAL(activated()), this, SLOT(collapseCurrentSession()));
d.mostActiveShortcut = new QShortcut(this);
connect(d.mostActiveShortcut, SIGNAL(activated()), this, SLOT(moveToMostActiveItem()));
applySettings(d.settings);
}
QSize SessionTreeWidget::sizeHint() const
{
return QSize(20 * fontMetrics().width('#'), QTreeWidget::sizeHint().height());
}
QByteArray SessionTreeWidget::saveState() const
{
QByteArray state;
QDataStream out(&state, QIODevice::WriteOnly);
QVariantHash hash;
for (int i = 0; i < topLevelItemCount(); ++i) {
QTreeWidgetItem* parent = topLevelItem(i);
QStringList receivers;
for (int j = 0; j < parent->childCount(); ++j)
receivers += parent->child(j)->text(0);
hash.insert(parent->text(0), receivers);
}
out << hash;
return state;
}
void SessionTreeWidget::restoreState(const QByteArray& state)
{
QDataStream in(state);
in >> d.state;
for (int i = 0; i < topLevelItemCount(); ++i)
topLevelItem(i)->sortChildren(0, Qt::AscendingOrder);
}
MenuFactory* SessionTreeWidget::menuFactory() const
{
if (!d.menuFactory) {
SessionTreeWidget* that = const_cast<SessionTreeWidget*>(this);
that->d.menuFactory = new MenuFactory(that);
}
return d.menuFactory;
}
void SessionTreeWidget::setMenuFactory(MenuFactory* factory)
{
if (d.menuFactory && d.menuFactory->parent() == this)
delete d.menuFactory;
d.menuFactory = factory;
}
QColor SessionTreeWidget::statusColor(SessionTreeWidget::ItemStatus status) const
{
return d.colors.value(status);
}
void SessionTreeWidget::setStatusColor(SessionTreeWidget::ItemStatus status, const QColor& color)
{
d.colors[status] = color;
}
SessionTreeItem* SessionTreeWidget::viewItem(MessageView* view) const
{
return d.viewItems.value(view);
}
SessionTreeItem* SessionTreeWidget::sessionItem(Session* session) const
{
return d.sessionItems.value(session);
}
void SessionTreeWidget::addView(MessageView* view)
{
SessionTreeItem* item = 0;
if (view->viewType() == MessageView::ServerView) {
item = new SessionTreeItem(view, this);
Session* session = view->session();
connect(session, SIGNAL(nameChanged(QString)), this, SLOT(updateSession()));
connect(session, SIGNAL(networkChanged(QString)), this, SLOT(updateSession()));
d.sessionItems.insert(session, item);
} else {
SessionTreeItem* parent = d.sessionItems.value(view->session());
item = new SessionTreeItem(view, parent);
}
connect(view, SIGNAL(activeChanged()), this, SLOT(updateView()));
connect(view, SIGNAL(receiverChanged(QString)), this, SLOT(updateView()));
d.viewItems.insert(view, item);
updateView(view);
}
void SessionTreeWidget::removeView(MessageView* view)
{
if (view->viewType() == MessageView::ServerView)
d.sessionItems.remove(view->session());
delete d.viewItems.take(view);
}
void SessionTreeWidget::renameView(MessageView* view)
{
SessionTreeItem* item = d.viewItems.value(view);
if (item)
item->setText(0, view->receiver());
}
void SessionTreeWidget::setCurrentView(MessageView* view)
{
SessionTreeItem* item = d.viewItems.value(view);
if (item)
setCurrentItem(item);
}
void SessionTreeWidget::moveToNextItem()
{
QTreeWidgetItem* item = nextItem(currentItem());
if (!item)
item = topLevelItem(0);
setCurrentItem(item);
}
void SessionTreeWidget::moveToPrevItem()
{
QTreeWidgetItem* item = previousItem(currentItem());
if (!item)
item = lastItem();
setCurrentItem(item);
}
void SessionTreeWidget::moveToNextUnreadItem()
{
QTreeWidgetItem* current = currentItem();
if (current) {
QTreeWidgetItemIterator it(current);
while (*++it && *it != current) {
SessionTreeItem* item = static_cast<SessionTreeItem*>(*it);
if (item->badge() > 0) {
setCurrentItem(item);
break;
}
}
}
}
void SessionTreeWidget::moveToPrevUnreadItem()
{
QTreeWidgetItem* current = currentItem();
if (current) {
QTreeWidgetItemIterator it(current);
while (*--it && *it != current) {
SessionTreeItem* item = static_cast<SessionTreeItem*>(*it);
if (item->badge() > 0) {
setCurrentItem(item);
break;
}
}
}
}
void SessionTreeWidget::moveToMostActiveItem()
{
QTreeWidgetItem *firstHighlight = 0;
QTreeWidgetItemIterator it(this, QTreeWidgetItemIterator::Unselected);
while (*it) {
SessionTreeItem* item = static_cast<SessionTreeItem*>(*it);
if (item->isHighlighted()) {
// we found a channel hilight or PM to us
setCurrentItem(item);
return;
}
// as a backup, also store the first window with any sort of activity
if (!firstHighlight && item->badge()) {
firstHighlight = item;
// can't break in case we find an alerted item
}
it++;
}
if (firstHighlight)
setCurrentItem(firstHighlight);
}
void SessionTreeWidget::expandCurrentSession()
{
QTreeWidgetItem* item = currentItem();
if (item && item->parent())
item = item->parent();
if (item)
expandItem(item);
}
void SessionTreeWidget::collapseCurrentSession()
{
QTreeWidgetItem* item = currentItem();
if (item && item->parent())
item = item->parent();
if (item) {
collapseItem(item);
setCurrentItem(item);
}
}
void SessionTreeWidget::applySettings(const Settings& settings)
{
QColor color(settings.colors.value(Settings::Highlight));
setStatusColor(Highlight, color);
d.prevShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateUp)));
d.nextShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateDown)));
d.prevUnreadShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NextUnreadUp)));
d.nextUnreadShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NextUnreadDown)));
d.expandShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateRight)));
d.collapseShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::NavigateLeft)));
d.mostActiveShortcut->setKey(QKeySequence("Ctrl+S"));
d.settings = settings;
}
void SessionTreeWidget::contextMenuEvent(QContextMenuEvent* event)
{
SessionTreeItem* item = static_cast<SessionTreeItem*>(itemAt(event->pos()));
if (item) {
QMenu* menu = menuFactory()->createSessionTreeMenu(item, this);
menu->exec(event->globalPos());
menu->deleteLater();
}
}
void SessionTreeWidget::dragMoveEvent(QDragMoveEvent* event)
{
QTreeWidgetItem* item = itemAt(event->pos());
if (!item || !item->parent() || item->parent() != d.dropParent)
event->ignore();
else
QTreeWidget::dragMoveEvent(event);
}
bool SessionTreeWidget::event(QEvent* event)
{
if (event->type() == QEvent::WindowActivate)
delayedItemReset();
return QTreeWidget::event(event);
}
QMimeData* SessionTreeWidget::mimeData(const QList<QTreeWidgetItem*> items) const
{
QTreeWidgetItem* item = items.value(0);
d.dropParent = item ? item->parent() : 0;
return QTreeWidget::mimeData(items);
}
void SessionTreeWidget::updateView(MessageView* view)
{
if (!view)
view = qobject_cast<MessageView*>(sender());
SessionTreeItem* item = d.viewItems.value(view);
if (item) {
if (!item->parent())
item->setText(0, item->session()->name().isEmpty() ? item->session()->host() : item->session()->name());
else
item->setText(0, view->receiver());
// re-read MessageView::isActive()
item->emitDataChanged();
}
}
void SessionTreeWidget::updateSession(Session* session)
{
if (!session)
session = qobject_cast<Session*>(sender());
SessionTreeItem* item = d.sessionItems.value(session);
if (item)
item->setText(0, session->name().isEmpty() ? session->host() : session->name());
}
void SessionTreeWidget::onItemExpanded(QTreeWidgetItem* item)
{
static_cast<SessionTreeItem*>(item)->emitDataChanged();
}
void SessionTreeWidget::onItemCollapsed(QTreeWidgetItem* item)
{
static_cast<SessionTreeItem*>(item)->emitDataChanged();
}
void SessionTreeWidget::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (previous)
resetItem(static_cast<SessionTreeItem*>(previous));
delayedItemReset();
SessionTreeItem* item = static_cast<SessionTreeItem*>(current);
emit currentViewChanged(item->session(), item->parent() ? item->text(0) : QString());
}
void SessionTreeWidget::delayedItemReset()
{
SessionTreeItem* item = static_cast<SessionTreeItem*>(currentItem());
if (item) {
d.resetedItems.insert(item);
QTimer::singleShot(500, this, SLOT(delayedItemResetTimeout()));
}
}
void SessionTreeWidget::delayedItemResetTimeout()
{
if (!d.resetedItems.isEmpty()) {
foreach (SessionTreeItem* item, d.resetedItems)
resetItem(item);
d.resetedItems.clear();
}
}
void SessionTreeWidget::resetItem(SessionTreeItem* item)
{
item->setBadge(0);
item->setHighlighted(false);
}
QTreeWidgetItem* SessionTreeWidget::lastItem() const
{
QTreeWidgetItem* item = topLevelItem(topLevelItemCount() - 1);
if (item->childCount() > 0)
item = item->child(item->childCount() - 1);
return item;
}
QTreeWidgetItem* SessionTreeWidget::nextItem(QTreeWidgetItem* from) const
{
if (!from)
return 0;
QTreeWidgetItemIterator it(from);
while (*++it) {
if (!(*it)->parent() || (*it)->parent()->isExpanded())
break;
}
return *it;
}
QTreeWidgetItem* SessionTreeWidget::previousItem(QTreeWidgetItem* from) const
{
if (!from)
return 0;
QTreeWidgetItemIterator it(from);
while (*--it) {
if (!(*it)->parent() || (*it)->parent()->isExpanded())
break;
}
return *it;
}
<|endoftext|> |
<commit_before>/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//////////////////////////////////////////////////////////////////////////////////////////////
// conditions.cc: Implementation of the condition classes
//
//
#include <unistd.h>
#include <ts/ts.h>
#include "conditions.h"
#include "lulu.h"
#include <sys/time.h>
// ConditionStatus
void
ConditionStatus::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<TSHttpStatus>* match = new Matchers<TSHttpStatus>(_cond_op);
match->set(static_cast<TSHttpStatus>(strtol(p.get_arg().c_str(), NULL, 10)));
_matcher = match;
require_resources(RSRC_SERVER_RESPONSE_HEADERS);
require_resources(RSRC_CLIENT_RESPONSE_HEADERS);
require_resources(RSRC_RESPONSE_STATUS);
}
void
ConditionStatus::initialize_hooks()
{
add_allowed_hook(TS_HTTP_READ_RESPONSE_HDR_HOOK);
add_allowed_hook(TS_HTTP_SEND_RESPONSE_HDR_HOOK);
}
bool
ConditionStatus::eval(const Resources& res)
{
TSDebug(PLUGIN_NAME, "Evaluating STATUS()"); // TODO: It'd be nice to get the args here ...
return static_cast<const Matchers<TSHttpStatus>*>(_matcher)->test(res.resp_status);
}
void
ConditionStatus::append_value(std::string& s, const Resources& res)
{
s += boost::lexical_cast<std::string>(res.resp_status);
TSDebug(PLUGIN_NAME, "Appending STATUS(%d) to evaluation value -> %s", res.resp_status, s.c_str());
}
// ConditionRandom: random 0 to (N-1)
void
ConditionRandom::initialize(Parser& p)
{
struct timeval tv;
Condition::initialize(p);
gettimeofday(&tv, NULL);
Matchers<unsigned int>* match = new Matchers<unsigned int>(_cond_op);
_seed = getpid()* tv.tv_usec;
_max = strtol(_qualifier.c_str(), NULL, 10);
match->set(static_cast<unsigned int>(strtol(p.get_arg().c_str(), NULL, 10)));
_matcher = match;
}
bool
ConditionRandom::eval(const Resources& /* res ATS_UNUSED */)
{
TSDebug(PLUGIN_NAME, "Evaluating RANDOM(%d)", _max);
return static_cast<const Matchers<unsigned int>*>(_matcher)->test(rand_r(&_seed) % _max);
}
void
ConditionRandom::append_value(std::string& s, const Resources& /* res ATS_UNUSED */)
{
s += boost::lexical_cast<std::string>(rand_r(&_seed) % _max);
TSDebug(PLUGIN_NAME, "Appending RANDOM(%d) to evaluation value -> %s", _max, s.c_str());
}
// ConditionAccess: access(file)
void
ConditionAccess::initialize(Parser& p)
{
struct timeval tv;
Condition::initialize(p);
gettimeofday(&tv, NULL);
_next = tv.tv_sec + 2;
_last = !access(_qualifier.c_str(), R_OK);
}
void
ConditionAccess::append_value(std::string& s, const Resources& res)
{
if (eval(res)) {
s += "OK";
} else {
s += "NOT OK";
}
}
bool
ConditionAccess::eval(const Resources& /* res ATS_UNUSED */)
{
struct timeval tv;
gettimeofday(&tv, NULL);
TSDebug(PLUGIN_NAME, "Evaluating ACCESS(%s)", _qualifier.c_str());
if (tv.tv_sec > _next) {
// There is a small "race" here, where we could end up calling access() a few times extra. I think
// that is OK, and not worth protecting with a lock.
bool check = !access(_qualifier.c_str(), R_OK);
tv.tv_sec += 2;
mb();
_next = tv.tv_sec; // I hope this is an atomic "set"...
_last = check; // This sure ought to be
}
return _last;
}
// ConditionHeader: request or response header
void
ConditionHeader::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
require_resources(RSRC_CLIENT_REQUEST_HEADERS);
require_resources(RSRC_CLIENT_RESPONSE_HEADERS);
require_resources(RSRC_SERVER_REQUEST_HEADERS);
require_resources(RSRC_SERVER_RESPONSE_HEADERS);
}
void
ConditionHeader::append_value(std::string& s, const Resources& res)
{
TSMBuffer bufp;
TSMLoc hdr_loc;
TSMLoc field_loc;
const char* value;
int len;
if (_client) {
bufp = res.client_bufp;
hdr_loc = res.client_hdr_loc;
} else {
bufp = res.bufp;
hdr_loc = res.hdr_loc;
}
if (bufp && hdr_loc) {
field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, _qualifier.c_str(), _qualifier.size());
TSDebug(PLUGIN_NAME, "Getting Header: %s, field_loc: %p", _qualifier.c_str(), field_loc);
if (field_loc != NULL) {
value = TSMimeHdrFieldValueStringGet(res.bufp, res.hdr_loc, field_loc, 0, &len);
TSDebug(PLUGIN_NAME, "Appending HEADER(%s) to evaluation value -> %.*s", _qualifier.c_str(), len, value);
s.append(value, len);
TSHandleMLocRelease(res.bufp, res.hdr_loc, field_loc);
}
}
}
bool
ConditionHeader::eval(const Resources& res)
{
std::string s;
append_value(s, res);
bool rval = static_cast<const Matchers<std::string>*>(_matcher)->test(s);
TSDebug(PLUGIN_NAME, "Evaluating HEADER(): %s - rval: %d", s.c_str(), rval);
return rval;
}
// ConditionPath
void
ConditionPath::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
}
void
ConditionPath::append_value(std::string& s, const Resources& res)
{
int path_len = 0;
const char *path = TSUrlPathGet(res._rri->requestBufp, res._rri->requestUrl, &path_len);
TSDebug(PLUGIN_NAME, "Appending PATH to evaluation value: %.*s", path_len, path);
s.append(path, path_len);
}
bool
ConditionPath::eval(const Resources& res)
{
std::string s;
if (NULL == res._rri) {
TSDebug(PLUGIN_NAME, "PATH requires remap initialization! Evaluating to false!");
return false;
}
append_value(s, res);
TSDebug(PLUGIN_NAME, "Evaluating PATH");
return static_cast<const Matchers<std::string>*>(_matcher)->test(s);
}
// ConditionQuery
void
ConditionQuery::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
}
void
ConditionQuery::append_value(std::string& s, const Resources& res)
{
int query_len = 0;
const char *query = TSUrlHttpQueryGet(res._rri->requestBufp, res._rri->requestUrl, &query_len);
TSDebug(PLUGIN_NAME, "Appending QUERY to evaluation value: %.*s", query_len, query);
s.append(query, query_len);
}
bool
ConditionQuery::eval(const Resources& res)
{
std::string s;
if (NULL == res._rri) {
TSDebug(PLUGIN_NAME, "QUERY requires remap initialization! Evaluating to false!");
return false;
}
append_value(s, res);
TSDebug(PLUGIN_NAME, "Evaluating QUERY - %s", s.c_str());
return static_cast<const Matchers<std::string>*>(_matcher)->test(s);
}
// ConditionUrl: request or response header. TODO: This is not finished, at all!!!
void
ConditionUrl::initialize(Parser& /* p ATS_UNUSED */)
{
}
void
ConditionUrl::set_qualifier(const std::string& q)
{
Condition::set_qualifier(q);
_url_qual = parse_url_qualifier(q);
}
void
ConditionUrl::append_value(std::string& /* s ATS_UNUSED */, const Resources& /* res ATS_UNUSED */)
{
}
bool
ConditionUrl::eval(const Resources& /* res ATS_UNUSED */)
{
bool ret = false;
return ret;
}
// ConditionDBM: do a lookup against a DBM
void
ConditionDBM::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
std::string::size_type pos = _qualifier.find_first_of(',');
if (pos != std::string::npos) {
_file = _qualifier.substr(0, pos);
//_dbm = mdbm_open(_file.c_str(), O_RDONLY, 0, 0, 0);
// if (NULL != _dbm) {
// TSDebug(PLUGIN_NAME, "Opened DBM file %s\n", _file.c_str());
// _key.set_value(_qualifier.substr(pos + 1));
// } else {
// TSError("Failed to open DBM file: %s", _file.c_str());
// }
} else {
TSError("%s: Malformed DBM condition", PLUGIN_NAME);
}
}
void
ConditionDBM::append_value(std::string& /* s ATS_UNUSED */, const Resources& /* res ATS_UNUSED */)
{
// std::string key;
// if (!_dbm)
// return;
// _key.append_value(key, res);
// if (key.size() > 0) {
// datum k, v;
// TSDebug(PLUGIN_NAME, "Looking up DBM(\"%s\")", key.c_str());
// k.dptr = const_cast<char*>(key.c_str());
// k.dsize = key.size();
// TSMutexLock(_mutex);
// //v = mdbm_fetch(_dbm, k);
// TSMutexUnlock(_mutex);
// if (v.dsize > 0) {
// TSDebug(PLUGIN_NAME, "Appending DBM(%.*s) to evaluation value -> %.*s", k.dsize, k.dptr, v.dsize, v.dptr);
// s.append(v.dptr, v.dsize);
// }
// }
}
bool
ConditionDBM::eval(const Resources& res)
{
std::string s;
append_value(s, res);
TSDebug(PLUGIN_NAME, "Evaluating DBM(%s, \"%s\")", _file.c_str(), s.c_str());
return static_cast<const Matchers<std::string>*>(_matcher)->test(s);
}
<commit_msg>TS-2316: header_rewrite: fixed segfaults in ConditionPath::append_value()<commit_after>/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//////////////////////////////////////////////////////////////////////////////////////////////
// conditions.cc: Implementation of the condition classes
//
//
#include <unistd.h>
#include <ts/ts.h>
#include "conditions.h"
#include "lulu.h"
#include <sys/time.h>
// ConditionStatus
void
ConditionStatus::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<TSHttpStatus>* match = new Matchers<TSHttpStatus>(_cond_op);
match->set(static_cast<TSHttpStatus>(strtol(p.get_arg().c_str(), NULL, 10)));
_matcher = match;
require_resources(RSRC_SERVER_RESPONSE_HEADERS);
require_resources(RSRC_CLIENT_RESPONSE_HEADERS);
require_resources(RSRC_RESPONSE_STATUS);
}
void
ConditionStatus::initialize_hooks()
{
add_allowed_hook(TS_HTTP_READ_RESPONSE_HDR_HOOK);
add_allowed_hook(TS_HTTP_SEND_RESPONSE_HDR_HOOK);
}
bool
ConditionStatus::eval(const Resources& res)
{
TSDebug(PLUGIN_NAME, "Evaluating STATUS()"); // TODO: It'd be nice to get the args here ...
return static_cast<const Matchers<TSHttpStatus>*>(_matcher)->test(res.resp_status);
}
void
ConditionStatus::append_value(std::string& s, const Resources& res)
{
s += boost::lexical_cast<std::string>(res.resp_status);
TSDebug(PLUGIN_NAME, "Appending STATUS(%d) to evaluation value -> %s", res.resp_status, s.c_str());
}
// ConditionRandom: random 0 to (N-1)
void
ConditionRandom::initialize(Parser& p)
{
struct timeval tv;
Condition::initialize(p);
gettimeofday(&tv, NULL);
Matchers<unsigned int>* match = new Matchers<unsigned int>(_cond_op);
_seed = getpid()* tv.tv_usec;
_max = strtol(_qualifier.c_str(), NULL, 10);
match->set(static_cast<unsigned int>(strtol(p.get_arg().c_str(), NULL, 10)));
_matcher = match;
}
bool
ConditionRandom::eval(const Resources& /* res ATS_UNUSED */)
{
TSDebug(PLUGIN_NAME, "Evaluating RANDOM(%d)", _max);
return static_cast<const Matchers<unsigned int>*>(_matcher)->test(rand_r(&_seed) % _max);
}
void
ConditionRandom::append_value(std::string& s, const Resources& /* res ATS_UNUSED */)
{
s += boost::lexical_cast<std::string>(rand_r(&_seed) % _max);
TSDebug(PLUGIN_NAME, "Appending RANDOM(%d) to evaluation value -> %s", _max, s.c_str());
}
// ConditionAccess: access(file)
void
ConditionAccess::initialize(Parser& p)
{
struct timeval tv;
Condition::initialize(p);
gettimeofday(&tv, NULL);
_next = tv.tv_sec + 2;
_last = !access(_qualifier.c_str(), R_OK);
}
void
ConditionAccess::append_value(std::string& s, const Resources& res)
{
if (eval(res)) {
s += "OK";
} else {
s += "NOT OK";
}
}
bool
ConditionAccess::eval(const Resources& /* res ATS_UNUSED */)
{
struct timeval tv;
gettimeofday(&tv, NULL);
TSDebug(PLUGIN_NAME, "Evaluating ACCESS(%s)", _qualifier.c_str());
if (tv.tv_sec > _next) {
// There is a small "race" here, where we could end up calling access() a few times extra. I think
// that is OK, and not worth protecting with a lock.
bool check = !access(_qualifier.c_str(), R_OK);
tv.tv_sec += 2;
mb();
_next = tv.tv_sec; // I hope this is an atomic "set"...
_last = check; // This sure ought to be
}
return _last;
}
// ConditionHeader: request or response header
void
ConditionHeader::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
require_resources(RSRC_CLIENT_REQUEST_HEADERS);
require_resources(RSRC_CLIENT_RESPONSE_HEADERS);
require_resources(RSRC_SERVER_REQUEST_HEADERS);
require_resources(RSRC_SERVER_RESPONSE_HEADERS);
}
void
ConditionHeader::append_value(std::string& s, const Resources& res)
{
TSMBuffer bufp;
TSMLoc hdr_loc;
TSMLoc field_loc;
const char* value;
int len;
if (_client) {
bufp = res.client_bufp;
hdr_loc = res.client_hdr_loc;
} else {
bufp = res.bufp;
hdr_loc = res.hdr_loc;
}
if (bufp && hdr_loc) {
field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, _qualifier.c_str(), _qualifier.size());
TSDebug(PLUGIN_NAME, "Getting Header: %s, field_loc: %p", _qualifier.c_str(), field_loc);
if (field_loc != NULL) {
value = TSMimeHdrFieldValueStringGet(res.bufp, res.hdr_loc, field_loc, 0, &len);
TSDebug(PLUGIN_NAME, "Appending HEADER(%s) to evaluation value -> %.*s", _qualifier.c_str(), len, value);
s.append(value, len);
TSHandleMLocRelease(res.bufp, res.hdr_loc, field_loc);
}
}
}
bool
ConditionHeader::eval(const Resources& res)
{
std::string s;
append_value(s, res);
bool rval = static_cast<const Matchers<std::string>*>(_matcher)->test(s);
TSDebug(PLUGIN_NAME, "Evaluating HEADER(): %s - rval: %d", s.c_str(), rval);
return rval;
}
// ConditionPath
void
ConditionPath::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
}
void ConditionPath::append_value(std::string& s, const Resources& res) {
TSMBuffer bufp;
TSMLoc url_loc;
if (TSHttpTxnPristineUrlGet(res.txnp, &bufp, &url_loc) == TS_SUCCESS) {
int path_length;
const char *path = TSUrlPathGet(bufp, url_loc, &path_length);
if (path && path_length)
s.append(path, path_length);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, url_loc);
}
}
bool
ConditionPath::eval(const Resources& res)
{
std::string s;
if (NULL == res._rri) {
TSDebug(PLUGIN_NAME, "PATH requires remap initialization! Evaluating to false!");
return false;
}
append_value(s, res);
TSDebug(PLUGIN_NAME, "Evaluating PATH");
return static_cast<const Matchers<std::string>*>(_matcher)->test(s);
}
// ConditionQuery
void
ConditionQuery::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
}
void
ConditionQuery::append_value(std::string& s, const Resources& res)
{
int query_len = 0;
const char *query = TSUrlHttpQueryGet(res._rri->requestBufp, res._rri->requestUrl, &query_len);
TSDebug(PLUGIN_NAME, "Appending QUERY to evaluation value: %.*s", query_len, query);
s.append(query, query_len);
}
bool
ConditionQuery::eval(const Resources& res)
{
std::string s;
if (NULL == res._rri) {
TSDebug(PLUGIN_NAME, "QUERY requires remap initialization! Evaluating to false!");
return false;
}
append_value(s, res);
TSDebug(PLUGIN_NAME, "Evaluating QUERY - %s", s.c_str());
return static_cast<const Matchers<std::string>*>(_matcher)->test(s);
}
// ConditionUrl: request or response header. TODO: This is not finished, at all!!!
void
ConditionUrl::initialize(Parser& /* p ATS_UNUSED */)
{
}
void
ConditionUrl::set_qualifier(const std::string& q)
{
Condition::set_qualifier(q);
_url_qual = parse_url_qualifier(q);
}
void
ConditionUrl::append_value(std::string& /* s ATS_UNUSED */, const Resources& /* res ATS_UNUSED */)
{
}
bool
ConditionUrl::eval(const Resources& /* res ATS_UNUSED */)
{
bool ret = false;
return ret;
}
// ConditionDBM: do a lookup against a DBM
void
ConditionDBM::initialize(Parser& p)
{
Condition::initialize(p);
Matchers<std::string>* match = new Matchers<std::string>(_cond_op);
match->set(p.get_arg());
_matcher = match;
std::string::size_type pos = _qualifier.find_first_of(',');
if (pos != std::string::npos) {
_file = _qualifier.substr(0, pos);
//_dbm = mdbm_open(_file.c_str(), O_RDONLY, 0, 0, 0);
// if (NULL != _dbm) {
// TSDebug(PLUGIN_NAME, "Opened DBM file %s\n", _file.c_str());
// _key.set_value(_qualifier.substr(pos + 1));
// } else {
// TSError("Failed to open DBM file: %s", _file.c_str());
// }
} else {
TSError("%s: Malformed DBM condition", PLUGIN_NAME);
}
}
void
ConditionDBM::append_value(std::string& /* s ATS_UNUSED */, const Resources& /* res ATS_UNUSED */)
{
// std::string key;
// if (!_dbm)
// return;
// _key.append_value(key, res);
// if (key.size() > 0) {
// datum k, v;
// TSDebug(PLUGIN_NAME, "Looking up DBM(\"%s\")", key.c_str());
// k.dptr = const_cast<char*>(key.c_str());
// k.dsize = key.size();
// TSMutexLock(_mutex);
// //v = mdbm_fetch(_dbm, k);
// TSMutexUnlock(_mutex);
// if (v.dsize > 0) {
// TSDebug(PLUGIN_NAME, "Appending DBM(%.*s) to evaluation value -> %.*s", k.dsize, k.dptr, v.dsize, v.dptr);
// s.append(v.dptr, v.dsize);
// }
// }
}
bool
ConditionDBM::eval(const Resources& res)
{
std::string s;
append_value(s, res);
TSDebug(PLUGIN_NAME, "Evaluating DBM(%s, \"%s\")", _file.c_str(), s.c_str());
return static_cast<const Matchers<std::string>*>(_matcher)->test(s);
}
<|endoftext|> |
<commit_before>
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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
*
*****************************************************************************/
// stl
#include <iostream>
// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/feature_factory.hpp>
#include "osm_featureset.hpp"
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::geometry_type;
using mapnik::feature_factory;
template <typename filterT>
osm_featureset<filterT>::osm_featureset(const filterT& filter,
osm_dataset* dataset,
const std::set<std::string>&
attribute_names,
std::string const& encoding)
: filter_(filter),
query_ext_(),
tr_(new transcoder(encoding)),
feature_id_(1),
dataset_ (dataset),
attribute_names_ (attribute_names),
ctx_(boost::make_shared<mapnik::context_type>())
{
dataset_->rewind();
}
template <typename filterT>
feature_ptr osm_featureset<filterT>::next()
{
feature_ptr feature;
osm_item* cur_item = dataset_->next_item();
if (!cur_item) return feature_ptr();
if (dataset_->current_item_is_node())
{
feature = feature_factory::create(ctx_,feature_id_);
++feature_id_;
double lat = static_cast<osm_node*>(cur_item)->lat;
double lon = static_cast<osm_node*>(cur_item)->lon;
geometry_type* point = new geometry_type(mapnik::Point);
point->move_to(lon, lat);
feature->add_geometry(point);
}
else if (dataset_->current_item_is_way())
{
// Loop until we find a feature which passes the filter
while (cur_item)
{
bounds b = static_cast<osm_way*>(cur_item)->get_bounds();
if (filter_.pass(box2d<double>(b.w, b.s, b.e, b.n))) break;
cur_item = dataset_->next_item();
}
if (!cur_item) return feature_ptr();
if (static_cast<osm_way*>(cur_item)->nodes.size())
{
feature = feature_factory::create(ctx_,feature_id_);
++feature_id_;
geometry_type* geom;
if (static_cast<osm_way*>(cur_item)->is_polygon())
{
geom = new geometry_type(mapnik::Polygon);
}
else
{
geom = new geometry_type(mapnik::LineString);
}
geom->move_to(static_cast<osm_way*>(cur_item)->nodes[0]->lon,
static_cast<osm_way*>(cur_item)->nodes[0]->lat);
for (unsigned int count = 1;
count < static_cast<osm_way*>(cur_item)->nodes.size();
count++)
{
geom->line_to(static_cast<osm_way*>(cur_item)->nodes[count]->lon,
static_cast<osm_way*>(cur_item)->nodes[count]->lat);
}
feature->add_geometry(geom);
}
}
std::set<std::string>::const_iterator itr = attribute_names_.begin();
std::set<std::string>::const_iterator end = attribute_names_.end();
std::map<std::string,std::string>::iterator end_keyvals = cur_item->keyvals.end();
for (; itr != end; itr++)
{
std::map<std::string,std::string>::iterator i = cur_item->keyvals.find(*itr);
if (i != end_keyvals) {
feature->put_new(i->first,tr_->transcode(i->second.c_str()));
} else {
feature->put_new(*itr, "");
}
}
return feature;
}
template <typename filterT>
osm_featureset<filterT>::~osm_featureset() {}
template class osm_featureset<mapnik::filter_in_box>;
template class osm_featureset<mapnik::filter_at_point>;
<commit_msg>Fix crash while processing empty ways in OSM data (e.g. deleted ways).<commit_after>
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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
*
*****************************************************************************/
// stl
#include <iostream>
// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/debug.hpp>
#include "osm_featureset.hpp"
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::geometry_type;
using mapnik::feature_factory;
template <typename filterT>
osm_featureset<filterT>::osm_featureset(const filterT& filter,
osm_dataset* dataset,
const std::set<std::string>&
attribute_names,
std::string const& encoding)
: filter_(filter),
query_ext_(),
tr_(new transcoder(encoding)),
feature_id_(1),
dataset_ (dataset),
attribute_names_ (attribute_names),
ctx_(boost::make_shared<mapnik::context_type>())
{
dataset_->rewind();
}
template <typename filterT>
feature_ptr osm_featureset<filterT>::next()
{
feature_ptr feature;
osm_item* cur_item = dataset_->next_item();
if (!cur_item) return feature_ptr();
if (dataset_->current_item_is_node())
{
feature = feature_factory::create(ctx_, feature_id_);
++feature_id_;
double lat = static_cast<osm_node*>(cur_item)->lat;
double lon = static_cast<osm_node*>(cur_item)->lon;
geometry_type* point = new geometry_type(mapnik::Point);
point->move_to(lon, lat);
feature->add_geometry(point);
}
else if (dataset_->current_item_is_way())
{
// Loop until we find a feature which passes the filter
while (cur_item)
{
bounds b = static_cast<osm_way*>(cur_item)->get_bounds();
if (filter_.pass(box2d<double>(b.w, b.s, b.e, b.n))
&&
static_cast<osm_way*>(cur_item)->nodes.size()) break;
cur_item = dataset_->next_item();
}
if (!cur_item) return feature_ptr();
feature = feature_factory::create(ctx_, feature_id_);
++feature_id_;
geometry_type* geom;
if (static_cast<osm_way*>(cur_item)->is_polygon())
{
geom = new geometry_type(mapnik::Polygon);
}
else
{
geom = new geometry_type(mapnik::LineString);
}
geom->move_to(static_cast<osm_way*>(cur_item)->nodes[0]->lon,
static_cast<osm_way*>(cur_item)->nodes[0]->lat);
for (unsigned int count = 1;
count < static_cast<osm_way*>(cur_item)->nodes.size();
count++)
{
geom->line_to(static_cast<osm_way*>(cur_item)->nodes[count]->lon,
static_cast<osm_way*>(cur_item)->nodes[count]->lat);
}
feature->add_geometry(geom);
} else
{
MAPNIK_LOG_FATAL(osm_featureset) << "Current item is neither node nor way.\n";
}
std::set<std::string>::const_iterator itr = attribute_names_.begin();
std::set<std::string>::const_iterator end = attribute_names_.end();
std::map<std::string,std::string>::iterator end_keyvals = cur_item->keyvals.end();
for (; itr != end; itr++)
{
std::map<std::string,std::string>::iterator i = cur_item->keyvals.find(*itr);
if (i != end_keyvals)
{
feature->put_new(i->first, tr_->transcode(i->second.c_str()));
} else
{
feature->put_new(*itr, "");
}
}
return feature;
}
template <typename filterT>
osm_featureset<filterT>::~osm_featureset() {}
template class osm_featureset<mapnik::filter_in_box>;
template class osm_featureset<mapnik::filter_at_point>;
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001 by Andreas Hfler <andreas.hoefler@gmx.at>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cssysdef.h"
#include "csutil/util.h"
#include "isound/loader.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "../common/soundraw.h"
#include "../common/sndload.h"
CS_IMPLEMENT_PLUGIN
// Microsoft Wav file loader
// support 8 and 16 bits PCM (RIFF)
/* ====================================
short description of wav-file-format
(from www.wotsit.org, look there for details)
====================================
WAV-data is contained within the RIFF-file-format. This file format
consists of headers and "chunks".
A RIFF file has an 8-byte RIFF header.
struct
{
char id[4]; // identifier string = "RIFF"
DWORD len; // remaining length after this header
} riff_hdr;
The riff_hdr is immediately followed by a 4-byte data type identifier.
For .WAV files this is "WAVE" as follows:
char wave_id[4]; // WAVE file identifier = "WAVE"
The remaining file consists of "chunks". A chunk is following:
struct
{
char id[4]; // identifier, e.g. "fmt " or "data"
DWORD len; // remaining chunk length after this header
} chunk_hdr;
The chunk is followed by the data of the chunk.
Unexpected chunks should be allowed (and ignored) within a RIFF-file.
For WAV-files following chunks can be expected:
(only necessary chunks are listed)
WAVE Format Chunk, this has to appear before the WAVE Data Chunk:
struct _FMTchk
{
char chunk_id[4]; // for the format-chunk of wav-files always "fmt "
unsigned long len; // length of this chunk after this 8 bytes of header
unsigned short fmt_tag; // format category of file. 0x0001 = Microsoft PCM
unsigned short channel; // number of channels (1 = mono, 2 = stereo)
unsigned long samples_per_sec; // sampling rate
unsigned long avg_bytes_per_sec; // for buffer estimation
unsigned short blk_align; // data block size
unsigned short bits_per_sample; // sample size (only if Microsoft PCM)
} fmtchk;
WAVE Data Chunk:
struct _WAVchk
{
char chunk_id[4]; // for the data-chunk of wav-files always "data"
unsigned long len; // length of this chunk after this 8 bytes of header
}
====================================
End of short format-description
====================================
*/
class csSoundLoader_WAV : public iSoundLoader
{
public:
SCF_DECLARE_IBASE;
struct eiComponent : public iComponent
{
SCF_DECLARE_EMBEDDED_IBASE(csSoundLoader_WAV);
virtual bool Initialize (iObjectRegistry*) { return true; }
} scfiComponent;
csSoundLoader_WAV(iBase *p) {
SCF_CONSTRUCT_IBASE(p);
SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);
}
virtual csPtr<iSoundData> LoadSound(void *Buffer, uint32 Size);
};
SCF_IMPLEMENT_IBASE(csSoundLoader_WAV)
SCF_IMPLEMENTS_INTERFACE(iSoundLoader)
SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent)
SCF_IMPLEMENT_IBASE_END;
SCF_IMPLEMENT_EMBEDDED_IBASE (csSoundLoader_WAV::eiComponent)
SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END
SCF_IMPLEMENT_FACTORY(csSoundLoader_WAV);
SCF_EXPORT_CLASS_TABLE (sndwav)
SCF_EXPORT_CLASS (csSoundLoader_WAV,
"crystalspace.sound.loader.wav", "WAV Sound Loader")
SCF_EXPORT_CLASS_TABLE_END;
// header of the RIFF-chunk
struct _RIFFchk
{
char riff_id[4]; // for RIFF-files always "RIFF"
unsigned long len; // length of chunk after this 8 bytes of header
char wave_id[4]; // for wav-files always "WAVE"
} riffchk;
// header of the wav-format-chunk
struct _FMTchk
{
char chunk_id[4]; // for the format-chunk of wav-files always "fmt "
unsigned long len; // length of this chunk after this 8 bytes of header
unsigned short fmt_tag;
unsigned short channel;
unsigned long samples_per_sec;
unsigned long avg_bytes_per_sec;
unsigned short blk_align;
unsigned short bits_per_sample;
} fmtchk;
// header of the wav-data-chunk
struct _WAVchk
{
char chunk_id[4]; // for wav-data-chunk this is always "data"
unsigned long len; // length of chunk after this 8 bytes of header
} wavchk;
// helper functions
/// Byte swap 32 bit data.
static inline unsigned long csByteSwap32bit( const unsigned long value )
{
return ((value >> 24 ) & 0x000000FF ) | ((value >> 8) & 0x0000FF00)
| ((value << 8) & 0x00FF0000) | (( value << 24) & 0xFF000000);
}
/// Byte swap 16 bit data.
static inline unsigned short csByteSwap16bit( const unsigned short value )
{
return (( value >> 8 ) & 0x000000FF ) | (( value << 8 ) & 0x0000FF00 );
}
static inline void csByteSwap16BitBuffer (uint16* ptr, size_t count)
{
for (; count > 0; --count, ++ptr)
{
*ptr = csByteSwap16bit (*ptr);
}
}
static inline void csByteSwap32bitBuffer (uint32* ptr, size_t count)
{
for (; count > 0; --count, ++ptr)
{
*ptr = csByteSwap32bit (*ptr);
}
}
csPtr<iSoundData>
csSoundLoader_WAV::LoadSound (void* databuf, uint32 size)
{
uint8* buf = (uint8*) databuf;
csSoundFormat format;
char* data = NULL;
int index = 0;
// check if this is a valid wav-file
// check if file has the size to be able to contain all necessary chunks
if (size < (sizeof (riffchk) + sizeof (fmtchk) + sizeof (wavchk)))
return 0;
// copy RIFF-header
if (memcpy(&riffchk, &buf[0], sizeof (riffchk)) == NULL)
return 0;
// check RIFF-header
if (memcmp (riffchk.riff_id, "RIFF", 4) != 0)
return 0;
// check WAVE-id
if (memcmp (riffchk.wave_id, "WAVE", 4) != 0)
return 0;
// find format-chunk, copy it into struct and make corrections if necessary
// set index after riff-header to the first chunk inside
index += sizeof (riffchk);
// find format-chunk
bool found = false; // true, if format-chunk was found
for ( ;
(found == false) && ((index + sizeof (fmtchk)) < size) ;
// +8, because chunk_id + len are not counted in len
index += fmtchk.len + 8
)
{
if (memcpy(&fmtchk, &buf[index], sizeof (fmtchk)) == NULL)
return 0;
if (memcmp(fmtchk.chunk_id, "fmt ", 4) == 0)
found = true;
// correct length of chunk on big endian system
#ifdef CS_BIG_ENDIAN // @@@ correct fmtchk.len on big-endian systems?
fmtchk.len = csByteSwap32bit (fmtchk.len);
#endif
}
// no format-chunk found -> no valid file
if (found == false)
return 0;
// correct the chunk, if under big-endian system
#ifdef CS_BIG_ENDIAN // @@@ is this correct?
fmtchk.fmt_tag = csByteSwap16bit (fmtchk.fmt_tag);
fmtchk.channel = csByteSwap16bit (fmtchk.channel);
fmtchk.samples_per_sec = csByteSwap32bit (fmtchk.samples_per_sec);
fmtchk.avg_bytes_per_sec = csByteSwap32bit (fmtchk.avg_bytes_per_sec);
fmtchk.blk_align = csByteSwap16bit (fmtchk.blk_align);
fmtchk.bits_per_sample = csByteSwap16bit (fmtchk.bits_per_sample);
#endif // CS_BIG_ENDIAN
// check format of file
// only 1 or 2 channels are valid
if (!((fmtchk.channel == 1) || (fmtchk.channel == 2)))
return 0;
// only Microsoft PCM wave files are valid
if (!(fmtchk.fmt_tag == 0x0001))
return 0;
// find wav-data-chunk
found = false; // true, if wav-data-chunk was found
for ( ;
(found == false) && ((index + sizeof (wavchk)) < size) ;
// +8, because chunk_id and len are not counted in len
index += wavchk.len + 8
)
{
if (memcpy(&wavchk, &buf[index], sizeof (wavchk)) == NULL)
return 0;
if (memcmp(wavchk.chunk_id, "data", 4) == 0)
found = true;
// correct length of chunk on big endian systems
#ifdef CS_BIG_ENDIAN // @@@ correct wavchk.len on big-endian systems?
wavchk.len = csByteSwap32bit (wavchk.len);
#endif
}
// no wav-data-chunk found -> no valid file
if (found == false)
return 0;
// index points now after wav-data, so correct it
index -= wavchk.len;
// make new buffer, which contains the wav-data
data = new char[wavchk.len];
// copy the wav-data into the buffer
if (memcpy(data, &buf[index], wavchk.len)==NULL)
{
delete[] data;
return 0;
}
#ifdef CS_BIG_ENDIAN
if (fmtchk.bits_per_sample == 16)
csByteSwap16bitBuffer ( (unsigned short*)data, wavchk.len / 2);
#endif // CS_BIG_ENDIAN
// set up format for csSoundDataRaw
format.Freq = fmtchk.samples_per_sec;
format.Bits = fmtchk.bits_per_sample;
format.Channels = fmtchk.channel;
// set up sound-buffer
int n = (fmtchk.bits_per_sample == 16 ? 2 : 1) * fmtchk.channel;
csSoundDataRaw* rawSound = new csSoundDataRaw(NULL, data,
(wavchk.len/n)-1, format);
return rawSound;
}
<commit_msg>fixed a problem on macosx<commit_after>/*
Copyright (C) 2001 by Andreas Hfler <andreas.hoefler@gmx.at>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cssysdef.h"
#include "csutil/util.h"
#include "isound/loader.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "../common/soundraw.h"
#include "../common/sndload.h"
CS_IMPLEMENT_PLUGIN
// Microsoft Wav file loader
// support 8 and 16 bits PCM (RIFF)
/* ====================================
short description of wav-file-format
(from www.wotsit.org, look there for details)
====================================
WAV-data is contained within the RIFF-file-format. This file format
consists of headers and "chunks".
A RIFF file has an 8-byte RIFF header.
struct
{
char id[4]; // identifier string = "RIFF"
DWORD len; // remaining length after this header
} riff_hdr;
The riff_hdr is immediately followed by a 4-byte data type identifier.
For .WAV files this is "WAVE" as follows:
char wave_id[4]; // WAVE file identifier = "WAVE"
The remaining file consists of "chunks". A chunk is following:
struct
{
char id[4]; // identifier, e.g. "fmt " or "data"
DWORD len; // remaining chunk length after this header
} chunk_hdr;
The chunk is followed by the data of the chunk.
Unexpected chunks should be allowed (and ignored) within a RIFF-file.
For WAV-files following chunks can be expected:
(only necessary chunks are listed)
WAVE Format Chunk, this has to appear before the WAVE Data Chunk:
struct _FMTchk
{
char chunk_id[4]; // for the format-chunk of wav-files always "fmt "
unsigned long len; // length of this chunk after this 8 bytes of header
unsigned short fmt_tag; // format category of file. 0x0001 = Microsoft PCM
unsigned short channel; // number of channels (1 = mono, 2 = stereo)
unsigned long samples_per_sec; // sampling rate
unsigned long avg_bytes_per_sec; // for buffer estimation
unsigned short blk_align; // data block size
unsigned short bits_per_sample; // sample size (only if Microsoft PCM)
} fmtchk;
WAVE Data Chunk:
struct _WAVchk
{
char chunk_id[4]; // for the data-chunk of wav-files always "data"
unsigned long len; // length of this chunk after this 8 bytes of header
}
====================================
End of short format-description
====================================
*/
class csSoundLoader_WAV : public iSoundLoader
{
public:
SCF_DECLARE_IBASE;
struct eiComponent : public iComponent
{
SCF_DECLARE_EMBEDDED_IBASE(csSoundLoader_WAV);
virtual bool Initialize (iObjectRegistry*) { return true; }
} scfiComponent;
csSoundLoader_WAV(iBase *p) {
SCF_CONSTRUCT_IBASE(p);
SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);
}
virtual csPtr<iSoundData> LoadSound(void *Buffer, uint32 Size);
};
SCF_IMPLEMENT_IBASE(csSoundLoader_WAV)
SCF_IMPLEMENTS_INTERFACE(iSoundLoader)
SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent)
SCF_IMPLEMENT_IBASE_END;
SCF_IMPLEMENT_EMBEDDED_IBASE (csSoundLoader_WAV::eiComponent)
SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END
SCF_IMPLEMENT_FACTORY(csSoundLoader_WAV);
SCF_EXPORT_CLASS_TABLE (sndwav)
SCF_EXPORT_CLASS (csSoundLoader_WAV,
"crystalspace.sound.loader.wav", "WAV Sound Loader")
SCF_EXPORT_CLASS_TABLE_END;
// header of the RIFF-chunk
struct _RIFFchk
{
char riff_id[4]; // for RIFF-files always "RIFF"
unsigned long len; // length of chunk after this 8 bytes of header
char wave_id[4]; // for wav-files always "WAVE"
} riffchk;
// header of the wav-format-chunk
struct _FMTchk
{
char chunk_id[4]; // for the format-chunk of wav-files always "fmt "
unsigned long len; // length of this chunk after this 8 bytes of header
unsigned short fmt_tag;
unsigned short channel;
unsigned long samples_per_sec;
unsigned long avg_bytes_per_sec;
unsigned short blk_align;
unsigned short bits_per_sample;
} fmtchk;
// header of the wav-data-chunk
struct _WAVchk
{
char chunk_id[4]; // for wav-data-chunk this is always "data"
unsigned long len; // length of chunk after this 8 bytes of header
} wavchk;
// helper functions
/// Byte swap 32 bit data.
static inline unsigned long csByteSwap32bit( const unsigned long value )
{
return ((value >> 24 ) & 0x000000FF ) | ((value >> 8) & 0x0000FF00)
| ((value << 8) & 0x00FF0000) | (( value << 24) & 0xFF000000);
}
/// Byte swap 16 bit data.
static inline unsigned short csByteSwap16bit( const unsigned short value )
{
return (( value >> 8 ) & 0x000000FF ) | (( value << 8 ) & 0x0000FF00 );
}
static inline void csByteSwap16bitBuffer (uint16* ptr, size_t count)
{
for (; count > 0; --count, ++ptr)
{
*ptr = csByteSwap16bit (*ptr);
}
}
static inline void csByteSwap32bitBuffer (uint32* ptr, size_t count)
{
for (; count > 0; --count, ++ptr)
{
*ptr = csByteSwap32bit (*ptr);
}
}
csPtr<iSoundData>
csSoundLoader_WAV::LoadSound (void* databuf, uint32 size)
{
uint8* buf = (uint8*) databuf;
csSoundFormat format;
char* data = NULL;
int index = 0;
// check if this is a valid wav-file
// check if file has the size to be able to contain all necessary chunks
if (size < (sizeof (riffchk) + sizeof (fmtchk) + sizeof (wavchk)))
return 0;
// copy RIFF-header
if (memcpy(&riffchk, &buf[0], sizeof (riffchk)) == NULL)
return 0;
// check RIFF-header
if (memcmp (riffchk.riff_id, "RIFF", 4) != 0)
return 0;
// check WAVE-id
if (memcmp (riffchk.wave_id, "WAVE", 4) != 0)
return 0;
// find format-chunk, copy it into struct and make corrections if necessary
// set index after riff-header to the first chunk inside
index += sizeof (riffchk);
// find format-chunk
bool found = false; // true, if format-chunk was found
for ( ;
(found == false) && ((index + sizeof (fmtchk)) < size) ;
// +8, because chunk_id + len are not counted in len
index += fmtchk.len + 8
)
{
if (memcpy(&fmtchk, &buf[index], sizeof (fmtchk)) == NULL)
return 0;
if (memcmp(fmtchk.chunk_id, "fmt ", 4) == 0)
found = true;
// correct length of chunk on big endian system
#ifdef CS_BIG_ENDIAN // @@@ correct fmtchk.len on big-endian systems?
fmtchk.len = csByteSwap32bit (fmtchk.len);
#endif
}
// no format-chunk found -> no valid file
if (found == false)
return 0;
// correct the chunk, if under big-endian system
#ifdef CS_BIG_ENDIAN // @@@ is this correct?
fmtchk.fmt_tag = csByteSwap16bit (fmtchk.fmt_tag);
fmtchk.channel = csByteSwap16bit (fmtchk.channel);
fmtchk.samples_per_sec = csByteSwap32bit (fmtchk.samples_per_sec);
fmtchk.avg_bytes_per_sec = csByteSwap32bit (fmtchk.avg_bytes_per_sec);
fmtchk.blk_align = csByteSwap16bit (fmtchk.blk_align);
fmtchk.bits_per_sample = csByteSwap16bit (fmtchk.bits_per_sample);
#endif // CS_BIG_ENDIAN
// check format of file
// only 1 or 2 channels are valid
if (!((fmtchk.channel == 1) || (fmtchk.channel == 2)))
return 0;
// only Microsoft PCM wave files are valid
if (!(fmtchk.fmt_tag == 0x0001))
return 0;
// find wav-data-chunk
found = false; // true, if wav-data-chunk was found
for ( ;
(found == false) && ((index + sizeof (wavchk)) < size) ;
// +8, because chunk_id and len are not counted in len
index += wavchk.len + 8
)
{
if (memcpy(&wavchk, &buf[index], sizeof (wavchk)) == NULL)
return 0;
if (memcmp(wavchk.chunk_id, "data", 4) == 0)
found = true;
// correct length of chunk on big endian systems
#ifdef CS_BIG_ENDIAN // @@@ correct wavchk.len on big-endian systems?
wavchk.len = csByteSwap32bit (wavchk.len);
#endif
}
// no wav-data-chunk found -> no valid file
if (found == false)
return 0;
// index points now after wav-data, so correct it
index -= wavchk.len;
// make new buffer, which contains the wav-data
data = new char[wavchk.len];
// copy the wav-data into the buffer
if (memcpy(data, &buf[index], wavchk.len)==NULL)
{
delete[] data;
return 0;
}
#ifdef CS_BIG_ENDIAN
if (fmtchk.bits_per_sample == 16)
csByteSwap16bitBuffer ( (unsigned short*)data, wavchk.len / 2);
#endif // CS_BIG_ENDIAN
// set up format for csSoundDataRaw
format.Freq = fmtchk.samples_per_sec;
format.Bits = fmtchk.bits_per_sample;
format.Channels = fmtchk.channel;
// set up sound-buffer
int n = (fmtchk.bits_per_sample == 16 ? 2 : 1) * fmtchk.channel;
csSoundDataRaw* rawSound = new csSoundDataRaw(NULL, data,
(wavchk.len/n)-1, format);
return rawSound;
}
<|endoftext|> |
<commit_before>/*
This file is part of libhttpserver
Copyright (C) 2011 Sebastiano Merlino
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
*/
#if !defined (_HTTPSERVER_HPP_INSIDE_) && !defined (HTTPSERVER_COMPILATION)
#error "Only <httpserver.hpp> or <httpserverpp> can be included directly."
#endif
#ifndef _HTTPUTILS_H_
#define _HTTPUTILS_H_
#include <microhttpd.h>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <exception>
#ifdef HAVE_GNUTLS
#include <gnutls/gnutls.h>
#endif
#define DEFAULT_MASK_VALUE 0xFFFF
namespace httpserver {
namespace http {
class bad_ip_format_exception: public std::exception
{
virtual const char* what() const throw()
{
return "IP is badly formatted!";
}
};
class file_access_exception: public std::exception
{
virtual const char* what() const throw()
{
return "Unable to open file!";
}
};
class http_utils
{
public:
enum cred_type_T
{
NONE = -1
#ifdef HAVE_GNUTLS
,CERTIFICATE = GNUTLS_CRD_CERTIFICATE,
ANON = GNUTLS_CRD_ANON,
SRP = GNUTLS_CRD_SRP,
PSK = GNUTLS_CRD_PSK,
IA = GNUTLS_CRD_IA
#endif
};
enum start_method_T
{
INTERNAL_SELECT = MHD_NO_FLAG,
THREADS = MHD_USE_THREAD_PER_CONNECTION,
POLL = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL
};
enum policy_T
{
ACCEPT,
REJECT
};
enum IP_version_T
{
IPV4 = 4, IPV6 = 16
};
static const short http_method_connect_code;
static const short http_method_delete_code;
static const short http_method_get_code;
static const short http_method_head_code;
static const short http_method_options_code;
static const short http_method_post_code;
static const short http_method_put_code;
static const short http_method_trace_code;
static const short http_method_unknown_code;
static const int http_continue;
static const int http_switching_protocol;
static const int http_processing;
static const int http_ok;
static const int http_created;
static const int http_accepted;
static const int http_non_authoritative_information;
static const int http_no_content;
static const int http_reset_content;
static const int http_partial_content;
static const int http_multi_status;
static const int http_multiple_choices;
static const int http_moved_permanently;
static const int http_found;
static const int http_see_other;
static const int http_not_modified;
static const int http_use_proxy;
static const int http_switch_proxy;
static const int http_temporary_redirect;
static const int http_bad_request;
static const int http_unauthorized;
static const int http_payment_required;
static const int http_forbidden;
static const int http_not_found;
static const int http_method_not_allowed;
static const int http_method_not_acceptable;
static const int http_proxy_authentication_required;
static const int http_request_timeout;
static const int http_conflict;
static const int http_gone;
static const int http_length_required;
static const int http_precondition_failed;
static const int http_request_entity_too_large;
static const int http_request_uri_too_long;
static const int http_unsupported_media_type;
static const int http_requested_range_not_satisfiable;
static const int http_expectation_failed;
static const int http_unprocessable_entity;
static const int http_locked;
static const int http_failed_dependency;
static const int http_unordered_collection;
static const int http_upgrade_required;
static const int http_retry_with;
static const int http_internal_server_error;
static const int http_not_implemented;
static const int http_bad_gateway;
static const int http_service_unavailable;
static const int http_gateway_timeout;
static const int http_version_not_supported;
static const int http_variant_also_negotiated;
static const int http_insufficient_storage;
static const int http_bandwidth_limit_exceeded;
static const int http_not_extended;
static const int shoutcast_response;
/* See also: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html */
static const std::string http_header_accept;
static const std::string http_header_accept_charset;
static const std::string http_header_accept_encoding;
static const std::string http_header_accept_language;
static const std::string http_header_accept_ranges;
static const std::string http_header_age;
static const std::string http_header_allow;
static const std::string http_header_authorization;
static const std::string http_header_cache_control;
static const std::string http_header_connection;
static const std::string http_header_content_encoding;
static const std::string http_header_content_language;
static const std::string http_header_content_length;
static const std::string http_header_content_location;
static const std::string http_header_content_md5;
static const std::string http_header_content_range;
static const std::string http_header_content_type;
static const std::string http_header_date;
static const std::string http_header_etag;
static const std::string http_header_expect;
static const std::string http_header_expires;
static const std::string http_header_from;
static const std::string http_header_host;
static const std::string http_header_if_match;
static const std::string http_header_if_modified_since;
static const std::string http_header_if_none_match;
static const std::string http_header_if_range;
static const std::string http_header_if_unmodified_since;
static const std::string http_header_last_modified;
static const std::string http_header_location;
static const std::string http_header_max_forwards;
static const std::string http_header_pragma;
static const std::string http_header_proxy_authenticate;
static const std::string http_header_proxy_authentication;
static const std::string http_header_range;
static const std::string http_header_referer;
static const std::string http_header_retry_after;
static const std::string http_header_server;
static const std::string http_header_te;
static const std::string http_header_trailer;
static const std::string http_header_transfer_encoding;
static const std::string http_header_upgrade;
static const std::string http_header_user_agent;
static const std::string http_header_vary;
static const std::string http_header_via;
static const std::string http_header_warning;
static const std::string http_header_www_authenticate;
static const std::string http_version_1_0;
static const std::string http_version_1_1;
static const std::string http_method_connect;
static const std::string http_method_delete;
static const std::string http_method_head;
static const std::string http_method_get;
static const std::string http_method_options;
static const std::string http_method_post;
static const std::string http_method_put;
static const std::string http_method_trace;
static const std::string http_post_encoding_form_urlencoded;
static const std::string http_post_encoding_multipart_formdata;
static size_t tokenize_url(const std::string&,
std::vector<std::string>& result, const char separator = '/'
);
static void standardize_url(const std::string&, std::string& result);
};
#define COMPARATOR(x, y, op) \
{ \
size_t l1 = (x).size();\
size_t l2 = (y).size();\
if (l1 < l2) return true;\
if (l1 > l2) return false;\
\
for (size_t n = 0; n < l1; n++)\
{\
char xc = op((x)[n]);\
char yc = op((y)[n]);\
if (xc < yc) return true;\
if (xc > yc) return false;\
}\
return false;\
}
class header_comparator {
public:
/**
* Operator used to compare strings.
* @param first string
* @param second string
**/
bool operator()(const std::string& x,const std::string& y) const
{
COMPARATOR(x, y, toupper);
}
};
/**
* Operator Class that is used to compare two strings. The comparison can be sensitive or insensitive.
* The default comparison is case sensitive. To obtain insensitive comparison you have to pass in
* compilation phase the flag CASE_INSENSITIVE to the preprocessor.
**/
class arg_comparator {
public:
/**
* Operator used to compare strings.
* @param first string
* @param second string
**/
bool operator()(const std::string& x,const std::string& y) const
{
#ifdef CASE_INSENSITIVE
COMPARATOR(x, y, toupper);
#else
COMPARATOR(x, y, );
#endif
}
};
struct ip_representation
{
http_utils::IP_version_T ip_version;
unsigned short pieces[16];
unsigned int mask:16;
ip_representation(http_utils::IP_version_T ip_version) :
ip_version(ip_version)
{
mask = DEFAULT_MASK_VALUE;
std::fill(pieces, pieces + 16, 0);
}
ip_representation(const std::string& ip);
ip_representation(const struct sockaddr* ip);
bool operator <(const ip_representation& b) const;
const int weight() const
{
//variable-precision SWAR algorithm
register unsigned int x = mask;
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
};
/**
* Method used to get an ip in form of string from a sockaddr structure
* @param sa The sockaddr object to find the ip address from
* @param maxlen Maxlen of the address (automatically discovered if not passed)
* @return string containing the ip address
**/
void get_ip_str(const struct sockaddr *sa,
std::string& result, socklen_t maxlen = 0
);
std::string get_ip_str_new(const struct sockaddr* sa,
socklen_t maxlen = 0
);
/**
* Method used to get a port from a sockaddr
* @param sa The sockaddr object to find the port from
* @return short representing the port
**/
short get_port(const struct sockaddr* sa);
/**
* Process escape sequences ('+'=space, %HH) Updates val in place; the
* result should be UTF-8 encoded and cannot be larger than the input.
* The result must also still be 0-terminated.
*
* @param val the string to unescape
* @return length of the resulting val (strlen(val) maybe
* shorter afterwards due to elimination of escape sequences)
*/
size_t http_unescape (char *val);
const struct sockaddr str_to_ip(const std::string& src);
char* load_file (const char *filename);
size_t load_file (const char* filename, char** content);
struct httpserver_ska
{
httpserver_ska(struct sockaddr* addr):
addr(addr),
ip(get_ip_str_new(addr)),
port(get_port(addr))
{
}
httpserver_ska(): addr(0x0) { }
httpserver_ska(const httpserver_ska& o): addr(o.addr) { }
bool operator<(const httpserver_ska& o) const
{
if(this->ip < o.ip)
return true;
else if(this->ip > o.ip)
return false;
else if(this->port < o.port)
return true;
else
return false;
}
httpserver_ska& operator=(const httpserver_ska& o)
{
this->addr = o.addr;
return *this;
}
struct sockaddr* addr;
std::string ip;
int port;
};
};
};
#endif
<commit_msg>Solved some problems with comet messages' indexing<commit_after>/*
This file is part of libhttpserver
Copyright (C) 2011 Sebastiano Merlino
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
*/
#if !defined (_HTTPSERVER_HPP_INSIDE_) && !defined (HTTPSERVER_COMPILATION)
#error "Only <httpserver.hpp> or <httpserverpp> can be included directly."
#endif
#ifndef _HTTPUTILS_H_
#define _HTTPUTILS_H_
#include <microhttpd.h>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <exception>
#ifdef HAVE_GNUTLS
#include <gnutls/gnutls.h>
#endif
#define DEFAULT_MASK_VALUE 0xFFFF
namespace httpserver {
namespace http {
class bad_ip_format_exception: public std::exception
{
virtual const char* what() const throw()
{
return "IP is badly formatted!";
}
};
class file_access_exception: public std::exception
{
virtual const char* what() const throw()
{
return "Unable to open file!";
}
};
class http_utils
{
public:
enum cred_type_T
{
NONE = -1
#ifdef HAVE_GNUTLS
,CERTIFICATE = GNUTLS_CRD_CERTIFICATE,
ANON = GNUTLS_CRD_ANON,
SRP = GNUTLS_CRD_SRP,
PSK = GNUTLS_CRD_PSK,
IA = GNUTLS_CRD_IA
#endif
};
enum start_method_T
{
INTERNAL_SELECT = MHD_NO_FLAG,
THREADS = MHD_USE_THREAD_PER_CONNECTION,
POLL = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL
};
enum policy_T
{
ACCEPT,
REJECT
};
enum IP_version_T
{
IPV4 = 4, IPV6 = 16
};
static const short http_method_connect_code;
static const short http_method_delete_code;
static const short http_method_get_code;
static const short http_method_head_code;
static const short http_method_options_code;
static const short http_method_post_code;
static const short http_method_put_code;
static const short http_method_trace_code;
static const short http_method_unknown_code;
static const int http_continue;
static const int http_switching_protocol;
static const int http_processing;
static const int http_ok;
static const int http_created;
static const int http_accepted;
static const int http_non_authoritative_information;
static const int http_no_content;
static const int http_reset_content;
static const int http_partial_content;
static const int http_multi_status;
static const int http_multiple_choices;
static const int http_moved_permanently;
static const int http_found;
static const int http_see_other;
static const int http_not_modified;
static const int http_use_proxy;
static const int http_switch_proxy;
static const int http_temporary_redirect;
static const int http_bad_request;
static const int http_unauthorized;
static const int http_payment_required;
static const int http_forbidden;
static const int http_not_found;
static const int http_method_not_allowed;
static const int http_method_not_acceptable;
static const int http_proxy_authentication_required;
static const int http_request_timeout;
static const int http_conflict;
static const int http_gone;
static const int http_length_required;
static const int http_precondition_failed;
static const int http_request_entity_too_large;
static const int http_request_uri_too_long;
static const int http_unsupported_media_type;
static const int http_requested_range_not_satisfiable;
static const int http_expectation_failed;
static const int http_unprocessable_entity;
static const int http_locked;
static const int http_failed_dependency;
static const int http_unordered_collection;
static const int http_upgrade_required;
static const int http_retry_with;
static const int http_internal_server_error;
static const int http_not_implemented;
static const int http_bad_gateway;
static const int http_service_unavailable;
static const int http_gateway_timeout;
static const int http_version_not_supported;
static const int http_variant_also_negotiated;
static const int http_insufficient_storage;
static const int http_bandwidth_limit_exceeded;
static const int http_not_extended;
static const int shoutcast_response;
/* See also: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html */
static const std::string http_header_accept;
static const std::string http_header_accept_charset;
static const std::string http_header_accept_encoding;
static const std::string http_header_accept_language;
static const std::string http_header_accept_ranges;
static const std::string http_header_age;
static const std::string http_header_allow;
static const std::string http_header_authorization;
static const std::string http_header_cache_control;
static const std::string http_header_connection;
static const std::string http_header_content_encoding;
static const std::string http_header_content_language;
static const std::string http_header_content_length;
static const std::string http_header_content_location;
static const std::string http_header_content_md5;
static const std::string http_header_content_range;
static const std::string http_header_content_type;
static const std::string http_header_date;
static const std::string http_header_etag;
static const std::string http_header_expect;
static const std::string http_header_expires;
static const std::string http_header_from;
static const std::string http_header_host;
static const std::string http_header_if_match;
static const std::string http_header_if_modified_since;
static const std::string http_header_if_none_match;
static const std::string http_header_if_range;
static const std::string http_header_if_unmodified_since;
static const std::string http_header_last_modified;
static const std::string http_header_location;
static const std::string http_header_max_forwards;
static const std::string http_header_pragma;
static const std::string http_header_proxy_authenticate;
static const std::string http_header_proxy_authentication;
static const std::string http_header_range;
static const std::string http_header_referer;
static const std::string http_header_retry_after;
static const std::string http_header_server;
static const std::string http_header_te;
static const std::string http_header_trailer;
static const std::string http_header_transfer_encoding;
static const std::string http_header_upgrade;
static const std::string http_header_user_agent;
static const std::string http_header_vary;
static const std::string http_header_via;
static const std::string http_header_warning;
static const std::string http_header_www_authenticate;
static const std::string http_version_1_0;
static const std::string http_version_1_1;
static const std::string http_method_connect;
static const std::string http_method_delete;
static const std::string http_method_head;
static const std::string http_method_get;
static const std::string http_method_options;
static const std::string http_method_post;
static const std::string http_method_put;
static const std::string http_method_trace;
static const std::string http_post_encoding_form_urlencoded;
static const std::string http_post_encoding_multipart_formdata;
static size_t tokenize_url(const std::string&,
std::vector<std::string>& result, const char separator = '/'
);
static void standardize_url(const std::string&, std::string& result);
};
#define COMPARATOR(x, y, op) \
{ \
size_t l1 = (x).size();\
size_t l2 = (y).size();\
if (l1 < l2) return true;\
if (l1 > l2) return false;\
\
for (size_t n = 0; n < l1; n++)\
{\
char xc = op((x)[n]);\
char yc = op((y)[n]);\
if (xc < yc) return true;\
if (xc > yc) return false;\
}\
return false;\
}
class header_comparator {
public:
/**
* Operator used to compare strings.
* @param first string
* @param second string
**/
bool operator()(const std::string& x,const std::string& y) const
{
COMPARATOR(x, y, toupper);
}
};
/**
* Operator Class that is used to compare two strings. The comparison can be sensitive or insensitive.
* The default comparison is case sensitive. To obtain insensitive comparison you have to pass in
* compilation phase the flag CASE_INSENSITIVE to the preprocessor.
**/
class arg_comparator {
public:
/**
* Operator used to compare strings.
* @param first string
* @param second string
**/
bool operator()(const std::string& x,const std::string& y) const
{
#ifdef CASE_INSENSITIVE
COMPARATOR(x, y, toupper);
#else
COMPARATOR(x, y, );
#endif
}
};
struct ip_representation
{
http_utils::IP_version_T ip_version;
unsigned short pieces[16];
unsigned int mask:16;
ip_representation(http_utils::IP_version_T ip_version) :
ip_version(ip_version)
{
mask = DEFAULT_MASK_VALUE;
std::fill(pieces, pieces + 16, 0);
}
ip_representation(const std::string& ip);
ip_representation(const struct sockaddr* ip);
bool operator <(const ip_representation& b) const;
const int weight() const
{
//variable-precision SWAR algorithm
register unsigned int x = mask;
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
};
/**
* Method used to get an ip in form of string from a sockaddr structure
* @param sa The sockaddr object to find the ip address from
* @param maxlen Maxlen of the address (automatically discovered if not passed)
* @return string containing the ip address
**/
void get_ip_str(const struct sockaddr *sa,
std::string& result, socklen_t maxlen = 0
);
std::string get_ip_str_new(const struct sockaddr* sa,
socklen_t maxlen = 0
);
/**
* Method used to get a port from a sockaddr
* @param sa The sockaddr object to find the port from
* @return short representing the port
**/
short get_port(const struct sockaddr* sa);
/**
* Process escape sequences ('+'=space, %HH) Updates val in place; the
* result should be UTF-8 encoded and cannot be larger than the input.
* The result must also still be 0-terminated.
*
* @param val the string to unescape
* @return length of the resulting val (strlen(val) maybe
* shorter afterwards due to elimination of escape sequences)
*/
size_t http_unescape (char *val);
const struct sockaddr str_to_ip(const std::string& src);
char* load_file (const char *filename);
size_t load_file (const char* filename, char** content);
struct httpserver_ska
{
httpserver_ska(struct sockaddr* addr):
addr(addr),
ip(get_ip_str_new(addr)),
port(get_port(addr))
{
}
httpserver_ska(): addr(0x0) { }
httpserver_ska(const httpserver_ska& o):
addr(o.addr),
ip(o.ip),
port(o.port)
{
}
bool operator<(const httpserver_ska& o) const
{
if(this->ip < o.ip)
return true;
else if(this->ip > o.ip)
return false;
else if(this->port < o.port)
return true;
else
return false;
}
httpserver_ska& operator=(const httpserver_ska& o)
{
this->addr = o.addr;
this->ip = o.ip;
this->port = o.port;
return *this;
}
httpserver_ska& operator=(struct sockaddr* addr)
{
this->addr = addr;
this->ip = get_ip_str_new(addr);
this->port = get_port(addr);
return *this;
}
struct sockaddr* addr;
std::string ip;
int port;
};
};
};
#endif
<|endoftext|> |
<commit_before>#include "configserver.h"
// POSIX
#include <fcntl.h>
// POSIX++
#include <cstdio>
#include <climits>
// PDTK
#include <cxxutils/syslogstream.h>
#include <specialized/procstat.h>
#define CONFIG_PATH "/etc/sxconfig"
#define REQUIRED_GROUPNAME "config"
static const char* configfilename(const char* base)
{
// construct config filename
static char name[PATH_MAX];
std::memset(name, 0, PATH_MAX);
if(std::snprintf(name, PATH_MAX, "%s/%s.conf", CONFIG_PATH, base) == posix::error_response) // I don't how this could fail
return nullptr; // unable to build config filename
return name;
}
static bool readconfig(const char* base, std::string& buffer)
{
const char* name = configfilename(base);
std::FILE* file = std::fopen(name, "a+b");
if(file == nullptr)
{
posix::syslog << "unable to open file: " << name << " : " << std::strerror(errno) << posix::eom;
return false;
}
buffer.resize(std::ftell(file), '\n');
if(buffer.size())
{
std::rewind(file);
std::fread(const_cast<char*>(buffer.data()), sizeof(std::string::value_type), buffer.size(), file);
}
std::fclose(file);
return true;
}
ConfigServer::ConfigServer(void) noexcept
{
Object::connect(newPeerRequest , this, &ConfigServer::request);
Object::connect(newPeerMessage , this, &ConfigServer::receive);
Object::connect(disconnectedPeer, this, &ConfigServer::removePeer);
}
ConfigServer::~ConfigServer(void) noexcept
{
for(auto& confpair : m_configfiles)
Object::disconnect(confpair.second.fd); // disconnect filesystem monitor
}
void ConfigServer::setCall(posix::fd_t socket, std::string& key, std::string& value) noexcept
{
int errcode = posix::success_response;
auto configfile = m_configfiles.find(socket);
if(configfile == m_configfiles.end())
errcode = int(std::errc::io_error); // not a valid key!
else
configfile->second.config.getNode(key)->value = value;
setReturn(socket, errcode);
}
void ConfigServer::getCall(posix::fd_t socket, std::string& key) noexcept
{
int errcode = posix::success_response;
std::list<std::string> children;
std::string value;
auto configfile = m_configfiles.find(socket);
if(configfile != m_configfiles.end())
errcode = int(std::errc::io_error); // no config file for socket
else
{
auto node = configfile->second.config.findNode(key);
if(node == nullptr)
errcode = int(std::errc::invalid_argument); // node doesn't exist
else
{
switch(node->type)
{
case node_t::type_e::array:
case node_t::type_e::multisection:
case node_t::type_e::section:
for(const auto& child : node->children)
children.push_back(child.first);
case node_t::type_e::invalid:
case node_t::type_e::value:
case node_t::type_e::string:
value = node->value;
}
}
}
getReturn(socket, errcode, value, children);
}
void ConfigServer::unsetCall(posix::fd_t socket, std::string& key) noexcept
{
int errcode = posix::success_response;
auto configfile = m_configfiles.find(socket);
if(configfile == m_configfiles.end())
errcode = int(std::errc::io_error); // no such config file!
else
{
posix::size_t offset = key.find_last_of('/');
auto node = configfile->second.config.findNode(key.substr(0, offset)); // look for parent node
if(node == nullptr)
errcode = int(std::errc::invalid_argument);
else
node->children.erase(key.substr(offset + 1)); // erase child node if it exists
}
unsetReturn(socket, errcode);
}
bool ConfigServer::peerChooser(posix::fd_t socket, const proccred_t& cred) noexcept
{
if(!posix::useringroup(REQUIRED_GROUPNAME, posix::getusername(cred.uid)))
return false;
process_state_t state;
if(::procstat(cred.pid, &state) == posix::error_response) // get state information about the connecting process
return false; // unable to get state
auto endpoint = m_endpoints.find(cred.pid);
if(endpoint == m_endpoints.end() || // if no connection exists OR
!peerData(endpoint->second)) // if old connection is mysteriously gone (can this happen?)
{
std::string buffer;
const char* confname = configfilename(state.name.c_str());
readconfig(confname, buffer);
posix::chown(confname, ::getuid(), cred.gid); // reset ownership
posix::chmod(confname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); // reset permissions
auto& conffile = m_configfiles[socket];
conffile.fd = EventBackend::watch(confname, EventFlags::FileMod);
conffile.config.write(buffer);
Object::connect(conffile.fd, this, &ConfigServer::fileUpdated);
m_endpoints[cred.pid] = socket; // insert or assign new value
return true;
}
return false; // reject multiple connections from one endpoint
}
void ConfigServer::fileUpdated(posix::fd_t file, EventData_t data) noexcept
{
(void)data;
posix::fd_t socket = 0;
for(auto& conffile : m_configfiles)
if(conffile.second.fd == file)
configUpdated(socket = conffile.first);
if(socket)
for(auto& endpoint : m_endpoints)
if(endpoint.second == socket)
std::printf("notify pid: %i\n", endpoint.first);
}
void ConfigServer::removePeer(posix::fd_t socket) noexcept
{
auto configfile = m_configfiles.find(socket);
if(configfile != m_configfiles.end())
{
Object::disconnect(configfile->second.fd);
m_configfiles.erase(configfile);
for(auto endpoint : m_endpoints)
if(socket == endpoint.second)
{ m_endpoints.erase(endpoint.first); break; }
}
}
void ConfigServer::request(posix::fd_t socket, posix::sockaddr_t addr, proccred_t cred) noexcept
{
(void)addr;
if(peerChooser(socket, cred))
acceptPeerRequest(socket);
else
rejectPeerRequest(socket);
}
void ConfigServer::receive(posix::fd_t socket, vfifo buffer, posix::fd_t fd) noexcept
{
(void)fd;
std::string key, value;
if(!(buffer >> value).hadError() && value == "RPC")
{
buffer >> value;
switch(hash(value))
{
case "setCall"_hash:
buffer >> key >> value;
if(!buffer.hadError())
setCall(socket, key, value);
break;
case "getCall"_hash:
buffer >> key;
if(!buffer.hadError())
getCall(socket, key);
break;
case "unsetCall"_hash:
buffer >> key;
if(!buffer.hadError())
unsetCall(socket, key);
break;
}
}
}
<commit_msg>updated disconnect to be explicit<commit_after>#include "configserver.h"
// POSIX
#include <fcntl.h>
// POSIX++
#include <cstdio>
#include <climits>
// PDTK
#include <cxxutils/syslogstream.h>
#include <specialized/procstat.h>
#define CONFIG_PATH "/etc/sxconfig"
#define REQUIRED_GROUPNAME "config"
static const char* configfilename(const char* base)
{
// construct config filename
static char name[PATH_MAX];
std::memset(name, 0, PATH_MAX);
if(std::snprintf(name, PATH_MAX, "%s/%s.conf", CONFIG_PATH, base) == posix::error_response) // I don't how this could fail
return nullptr; // unable to build config filename
return name;
}
static bool readconfig(const char* base, std::string& buffer)
{
const char* name = configfilename(base);
std::FILE* file = std::fopen(name, "a+b");
if(file == nullptr)
{
posix::syslog << "unable to open file: " << name << " : " << std::strerror(errno) << posix::eom;
return false;
}
buffer.resize(std::ftell(file), '\n');
if(buffer.size())
{
std::rewind(file);
std::fread(const_cast<char*>(buffer.data()), sizeof(std::string::value_type), buffer.size(), file);
}
std::fclose(file);
return true;
}
ConfigServer::ConfigServer(void) noexcept
{
Object::connect(newPeerRequest , this, &ConfigServer::request);
Object::connect(newPeerMessage , this, &ConfigServer::receive);
Object::connect(disconnectedPeer, this, &ConfigServer::removePeer);
}
ConfigServer::~ConfigServer(void) noexcept
{
for(auto& confpair : m_configfiles)
Object::disconnect(confpair.second.fd, EventFlags::Readable); // disconnect filesystem monitor
}
void ConfigServer::setCall(posix::fd_t socket, std::string& key, std::string& value) noexcept
{
int errcode = posix::success_response;
auto configfile = m_configfiles.find(socket);
if(configfile == m_configfiles.end())
errcode = int(std::errc::io_error); // not a valid key!
else
configfile->second.config.getNode(key)->value = value;
setReturn(socket, errcode);
}
void ConfigServer::getCall(posix::fd_t socket, std::string& key) noexcept
{
int errcode = posix::success_response;
std::list<std::string> children;
std::string value;
auto configfile = m_configfiles.find(socket);
if(configfile != m_configfiles.end())
errcode = int(std::errc::io_error); // no config file for socket
else
{
auto node = configfile->second.config.findNode(key);
if(node == nullptr)
errcode = int(std::errc::invalid_argument); // node doesn't exist
else
{
switch(node->type)
{
case node_t::type_e::array:
case node_t::type_e::multisection:
case node_t::type_e::section:
for(const auto& child : node->children)
children.push_back(child.first);
case node_t::type_e::invalid:
case node_t::type_e::value:
case node_t::type_e::string:
value = node->value;
}
}
}
getReturn(socket, errcode, value, children);
}
void ConfigServer::unsetCall(posix::fd_t socket, std::string& key) noexcept
{
int errcode = posix::success_response;
auto configfile = m_configfiles.find(socket);
if(configfile == m_configfiles.end())
errcode = int(std::errc::io_error); // no such config file!
else
{
posix::size_t offset = key.find_last_of('/');
auto node = configfile->second.config.findNode(key.substr(0, offset)); // look for parent node
if(node == nullptr)
errcode = int(std::errc::invalid_argument);
else
node->children.erase(key.substr(offset + 1)); // erase child node if it exists
}
unsetReturn(socket, errcode);
}
bool ConfigServer::peerChooser(posix::fd_t socket, const proccred_t& cred) noexcept
{
if(!posix::useringroup(REQUIRED_GROUPNAME, posix::getusername(cred.uid)))
return false;
process_state_t state;
if(::procstat(cred.pid, &state) == posix::error_response) // get state information about the connecting process
return false; // unable to get state
auto endpoint = m_endpoints.find(cred.pid);
if(endpoint == m_endpoints.end() || // if no connection exists OR
!peerData(endpoint->second)) // if old connection is mysteriously gone (can this happen?)
{
std::string buffer;
const char* confname = configfilename(state.name.c_str());
readconfig(confname, buffer);
posix::chown(confname, ::getuid(), cred.gid); // reset ownership
posix::chmod(confname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); // reset permissions
auto& conffile = m_configfiles[socket];
conffile.fd = EventBackend::watch(confname, EventFlags::FileMod);
conffile.config.write(buffer);
Object::connect(conffile.fd, EventFlags::Readable, this, &ConfigServer::fileUpdated);
m_endpoints[cred.pid] = socket; // insert or assign new value
return true;
}
return false; // reject multiple connections from one endpoint
}
void ConfigServer::fileUpdated(posix::fd_t file, EventData_t data) noexcept
{
(void)data;
posix::fd_t socket = 0;
for(auto& conffile : m_configfiles)
if(conffile.second.fd == file)
configUpdated(socket = conffile.first);
if(socket)
for(auto& endpoint : m_endpoints)
if(endpoint.second == socket)
std::printf("notify pid: %i\n", endpoint.first);
}
void ConfigServer::removePeer(posix::fd_t socket) noexcept
{
auto configfile = m_configfiles.find(socket);
if(configfile != m_configfiles.end())
{
Object::disconnect(configfile->second.fd, EventFlags::Readable);
m_configfiles.erase(configfile);
for(auto endpoint : m_endpoints)
if(socket == endpoint.second)
{ m_endpoints.erase(endpoint.first); break; }
}
}
void ConfigServer::request(posix::fd_t socket, posix::sockaddr_t addr, proccred_t cred) noexcept
{
(void)addr;
if(peerChooser(socket, cred))
acceptPeerRequest(socket);
else
rejectPeerRequest(socket);
}
void ConfigServer::receive(posix::fd_t socket, vfifo buffer, posix::fd_t fd) noexcept
{
(void)fd;
std::string key, value;
if(!(buffer >> value).hadError() && value == "RPC")
{
buffer >> value;
switch(hash(value))
{
case "setCall"_hash:
buffer >> key >> value;
if(!buffer.hadError())
setCall(socket, key, value);
break;
case "getCall"_hash:
buffer >> key;
if(!buffer.hadError())
getCall(socket, key);
break;
case "unsetCall"_hash:
buffer >> key;
if(!buffer.hadError())
unsetCall(socket, key);
break;
}
}
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: rtti.C,v 1.14 2003/08/26 09:17:44 oliver Exp $
//
#include <BALL/COMMON/global.h>
#include <BALL/COMMON/rtti.h>
#include <typeinfo>
#include <ctype.h>
// Nasty hacks to demangle the stupid name mangling schemes
// of diverse compilers.
// GNU g++:
// Starting V3.0 we use __cxa_demangle to demangle the names,
// which is declared in <cxxabi.h>.
#ifdef BALL_COMPILER_GXX
# if (BALL_COMPILER_VERSION_MAJOR > 2)
#include <cxxabi.h>
# endif
#endif
#if (defined(BALL_COMPILER_INTEL) || defined(BALL_COMPILER_LLVM))
// Declare the __cxa_demangle method for Intel's C++ compiler.
// Intel does not provide the cxxabi.h header G++ provides, so
// this hack is somewhat rough.
namespace abi
{
extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
}
#endif
namespace BALL
{
string streamClassName(const std::type_info& t)
{
#if (defined(BALL_COMPILER_GXX) || defined(BALL_COMPILER_INTEL) || defined(BALL_COMPILER_LLVM))
#if (BALL_COMPILER_VERSION_MAJOR < 3)
string s(t.name());
s = GNUDemangling::demangle(s);
#else
char buf[BALL_MAX_LINE_LENGTH];
size_t length = BALL_MAX_LINE_LENGTH - 1;
int status = 0;
string s("_Z");
s += t.name();
char* name = abi::__cxa_demangle(s.c_str(), buf, &length, &status);
if (name != 0)
{
s = name;
}
#endif
#else
string s(t.name());
#ifdef BALL_COMPILER_MSVC
// MSVC prefixes all class names with "class " -- delete it!
while (s.find("class ") != string::npos)
s.erase(s.find("class "), 6);
#endif
#endif
for (unsigned int i = 0; i < s.size(); i++)
{
if (s[i] == ' ')
{
s[i] = '_';
}
}
if (string(s, 0, 6) == "const_")
{
s.erase(0, 6);
}
return s;
}
#ifdef BALL_COMPILER_GXX
# if (BALL_COMPILER_VERSION_MAJOR < 3)
namespace GNUDemangling
{
string decode_mangling(string& s)
{
string tmp;
int i,len;
if (s.size() == 0)
return "";
if (!isdigit(s[0]))
{ // decode GNU shortcuts for built-in types
char c = s[0];
s.erase(0, 1);
switch (c)
{
case 'Q': // start of class name
len = atoi(string(s,1,1).c_str());
s.erase(0, 1);
for (i = 0; i < len; i++)
{
tmp.append(decode_mangling(s));
tmp.append("::");
}
tmp.erase(tmp.end() - 2, tmp.end());
break;
case 'Z': // template parameter
return decode_mangling(s);
break;
case 'i':
return "int";
break;
case 'l':
return "long";
break;
case 's':
return "short";
break;
case 'c':
return "char";
break;
case 'x':
return "long long";
break;
case 'f':
return "float";
break;
case 'd':
return "double";
break;
case 'b':
return "bool";
break;
case 'w':
return "wchar_t";
break;
case 'U': // unsigned variants
tmp = "unsigned ";
tmp.append(decode_mangling(s));
break;
case 'C': // const
tmp = "const ";
tmp.append(decode_mangling(s));
break;
case 'P': // pointer
tmp = decode_mangling(s);
tmp.append("*");
break;
case 'R': // reference
tmp = decode_mangling(s);
tmp.append("&");
break;
case 't':
tmp = decode_mangling(s);
tmp.append("<");
len = atoi(string(1, s[0]).c_str());
s.erase(0,1);
for (i = 0; i < len; i++)
{
tmp.append(decode_mangling(s));
tmp.append(",");
}
// remove last ','
tmp.erase(tmp.end() - 1, tmp.end());
tmp.append(">");
break;
default:
tmp = "?";
}
return tmp;
}
else
{
i = s.find_first_not_of("0123456789");
len = atol(string(s, 0, i).c_str());
if (len == 0)
{
s.erase(0,1);
if (s.size() > 0)
{
return decode_mangling(s);
}
else
{
return "";
}
}
else
{
string h(s, i, len);
s.erase(0, i + len);
return h;
}
}
}
string demangle(string s)
{
string tmp = decode_mangling(s);
while (tmp[tmp.size() - 1] == ':')
{
tmp.erase(tmp.end() - 1, tmp.end());
}
while (tmp[0] == ':')
{
tmp.erase(0, 1);
}
return tmp;
}
} // namespace GNUDemangling
# endif // (BALL_COMPILER_VERSION_MAJOR < 3)
#endif // BALL_COMPILER_GXX
} // namespace BALL
<commit_msg>Fix rtti.C for CLANG/LLVM<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: rtti.C,v 1.14 2003/08/26 09:17:44 oliver Exp $
//
#include <BALL/COMMON/global.h>
#include <BALL/COMMON/rtti.h>
#include <typeinfo>
#include <ctype.h>
// Nasty hacks to demangle the stupid name mangling schemes
// of diverse compilers.
// GNU g++:
// Starting V3.0 we use __cxa_demangle to demangle the names,
// which is declared in <cxxabi.h>.
#ifdef BALL_COMPILER_GXX
# if (BALL_COMPILER_VERSION_MAJOR > 2)
#include <cxxabi.h>
# endif
#endif
// LLVM/Clang always offers <cxxabi.h>
#ifdef BALL_COMPILER_LLVM
#include <cxxabi.h>
#endif
#ifdef BALL_COMPILER_INTEL
// Declare the __cxa_demangle method for Intel's C++ compiler.
// Intel does not provide the cxxabi.h header G++ provides, so
// this hack is somewhat rough.
namespace abi
{
extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
}
#endif
namespace BALL
{
string streamClassName(const std::type_info& t)
{
#if (defined(BALL_COMPILER_GXX) || defined(BALL_COMPILER_INTEL)|| defined(BALL_COMPILER_LLVM))
#if defined(BALL_COMPILER_GXX) && (BALL_COMPILER_VERSION_MAJOR < 3)
string s(t.name());
s = GNUDemangling::demangle(s);
#else
char buf[BALL_MAX_LINE_LENGTH];
size_t length = BALL_MAX_LINE_LENGTH - 1;
int status = 0;
string s("_Z");
s += t.name();
char* name = abi::__cxa_demangle(s.c_str(), buf, &length, &status);
if (name != 0)
{
s = name;
}
#endif
#else
string s(t.name());
#ifdef BALL_COMPILER_MSVC
// MSVC prefixes all class names with "class " -- delete it!
while (s.find("class ") != string::npos)
s.erase(s.find("class "), 6);
#endif
#endif
for (unsigned int i = 0; i < s.size(); i++)
{
if (s[i] == ' ')
{
s[i] = '_';
}
}
if (string(s, 0, 6) == "const_")
{
s.erase(0, 6);
}
return s;
}
#ifdef BALL_COMPILER_GXX
# if (BALL_COMPILER_VERSION_MAJOR < 3)
namespace GNUDemangling
{
string decode_mangling(string& s)
{
string tmp;
int i,len;
if (s.size() == 0)
return "";
if (!isdigit(s[0]))
{ // decode GNU shortcuts for built-in types
char c = s[0];
s.erase(0, 1);
switch (c)
{
case 'Q': // start of class name
len = atoi(string(s,1,1).c_str());
s.erase(0, 1);
for (i = 0; i < len; i++)
{
tmp.append(decode_mangling(s));
tmp.append("::");
}
tmp.erase(tmp.end() - 2, tmp.end());
break;
case 'Z': // template parameter
return decode_mangling(s);
break;
case 'i':
return "int";
break;
case 'l':
return "long";
break;
case 's':
return "short";
break;
case 'c':
return "char";
break;
case 'x':
return "long long";
break;
case 'f':
return "float";
break;
case 'd':
return "double";
break;
case 'b':
return "bool";
break;
case 'w':
return "wchar_t";
break;
case 'U': // unsigned variants
tmp = "unsigned ";
tmp.append(decode_mangling(s));
break;
case 'C': // const
tmp = "const ";
tmp.append(decode_mangling(s));
break;
case 'P': // pointer
tmp = decode_mangling(s);
tmp.append("*");
break;
case 'R': // reference
tmp = decode_mangling(s);
tmp.append("&");
break;
case 't':
tmp = decode_mangling(s);
tmp.append("<");
len = atoi(string(1, s[0]).c_str());
s.erase(0,1);
for (i = 0; i < len; i++)
{
tmp.append(decode_mangling(s));
tmp.append(",");
}
// remove last ','
tmp.erase(tmp.end() - 1, tmp.end());
tmp.append(">");
break;
default:
tmp = "?";
}
return tmp;
}
else
{
i = s.find_first_not_of("0123456789");
len = atol(string(s, 0, i).c_str());
if (len == 0)
{
s.erase(0,1);
if (s.size() > 0)
{
return decode_mangling(s);
}
else
{
return "";
}
}
else
{
string h(s, i, len);
s.erase(0, i + len);
return h;
}
}
}
string demangle(string s)
{
string tmp = decode_mangling(s);
while (tmp[tmp.size() - 1] == ':')
{
tmp.erase(tmp.end() - 1, tmp.end());
}
while (tmp[0] == ':')
{
tmp.erase(0, 1);
}
return tmp;
}
} // namespace GNUDemangling
# endif // (BALL_COMPILER_VERSION_MAJOR < 3)
#endif // BALL_COMPILER_GXX
} // namespace BALL
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sysdir_win.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-03-26 13:42:22 $
*
* 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_automation.hxx"
////////////////////////////////////////////////////////////////////////////
////
//// Windows ONLY
////
////////////////////////////////////////////////////////////////////////////
#include <tools/prewin.h>
#ifndef _SHOBJ_H
#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable: 4917)
#endif
#include <shlobj.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif
#include <tools/postwin.h>
// as we define it ourselves further down the line we remove it here
#ifdef IS_ERROR
#undef IS_ERROR
#endif
#include <tchar.h>
#include "sysdir_win.hxx"
//////// copied this from setup2\win\source\system\winos.cxx
void _SHFree( void *pv )
{
IMalloc *pMalloc;
if( NOERROR == SHGetMalloc(&pMalloc) )
{
pMalloc->Free( pv );
pMalloc->Release();
}
}
#define ALLOC(type, n) ((type *) HeapAlloc(GetProcessHeap(), 0, sizeof(type) * n ))
#define FREE(p) HeapFree(GetProcessHeap(), 0, p)
UniString _SHGetSpecialFolder( int nFolderID )
{
LPITEMIDLIST pidl;
HRESULT hHdl = SHGetSpecialFolderLocation( NULL, nFolderID, &pidl );
UniString aFolder;
if( hHdl == NOERROR )
{
WCHAR *lpFolderW;
lpFolderW = ALLOC( WCHAR, 16000 );
SHGetPathFromIDListW( pidl, lpFolderW );
aFolder = UniString( reinterpret_cast<const sal_Unicode*>(lpFolderW) );
FREE( lpFolderW );
_SHFree( pidl );
}
return aFolder;
}
/////////////// end of copy
String _SHGetSpecialFolder_COMMON_APPDATA()
{
return _SHGetSpecialFolder( CSIDL_COMMON_APPDATA );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.48); FILE MERGED 2008/03/28 16:03:40 rt 1.7.48.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: sysdir_win.cxx,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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_automation.hxx"
////////////////////////////////////////////////////////////////////////////
////
//// Windows ONLY
////
////////////////////////////////////////////////////////////////////////////
#include <tools/prewin.h>
#ifndef _SHOBJ_H
#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable: 4917)
#endif
#include <shlobj.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif
#include <tools/postwin.h>
// as we define it ourselves further down the line we remove it here
#ifdef IS_ERROR
#undef IS_ERROR
#endif
#include <tchar.h>
#include "sysdir_win.hxx"
//////// copied this from setup2\win\source\system\winos.cxx
void _SHFree( void *pv )
{
IMalloc *pMalloc;
if( NOERROR == SHGetMalloc(&pMalloc) )
{
pMalloc->Free( pv );
pMalloc->Release();
}
}
#define ALLOC(type, n) ((type *) HeapAlloc(GetProcessHeap(), 0, sizeof(type) * n ))
#define FREE(p) HeapFree(GetProcessHeap(), 0, p)
UniString _SHGetSpecialFolder( int nFolderID )
{
LPITEMIDLIST pidl;
HRESULT hHdl = SHGetSpecialFolderLocation( NULL, nFolderID, &pidl );
UniString aFolder;
if( hHdl == NOERROR )
{
WCHAR *lpFolderW;
lpFolderW = ALLOC( WCHAR, 16000 );
SHGetPathFromIDListW( pidl, lpFolderW );
aFolder = UniString( reinterpret_cast<const sal_Unicode*>(lpFolderW) );
FREE( lpFolderW );
_SHFree( pidl );
}
return aFolder;
}
/////////////// end of copy
String _SHGetSpecialFolder_COMMON_APPDATA()
{
return _SHGetSpecialFolder( CSIDL_COMMON_APPDATA );
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 True Interactions
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/control/control.h"
#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/api/controlitem/controlitem.h"
#include "content/nw/src/nw_shell.h"
namespace nwapi {
Control::Control(int id,
DispatcherHost* dispatcher_host,
const base::DictionaryValue& option)
: Base(id, dispatcher_host, option) {
Create(option);
}
Control::~Control() {
Destroy();
}
void Control::Call(const std::string& method,
const base::ListValue& arguments) {
if (method == "Append") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
Append(dispatcher_host()->GetApiObject<Control>(object_id));
} else if (method == "Insert") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
int pos = 0;
arguments.GetInteger(1, &pos);
Insert(dispatcher_host()->GetApiObject<Control>(object_id), pos);
} else if (method == "Remove") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
int pos = 0;
arguments.GetInteger(1, &pos);
Remove(dispatcher_host()->GetApiObject<Control>(object_id), pos);
} else if (method == "SetOptions") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
const base::DictionaryValue* values;
arguments.GetDictionary(1, &values);
SetOptions(*values);
} else if (method == "SetValue") {
SetValue(arguments);
} else {
NOTREACHED() << "Invalid call to Control method:" << method
<< " arguments:" << arguments;
}
}
void Control::CallSync(const std::string& method,
const base::ListValue& arguments,
base::ListValue* result) {
if (method == "GetOptions") {
result->Set(0,GetOptions());
} else if (method == "GetValue") {
result->Set(0,GetValue());
} else {
NOTREACHED() << "Invalid call to Control method:" << method
<< " arguments:" << arguments;
}
}
} // namespace nwapi
<commit_msg>Commited Control.cc<commit_after>// Copyright (c) 2013 True Interactions
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/control/control.h"
#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/nw_shell.h"
namespace nwapi {
Control::Control(int id,
DispatcherHost* dispatcher_host,
const base::DictionaryValue& option)
: Base(id, dispatcher_host, option) {
Create(option);
}
Control::~Control() {
Destroy();
}
void Control::Call(const std::string& method,
const base::ListValue& arguments) {
if (method == "Append") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
Append(dispatcher_host()->GetApiObject<Control>(object_id));
} else if (method == "Insert") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
int pos = 0;
arguments.GetInteger(1, &pos);
Insert(dispatcher_host()->GetApiObject<Control>(object_id), pos);
} else if (method == "Remove") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
int pos = 0;
arguments.GetInteger(1, &pos);
Remove(dispatcher_host()->GetApiObject<Control>(object_id), pos);
} else if (method == "SetOptions") {
int object_id = 0;
arguments.GetInteger(0, &object_id);
const base::DictionaryValue* values;
arguments.GetDictionary(1, &values);
SetOptions(*values);
} else if (method == "SetValue") {
SetValue(arguments);
} else {
NOTREACHED() << "Invalid call to Control method:" << method
<< " arguments:" << arguments;
}
}
void Control::CallSync(const std::string& method,
const base::ListValue& arguments,
base::ListValue* result) {
if (method == "GetOptions") {
result->Set(0,GetOptions());
} else if (method == "GetValue") {
result->Set(0,GetValue());
} else {
NOTREACHED() << "Invalid call to Control method:" << method
<< " arguments:" << arguments;
}
}
} // namespace nwapi
<|endoftext|> |
<commit_before>/* Copyright 2013 Yurii Litvinov
*
* 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 <QtCore/qglobal.h>
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#include <QtGui/QApplication>
#else
#include <QtWidgets/QApplication>
#endif
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <trikScriptRunner/trikScriptRunner.h>
void printUsage()
{
qDebug() << "Usage: trikRun <QtScript file name> [-c <config file name]>";
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList const args = app.arguments();
if (args.count() != 2) {
printUsage();
return 1;
}
QString const scriptFileName = args[1];
QString configPath = "./";
if (app.arguments().contains("-c")) {
int const index = app.arguments().indexOf("-c");
if (app.arguments().count() <= index + 1) {
printUsage();
return 1;
}
configPath = app.arguments()[index + 1];
if (configPath.right(1) != "/") {
configPath += "/";
}
}
trikScriptRunner::TrikScriptRunner runner(configPath);
QObject::connect(&runner, SIGNAL(completed()), &app, SLOT(quit()));
runner.runFromFile(scriptFileName);
return app.exec();
}
<commit_msg>Added writing scripts in console.<commit_after>/* Copyright 2013 Yurii Litvinov
*
* 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 <QtCore/qglobal.h>
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#include <QtGui/QApplication>
#else
#include <QtWidgets/QApplication>
#endif
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <trikScriptRunner/trikScriptRunner.h>
void printUsage()
{
qDebug() << "Usage: trikRun <QtScript file name> [-c <config file name]>";
qDebug() << "Or";
qDebug() << "Usage: trikRun -h <your script>";
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList const args = app.arguments();
if (args.count() != 2) {
printUsage();
return 1;
}
QString configPath = "./";
if (app.arguments().contains("-c")) {
int const index = app.arguments().indexOf("-c");
if (app.arguments().count() <= index + 1) {
printUsage();
return 1;
}
configPath = app.arguments()[index + 1];
if (configPath.right(1) != "/") {
configPath += "/";
}
}
trikScriptRunner::TrikScriptRunner runner(configPath);
QObject::connect(&runner, SIGNAL(completed()), &app, SLOT(quit()));
if (args[0] == "-h") {
runner.run(args[1]);
} else {
runner.runFromFile(args[1]);
}
return app.exec();
}
<|endoftext|> |
<commit_before>// https://leetcode.com/problems/lru-cache/
/*
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if
the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least
recently used item before inserting a new item.
*/
#include <deque>
#include <iostream>
#include <utility>
#include <unordered_map>
using std::pair;
using std::deque;
using std::unordered_map;
class LRUCache {
public:
explicit LRUCache(int capacity): m_capacity(capacity - 1) {}
int get(int key) {
auto cacheIter = m_cache.find(key);
return cacheIter != m_cache.end() ? prioritize(cacheIter, key) : -1;
}
void set(int key, int value) {
std::cout << "setting " << key << " to " << value << std::endl;
auto cacheIter = m_cache.find(key);
if (cacheIter != m_cache.end()) {
prioritize(cacheIter, key);
m_keys.front().second = value;
} else {
if (m_keys.size() > m_capacity) {
m_cache.erase(m_keys.back().first);
m_keys.pop_back();
}
m_keys.push_front(std::make_pair(key, value));
}
for (auto x : m_keys) std::cout << x.first << " ";
std::cout << std::endl << std::endl;
m_cache[key] = m_keys.begin();
}
private:
size_t m_capacity;
deque<pair<int, int>> m_keys;
unordered_map<int, deque<pair<int, int>>::iterator> m_cache;
int prioritize(unordered_map<int, deque<pair<int, int>>::iterator>::iterator mapIter, int key) {
auto pairIter = mapIter->second;
int val = pairIter->second;
m_keys.push_front(std::move(*pairIter));
m_keys.erase(pairIter);
m_cache[key] = m_keys.begin();
return val;
}
};
int main() {
LRUCache c(105);
c.set(33,219);
c.get(39);
c.set(96,56);
c.get(129);
c.get(115);
c.get(112);
c.set(3,280);
c.get(40);
c.set(85,193);
c.set(10,10);
c.set(100,136);
c.set(12,66);
c.set(81,261);
c.set(33,58);
c.get(3);
c.set(121,308);
c.set(129,263);
c.get(105);
c.set(104,38);
c.set(65,85);
c.set(3,141);
c.set(29,30);
c.set(80,191);
c.set(52,191);
c.set(8,300);
c.get(136);
c.set(48,261);
c.set(3,193);
c.set(133,193);
c.set(60,183);
c.set(128,148);
c.set(52,176);
}
<commit_msg>:art: fix LRUCache with std::list, which keeps iterators valid<commit_after>// https://leetcode.com/problems/lru-cache/
/*
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if
the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least
recently used item before inserting a new item.
*/
#include <list>
#include <utility>
#include <unordered_map>
using std::pair;
using std::list;
using std::unordered_map;
class LRUCache {
public:
explicit LRUCache(int capacity): m_capacity(capacity - 1) {}
int get(int key) {
auto cacheIter = m_cache.find(key);
return cacheIter != m_cache.end() ? prioritize(cacheIter->second) : -1;
}
void set(int key, int value) {
auto cacheIter = m_cache.find(key);
// Key already exists -> move to front of cache and adjust value at key
if (cacheIter != m_cache.end()) {
prioritize(cacheIter->second);
cacheIter->second->second = value;
return;
}
// Capacity max reached -> remove least used cache value
if (m_keys.size() > m_capacity) {
m_cache.erase(m_keys.back().first);
m_keys.pop_back();
}
// Key didn't exist -> add new pair to front of cache
m_keys.push_front(std::make_pair(key, value));
m_cache[key] = m_keys.begin();
}
private:
size_t m_capacity;
list<pair<int, int>> m_keys;
unordered_map<int, list<pair<int, int>>::iterator> m_cache;
// Moves pair to the front of the cache
int prioritize(list<pair<int, int>>::iterator listIter) {
m_keys.splice(m_keys.begin(), m_keys, listIter);
return listIter->second;
}
};
<|endoftext|> |
<commit_before>#include "bytes.hpp"
#include "dns.hpp"
#include "dns-resolver.hpp"
#include "error-code.hpp"
#include "for-each.hpp"
#include "net.hpp"
#include "poller.hpp"
#include "stream.hpp"
#include "var.hpp"
#ifdef SCRIPTED
#include "dns.cpp"
#include "net.cpp"
#include "poller.cpp"
#endif
#include <iostream>
using namespace relight;
static void make_request() {
dns::resolve4("www.torproject.org",
[](int err, std::vector<std::string> addrs) {
if (err) throw err;
for_each<std::string>(addrs, [=](std::string s, next_func next) {
std::cout << " - " << s;
dns::reverse4(s, [=](int err, std::vector<std::string> revs) {
if (err) throw err;
for (auto &s : revs) std::cout << " " << s;
std::cout << "\n";
next();
});
},
[=]() { Poller::get_default()->break_loop(); });
});
}
int main() {
make_request();
Poller::get_default()->loop();
}
<commit_msg>cosmetic change<commit_after>#include "bytes.hpp"
#include "dns.hpp"
#include "dns-resolver.hpp"
#include "error-code.hpp"
#include "for-each.hpp"
#include "net.hpp"
#include "poller.hpp"
#include "stream.hpp"
#include "var.hpp"
#ifdef SCRIPTED
#include "dns.cpp"
#include "net.cpp"
#include "poller.cpp"
#endif
#include <iostream>
using namespace relight;
static void make_request() {
dns::resolve4("www.torproject.org",
[](int err, std::vector<std::string> addrs) {
if (err) throw err;
for_each<std::string>(addrs, [=](std::string s, next_func next) {
std::cout << " - " << s;
dns::reverse4(s, [=](int err, std::vector<std::string> revs) {
if (err) throw err;
for (auto &s : revs) std::cout << " " << s;
std::cout << "\n";
next();
});
}, [=]() { Poller::get_default()->break_loop(); });
});
}
int main() {
make_request();
Poller::get_default()->loop();
}
<|endoftext|> |
<commit_before>#include <libmemcached/memcached.h>
#include <string>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
std::string fetch(std::string& key, size_t *key_length, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_fetch(&memc, const_cast<char *>(key.c_str()), key_length,
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string get(const std::string& key, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get(&memc, key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string get_by_key(const std::string& master_key,
const std::string& key,
size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get_by_key(&memc, master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
bool mget(char **keys, size_t *key_length,
unsigned int number_of_keys)
{
memcached_return rc= memcached_mget(&memc, keys, key_length, number_of_keys);
return (rc == MEMCACHED_SUCCESS);
}
bool set(const std::string& key, const std::string& value)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
value.c_str(), value.length(),
time_t(0), uint32_t(0));
return (rc == MEMCACHED_SUCCESS);
}
bool set_by_key(const std::string& master_key,
const std::string& key,
const std::string& value)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
value.c_str(), value.length(),
time_t(0),
uint32_t(0));
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string& key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string& key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string& key, const std::string& value, size_t value_length)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
value.c_str(), value_length, 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool add_by_key(const std::string& master_key, const std::string& key,
const std::string& value, size_t value_length)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value_length,
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string& key, const std::string& value,
size_t value_length)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
value.c_str(), value_length,
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace_by_key(const std::string& master_key, const std::string& key,
const std::string& value, size_t value_length)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value_length,
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string& key, const std::string& value,
size_t value_length)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
value.c_str(), value_length, 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend_by_key(const std::string& master_key, const std::string& key,
const std::string& value, size_t value_length)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value_length,
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string& key, const std::string& value,
size_t value_length)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
value.c_str(),
value_length, 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool append_by_key(const std::string& master_key, const std::string& key,
const std::string& value, size_t value_length)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value_length, 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string& key, const std::string& value,
size_t value_length, uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
value.c_str(), value_length, 0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool cas_by_key(const std::string& master_key, const std::string& key,
const std::string& value, size_t value_length,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value_length,
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
// using 'remove' vs. 'delete' since 'delete' is a keyword
bool remove(const std::string& key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool delete_by_key(const std::string& master_key,
const std::string& key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
const std::string lib_version() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
<commit_msg>Cleaning up formatting in the C++ interface.<commit_after>#include <libmemcached/memcached.h>
#include <string>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
std::string fetch(std::string &key, size_t *key_length, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_fetch(&memc, const_cast<char *>(key.c_str()), key_length,
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string get(const std::string &key, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get(&memc, key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string get_by_key(const std::string &master_key,
const std::string &key,
size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get_by_key(&memc, master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
bool mget(char **keys, size_t *key_length,
unsigned int number_of_keys)
{
memcached_return rc= memcached_mget(&memc, keys, key_length, number_of_keys);
return (rc == MEMCACHED_SUCCESS);
}
bool set(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
value.c_str(), value.length(),
time_t(0), uint32_t(0));
return (rc == MEMCACHED_SUCCESS);
}
bool set_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
value.c_str(), value.length(),
time_t(0),
uint32_t(0));
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool add_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool append_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool cas_by_key(const std::string &master_key,
const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
// using 'remove' vs. 'delete' since 'delete' is a keyword
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool delete_by_key(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
const std::string lib_version() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
<|endoftext|> |
<commit_before>/*
Bacula® - The Network Backup Solution
Copyright (C) 2007-2009 Free Software Foundation Europe e.V.
The main author of Bacula is Kern Sibbald, with contributions from
many others, a complete list can be found in the file AUTHORS.
This program is Free Software; you can redistribute it and/or
modify it under the terms of version two of the GNU General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
Bacula® is a registered trademark of Kern Sibbald.
The licensor of Bacula is the Free Software Foundation Europe
(FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
Switzerland, email:ftf@fsfeurope.org.
*/
/*
* Version $Id$
*
* FileSet Class
*
* Dirk Bartley, March 2007
*
*/
#include "bat.h"
#include <QAbstractEventDispatcher>
#include <QMenu>
#include "fileset/fileset.h"
#include "util/fmtwidgetitem.h"
FileSet::FileSet()
{
setupUi(this);
m_name = tr("FileSets");
pgInitialize();
QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/system-file-manager.png")));
/* tableWidget, FileSet Tree Tree Widget inherited from ui_fileset.h */
m_populated = false;
m_checkcurwidget = true;
m_closeable = false;
readSettings();
/* add context sensitive menu items specific to this classto the page
* selector tree. m_contextActions is QList of QActions */
m_contextActions.append(actionRefreshFileSet);
dockPage();
}
FileSet::~FileSet()
{
writeSettings();
}
/*
* The main meat of the class!! The function that querries the director and
* creates the widgets with appropriate values.
*/
void FileSet::populateTable()
{
m_populated = true;
Freeze frz(*tableWidget); /* disable updating*/
m_checkcurwidget = false;
tableWidget->clear();
m_checkcurwidget = true;
QStringList headerlist = (QStringList() << tr("FileSet Name") << tr("FileSet Id")
<< tr("Create Time"));
tableWidget->setColumnCount(headerlist.count());
tableWidget->setHorizontalHeaderLabels(headerlist);
tableWidget->horizontalHeader()->setHighlightSections(false);
tableWidget->verticalHeader()->hide();
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
tableWidget->setSortingEnabled(false); /* rows move on insert if sorting enabled */
QString fileset_comsep("");
bool first = true;
foreach(QString filesetName, m_console->fileset_list) {
if (first) {
fileset_comsep += "'" + filesetName + "'";
first = false;
}
else
fileset_comsep += ",'" + filesetName + "'";
}
if (fileset_comsep != "") {
/* Set up query QString and header QStringList */
QString query("");
query += "SELECT FileSet AS Name, FileSetId AS Id, CreateTime"
" FROM FileSet"
" WHERE FileSetId IN (SELECT MAX(FileSetId) FROM FileSet WHERE";
query += " FileSet IN (" + fileset_comsep + ")";
query += " GROUP BY FileSet) ORDER BY FileSet";
QStringList results;
if (mainWin->m_sqlDebug) {
Pmsg1(000, "FileSet query cmd : %s\n",query.toUtf8().data());
}
if (m_console->sql_cmd(query, results)) {
int row = 0;
QStringList fieldlist;
tableWidget->setRowCount(results.count());
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
fieldlist = resultline.split("\t");
TableItemFormatter item(*tableWidget, row);
/* Iterate through fields in the record */
QStringListIterator fld(fieldlist);
int col = 0;
/* name */
item.setTextFld(col++, fld.next());
/* id */
item.setNumericFld(col++, fld.next());
/* creation time */
item.setTextFld(col++, fld.next());
row++;
}
}
}
/* set default sorting */
tableWidget->sortByColumn(headerlist.indexOf(tr("Create Time")), Qt::DescendingOrder);
tableWidget->setSortingEnabled(true);
/* Resize rows and columns */
tableWidget->resizeColumnsToContents();
tableWidget->resizeRowsToContents();
/* make read only */
int rcnt = tableWidget->rowCount();
int ccnt = tableWidget->columnCount();
for(int r=0; r < rcnt; r++) {
for(int c=0; c < ccnt; c++) {
QTableWidgetItem* item = tableWidget->item(r, c);
if (item) {
item->setFlags(Qt::ItemFlags(item->flags() & (~Qt::ItemIsEditable)));
}
}
}
}
/*
* When the treeWidgetItem in the page selector tree is singleclicked, Make sure
* The tree has been populated.
*/
void FileSet::PgSeltreeWidgetClicked()
{
if (!m_populated) {
populateTable();
createContextMenu();
}
}
/*
* Added to set the context menu policy based on currently active treeWidgetItem
* signaled by currentItemChanged
*/
void FileSet::tableItemChanged(QTableWidgetItem *currentwidgetitem, QTableWidgetItem *previouswidgetitem)
{
/* m_checkcurwidget checks to see if this is during a refresh, which will segfault */
if (m_checkcurwidget) {
int currentRow = currentwidgetitem->row();
QTableWidgetItem *currentrowzeroitem = tableWidget->item(currentRow, 0);
m_currentlyselected = currentrowzeroitem->text();
/* The Previous item */
if (previouswidgetitem) { /* avoid a segfault if first time */
tableWidget->removeAction(actionStatusFileSetInConsole);
tableWidget->removeAction(actionShowJobs);
}
if (m_currentlyselected.length() != 0) {
/* set a hold variable to the fileset name in case the context sensitive
* menu is used */
tableWidget->addAction(actionStatusFileSetInConsole);
tableWidget->addAction(actionShowJobs);
}
}
}
/*
* Setup a context menu
* Made separate from populate so that it would not create context menu over and
* over as the tree is repopulated.
*/
void FileSet::createContextMenu()
{
tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
tableWidget->addAction(actionRefreshFileSet);
connect(tableWidget, SIGNAL(
currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *)));
/* connect to the action specific to this pages class */
connect(actionRefreshFileSet, SIGNAL(triggered()), this,
SLOT(populateTable()));
connect(actionStatusFileSetInConsole, SIGNAL(triggered()), this,
SLOT(consoleShowFileSet()));
connect(actionShowJobs, SIGNAL(triggered()), this,
SLOT(showJobs()));
}
/*
* Function responding to actionListJobsofFileSet which calls mainwin function
* to create a window of a list of jobs of this fileset.
*/
void FileSet::consoleShowFileSet()
{
QString cmd("show fileset=\"");
cmd += m_currentlyselected + "\"";
consoleCommand(cmd);
}
/*
* Virtual function which is called when this page is visible on the stack
*/
void FileSet::currentStackItem()
{
if(!m_populated) {
populateTable();
/* Create the context menu for the fileset table */
createContextMenu();
}
}
/*
* Save user settings associated with this page
*/
void FileSet::writeSettings()
{
QSettings settings(m_console->m_dir->name(), "bat");
settings.beginGroup("FileSet");
settings.setValue("geometry", saveGeometry());
settings.endGroup();
}
/*
* Read and restore user settings associated with this page
*/
void FileSet::readSettings()
{
QSettings settings(m_console->m_dir->name(), "bat");
settings.beginGroup("FileSet");
restoreGeometry(settings.value("geometry").toByteArray());
settings.endGroup();
}
/*
* Create a JobList object pre-populating a fileset
*/
void FileSet::showJobs()
{
QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
mainWin->createPageJobList("", "", "", m_currentlyselected, parentItem);
}
<commit_msg>Add a stringlist and a foreach after populating to at least acknowledge to the user that a new fileset. Bat would not show the fileset until the database table had the fileset which was not until used.<commit_after>/*
Bacula® - The Network Backup Solution
Copyright (C) 2007-2009 Free Software Foundation Europe e.V.
The main author of Bacula is Kern Sibbald, with contributions from
many others, a complete list can be found in the file AUTHORS.
This program is Free Software; you can redistribute it and/or
modify it under the terms of version two of the GNU General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
Bacula® is a registered trademark of Kern Sibbald.
The licensor of Bacula is the Free Software Foundation Europe
(FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
Switzerland, email:ftf@fsfeurope.org.
*/
/*
* Version $Id$
*
* FileSet Class
*
* Dirk Bartley, March 2007
*
*/
#include "bat.h"
#include <QAbstractEventDispatcher>
#include <QMenu>
#include "fileset/fileset.h"
#include "util/fmtwidgetitem.h"
FileSet::FileSet()
{
setupUi(this);
m_name = tr("FileSets");
pgInitialize();
QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/system-file-manager.png")));
/* tableWidget, FileSet Tree Tree Widget inherited from ui_fileset.h */
m_populated = false;
m_checkcurwidget = true;
m_closeable = false;
readSettings();
/* add context sensitive menu items specific to this classto the page
* selector tree. m_contextActions is QList of QActions */
m_contextActions.append(actionRefreshFileSet);
dockPage();
}
FileSet::~FileSet()
{
writeSettings();
}
/*
* The main meat of the class!! The function that querries the director and
* creates the widgets with appropriate values.
*/
void FileSet::populateTable()
{
m_populated = true;
Freeze frz(*tableWidget); /* disable updating*/
m_checkcurwidget = false;
tableWidget->clear();
m_checkcurwidget = true;
QStringList headerlist = (QStringList() << tr("FileSet Name") << tr("FileSet Id")
<< tr("Create Time"));
tableWidget->setColumnCount(headerlist.count());
tableWidget->setHorizontalHeaderLabels(headerlist);
tableWidget->horizontalHeader()->setHighlightSections(false);
tableWidget->verticalHeader()->hide();
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
tableWidget->setSortingEnabled(false); /* rows move on insert if sorting enabled */
QString fileset_comsep("");
bool first = true;
QStringList notFoundList = m_console->fileset_list;
foreach(QString filesetName, m_console->fileset_list) {
if (first) {
fileset_comsep += "'" + filesetName + "'";
first = false;
}
else
fileset_comsep += ",'" + filesetName + "'";
}
int row = 0;
tableWidget->setRowCount(m_console->fileset_list.count());
if (fileset_comsep != "") {
/* Set up query QString and header QStringList */
QString query("");
query += "SELECT FileSet AS Name, FileSetId AS Id, CreateTime"
" FROM FileSet"
" WHERE FileSetId IN (SELECT MAX(FileSetId) FROM FileSet WHERE";
query += " FileSet IN (" + fileset_comsep + ")";
query += " GROUP BY FileSet) ORDER BY FileSet";
QStringList results;
if (mainWin->m_sqlDebug) {
Pmsg1(000, "FileSet query cmd : %s\n",query.toUtf8().data());
}
if (m_console->sql_cmd(query, results)) {
QStringList fieldlist;
/* Iterate through the record returned from the query */
foreach (QString resultline, results) {
fieldlist = resultline.split("\t");
/* remove this fileSet from notFoundList */
int indexOf = notFoundList.indexOf(fieldlist[0]);
if (indexOf != -1) { notFoundList.removeAt(indexOf); }
TableItemFormatter item(*tableWidget, row);
/* Iterate through fields in the record */
QStringListIterator fld(fieldlist);
int col = 0;
/* name */
item.setTextFld(col++, fld.next());
/* id */
item.setNumericFld(col++, fld.next());
/* creation time */
item.setTextFld(col++, fld.next());
row++;
}
}
}
foreach(QString filesetName, notFoundList) {
TableItemFormatter item(*tableWidget, row);
item.setTextFld(0, filesetName);
row++;
}
/* set default sorting */
tableWidget->sortByColumn(headerlist.indexOf(tr("Create Time")), Qt::DescendingOrder);
tableWidget->setSortingEnabled(true);
/* Resize rows and columns */
tableWidget->resizeColumnsToContents();
tableWidget->resizeRowsToContents();
/* make read only */
int rcnt = tableWidget->rowCount();
int ccnt = tableWidget->columnCount();
for(int r=0; r < rcnt; r++) {
for(int c=0; c < ccnt; c++) {
QTableWidgetItem* item = tableWidget->item(r, c);
if (item) {
item->setFlags(Qt::ItemFlags(item->flags() & (~Qt::ItemIsEditable)));
}
}
}
}
/*
* When the treeWidgetItem in the page selector tree is singleclicked, Make sure
* The tree has been populated.
*/
void FileSet::PgSeltreeWidgetClicked()
{
if (!m_populated) {
populateTable();
createContextMenu();
}
}
/*
* Added to set the context menu policy based on currently active treeWidgetItem
* signaled by currentItemChanged
*/
void FileSet::tableItemChanged(QTableWidgetItem *currentwidgetitem, QTableWidgetItem *previouswidgetitem)
{
/* m_checkcurwidget checks to see if this is during a refresh, which will segfault */
if (m_checkcurwidget) {
int currentRow = currentwidgetitem->row();
QTableWidgetItem *currentrowzeroitem = tableWidget->item(currentRow, 0);
m_currentlyselected = currentrowzeroitem->text();
/* The Previous item */
if (previouswidgetitem) { /* avoid a segfault if first time */
tableWidget->removeAction(actionStatusFileSetInConsole);
tableWidget->removeAction(actionShowJobs);
}
if (m_currentlyselected.length() != 0) {
/* set a hold variable to the fileset name in case the context sensitive
* menu is used */
tableWidget->addAction(actionStatusFileSetInConsole);
tableWidget->addAction(actionShowJobs);
}
}
}
/*
* Setup a context menu
* Made separate from populate so that it would not create context menu over and
* over as the tree is repopulated.
*/
void FileSet::createContextMenu()
{
tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
tableWidget->addAction(actionRefreshFileSet);
connect(tableWidget, SIGNAL(
currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *)));
/* connect to the action specific to this pages class */
connect(actionRefreshFileSet, SIGNAL(triggered()), this,
SLOT(populateTable()));
connect(actionStatusFileSetInConsole, SIGNAL(triggered()), this,
SLOT(consoleShowFileSet()));
connect(actionShowJobs, SIGNAL(triggered()), this,
SLOT(showJobs()));
}
/*
* Function responding to actionListJobsofFileSet which calls mainwin function
* to create a window of a list of jobs of this fileset.
*/
void FileSet::consoleShowFileSet()
{
QString cmd("show fileset=\"");
cmd += m_currentlyselected + "\"";
consoleCommand(cmd);
}
/*
* Virtual function which is called when this page is visible on the stack
*/
void FileSet::currentStackItem()
{
if(!m_populated) {
populateTable();
/* Create the context menu for the fileset table */
createContextMenu();
}
}
/*
* Save user settings associated with this page
*/
void FileSet::writeSettings()
{
QSettings settings(m_console->m_dir->name(), "bat");
settings.beginGroup("FileSet");
settings.setValue("geometry", saveGeometry());
settings.endGroup();
}
/*
* Read and restore user settings associated with this page
*/
void FileSet::readSettings()
{
QSettings settings(m_console->m_dir->name(), "bat");
settings.beginGroup("FileSet");
restoreGeometry(settings.value("geometry").toByteArray());
settings.endGroup();
}
/*
* Create a JobList object pre-populating a fileset
*/
void FileSet::showJobs()
{
QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
mainWin->createPageJobList("", "", "", m_currentlyselected, parentItem);
}
<|endoftext|> |
<commit_before>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// Code that is used by both the Unix corerun and coreconsole.
//
#include <cstdlib>
#include <assert.h>
#include <dirent.h>
#include <dlfcn.h>
#include <limits.h>
#include <set>
#include <string>
#include <string.h>
#include <sys/stat.h>
// The name of the CoreCLR native runtime DLL
#if defined(__APPLE__)
static const char * const coreClrDll = "libcoreclr.dylib";
#else
static const char * const coreClrDll = "libcoreclr.so";
#endif
// Windows types used by the ExecuteAssembly function
typedef unsigned int DWORD;
typedef const char16_t* LPCWSTR;
typedef const char* LPCSTR;
typedef int32_t HRESULT;
#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)
// Prototype of the ExecuteAssembly function from the libcoreclr.do
typedef HRESULT (*ExecuteAssemblyFunction)(
LPCSTR exePath,
LPCSTR coreClrPath,
LPCSTR appDomainFriendlyName,
int propertyCount,
LPCSTR* propertyKeys,
LPCSTR* propertyValues,
int argc,
LPCSTR* argv,
LPCSTR managedAssemblyPath,
LPCSTR entryPointAssemblyName,
LPCSTR entryPointTypeName,
LPCSTR entryPointMethodsName,
DWORD* exitCode);
bool GetAbsolutePath(const char* path, std::string& absolutePath)
{
bool result = false;
char realPath[PATH_MAX];
if (realpath(path, realPath) != nullptr && realPath[0] != '\0')
{
absolutePath.assign(realPath);
// realpath should return canonicalized path without the trailing slash
assert(absolutePath.back() != '/');
result = true;
}
return result;
}
bool GetDirectory(const char* absolutePath, std::string& directory)
{
directory.assign(absolutePath);
size_t lastSlash = directory.rfind('/');
if (lastSlash != std::string::npos)
{
directory.erase(lastSlash);
return true;
}
return false;
}
bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)
{
std::string clrFilesRelativePath;
const char* clrFilesPathLocal = clrFilesPath;
if (clrFilesPathLocal == nullptr)
{
// There was no CLR files path specified, use the folder of the corerun/coreconsole
if (!GetDirectory(currentExePath, clrFilesRelativePath))
{
perror("Failed to get directory from argv[0]");
return false;
}
clrFilesPathLocal = clrFilesRelativePath.c_str();
// TODO: consider using an env variable (if defined) as a fall-back.
// The windows version of the corerun uses core_root env variable
}
if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))
{
perror("Failed to convert CLR files path to absolute path");
return false;
}
return true;
}
void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)
{
const char * const tpaExtensions[] = {
".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir
".dll",
".ni.exe",
".exe",
};
DIR* dir = opendir(directory);
if (dir == nullptr)
{
return;
}
std::set<std::string> addedAssemblies;
// Walk the directory for each extension separately so that we first get files with .ni.dll extension,
// then files with .dll extension, etc.
for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++)
{
const char* ext = tpaExtensions[extIndex];
int extLength = strlen(ext);
struct dirent* entry;
// For all entries in the directory
while ((entry = readdir(dir)) != nullptr)
{
// We are interested in files only
switch (entry->d_type)
{
case DT_REG:
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
std::string fullFilename;
fullFilename.append(directory);
fullFilename.append("/");
fullFilename.append(entry->d_name);
struct stat sb;
if (stat(fullFilename.c_str(), &sb) == -1)
{
continue;
}
if (!S_ISREG(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
std::string filename(entry->d_name);
// Check if the extension matches the one we are looking for
int extPos = filename.length() - extLength;
if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))
{
continue;
}
std::string filenameWithoutExt(filename.substr(0, extPos));
// Make sure if we have an assembly with multiple extensions present,
// we insert only one version of it.
if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())
{
addedAssemblies.insert(filenameWithoutExt);
tpaList.append(directory);
tpaList.append("/");
tpaList.append(filename);
tpaList.append(":");
}
}
// Rewind the directory stream to be able to iterate over it for the next extension
rewinddir(dir);
}
closedir(dir);
}
int ExecuteManagedAssembly(
const char* currentExeAbsolutePath,
const char* clrFilesAbsolutePath,
const char* managedAssemblyAbsolutePath,
int managedAssemblyArgc,
const char** managedAssemblyArgv)
{
// Indicates failure
int exitCode = -1;
std::string coreClrDllPath(clrFilesAbsolutePath);
coreClrDllPath.append("/");
coreClrDllPath.append(coreClrDll);
if (coreClrDllPath.length() >= PATH_MAX)
{
fprintf(stderr, "Absolute path to libcoreclr.so too long\n");
return -1;
}
// Get just the path component of the managed assembly path
std::string appPath;
GetDirectory(managedAssemblyAbsolutePath, appPath);
std::string nativeDllSearchDirs(appPath);
nativeDllSearchDirs.append(":");
nativeDllSearchDirs.append(clrFilesAbsolutePath);
std::string tpaList;
AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);
void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);
if (coreclrLib != nullptr)
{
ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly");
if (executeAssembly != nullptr)
{
// Allowed property names:
// APPBASE
// - The base path of the application from which the exe and other assemblies will be loaded
//
// TRUSTED_PLATFORM_ASSEMBLIES
// - The list of complete paths to each of the fully trusted assemblies
//
// APP_PATHS
// - The list of paths which will be probed by the assembly loader
//
// APP_NI_PATHS
// - The list of additional paths that the assembly loader will probe for ngen images
//
// NATIVE_DLL_SEARCH_DIRECTORIES
// - The list of paths that will be probed for native DLLs called by PInvoke
//
const char *propertyKeys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES",
"APP_PATHS",
"APP_NI_PATHS",
"NATIVE_DLL_SEARCH_DIRECTORIES",
"AppDomainCompatSwitch"
};
const char *propertyValues[] = {
// TRUSTED_PLATFORM_ASSEMBLIES
tpaList.c_str(),
// APP_PATHS
appPath.c_str(),
// APP_NI_PATHS
appPath.c_str(),
// NATIVE_DLL_SEARCH_DIRECTORIES
nativeDllSearchDirs.c_str(),
// AppDomainCompatSwitch
"UseLatestBehaviorWhenTFMNotSpecified"
};
HRESULT st = executeAssembly(
currentExeAbsolutePath,
coreClrDllPath.c_str(),
"unixcorerun",
sizeof(propertyKeys) / sizeof(propertyKeys[0]),
propertyKeys,
propertyValues,
managedAssemblyArgc,
managedAssemblyArgv,
managedAssemblyAbsolutePath,
NULL,
NULL,
NULL,
(DWORD*)&exitCode);
if (!SUCCEEDED(st))
{
fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st);
exitCode = -1;
}
}
else
{
fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n");
}
if (dlclose(coreclrLib) != 0)
{
fprintf(stderr, "Warning - dlclose failed\n");
}
}
else
{
char* error = dlerror();
fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error);
}
return exitCode;
}
<commit_msg>Extend the Unix hosting API<commit_after>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// Code that is used by both the Unix corerun and coreconsole.
//
#include <cstdlib>
#include <assert.h>
#include <dirent.h>
#include <dlfcn.h>
#include <limits.h>
#include <set>
#include <string>
#include <string.h>
#include <sys/stat.h>
// The name of the CoreCLR native runtime DLL
#if defined(__APPLE__)
static const char * const coreClrDll = "libcoreclr.dylib";
#else
static const char * const coreClrDll = "libcoreclr.so";
#endif
#define SUCCEEDED(Status) ((Status) >= 0)
// Prototype of the coreclr_initialize function from the libcoreclr.so
typedef int (*InitializeCoreCLRFunction)(
const char* exePath,
const char* appDomainFriendlyName,
int propertyCount,
const char** propertyKeys,
const char** propertyValues,
void** hostHandle,
unsigned int* domainId);
// Prototype of the coreclr_shutdown function from the libcoreclr.so
typedef int (*ShutdownCoreCLRFunction)(
void* hostHandle,
unsigned int domainId);
// Prototype of the coreclr_execute_assembly function from the libcoreclr.so
typedef int (*ExecuteAssemblyFunction)(
void* hostHandle,
unsigned int domainId,
int argc,
const char** argv,
const char* managedAssemblyPath,
unsigned int* exitCode);
bool GetAbsolutePath(const char* path, std::string& absolutePath)
{
bool result = false;
char realPath[PATH_MAX];
if (realpath(path, realPath) != nullptr && realPath[0] != '\0')
{
absolutePath.assign(realPath);
// realpath should return canonicalized path without the trailing slash
assert(absolutePath.back() != '/');
result = true;
}
return result;
}
bool GetDirectory(const char* absolutePath, std::string& directory)
{
directory.assign(absolutePath);
size_t lastSlash = directory.rfind('/');
if (lastSlash != std::string::npos)
{
directory.erase(lastSlash);
return true;
}
return false;
}
bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)
{
std::string clrFilesRelativePath;
const char* clrFilesPathLocal = clrFilesPath;
if (clrFilesPathLocal == nullptr)
{
// There was no CLR files path specified, use the folder of the corerun/coreconsole
if (!GetDirectory(currentExePath, clrFilesRelativePath))
{
perror("Failed to get directory from argv[0]");
return false;
}
clrFilesPathLocal = clrFilesRelativePath.c_str();
// TODO: consider using an env variable (if defined) as a fall-back.
// The windows version of the corerun uses core_root env variable
}
if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))
{
perror("Failed to convert CLR files path to absolute path");
return false;
}
return true;
}
void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)
{
const char * const tpaExtensions[] = {
".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir
".dll",
".ni.exe",
".exe",
};
DIR* dir = opendir(directory);
if (dir == nullptr)
{
return;
}
std::set<std::string> addedAssemblies;
// Walk the directory for each extension separately so that we first get files with .ni.dll extension,
// then files with .dll extension, etc.
for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++)
{
const char* ext = tpaExtensions[extIndex];
int extLength = strlen(ext);
struct dirent* entry;
// For all entries in the directory
while ((entry = readdir(dir)) != nullptr)
{
// We are interested in files only
switch (entry->d_type)
{
case DT_REG:
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
std::string fullFilename;
fullFilename.append(directory);
fullFilename.append("/");
fullFilename.append(entry->d_name);
struct stat sb;
if (stat(fullFilename.c_str(), &sb) == -1)
{
continue;
}
if (!S_ISREG(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
std::string filename(entry->d_name);
// Check if the extension matches the one we are looking for
int extPos = filename.length() - extLength;
if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))
{
continue;
}
std::string filenameWithoutExt(filename.substr(0, extPos));
// Make sure if we have an assembly with multiple extensions present,
// we insert only one version of it.
if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())
{
addedAssemblies.insert(filenameWithoutExt);
tpaList.append(directory);
tpaList.append("/");
tpaList.append(filename);
tpaList.append(":");
}
}
// Rewind the directory stream to be able to iterate over it for the next extension
rewinddir(dir);
}
closedir(dir);
}
int ExecuteManagedAssembly(
const char* currentExeAbsolutePath,
const char* clrFilesAbsolutePath,
const char* managedAssemblyAbsolutePath,
int managedAssemblyArgc,
const char** managedAssemblyArgv)
{
// Indicates failure
int exitCode = -1;
std::string coreClrDllPath(clrFilesAbsolutePath);
coreClrDllPath.append("/");
coreClrDllPath.append(coreClrDll);
if (coreClrDllPath.length() >= PATH_MAX)
{
fprintf(stderr, "Absolute path to libcoreclr.so too long\n");
return -1;
}
// Get just the path component of the managed assembly path
std::string appPath;
GetDirectory(managedAssemblyAbsolutePath, appPath);
std::string nativeDllSearchDirs(appPath);
nativeDllSearchDirs.append(":");
nativeDllSearchDirs.append(clrFilesAbsolutePath);
std::string tpaList;
AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);
void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);
if (coreclrLib != nullptr)
{
InitializeCoreCLRFunction initializeCoreCLR = (InitializeCoreCLRFunction)dlsym(coreclrLib, "coreclr_initialize");
ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "coreclr_execute_assembly");
ShutdownCoreCLRFunction shutdownCoreCLR = (ShutdownCoreCLRFunction)dlsym(coreclrLib, "coreclr_shutdown");
if (initializeCoreCLR == nullptr)
{
fprintf(stderr, "Function coreclr_initialize not found in the libcoreclr.so\n");
}
else if (executeAssembly == nullptr)
{
fprintf(stderr, "Function coreclr_execute_assembly not found in the libcoreclr.so\n");
}
else if (shutdownCoreCLR == nullptr)
{
fprintf(stderr, "Function coreclr_shutdown not found in the libcoreclr.so\n");
}
else
{
// Allowed property names:
// APPBASE
// - The base path of the application from which the exe and other assemblies will be loaded
//
// TRUSTED_PLATFORM_ASSEMBLIES
// - The list of complete paths to each of the fully trusted assemblies
//
// APP_PATHS
// - The list of paths which will be probed by the assembly loader
//
// APP_NI_PATHS
// - The list of additional paths that the assembly loader will probe for ngen images
//
// NATIVE_DLL_SEARCH_DIRECTORIES
// - The list of paths that will be probed for native DLLs called by PInvoke
//
const char *propertyKeys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES",
"APP_PATHS",
"APP_NI_PATHS",
"NATIVE_DLL_SEARCH_DIRECTORIES",
"AppDomainCompatSwitch"
};
const char *propertyValues[] = {
// TRUSTED_PLATFORM_ASSEMBLIES
tpaList.c_str(),
// APP_PATHS
appPath.c_str(),
// APP_NI_PATHS
appPath.c_str(),
// NATIVE_DLL_SEARCH_DIRECTORIES
nativeDllSearchDirs.c_str(),
// AppDomainCompatSwitch
"UseLatestBehaviorWhenTFMNotSpecified"
};
void* hostHandle;
unsigned int domainId;
int st = initializeCoreCLR(
currentExeAbsolutePath,
"unixcorerun",
sizeof(propertyKeys) / sizeof(propertyKeys[0]),
propertyKeys,
propertyValues,
&hostHandle,
&domainId);
if (!SUCCEEDED(st))
{
fprintf(stderr, "coreclr_initialize failed - status: 0x%08x\n", st);
exitCode = -1;
}
else
{
st = executeAssembly(
hostHandle,
domainId,
managedAssemblyArgc,
managedAssemblyArgv,
managedAssemblyAbsolutePath,
(unsigned int*)&exitCode);
if (!SUCCEEDED(st))
{
fprintf(stderr, "coreclr_execute_assembly failed - status: 0x%08x\n", st);
exitCode = -1;
}
st = shutdownCoreCLR(hostHandle, domainId);
if (!SUCCEEDED(st))
{
fprintf(stderr, "coreclr_shutdown failed - status: 0x%08x\n", st);
exitCode = -1;
}
}
}
if (dlclose(coreclrLib) != 0)
{
fprintf(stderr, "Warning - dlclose failed\n");
}
}
else
{
char* error = dlerror();
fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error);
}
return exitCode;
}
<|endoftext|> |
<commit_before>
/*
* examples/minpoly.C
*
* Copyright (C) 2005, 2010 D Saunders, J-G Dumas
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/** \file examples/minpoly.C
* @example examples/minpoly.C
\brief Minimal polynomial of a sparse matrix.
\ingroup examples
*/
#include <iostream>
template <class Field, class Polynomial>
void printPolynomial (const Field &F, const Polynomial &v)
{
for (int i = (int)v.size () ; i-- ; ) {
F.write (std::cout, v[i]);
if (i > 0)
std::cout << " x^" << i << " + ";
}
std::cout << std::endl;
}
#include "linbox/field/modular.h"
#include "linbox/blackbox/sparse.h"
#include "linbox/solutions/minpoly.h"
using namespace LinBox;
using namespace std;
int main (int argc, char **argv)
{
commentator().setMaxDetailLevel (-1);
commentator().setMaxDepth (-1);
commentator().setReportStream (std::cerr);
int a = argc;
while(a--){
cerr << "argv[" << a << "] = " << argv[a] << endl;
}
if (argc < 2) {
cerr << "Usage: minpoly <matrix-file-in-SMS-format> [<p>]" << endl;
return -1;
}
ifstream input (argv[1]);
if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; }
if (argc != 3) {
int process = 0;
Method::Blackbox M;
#ifdef __LINBOX_HAVE_MPI
Communicator C(&argc, &argv);
process = C.rank();
M.communicatorp(&C);
#endif
PID_integer ZZ;
SparseMatrix<PID_integer> A (ZZ);
A.read (input);
if(process == 0)
cout << "A is " << A.rowdim() << " by " << A.coldim() << endl;
vector<PID_integer::Element> m_A;
VectorDomain<PID_integer> VD(ZZ);
SparseMatrix<P>::Col b = *(A.colBegin()+i);
SparseMatrix<P>::Col b = A.colBegin()[i];
SparseMatrix<P>::ColIterator p = A.colBegin();
for ( ; p < A.colEnd(); ++p) use *p
p[i]
*(p + i)
b = *p;
VD.axpyin(m_a, alpha, b);
minpoly (m_A, A, M);
if(process == 0){
cout << "Minimal Polynomial is ";
printPolynomial (ZZ, m_A);
}
// minpoly (m_A, A, Method::BlasElimination() );
// if(process == 0){
// cout << "Minimal Polynomial is ";
// printPolynomial (ZZ, m_A);
// }
}
else{
typedef Modular<double> Field;
double q = atof(argv[2]);
Field F(q);
SparseMatrix<Field> B (F);
B.read (input);
cout << "B is " << B.rowdim() << " by " << B.coldim() << endl;
vector<Field::Element> m_B;
minpoly (m_B, B);
cout << "Minimal Polynomial is ";
printPolynomial (F, m_B);
// minpoly (m_A, A, Method::BlasElimination() );
// cout << "Minimal Polynomial is ";
// printPolynomial (F, m_B);
}
return 0;
}
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s
// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:
<commit_msg> clean up<commit_after>
/*
* examples/minpoly.C
*
* Copyright (C) 2005, 2010 D Saunders, J-G Dumas
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/** \file examples/minpoly.C
* @example examples/minpoly.C
\brief Minimal polynomial of a sparse matrix.
\ingroup examples
*/
#include <iostream>
template <class Field, class Polynomial>
void printPolynomial (const Field &F, const Polynomial &v)
{
for (int i = (int)v.size () ; i-- ; ) {
F.write (std::cout, v[i]);
if (i > 0)
std::cout << " x^" << i << " + ";
}
std::cout << std::endl;
}
#include "linbox/field/modular.h"
#include "linbox/blackbox/sparse.h"
#include "linbox/solutions/minpoly.h"
using namespace LinBox;
using namespace std;
int main (int argc, char **argv)
{
commentator().setMaxDetailLevel (-1);
commentator().setMaxDepth (-1);
commentator().setReportStream (std::cerr);
int a = argc;
while(a--){
cerr << "argv[" << a << "] = " << argv[a] << endl;
}
if (argc < 2) {
cerr << "Usage: minpoly <matrix-file-in-SMS-format> [<p>]" << endl;
return -1;
}
ifstream input (argv[1]);
if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; }
if (argc != 3) {
int process = 0;
Method::Blackbox M;
#ifdef __LINBOX_HAVE_MPI
Communicator C(&argc, &argv);
process = C.rank();
M.communicatorp(&C);
#endif
PID_integer ZZ;
SparseMatrix<PID_integer> A (ZZ);
A.read (input);
if(process == 0)
cout << "A is " << A.rowdim() << " by " << A.coldim() << endl;
vector<PID_integer::Element> m_A;
minpoly (m_A, A, M);
if(process == 0){
cout << "Minimal Polynomial is ";
printPolynomial (ZZ, m_A);
}
// minpoly (m_A, A, Method::BlasElimination() );
// if(process == 0){
// cout << "Minimal Polynomial is ";
// printPolynomial (ZZ, m_A);
// }
}
else{
typedef Modular<double> Field;
double q = atof(argv[2]);
Field F(q);
SparseMatrix<Field> B (F);
B.read (input);
cout << "B is " << B.rowdim() << " by " << B.coldim() << endl;
vector<Field::Element> m_B;
minpoly (m_B, B);
cout << "Minimal Polynomial is ";
printPolynomial (F, m_B);
// minpoly (m_A, A, Method::BlasElimination() );
// cout << "Minimal Polynomial is ";
// printPolynomial (F, m_B);
}
return 0;
}
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s
// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:
<|endoftext|> |
<commit_before>#include <cstddef>
#include <cstdint>
#include <insertionfinder/algorithm.hpp>
#include <insertionfinder/cube.hpp>
#include <insertionfinder/twist.hpp>
#include <insertionfinder/improver/improver.hpp>
#include <insertionfinder/improver/slice.hpp>
using std::size_t;
using std::uint32_t;
using InsertionFinder::Algorithm;
using InsertionFinder::Cube;
using InsertionFinder::InsertionAlgorithm;
using InsertionFinder::Rotation;
using InsertionFinder::SliceImprover;
using InsertionFinder::Twist;
namespace CubeTwist = InsertionFinder::CubeTwist;
void SliceImprover::Worker::search() {
static constexpr std::byte twist_flag = CubeTwist::edges | CubeTwist::centers;
Cube state;
for (size_t insert_place = 0; insert_place <= this->skeleton.length(); ++insert_place) {
if (insert_place == 0) {
state.twist(this->skeleton, twist_flag);
state.rotate(this->placement, twist_flag);
state.twist(this->improver.inverse_skeleton_cube, twist_flag);
} else {
Twist twist = this->skeleton[insert_place - 1];
state.twist_before(twist.inverse(), twist_flag);
state.twist(twist, twist_flag);
}
this->try_insertion(insert_place, state);
if (this->skeleton.swappable(insert_place)) {
Twist twist0 = this->skeleton[insert_place - 1];
Twist twist1 = this->skeleton[insert_place];
Cube swapped_state;
swapped_state.twist(twist0, twist_flag);
swapped_state.twist(twist1.inverse(), twist_flag);
swapped_state.twist(state, twist_flag);
swapped_state.twist(twist1, twist_flag);
swapped_state.twist(twist0.inverse(), twist_flag);
this->try_insertion(insert_place, swapped_state, true);
}
}
}
void SliceImprover::Worker::try_insertion(size_t insert_place, const Cube& state, bool swapped) {
static constexpr std::byte twist_flag = CubeTwist::edges | CubeTwist::centers;
static constexpr uint32_t valid_masks[3] = {0x3cf0000, 0x3305500, 0x0f0aa00};
Algorithm skeleton = this->skeleton;
if (swapped) {
skeleton.swap_adjacent(insert_place);
}
auto insert_place_mask = skeleton.get_insert_place_mask(insert_place);
for (const Case& _case: this->improver.cases) {
Cube cube = Cube::twist(state, _case.get_state(), twist_flag, twist_flag);
uint32_t mask = cube.mask();
if ((mask & ~valid_masks[0]) && (mask & ~valid_masks[1]) && (mask & ~valid_masks[2])) {
continue;
}
for (const InsertionAlgorithm& algorithm: _case.algorithm_list()) {
size_t target = this->improver.fewest_moves + this->improver.options.threshold;
if (!skeleton.is_worthy_insertion(algorithm, insert_place, insert_place_mask, target)) {
continue;
}
Algorithm new_skeleton = skeleton.insert(algorithm, insert_place).first;
if (new_skeleton.length() > target) {
continue;
}
new_skeleton.normalize();
if (cube.mask() == 0) {
std::lock_guard<std::mutex> lock(this->improver.fewest_moves_mutex);
if (new_skeleton.length() < this->improver.fewest_moves) {
this->improver.fewest_moves = new_skeleton.length();
this->improver.partial_solution_list.clear();
}
this->improver.partial_solution_list.insert(new_skeleton);
}
this->improver.run_worker(
this->pool,
std::move(new_skeleton),
SolvingStep {
&this->skeleton, insert_place, &algorithm, swapped, cube.placement(),
this->cancellation + this->skeleton.length() + algorithm.length() - new_skeleton.length()
}
);
}
}
}
<commit_msg>improve SliceImprover pruning algorithm<commit_after>#include <cstddef>
#include <cstdint>
#include <bitset>
#include <insertionfinder/algorithm.hpp>
#include <insertionfinder/cube.hpp>
#include <insertionfinder/twist.hpp>
#include <insertionfinder/improver/improver.hpp>
#include <insertionfinder/improver/slice.hpp>
using std::size_t;
using std::uint32_t;
using InsertionFinder::Algorithm;
using InsertionFinder::Cube;
using InsertionFinder::InsertionAlgorithm;
using InsertionFinder::Rotation;
using InsertionFinder::SliceImprover;
using InsertionFinder::Twist;
namespace CubeTwist = InsertionFinder::CubeTwist;
namespace {
constexpr size_t bitcount(uint32_t n) noexcept {
return std::bitset<32>(n).count();
}
};
void SliceImprover::Worker::search() {
static constexpr std::byte twist_flag = CubeTwist::edges | CubeTwist::centers;
Cube state;
for (size_t insert_place = 0; insert_place <= this->skeleton.length(); ++insert_place) {
if (insert_place == 0) {
state.twist(this->skeleton, twist_flag);
state.rotate(this->placement, twist_flag);
state.twist(this->improver.inverse_skeleton_cube, twist_flag);
} else {
Twist twist = this->skeleton[insert_place - 1];
state.twist_before(twist.inverse(), twist_flag);
state.twist(twist, twist_flag);
}
this->try_insertion(insert_place, state);
if (this->skeleton.swappable(insert_place)) {
Twist twist0 = this->skeleton[insert_place - 1];
Twist twist1 = this->skeleton[insert_place];
Cube swapped_state;
swapped_state.twist(twist0, twist_flag);
swapped_state.twist(twist1.inverse(), twist_flag);
swapped_state.twist(state, twist_flag);
swapped_state.twist(twist1, twist_flag);
swapped_state.twist(twist0.inverse(), twist_flag);
this->try_insertion(insert_place, swapped_state, true);
}
}
}
void SliceImprover::Worker::try_insertion(size_t insert_place, const Cube& state, bool swapped) {
static constexpr std::byte twist_flag = CubeTwist::edges | CubeTwist::centers;
Algorithm skeleton = this->skeleton;
if (swapped) {
skeleton.swap_adjacent(insert_place);
}
auto insert_place_mask = skeleton.get_insert_place_mask(insert_place);
for (const Case& _case: this->improver.cases) {
Cube cube = Cube::twist(state, _case.get_state(), twist_flag, twist_flag);
uint32_t mask = cube.mask();
if ((mask & 0xff) || bitcount(mask & 0xfff00) > 4 || bitcount(mask & 0x3f0000) > 4) {
continue;
}
for (const InsertionAlgorithm& algorithm: _case.algorithm_list()) {
size_t target = this->improver.fewest_moves + this->improver.options.threshold;
if (!skeleton.is_worthy_insertion(algorithm, insert_place, insert_place_mask, target)) {
continue;
}
Algorithm new_skeleton = skeleton.insert(algorithm, insert_place).first;
if (new_skeleton.length() > target) {
continue;
}
new_skeleton.normalize();
if (mask == 0) {
std::lock_guard<std::mutex> lock(this->improver.fewest_moves_mutex);
if (new_skeleton.length() < this->improver.fewest_moves) {
this->improver.fewest_moves = new_skeleton.length();
this->improver.partial_solution_list.clear();
}
this->improver.partial_solution_list.insert(new_skeleton);
}
this->improver.run_worker(
this->pool,
std::move(new_skeleton),
SolvingStep {
&this->skeleton, insert_place, &algorithm, swapped, cube.placement(),
this->cancellation + this->skeleton.length() + algorithm.length() - new_skeleton.length()
}
);
}
}
}
<|endoftext|> |
<commit_before>#include "childprocess.h"
// POSIX
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
// POSIX++
#include <cerrno>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <cassert>
// PDTK
#include <specialized/procstat.h>
#include <specialized/eventbackend.h>
#include <cxxutils/error_helpers.h>
#include <cxxutils/vterm.h>
static std::unordered_map<pid_t, ChildProcess*> process_map; // do not try to own Process memory
void ChildProcess::init_once(void) noexcept
{
static bool first = true;
if(first)
{
first = false;
struct sigaction actions;
actions.sa_handler = &handler;
sigemptyset(&actions.sa_mask);
actions.sa_flags = SA_RESTART | SA_NOCLDSTOP;
flaw(::sigaction(SIGCHLD, &actions, nullptr) == posix::error_response,
terminal::critical,
std::exit(errno),,
"Unable assign action to a signal: %s", std::strerror(errno))
}
}
// in case of incomplete implementations
#if !defined(WCONTINUED)
#define WCONTINUED 0
#endif
void ChildProcess::handler(int signum) noexcept
{
flaw(signum != SIGCHLD,
terminal::warning,
posix::error(std::errc::invalid_argument),,
"Process::reaper() has been called improperly")
pid_t pid = posix::error_response; // set value just in case
int status = 0;
while((pid = ::waitpid(pid_t(-1), &status, WNOHANG | WCONTINUED | WUNTRACED)) > 0) // get the next dead process (if there is one)... while the currently reaped process was valid
{
auto process_map_iter = process_map.find(pid); // find dead process
if(process_map_iter != process_map.end()) // if the dead process exists...
{
ChildProcess* p = process_map_iter->second;
if(WIFEXITED(status))
{
EventBackend::remove(p->getStdOut(), EventBackend::SimplePollReadFlags);
EventBackend::remove(p->getStdErr(), EventBackend::SimplePollReadFlags);
posix::close(p->getStdOut());
posix::close(p->getStdErr());
posix::close(p->getStdIn());
p->m_state = ChildProcess::State::Finished;
if(WIFSIGNALED(status))
Object::enqueue_copy(p->killed, p->processId(), posix::signal::EId(WTERMSIG(status)));
else
Object::enqueue_copy(p->finished, p->processId(), posix::error_t(WEXITSTATUS(status)));
process_map.erase(process_map_iter); // remove finished process from the process map
}
else if(WIFSTOPPED(status))
{
p->m_state = ChildProcess::State::Stopped;
Object::enqueue_copy(p->stopped, p->processId());
}
#if defined(WIFCONTINUED)
else if(WIFCONTINUED(status))
{
p->m_state = ChildProcess::State::Running;
Object::enqueue_copy(p->started, p->processId());
}
#endif
}
}
}
ChildProcess::ChildProcess(void) noexcept
: m_state(State::Initializing)
{
init_once();
process_map.emplace(processId(), this); // add self to process map
}
ChildProcess::~ChildProcess(void) noexcept
{
EventBackend::remove(getStdOut(), EventBackend::SimplePollReadFlags);
EventBackend::remove(getStdErr(), EventBackend::SimplePollReadFlags);
}
bool ChildProcess::setOption(const std::string& name, const std::string& value) noexcept
{
m_iobuf.reset();
return !(m_iobuf << name << value).hadError() && writeStdIn(m_iobuf);
}
bool ChildProcess::sendSignal(posix::signal::EId id, int value) const noexcept
{
return posix::signal::send(processId(), id, value);
}
bool ChildProcess::invoke(void) noexcept
{
posix::success();
flaw(m_state != State::Initializing,
terminal::severe,
posix::error(std::errc::device_or_resource_busy),
false,
"Called Process::invoke() on an active process!");
EventBackend::add(getStdOut(), EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{ Object::enqueue(stdoutMessage, lambda_fd); });
EventBackend::add(getStdErr(), EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{ Object::enqueue(stderrMessage, lambda_fd); });
m_iobuf.reset();
if((m_iobuf << "Launch").hadError() ||
!writeStdIn(m_iobuf))
return false;
m_state = State::Invalid;
if(state() == State::Running)
Object::enqueue_copy(started, processId());
return errno == posix::success_response;
}
ChildProcess::State ChildProcess::state(void) noexcept
{
switch(m_state)
{
case State::Finished:
case State::Initializing:
break;
default:
process_state_t data;
flaw(::procstat(processId(), data) == posix::error_response && m_state != State::Finished,
terminal::severe,
m_state = State::Invalid,
m_state,
"Process %i does not exist.", processId()); // process must exist (rare case where process could exit durring this call is handled)
switch (data.state)
{
case WaitingInterruptable:
case WaitingUninterruptable:
m_state = State::Waiting; break;
case Zombie : m_state = State::Zombie ; break;
case Stopped: m_state = State::Stopped; break;
case Running: m_state = State::Running; break;
default: break; // invalid state (process exited before it could be stat'd
}
}
return m_state;
}
<commit_msg>accept child start/stop<commit_after>#include "childprocess.h"
// POSIX
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
// POSIX++
#include <cerrno>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <cassert>
// PDTK
#include <specialized/procstat.h>
#include <specialized/eventbackend.h>
#include <cxxutils/error_helpers.h>
#include <cxxutils/vterm.h>
static std::unordered_map<pid_t, ChildProcess*> process_map; // do not try to own Process memory
void ChildProcess::init_once(void) noexcept
{
static bool first = true;
if(first)
{
first = false;
struct sigaction actions;
actions.sa_handler = &handler; // don't bother sending signal info (it's provided by waitpid())
sigemptyset(&actions.sa_mask);
actions.sa_flags = SA_RESTART;
flaw(::sigaction(SIGCHLD, &actions, nullptr) == posix::error_response,
terminal::critical,
std::exit(errno),,
"Unable assign action to a signal: %s", std::strerror(errno))
}
}
// in case of incomplete implementations
#if !defined(WCONTINUED)
#define WCONTINUED 0
#endif
void ChildProcess::handler(int signum) noexcept
{
flaw(signum != SIGCHLD,
terminal::warning,
posix::error(std::errc::invalid_argument),,
"Process::reaper() has been called improperly")
pid_t pid = posix::error_response; // set value just in case
int status = 0;
while((pid = ::waitpid(pid_t(-1), &status, WNOHANG | WCONTINUED | WUNTRACED)) > 0) // get the next dead process (if there is one)... while the currently reaped process was valid
{
auto process_map_iter = process_map.find(pid); // find dead process
if(process_map_iter != process_map.end()) // if the dead process exists...
{
ChildProcess* p = process_map_iter->second;
if(WIFEXITED(status))
{
EventBackend::remove(p->getStdOut(), EventBackend::SimplePollReadFlags);
EventBackend::remove(p->getStdErr(), EventBackend::SimplePollReadFlags);
posix::close(p->getStdOut());
posix::close(p->getStdErr());
posix::close(p->getStdIn());
p->m_state = ChildProcess::State::Finished;
if(WIFSIGNALED(status))
Object::enqueue_copy(p->killed, p->processId(), posix::signal::EId(WTERMSIG(status)));
else
Object::enqueue_copy(p->finished, p->processId(), posix::error_t(WEXITSTATUS(status)));
process_map.erase(process_map_iter); // remove finished process from the process map
}
else if(WIFSTOPPED(status))
{
p->m_state = ChildProcess::State::Stopped;
Object::enqueue_copy(p->stopped, p->processId());
}
#if defined(WIFCONTINUED)
else if(WIFCONTINUED(status))
{
p->m_state = ChildProcess::State::Running;
Object::enqueue_copy(p->started, p->processId());
}
#endif
}
}
}
ChildProcess::ChildProcess(void) noexcept
: m_state(State::Initializing)
{
init_once();
process_map.emplace(processId(), this); // add self to process map
}
ChildProcess::~ChildProcess(void) noexcept
{
EventBackend::remove(getStdOut(), EventBackend::SimplePollReadFlags);
EventBackend::remove(getStdErr(), EventBackend::SimplePollReadFlags);
}
bool ChildProcess::setOption(const std::string& name, const std::string& value) noexcept
{
m_iobuf.reset();
return !(m_iobuf << name << value).hadError() && writeStdIn(m_iobuf);
}
bool ChildProcess::sendSignal(posix::signal::EId id, int value) const noexcept
{
return posix::signal::send(processId(), id, value);
}
bool ChildProcess::invoke(void) noexcept
{
posix::success();
flaw(m_state != State::Initializing,
terminal::severe,
posix::error(std::errc::device_or_resource_busy),
false,
"Called Process::invoke() on an active process!");
EventBackend::add(getStdOut(), EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{ Object::enqueue(stdoutMessage, lambda_fd); });
EventBackend::add(getStdErr(), EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{ Object::enqueue(stderrMessage, lambda_fd); });
m_iobuf.reset();
if((m_iobuf << "Launch").hadError() ||
!writeStdIn(m_iobuf))
return false;
m_state = State::Invalid;
if(state() == State::Running)
Object::enqueue_copy(started, processId());
return errno == posix::success_response;
}
ChildProcess::State ChildProcess::state(void) noexcept
{
switch(m_state)
{
case State::Finished:
case State::Initializing:
break;
default:
process_state_t data;
flaw(::procstat(processId(), data) == posix::error_response && m_state != State::Finished,
terminal::severe,
m_state = State::Invalid,
m_state,
"Process %i does not exist.", processId()); // process must exist (rare case where process could exit durring this call is handled)
switch (data.state)
{
case WaitingInterruptable:
case WaitingUninterruptable:
m_state = State::Waiting; break;
case Zombie : m_state = State::Zombie ; break;
case Stopped: m_state = State::Stopped; break;
case Running: m_state = State::Running; break;
default: break; // invalid state (process exited before it could be stat'd
}
}
return m_state;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, 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.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LOGGER_HPP
#define GUARD_MIOPEN_LOGGER_HPP
#include <array>
#include <iostream>
#include <miopen/each_args.hpp>
#include <sstream>
#include <type_traits>
// Helper macros to output a cmdline argument for the driver
#define MIOPEN_DRIVER_CMD(op) \
__func__ << ": " \
<< "./bin/MIOpenDriver " << op
// See https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms
#define MIOPEN_PP_CAT(x, y) MIOPEN_PP_PRIMITIVE_CAT(x, y)
#define MIOPEN_PP_PRIMITIVE_CAT(x, y) x##y
#define MIOPEN_PP_IIF(c) MIOPEN_PP_PRIMITIVE_CAT(MIOPEN_PP_IIF_, c)
#define MIOPEN_PP_IIF_0(t, ...) __VA_ARGS__
#define MIOPEN_PP_IIF_1(t, ...) t
#define MIOPEN_PP_IS_PAREN(x) MIOPEN_PP_IS_PAREN_CHECK(MIOPEN_PP_IS_PAREN_PROBE x)
#define MIOPEN_PP_IS_PAREN_CHECK(...) MIOPEN_PP_IS_PAREN_CHECK_N(__VA_ARGS__, 0)
#define MIOPEN_PP_IS_PAREN_PROBE(...) ~, 1,
#define MIOPEN_PP_IS_PAREN_CHECK_N(x, n, ...) n
#define MIOPEN_PP_EAT(...)
#define MIOPEN_PP_EXPAND(...) __VA_ARGS__
#define MIOPEN_PP_COMMA(...) ,
#define MIOPEN_PP_TRANSFORM_ARGS(m, ...) \
MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \
MIOPEN_PP_COMMA, \
__VA_ARGS__, \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
()))
#define MIOPEN_PP_EACH_ARGS(m, ...) \
MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \
MIOPEN_PP_EAT, \
__VA_ARGS__, \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
()))
#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS( \
m, delim, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, ...) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x0) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x1) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x1) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x2) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x2) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x3) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x3) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x4) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x4) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x5) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x5) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x6) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x6) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x7) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x7) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x8) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x8) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x9) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x9) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x10) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x10) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x11) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x11) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x12) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x12) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x13) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x13) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x14) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x14) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x15) MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x15)
#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x) \
MIOPEN_PP_IIF(MIOPEN_PP_IS_PAREN(x))(MIOPEN_PP_EAT, m)(x)
namespace miopen {
template <class Range>
std::ostream& LogRange(std::ostream& os, Range&& r, std::string delim)
{
bool first = true;
for(auto&& x : r)
{
if(first)
first = false;
else
os << delim;
os << x;
}
return os;
}
template <class T, class... Ts>
std::array<T, sizeof...(Ts) + 1> make_array(T x, Ts... xs)
{
return {{x, xs...}};
}
#define MIOPEN_LOG_ENUM_EACH(x) std::pair<std::string, decltype(x)>(#x, x)
#ifdef _MSC_VER
#define MIOPEN_LOG_ENUM(os, ...) os
#else
#define MIOPEN_LOG_ENUM(os, x, ...) \
miopen::LogEnum(os, x, make_array(MIOPEN_PP_TRANSFORM_ARGS(MIOPEN_LOG_ENUM_EACH, __VA_ARGS__)))
#endif
template <class T, class Range>
std::ostream& LogEnum(std::ostream& os, T x, Range&& values)
{
for(auto&& p : values)
{
if(p.second == x)
{
os << p.first;
return os;
}
}
os << "Unknown: " << x;
return os;
}
enum class LoggingLevel
{
Default = 0, // WARNING for Release builds, INFO for Debug builds.
Quiet,
Fatal,
Error,
Warning,
Info,
Info2,
Trace // E.g. messages output by MIOPEN_LOG_FUNCTION).
};
const char* LoggingLevelToCString(LoggingLevel level);
std::string PlatformName();
/// \return true if level is enabled.
/// \param level - one of the values defined in LoggingLevel.
int IsLogging(LoggingLevel level = LoggingLevel::Error);
bool IsLoggingCmd();
template <class T>
auto LogObjImpl(T* x) -> decltype(get_object(*x))
{
return get_object(*x);
}
inline void* LogObjImpl(void* x) { return x; }
inline const void* LogObjImpl(const void* x) { return x; }
#ifndef _MSC_VER
template <class T, typename std::enable_if<(std::is_pointer<T>{}), int>::type = 0>
std::ostream& LogParam(std::ostream& os, std::string name, const T& x)
{
os << name << " = ";
if(x == nullptr)
os << "nullptr";
else
os << LogObjImpl(x);
return os;
}
template <class T, typename std::enable_if<(not std::is_pointer<T>{}), int>::type = 0>
std::ostream& LogParam(std::ostream& os, std::string name, const T& x)
{
os << name << " = " << get_object(x);
return os;
}
#define MIOPEN_LOG_FUNCTION_EACH(param) miopen::LogParam(std::cerr, #param, param) << std::endl;
#define MIOPEN_LOG_FUNCTION(...) \
if(miopen::IsLogging(miopen::LoggingLevel::Trace)) \
{ \
std::cerr << miopen::PlatformName() << ": " << __PRETTY_FUNCTION__ << "{" << std::endl; \
MIOPEN_PP_EACH_ARGS(MIOPEN_LOG_FUNCTION_EACH, __VA_ARGS__) \
std::cerr << "}" << std::endl; \
}
#else
#define MIOPEN_LOG_FUNCTION(...)
#endif
/// \todo __PRETTY_FUNCTION__ is too verbose, __func_ it too short.
/// Shall we add filename (no path, no ext) prior __func__.
#define MIOPEN_LOG(level, ...) \
do \
{ \
if(miopen::IsLogging(level)) \
{ \
std::stringstream MIOPEN_LOG_ss; \
MIOPEN_LOG_ss << miopen::PlatformName() << ": " << LoggingLevelToCString(level) \
<< " [" << __func__ << "] " << __VA_ARGS__ << std::endl; \
std::cerr << MIOPEN_LOG_ss.str(); \
} \
} while(false)
#define MIOPEN_LOG_E(...) MIOPEN_LOG(miopen::LoggingLevel::Error, __VA_ARGS__)
#define MIOPEN_LOG_W(...) MIOPEN_LOG(miopen::LoggingLevel::Warning, __VA_ARGS__)
#define MIOPEN_LOG_I(...) MIOPEN_LOG(miopen::LoggingLevel::Info, __VA_ARGS__)
#define MIOPEN_LOG_I2(...) MIOPEN_LOG(miopen::LoggingLevel::Info2, __VA_ARGS__)
} // namespace miopen
#endif
<commit_msg>verbose-test-perfdb(a2) Lowercase fix.<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, 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.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LOGGER_HPP
#define GUARD_MIOPEN_LOGGER_HPP
#include <array>
#include <iostream>
#include <miopen/each_args.hpp>
#include <sstream>
#include <type_traits>
// Helper macros to output a cmdline argument for the driver
#define MIOPEN_DRIVER_CMD(op) \
__func__ << ": " \
<< "./bin/MIOpenDriver " << op
// See https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms
#define MIOPEN_PP_CAT(x, y) MIOPEN_PP_PRIMITIVE_CAT(x, y)
#define MIOPEN_PP_PRIMITIVE_CAT(x, y) x##y
#define MIOPEN_PP_IIF(c) MIOPEN_PP_PRIMITIVE_CAT(MIOPEN_PP_IIF_, c)
#define MIOPEN_PP_IIF_0(t, ...) __VA_ARGS__
#define MIOPEN_PP_IIF_1(t, ...) t
#define MIOPEN_PP_IS_PAREN(x) MIOPEN_PP_IS_PAREN_CHECK(MIOPEN_PP_IS_PAREN_PROBE x)
#define MIOPEN_PP_IS_PAREN_CHECK(...) MIOPEN_PP_IS_PAREN_CHECK_N(__VA_ARGS__, 0)
#define MIOPEN_PP_IS_PAREN_PROBE(...) ~, 1,
#define MIOPEN_PP_IS_PAREN_CHECK_N(x, n, ...) n
#define MIOPEN_PP_EAT(...)
#define MIOPEN_PP_EXPAND(...) __VA_ARGS__
#define MIOPEN_PP_COMMA(...) ,
#define MIOPEN_PP_TRANSFORM_ARGS(m, ...) \
MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \
MIOPEN_PP_COMMA, \
__VA_ARGS__, \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
()))
#define MIOPEN_PP_EACH_ARGS(m, ...) \
MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \
MIOPEN_PP_EAT, \
__VA_ARGS__, \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
(), \
()))
#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS( \
m, delim, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, ...) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x0) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x1) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x1) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x2) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x2) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x3) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x3) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x4) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x4) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x5) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x5) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x6) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x6) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x7) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x7) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x8) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x8) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x9) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x9) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x10) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x10) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x11) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x11) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x12) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x12) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x13) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x13) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x14) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x14) \
MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x15) MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x15)
#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x) \
MIOPEN_PP_IIF(MIOPEN_PP_IS_PAREN(x))(MIOPEN_PP_EAT, m)(x)
namespace miopen {
template <class Range>
std::ostream& LogRange(std::ostream& os, Range&& r, std::string delim)
{
bool first = true;
for(auto&& x : r)
{
if(first)
first = false;
else
os << delim;
os << x;
}
return os;
}
template <class T, class... Ts>
std::array<T, sizeof...(Ts) + 1> make_array(T x, Ts... xs)
{
return {{x, xs...}};
}
#define MIOPEN_LOG_ENUM_EACH(x) std::pair<std::string, decltype(x)>(#x, x)
#ifdef _MSC_VER
#define MIOPEN_LOG_ENUM(os, ...) os
#else
#define MIOPEN_LOG_ENUM(os, x, ...) \
miopen::LogEnum(os, x, make_array(MIOPEN_PP_TRANSFORM_ARGS(MIOPEN_LOG_ENUM_EACH, __VA_ARGS__)))
#endif
template <class T, class Range>
std::ostream& LogEnum(std::ostream& os, T x, Range&& values)
{
for(auto&& p : values)
{
if(p.second == x)
{
os << p.first;
return os;
}
}
os << "Unknown: " << x;
return os;
}
enum class LoggingLevel
{
Default = 0, // WARNING for Release builds, INFO for Debug builds.
Quiet,
Fatal,
Error,
Warning,
Info,
Info2,
Trace // E.g. messages output by MIOPEN_LOG_FUNCTION).
};
const char* LoggingLevelToCString(LoggingLevel level);
std::string PlatformName();
/// \return true if level is enabled.
/// \param level - one of the values defined in LoggingLevel.
int IsLogging(LoggingLevel level = LoggingLevel::Error);
bool IsLoggingCmd();
template <class T>
auto LogObjImpl(T* x) -> decltype(get_object(*x))
{
return get_object(*x);
}
inline void* LogObjImpl(void* x) { return x; }
inline const void* LogObjImpl(const void* x) { return x; }
#ifndef _MSC_VER
template <class T, typename std::enable_if<(std::is_pointer<T>{}), int>::type = 0>
std::ostream& LogParam(std::ostream& os, std::string name, const T& x)
{
os << name << " = ";
if(x == nullptr)
os << "nullptr";
else
os << LogObjImpl(x);
return os;
}
template <class T, typename std::enable_if<(not std::is_pointer<T>{}), int>::type = 0>
std::ostream& LogParam(std::ostream& os, std::string name, const T& x)
{
os << name << " = " << get_object(x);
return os;
}
#define MIOPEN_LOG_FUNCTION_EACH(param) miopen::LogParam(std::cerr, #param, param) << std::endl;
#define MIOPEN_LOG_FUNCTION(...) \
if(miopen::IsLogging(miopen::LoggingLevel::Trace)) \
{ \
std::cerr << miopen::PlatformName() << ": " << __PRETTY_FUNCTION__ << "{" << std::endl; \
MIOPEN_PP_EACH_ARGS(MIOPEN_LOG_FUNCTION_EACH, __VA_ARGS__) \
std::cerr << "}" << std::endl; \
}
#else
#define MIOPEN_LOG_FUNCTION(...)
#endif
/// \todo __PRETTY_FUNCTION__ is too verbose, __func_ it too short.
/// Shall we add filename (no path, no ext) prior __func__.
#define MIOPEN_LOG(level, ...) \
do \
{ \
if(miopen::IsLogging(level)) \
{ \
std::stringstream miopen_log_ss; /* long name to avoid "shadowing name" warning */ \
miopen_log_ss << miopen::PlatformName() << ": " << LoggingLevelToCString(level) \
<< " [" << __func__ << "] " << __VA_ARGS__ << std::endl; \
std::cerr << miopen_log_ss.str(); \
} \
} while(false)
#define MIOPEN_LOG_E(...) MIOPEN_LOG(miopen::LoggingLevel::Error, __VA_ARGS__)
#define MIOPEN_LOG_W(...) MIOPEN_LOG(miopen::LoggingLevel::Warning, __VA_ARGS__)
#define MIOPEN_LOG_I(...) MIOPEN_LOG(miopen::LoggingLevel::Info, __VA_ARGS__)
#define MIOPEN_LOG_I2(...) MIOPEN_LOG(miopen::LoggingLevel::Info2, __VA_ARGS__)
} // namespace miopen
#endif
<|endoftext|> |
<commit_before>#ifndef __BUFFER_CACHE_TYPES_HPP__
#define __BUFFER_CACHE_TYPES_HPP__
#include <limits.h>
#include <stdint.h>
#include "serializer/types.hpp"
const int DEFAULT_EVICTION_PRIORITY = INT_MAX / 2;
// TODO: Get rid of FAKE_EVICTION_PRIORITY. It's just the default
// eviction priority, with the connotation the code using is is doing
// something stupid and needs to be fixed.
const int FAKE_EVICTION_PRIORITY = INT_MAX / 2;
typedef uint32_t block_magic_comparison_t;
struct block_magic_t {
char bytes[sizeof(block_magic_comparison_t)];
bool operator==(const block_magic_t& other) const {
union {
block_magic_t x;
block_magic_comparison_t n;
} u, v;
u.x = *this;
v.x = other;
return u.n == v.n;
}
bool operator!=(const block_magic_t& other) const {
return !(operator==(other));
}
};
// HEY: put this somewhere else.
class get_subtree_recencies_callback_t {
public:
virtual void got_subtree_recencies() = 0;
protected:
virtual ~get_subtree_recencies_callback_t() { }
};
template <class T> class scoped_malloc;
// HEY: This is kind of fsck-specific, maybe it belongs somewhere else.
class block_getter_t {
public:
virtual bool get_block(block_id_t, scoped_malloc<char>& block_out) = 0;
protected:
virtual ~block_getter_t() { }
};
// This line is hereby labeled BLAH.
// Keep this part below synced up with buffer_cache.hpp.
#ifndef MOCK_CACHE_CHECK
class mc_cache_t;
class mc_buf_t;
class mc_transaction_t;
class mc_cache_account_t;
#if !defined(VALGRIND) && !defined(NDEBUG)
template <class inner_cache_type> class scc_cache_t;
template <class inner_cache_type> class scc_buf_t;
template <class inner_cache_type> class scc_transaction_t;
typedef scc_cache_t<mc_cache_t> cache_t;
typedef scc_buf_t<mc_cache_t> buf_t;
typedef scc_transaction_t<mc_cache_t> transaction_t;
typedef mc_cache_account_t cache_account_t;
#else // !defined(VALGRIND) && !defined(NDEBUG)
// scc_cache_t is way too slow under valgrind and makes automated
// tests run forever.
typedef mc_cache_t cache_t;
typedef mc_buf_t buf_t;
typedef mc_transaction_t transaction_t;
typedef mc_cache_account_t cache_account_t;
#endif // !defined(VALGRIND) && !defined(NDEBUG)
#else
class mock_cache_t;
class mock_cache_account_t;
#if !defined(VALGRIND)
template <class inner_cache_type> class scc_cache_t;
template <class inner_cache_type> class scc_buf_t;
template <class inner_cache_type> class scc_transaction_t;
typedef scc_cache_t<mock_cache_t> cache_t;
typedef scc_buf_t<mock_cache_t> buf_t;
typedef scc_transaction_t<mock_cache_t> transaction_t;
typedef mock_cache_account_t cache_account_t;
#else // !defined(VALGRIND)
class mock_buf_t;
class mock_transaction_t;
class mock_cache_account_t;
typedef mock_cache_t cache_t;
typedef mock_buf_t buf_t;
typedef mock_transaction_t transaction_t;
typedef mock_cache_account_t cache_account_t;
#endif // !defined(VALGRIND)
#endif // MOCK_CACHE_CHECK
// Don't put anything down here, put it above the line labeled "BLAH".
#endif /* __BUFFER_CACHE_TYPES_HPP__ */
<commit_msg>This line is hereby unlabeled.<commit_after>#ifndef __BUFFER_CACHE_TYPES_HPP__
#define __BUFFER_CACHE_TYPES_HPP__
#include <limits.h>
#include <stdint.h>
#include "serializer/types.hpp"
const int DEFAULT_EVICTION_PRIORITY = INT_MAX / 2;
// TODO: Get rid of FAKE_EVICTION_PRIORITY. It's just the default
// eviction priority, with the connotation the code using is is doing
// something stupid and needs to be fixed.
const int FAKE_EVICTION_PRIORITY = INT_MAX / 2;
typedef uint32_t block_magic_comparison_t;
struct block_magic_t {
char bytes[sizeof(block_magic_comparison_t)];
bool operator==(const block_magic_t& other) const {
union {
block_magic_t x;
block_magic_comparison_t n;
} u, v;
u.x = *this;
v.x = other;
return u.n == v.n;
}
bool operator!=(const block_magic_t& other) const {
return !(operator==(other));
}
};
// HEY: put this somewhere else.
class get_subtree_recencies_callback_t {
public:
virtual void got_subtree_recencies() = 0;
protected:
virtual ~get_subtree_recencies_callback_t() { }
};
template <class T> class scoped_malloc;
// HEY: This is kind of fsck-specific, maybe it belongs somewhere else.
class block_getter_t {
public:
virtual bool get_block(block_id_t, scoped_malloc<char>& block_out) = 0;
protected:
virtual ~block_getter_t() { }
};
// Keep this part below synced up with buffer_cache.hpp.
#ifndef MOCK_CACHE_CHECK
class mc_cache_t;
class mc_buf_t;
class mc_transaction_t;
class mc_cache_account_t;
#if !defined(VALGRIND) && !defined(NDEBUG)
template <class inner_cache_type> class scc_cache_t;
template <class inner_cache_type> class scc_buf_t;
template <class inner_cache_type> class scc_transaction_t;
typedef scc_cache_t<mc_cache_t> cache_t;
typedef scc_buf_t<mc_cache_t> buf_t;
typedef scc_transaction_t<mc_cache_t> transaction_t;
typedef mc_cache_account_t cache_account_t;
#else // !defined(VALGRIND) && !defined(NDEBUG)
// scc_cache_t is way too slow under valgrind and makes automated
// tests run forever.
typedef mc_cache_t cache_t;
typedef mc_buf_t buf_t;
typedef mc_transaction_t transaction_t;
typedef mc_cache_account_t cache_account_t;
#endif // !defined(VALGRIND) && !defined(NDEBUG)
#else
class mock_cache_t;
class mock_cache_account_t;
#if !defined(VALGRIND)
template <class inner_cache_type> class scc_cache_t;
template <class inner_cache_type> class scc_buf_t;
template <class inner_cache_type> class scc_transaction_t;
typedef scc_cache_t<mock_cache_t> cache_t;
typedef scc_buf_t<mock_cache_t> buf_t;
typedef scc_transaction_t<mock_cache_t> transaction_t;
typedef mock_cache_account_t cache_account_t;
#else // !defined(VALGRIND)
class mock_buf_t;
class mock_transaction_t;
class mock_cache_account_t;
typedef mock_cache_t cache_t;
typedef mock_buf_t buf_t;
typedef mock_transaction_t transaction_t;
typedef mock_cache_account_t cache_account_t;
#endif // !defined(VALGRIND)
#endif // MOCK_CACHE_CHECK
// Don't put anything down here, put it above the line labeled "BLAH".
#endif /* __BUFFER_CACHE_TYPES_HPP__ */
<|endoftext|> |
<commit_before>#include "data-course.hpp"
using namespace std;
void Course::init(string identifier) {
// Remove a possible space at the front
if (identifier[0] == ' ')
identifier.erase(0, 1);
// add a space into the course id, if there isn't one already
int shouldBeSpaceIndex = identifier.length()-4;
if (identifier[shouldBeSpaceIndex] != ' ')
identifier.insert(shouldBeSpaceIndex+1, 1, ' ');
// cout << identifier << endl;
copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
id = c.id;
number = c.number;
title = c.title;
description = c.description;
section = c.section;
majors = c.majors;
department = c.department;
concentrations = c.concentrations;
conversations = c.conversations;
professor = c.professor;
half_semester = c.half_semester;
pass_fail = c.pass_fail;
credits = c.credits;
location = c.location;
lab = c.lab;
geneds = c.geneds;
for (int i = 0; i < 7; ++i){
days[i] = c.days[i];
time[i] = c.time[i];
}
}
Course::Course() {
}
Course::Course(string str) {
init(str);
}
Course::Course(const Course& c) {
copy(c);
}
Course& Course::operator = (const Course &c) {
if (this == &c) return *this;
copy(c);
return *this;
}
Course::Course(istream &is) {
// cout << "Now indise Course()" << endl;
if (!is) return;
// cout << "Now inside Course(after return)" << endl;
string tmpLine;
getline(is, tmpLine); // read in so we can do things with it.
vector<string> record = split(tmpLine, ',');
for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
*i = removeAllQuotes(*i);
*i = removeTrailingSlashes(*i);
}
printEntireRecord(record);
// Ignore the first column;
// record.at(0);
// so, the *first* column (that we care about) has the course id,
id = record.at(1);
parseID(id);
// Second column has the section,
section = record.at(2);
// Third holds the lab boolean,
if (record.at(3).empty()) lab = false;
else lab = true;
// while Fourth contains the title of the course;
title = record.at(4);
cleanTitle();
// Fifth hands over the length (half semester or not)
// it's actually an int that tells us how many times the course is offered per semester.
half_semester = stringToInt(record.at(5));
if (half_semester != 0 && half_semester != 1 && half_semester != 2)
half_semester = 0;
// Sixth tells us the number of credits,
credits = stringToFloat(record.at(6));
// Seventh shows us if it can be taken pass/no-pass,
if (record.at(7) == "Y")
pass_fail = true;
else
pass_fail = false;
// while Eighth gives us the GEs of the course,
// GEreqs = record.at(8);
// and Nine spits out the days and times;
// Times = record.at(9);
// Ten holds the location,
location = record.at(10);
location = deDoubleString(location);
// and Eleven knows who teaches.
if (record.size() == 13) {
string profLastName = record.at(11);
string profFirstName = record.at(12);
profFirstName.erase(0, 1); // remove the extra space from the start of the name
professor = profFirstName + " " + profLastName;
}
else {
professor = record.at(11);
}
updateID();
record.clear();
}
void Course::cleanTitle() {
// TODO: Refactor this to work on strings.
vector<string> badEndings, badBeginnings;
badEndings.push_back("Prerequisite");
badEndings.push_back("Prerequsiite");
badEndings.push_back("This course has class");
badEndings.push_back("This course is open to ");
badEndings.push_back("First-Year Students may register only");
badEndings.push_back("Open to ");
badEndings.push_back("Especially for ");
badEndings.push_back("Registration by permission of instructor only.");
badEndings.push_back("Permission of instructor required.");
badEndings.push_back("Not open to first-year students.");
badEndings.push_back("Film screenings");
badEndings.push_back("Open only to ");
badEndings.push_back("This course has been canceled.");
badEndings.push_back("This course has been cancelled.");
badEndings.push_back("Open only to seniors");
badEndings.push_back("Closed during web registration.");
badEndings.push_back("During course submission process");
badEndings.push_back("Taught in English.");
badEndings.push_back("Closed to First-Year Students.");
badEndings.push_back("Closed to first-year students.");
badEndings.push_back("New course");
badEndings.push_back("This course does");
badEndings.push_back("This course open to seniors only.");
badEndings.push_back("This lab has been canceled.");
badEndings.push_back("Permission of the instructor");
badEndings.push_back("Registration restricted");
badEndings.push_back("Students in " + department[0].getFullName() + " " + tostring(number));
badEndings.push_back("Students in " + department[0].getName() + " " + tostring(number));
badBeginnings.push_back("Top: ");
badBeginnings.push_back("Sem: ");
badBeginnings.push_back("Res: ");
for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
title = removeTrailingText(title, *i);
for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
title = removeStartingText(title, *i);
}
void Course::parseID(string str) {
// Get the number of the course, aka the last three slots.
stringstream(str.substr(str.size() - 3)) >> number;
// Check if it's one of those dastardly "split courses".
string dept = str.substr(0,str.size()-3);
if (str.find('/') != string::npos) {
department.push_back(Department(dept.substr(0,2)));
department.push_back(Department(dept.substr(3,2)));
}
else {
department.push_back(Department(dept));
}
}
void Course::updateID() {
string dept;
for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
dept += i->getName();
if (department.size() > 1)
dept += "/";
}
// ignore section until we get it assigning properly in the constructor
id = dept + " " + tostring(number) + section;
}
string Course::getID() {
return id;
}
ostream& Course::getData(ostream &os) {
os << id << " - ";
os << title << " | ";
if (professor.length() > 0 && professor != " ")
os << professor;
return os;
}
void Course::showAll() {
cout << id << section << endl;
cout << "Title: " << title << endl;
cout << "Professor: " << professor << endl;
cout << "Lab? " << lab << endl;
cout << "Half-semester? " << half_semester << endl;
cout << "Credits: " << credits << endl;
cout << "Pass/Fail? " << pass_fail << endl;
cout << "Location: " << location << endl;
cout << endl;
}
ostream &operator<<(ostream &os, Course &item) {
return item.getData(os);
}
void Course::display() {
cout << *this << endl;
}
Course getCourse(string id) {
std::transform(id.begin(), id.end(), id.begin(), ::toupper);
Course c;
for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
if (i->getID() == id)
return *i;
return c;
}
<commit_msg>Alphabetize badEndings.push_back<commit_after>#include "data-course.hpp"
using namespace std;
void Course::init(string identifier) {
// Remove a possible space at the front
if (identifier[0] == ' ')
identifier.erase(0, 1);
// add a space into the course id, if there isn't one already
int shouldBeSpaceIndex = identifier.length()-4;
if (identifier[shouldBeSpaceIndex] != ' ')
identifier.insert(shouldBeSpaceIndex+1, 1, ' ');
// cout << identifier << endl;
copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
id = c.id;
number = c.number;
title = c.title;
description = c.description;
section = c.section;
majors = c.majors;
department = c.department;
concentrations = c.concentrations;
conversations = c.conversations;
professor = c.professor;
half_semester = c.half_semester;
pass_fail = c.pass_fail;
credits = c.credits;
location = c.location;
lab = c.lab;
geneds = c.geneds;
for (int i = 0; i < 7; ++i){
days[i] = c.days[i];
time[i] = c.time[i];
}
}
Course::Course() {
}
Course::Course(string str) {
init(str);
}
Course::Course(const Course& c) {
copy(c);
}
Course& Course::operator = (const Course &c) {
if (this == &c) return *this;
copy(c);
return *this;
}
Course::Course(istream &is) {
// cout << "Now indise Course()" << endl;
if (!is) return;
// cout << "Now inside Course(after return)" << endl;
string tmpLine;
getline(is, tmpLine); // read in so we can do things with it.
vector<string> record = split(tmpLine, ',');
for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
*i = removeAllQuotes(*i);
*i = removeTrailingSlashes(*i);
}
printEntireRecord(record);
// Ignore the first column;
// record.at(0);
// so, the *first* column (that we care about) has the course id,
id = record.at(1);
parseID(id);
// Second column has the section,
section = record.at(2);
// Third holds the lab boolean,
if (record.at(3).empty()) lab = false;
else lab = true;
// while Fourth contains the title of the course;
title = record.at(4);
cleanTitle();
// Fifth hands over the length (half semester or not)
// it's actually an int that tells us how many times the course is offered per semester.
half_semester = stringToInt(record.at(5));
if (half_semester != 0 && half_semester != 1 && half_semester != 2)
half_semester = 0;
// Sixth tells us the number of credits,
credits = stringToFloat(record.at(6));
// Seventh shows us if it can be taken pass/no-pass,
if (record.at(7) == "Y")
pass_fail = true;
else
pass_fail = false;
// while Eighth gives us the GEs of the course,
// GEreqs = record.at(8);
// and Nine spits out the days and times;
// Times = record.at(9);
// Ten holds the location,
location = record.at(10);
location = deDoubleString(location);
// and Eleven knows who teaches.
if (record.size() == 13) {
string profLastName = record.at(11);
string profFirstName = record.at(12);
profFirstName.erase(0, 1); // remove the extra space from the start of the name
professor = profFirstName + " " + profLastName;
}
else {
professor = record.at(11);
}
updateID();
record.clear();
}
void Course::cleanTitle() {
// TODO: Refactor this to work on strings.
vector<string> badEndings, badBeginnings;
badEndings.push_back("Closed during web registration.");
badEndings.push_back("Closed to First-Year Students.");
badEndings.push_back("Closed to first-year students.");
badEndings.push_back("During course submission process");
badEndings.push_back("Especially for ");
badEndings.push_back("Film screenings");
badEndings.push_back("First-Year Students may register only");
badEndings.push_back("New course");
badEndings.push_back("Not open to first-year students.");
badEndings.push_back("Open only to ");
badEndings.push_back("Open only to seniors");
badEndings.push_back("Open to ");
badEndings.push_back("Permission of instructor required.");
badEndings.push_back("Permission of the instructor");
badEndings.push_back("Prerequisite");
badEndings.push_back("Prerequsiite");
badEndings.push_back("Registration by permission of instructor only.");
badEndings.push_back("Registration restricted");
badEndings.push_back("Taught in English.");
badEndings.push_back("This course does");
badEndings.push_back("This course has been canceled.");
badEndings.push_back("This course has been cancelled.");
badEndings.push_back("This course has class");
badEndings.push_back("This course is open to ");
badEndings.push_back("This course open to seniors only.");
badEndings.push_back("This lab has been canceled.");
badEndings.push_back("Students in " + department[0].getFullName() + " " + tostring(number));
badEndings.push_back("Students in " + department[0].getName() + " " + tostring(number));
badBeginnings.push_back("Top: ");
badBeginnings.push_back("Sem: ");
badBeginnings.push_back("Res: ");
for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
title = removeTrailingText(title, *i);
for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
title = removeStartingText(title, *i);
}
void Course::parseID(string str) {
// Get the number of the course, aka the last three slots.
stringstream(str.substr(str.size() - 3)) >> number;
// Check if it's one of those dastardly "split courses".
string dept = str.substr(0,str.size()-3);
if (str.find('/') != string::npos) {
department.push_back(Department(dept.substr(0,2)));
department.push_back(Department(dept.substr(3,2)));
}
else {
department.push_back(Department(dept));
}
}
void Course::updateID() {
string dept;
for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
dept += i->getName();
if (department.size() > 1)
dept += "/";
}
// ignore section until we get it assigning properly in the constructor
id = dept + " " + tostring(number) + section;
}
string Course::getID() {
return id;
}
ostream& Course::getData(ostream &os) {
os << id << " - ";
os << title << " | ";
if (professor.length() > 0 && professor != " ")
os << professor;
return os;
}
void Course::showAll() {
cout << id << section << endl;
cout << "Title: " << title << endl;
cout << "Professor: " << professor << endl;
cout << "Lab? " << lab << endl;
cout << "Half-semester? " << half_semester << endl;
cout << "Credits: " << credits << endl;
cout << "Pass/Fail? " << pass_fail << endl;
cout << "Location: " << location << endl;
cout << endl;
}
ostream &operator<<(ostream &os, Course &item) {
return item.getData(os);
}
void Course::display() {
cout << *this << endl;
}
Course getCourse(string id) {
std::transform(id.begin(), id.end(), id.begin(), ::toupper);
Course c;
for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
if (i->getID() == id)
return *i;
return c;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008 Stephen Liu
* For license terms, see the file COPYING along with this library.
*/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include "spnkporting.hpp"
#include "spnklog.hpp"
#include "spnkthread.hpp"
#ifdef WIN32
void spnk_syslog (int priority, const char * format, ...)
{
char logTemp[ 1024 ] = { 0 };
va_list vaList;
va_start( vaList, format );
_vsnprintf( logTemp, sizeof( logTemp ), format, vaList );
va_end ( vaList );
if( strchr( logTemp, '\n' ) ) {
printf( "%s", logTemp );
} else {
printf( "%s\n", logTemp );
}
}
void spnk_openlog (const char *ident , int option , int facility)
{
}
void spnk_setlogmask( int mask )
{
}
/*
* Option flags for openlog.
*
* LOG_ODELAY no longer does anything.
* LOG_NDELAY is the inverse of what it used to be.
*/
#define LOG_PID 0x01 /* log the pid with each message */
#define LOG_CONS 0x02 /* log on the console if errors in sending */
#define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
#define LOG_NDELAY 0x08 /* don't delay open */
#define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
#define LOG_PERROR 0x20 /* log to stderr as well */
#define LOG_USER (1<<3)
/*
* arguments to setlogmask.
*/
#define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */
#define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */
#define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */
/* extract priority */
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
#define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri))
#define spnk_threadid GetCurrentThreadId
#else
#include <pthread.h>
#define spnk_syslog syslog
#define spnk_openlog openlog
#define spnk_setlogmask setlogmask
#define spnk_threadid pthread_self
#endif
SP_NKLog::LogFunc_t SP_NKLog::mFunc = spnk_syslog;
int SP_NKLog::mLevel = LOG_NOTICE;
int SP_NKLog::mIsLogTimeStamp = 0;
int SP_NKLog::mIsLogPriName = 0;
#ifndef LOG_PRI
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
#endif
void SP_NKLog :: setLogFunc( LogFunc_t func )
{
if( NULL != func ) mFunc = func;
}
void SP_NKLog :: setLogLevel( int level )
{
mLevel = level;
setlogmask( LOG_UPTO( mLevel ) );
}
void SP_NKLog :: setLogTimeStamp( int logTimeStamp )
{
mIsLogTimeStamp = logTimeStamp;
}
void SP_NKLog :: setLogPriName( int logPriName )
{
mIsLogPriName = logPriName;
}
void SP_NKLog :: init4test( const char *ident )
{
int option = LOG_CONS | LOG_PID;
#ifdef LOG_PERROR
option = option | LOG_PERROR;
#endif
spnk_openlog( ident, option, LOG_USER );
}
const char * SP_NKLog :: getPriName( int pri )
{
typedef struct tagPriName {
int mPri;
const char * mName;
} PriName_t;
static PriName_t priNameList [ ] = {
{ LOG_EMERG, "EMERG" },
{ LOG_ALERT, "ALERT" },
{ LOG_CRIT, "CRIT " },
{ LOG_ERR, "ERR " },
{ LOG_WARNING, "WARN " },
{ LOG_NOTICE, "NOTICE" },
{ LOG_INFO, "INFO " },
{ LOG_DEBUG, "DEBUG" },
{ -1, "NONE " }
};
pri = LOG_PRI( pri );
PriName_t * iter = NULL;
for( iter = priNameList; -1 != iter->mPri; iter++ ) {
if( iter->mPri == pri ) break;
}
return iter->mName;
}
void SP_NKLog :: log( int pri, const char * fmt, ... )
{
if( LOG_PRI( pri ) > mLevel ) return;
int olderrno = errno;
char logText[ 1024 ] = { 0 }, logTemp[ 1024 ] = { 0 };
const char * tempPtr = logTemp;
if( NULL != strchr( fmt, '%' ) ) {
va_list vaList;
va_start( vaList, fmt );
vsnprintf( logTemp, sizeof( logTemp ), fmt, vaList );
va_end ( vaList );
} else {
tempPtr = fmt;
}
if( mIsLogTimeStamp ) {
time_t now = time( NULL );
struct tm tmTime;
localtime_r( &now, &tmTime );
snprintf( logText, sizeof( logText ),
"%04i-%02i-%02i %02i:%02i:%02i #%i ",
1900 + tmTime.tm_year, tmTime.tm_mon+1, tmTime.tm_mday,
tmTime.tm_hour, tmTime.tm_min, tmTime.tm_sec, (int)spnk_threadid() );
}
if( mIsLogPriName ) {
strcat( logText, getPriName( pri ) );
strcat( logText, " : " );
}
size_t textPos = strlen( logText );
for( ; textPos < ( sizeof( logText ) - 4 ) && '\0' != *tempPtr; tempPtr++ ) {
if( '\r' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'r';
} else if( '\n' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'n';
} else {
logText[ textPos++ ] = *tempPtr;
}
}
//logText[ textPos++ ] = '\n';
//logText[ textPos++ ] = '\0';
mFunc( pri, logText );
errno = olderrno;
}
//---------------------------------------------------------------------------
typedef struct tagSP_NKFileLogImpl {
char mLogFile[ 512 ];
char mLevel;
char mIsCont;
int mMaxSize;
int mMaxFile;
int mFile;
int mSize;
spnk_thread_mutex_t mMutex;
} SP_NKFileLogImpl_t;
SP_NKFileLog * SP_NKFileLog :: getDefault()
{
static SP_NKFileLog defaultLog;
return &defaultLog;
}
void SP_NKFileLog :: logDefault( int level, const char * fmt, ... )
{
va_list vaList;
va_start( vaList, fmt );
getDefault()->vlog( level, fmt, vaList );
va_end ( vaList );
}
SP_NKFileLog :: SP_NKFileLog()
{
mImpl = NULL;
}
SP_NKFileLog :: ~SP_NKFileLog()
{
if( NULL != mImpl ) {
if( mImpl->mFile >= 0 ) close( mImpl->mFile );
spnk_thread_mutex_destroy( &( mImpl->mMutex ) );
free( mImpl );
mImpl = NULL;
}
}
void SP_NKFileLog :: setOpts( int level, int maxSize, int maxFile )
{
if( NULL != mImpl ) {
mImpl->mLevel = level;
mImpl->mMaxSize = maxSize;
mImpl->mMaxFile = maxFile;
if( mImpl->mMaxSize <= 0 ) mImpl->mMaxSize = 1024 * 1024;
if( mImpl->mMaxFile <= 0 ) mImpl->mMaxFile = 1;
}
}
int SP_NKFileLog :: init( const char * logFile, int isCont )
{
mImpl = (SP_NKFileLogImpl_t*)calloc( sizeof( SP_NKFileLogImpl_t ), 1 );
strncpy( mImpl->mLogFile, logFile, sizeof( mImpl->mLogFile ) - 1 );
mImpl->mLevel = LOG_NOTICE;
mImpl->mIsCont = isCont;
mImpl->mMaxSize = 1024 * 1024;
mImpl->mMaxFile = 1;
mImpl->mFile = -1;
mImpl->mSize = 0;
spnk_thread_mutex_init( &( mImpl->mMutex ), NULL );
return 0;
}
void SP_NKFileLog :: check( SP_NKFileLogImpl_t * impl )
{
if( impl->mFile < 0 && impl->mIsCont ) {
impl->mFile = open( impl->mLogFile, O_WRONLY | O_NONBLOCK | O_APPEND | O_CREAT,
S_IRUSR | S_IWUSR ) ;
if( impl->mFile >= 0 ) {
struct stat fileStat;
if( 0 == fstat( impl->mFile, &fileStat ) ) impl->mSize = fileStat.st_size;
}
}
if( impl->mFile < 0 || ( impl->mSize > impl->mMaxSize ) ) {
spnk_thread_mutex_lock( &( impl->mMutex ) );
if( impl->mFile >= 0 ) {
close( impl->mFile );
impl->mFile = -1;
impl->mSize = 0;
}
char newFile [ 512 ] = { 0 }, oldFile[ 512 ] = { 0 };
snprintf( oldFile, sizeof( oldFile ), "%s.%d", impl->mLogFile, impl->mMaxFile );
unlink( oldFile );
for( int i = impl->mMaxFile - 1; i > 0; i-- ) {
snprintf( oldFile, sizeof( oldFile ), "%s.%d", impl->mLogFile, i - 1 );
snprintf( newFile, sizeof( newFile ), "%s.%d", impl->mLogFile, i );
rename( oldFile, newFile );
}
rename( impl->mLogFile, oldFile );
impl->mFile = open( impl->mLogFile, O_WRONLY | O_NONBLOCK | O_TRUNC | O_CREAT,
S_IRUSR | S_IWUSR ) ;
spnk_thread_mutex_unlock( &( impl->mMutex ) );
}
}
void SP_NKFileLog :: log( int level, const char * fmt, ... )
{
if( NULL == mImpl ) return;
if( LOG_PRI( level ) > mImpl->mLevel ) return;
va_list vaList;
va_start( vaList, fmt );
vlog( level, fmt, vaList );
va_end ( vaList );
}
void SP_NKFileLog :: vlog( int level, const char * fmt, va_list ap )
{
if( NULL == mImpl ) return;
if( LOG_PRI( level ) > mImpl->mLevel ) return;
int olderrno = errno;
char logText[ 1024 ] = { 0 }, logTemp[ 1024 ] = { 0 };
const char * tempPtr = logTemp;
if( NULL != strchr( fmt, '%' ) ) {
vsnprintf( logTemp, sizeof( logTemp ), fmt, ap );
} else {
tempPtr = fmt;
}
time_t now = time( NULL );
struct tm tmTime;
localtime_r( &now, &tmTime );
snprintf( logText, sizeof( logText ),
"%04i-%02i-%02i %02i:%02i:%02i #%u ",
1900 + tmTime.tm_year, tmTime.tm_mon+1, tmTime.tm_mday,
tmTime.tm_hour, tmTime.tm_min, tmTime.tm_sec, (int)spnk_threadid() );
size_t textPos = strlen( logText );
for( ; textPos < ( sizeof( logText ) - 5 ) && '\0' != *tempPtr; tempPtr++ ) {
if( '\r' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'r';
} else if( '\n' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'n';
} else {
logText[ textPos++ ] = *tempPtr;
}
}
logText[ textPos++ ] = '\r';
logText[ textPos++ ] = '\n';
logText[ textPos++ ] = '\0';
check( mImpl );
if( mImpl->mFile >= 0 ) {
write( mImpl->mFile, logText, textPos - 1 );
mImpl->mSize += textPos;
}
errno = olderrno;
}
<commit_msg>add append flag for log<commit_after>/*
* Copyright 2008 Stephen Liu
* For license terms, see the file COPYING along with this library.
*/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include "spnkporting.hpp"
#include "spnklog.hpp"
#include "spnkthread.hpp"
#ifdef WIN32
void spnk_syslog (int priority, const char * format, ...)
{
char logTemp[ 1024 ] = { 0 };
va_list vaList;
va_start( vaList, format );
_vsnprintf( logTemp, sizeof( logTemp ), format, vaList );
va_end ( vaList );
if( strchr( logTemp, '\n' ) ) {
printf( "%s", logTemp );
} else {
printf( "%s\n", logTemp );
}
}
void spnk_openlog (const char *ident , int option , int facility)
{
}
void spnk_setlogmask( int mask )
{
}
/*
* Option flags for openlog.
*
* LOG_ODELAY no longer does anything.
* LOG_NDELAY is the inverse of what it used to be.
*/
#define LOG_PID 0x01 /* log the pid with each message */
#define LOG_CONS 0x02 /* log on the console if errors in sending */
#define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
#define LOG_NDELAY 0x08 /* don't delay open */
#define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
#define LOG_PERROR 0x20 /* log to stderr as well */
#define LOG_USER (1<<3)
/*
* arguments to setlogmask.
*/
#define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */
#define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */
#define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */
/* extract priority */
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
#define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri))
#define spnk_threadid GetCurrentThreadId
#else
#include <pthread.h>
#define spnk_syslog syslog
#define spnk_openlog openlog
#define spnk_setlogmask setlogmask
#define spnk_threadid pthread_self
#endif
SP_NKLog::LogFunc_t SP_NKLog::mFunc = spnk_syslog;
int SP_NKLog::mLevel = LOG_NOTICE;
int SP_NKLog::mIsLogTimeStamp = 0;
int SP_NKLog::mIsLogPriName = 0;
#ifndef LOG_PRI
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
#endif
void SP_NKLog :: setLogFunc( LogFunc_t func )
{
if( NULL != func ) mFunc = func;
}
void SP_NKLog :: setLogLevel( int level )
{
mLevel = level;
setlogmask( LOG_UPTO( mLevel ) );
}
void SP_NKLog :: setLogTimeStamp( int logTimeStamp )
{
mIsLogTimeStamp = logTimeStamp;
}
void SP_NKLog :: setLogPriName( int logPriName )
{
mIsLogPriName = logPriName;
}
void SP_NKLog :: init4test( const char *ident )
{
int option = LOG_CONS | LOG_PID;
#ifdef LOG_PERROR
option = option | LOG_PERROR;
#endif
spnk_openlog( ident, option, LOG_USER );
}
const char * SP_NKLog :: getPriName( int pri )
{
typedef struct tagPriName {
int mPri;
const char * mName;
} PriName_t;
static PriName_t priNameList [ ] = {
{ LOG_EMERG, "EMERG" },
{ LOG_ALERT, "ALERT" },
{ LOG_CRIT, "CRIT " },
{ LOG_ERR, "ERR " },
{ LOG_WARNING, "WARN " },
{ LOG_NOTICE, "NOTICE" },
{ LOG_INFO, "INFO " },
{ LOG_DEBUG, "DEBUG" },
{ -1, "NONE " }
};
pri = LOG_PRI( pri );
PriName_t * iter = NULL;
for( iter = priNameList; -1 != iter->mPri; iter++ ) {
if( iter->mPri == pri ) break;
}
return iter->mName;
}
void SP_NKLog :: log( int pri, const char * fmt, ... )
{
if( LOG_PRI( pri ) > mLevel ) return;
int olderrno = errno;
char logText[ 1024 ] = { 0 }, logTemp[ 1024 ] = { 0 };
const char * tempPtr = logTemp;
if( NULL != strchr( fmt, '%' ) ) {
va_list vaList;
va_start( vaList, fmt );
vsnprintf( logTemp, sizeof( logTemp ), fmt, vaList );
va_end ( vaList );
} else {
tempPtr = fmt;
}
if( mIsLogTimeStamp ) {
time_t now = time( NULL );
struct tm tmTime;
localtime_r( &now, &tmTime );
snprintf( logText, sizeof( logText ),
"%04i-%02i-%02i %02i:%02i:%02i #%i ",
1900 + tmTime.tm_year, tmTime.tm_mon+1, tmTime.tm_mday,
tmTime.tm_hour, tmTime.tm_min, tmTime.tm_sec, (int)spnk_threadid() );
}
if( mIsLogPriName ) {
strcat( logText, getPriName( pri ) );
strcat( logText, " : " );
}
size_t textPos = strlen( logText );
for( ; textPos < ( sizeof( logText ) - 4 ) && '\0' != *tempPtr; tempPtr++ ) {
if( '\r' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'r';
} else if( '\n' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'n';
} else {
logText[ textPos++ ] = *tempPtr;
}
}
//logText[ textPos++ ] = '\n';
//logText[ textPos++ ] = '\0';
mFunc( pri, logText );
errno = olderrno;
}
//---------------------------------------------------------------------------
typedef struct tagSP_NKFileLogImpl {
char mLogFile[ 512 ];
char mLevel;
char mIsCont;
int mMaxSize;
int mMaxFile;
int mFile;
int mSize;
spnk_thread_mutex_t mMutex;
} SP_NKFileLogImpl_t;
SP_NKFileLog * SP_NKFileLog :: getDefault()
{
static SP_NKFileLog defaultLog;
return &defaultLog;
}
void SP_NKFileLog :: logDefault( int level, const char * fmt, ... )
{
va_list vaList;
va_start( vaList, fmt );
getDefault()->vlog( level, fmt, vaList );
va_end ( vaList );
}
SP_NKFileLog :: SP_NKFileLog()
{
mImpl = NULL;
}
SP_NKFileLog :: ~SP_NKFileLog()
{
if( NULL != mImpl ) {
if( mImpl->mFile >= 0 ) close( mImpl->mFile );
spnk_thread_mutex_destroy( &( mImpl->mMutex ) );
free( mImpl );
mImpl = NULL;
}
}
void SP_NKFileLog :: setOpts( int level, int maxSize, int maxFile )
{
if( NULL != mImpl ) {
mImpl->mLevel = level;
mImpl->mMaxSize = maxSize;
mImpl->mMaxFile = maxFile;
if( mImpl->mMaxSize <= 0 ) mImpl->mMaxSize = 1024 * 1024;
if( mImpl->mMaxFile <= 0 ) mImpl->mMaxFile = 1;
}
}
int SP_NKFileLog :: init( const char * logFile, int isCont )
{
mImpl = (SP_NKFileLogImpl_t*)calloc( sizeof( SP_NKFileLogImpl_t ), 1 );
strncpy( mImpl->mLogFile, logFile, sizeof( mImpl->mLogFile ) - 1 );
mImpl->mLevel = LOG_NOTICE;
mImpl->mIsCont = isCont;
mImpl->mMaxSize = 1024 * 1024;
mImpl->mMaxFile = 1;
mImpl->mFile = -1;
mImpl->mSize = 0;
spnk_thread_mutex_init( &( mImpl->mMutex ), NULL );
return 0;
}
void SP_NKFileLog :: check( SP_NKFileLogImpl_t * impl )
{
if( impl->mFile < 0 && impl->mIsCont ) {
impl->mFile = open( impl->mLogFile, O_WRONLY | O_NONBLOCK | O_APPEND | O_CREAT,
S_IRUSR | S_IWUSR ) ;
if( impl->mFile >= 0 ) {
struct stat fileStat;
if( 0 == fstat( impl->mFile, &fileStat ) ) impl->mSize = fileStat.st_size;
}
}
if( impl->mFile < 0 || ( impl->mSize > impl->mMaxSize ) ) {
spnk_thread_mutex_lock( &( impl->mMutex ) );
if( impl->mFile >= 0 ) {
close( impl->mFile );
impl->mFile = -1;
impl->mSize = 0;
}
char newFile [ 512 ] = { 0 }, oldFile[ 512 ] = { 0 };
snprintf( oldFile, sizeof( oldFile ), "%s.%d", impl->mLogFile, impl->mMaxFile );
unlink( oldFile );
for( int i = impl->mMaxFile - 1; i > 0; i-- ) {
snprintf( oldFile, sizeof( oldFile ), "%s.%d", impl->mLogFile, i - 1 );
snprintf( newFile, sizeof( newFile ), "%s.%d", impl->mLogFile, i );
rename( oldFile, newFile );
}
rename( impl->mLogFile, oldFile );
impl->mFile = open( impl->mLogFile,
O_WRONLY | O_NONBLOCK | O_TRUNC | O_CREAT | O_APPEND,
S_IRUSR | S_IWUSR ) ;
spnk_thread_mutex_unlock( &( impl->mMutex ) );
}
}
void SP_NKFileLog :: log( int level, const char * fmt, ... )
{
if( NULL == mImpl ) return;
if( LOG_PRI( level ) > mImpl->mLevel ) return;
va_list vaList;
va_start( vaList, fmt );
vlog( level, fmt, vaList );
va_end ( vaList );
}
void SP_NKFileLog :: vlog( int level, const char * fmt, va_list ap )
{
if( NULL == mImpl ) return;
if( LOG_PRI( level ) > mImpl->mLevel ) return;
int olderrno = errno;
char logText[ 1024 ] = { 0 }, logTemp[ 1024 ] = { 0 };
const char * tempPtr = logTemp;
if( NULL != strchr( fmt, '%' ) ) {
vsnprintf( logTemp, sizeof( logTemp ), fmt, ap );
} else {
tempPtr = fmt;
}
time_t now = time( NULL );
struct tm tmTime;
localtime_r( &now, &tmTime );
snprintf( logText, sizeof( logText ),
"%04i-%02i-%02i %02i:%02i:%02i #%u ",
1900 + tmTime.tm_year, tmTime.tm_mon+1, tmTime.tm_mday,
tmTime.tm_hour, tmTime.tm_min, tmTime.tm_sec, (int)spnk_threadid() );
size_t textPos = strlen( logText );
for( ; textPos < ( sizeof( logText ) - 5 ) && '\0' != *tempPtr; tempPtr++ ) {
if( '\r' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'r';
} else if( '\n' == *tempPtr ) {
logText[ textPos++ ] = '\\';
logText[ textPos++ ] = 'n';
} else {
logText[ textPos++ ] = *tempPtr;
}
}
logText[ textPos++ ] = '\r';
logText[ textPos++ ] = '\n';
logText[ textPos++ ] = '\0';
check( mImpl );
if( mImpl->mFile >= 0 ) {
write( mImpl->mFile, logText, textPos - 1 );
mImpl->mSize += textPos;
}
errno = olderrno;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "BasicThread.h"
#include "Autowired.h"
#include "BasicThreadStateBlock.h"
#include "fast_pointer_cast.h"
#include "move_only.h"
#include <boost/thread.hpp>
// Explicit instantiation of supported time point types:
template<> bool BasicThread::WaitUntil(boost::chrono::high_resolution_clock::time_point);
template<> bool BasicThread::WaitUntil(boost::chrono::system_clock::time_point);
BasicThread::BasicThread(const char* pName):
ContextMember(pName),
m_priority(ThreadPriority::Default),
m_state(std::make_shared<BasicThreadStateBlock>()),
m_stop(false),
m_running(false),
m_completed(false)
{}
boost::mutex& BasicThread::GetLock(void) {
return m_state->m_lock;
}
void BasicThread::DoRun(std::shared_ptr<Object>&& refTracker) {
assert(m_running);
// Make our own session current before we do anything else:
CurrentContextPusher pusher(GetContext());
// Set the thread name no matter what:
if(GetName())
SetCurrentThreadName();
// Now we wait for the thread to be good to go:
try {
Run();
}
catch(dispatch_aborted_exception&) {
// Okay, this is fine, a dispatcher is terminating--this is a normal way to
// end a dispatcher loop.
}
catch(...) {
try {
// Ask that the enclosing context filter this exception, if possible:
GetContext()->FilterException();
}
catch(...) {
// Generic exception, unhandled, we can't do anything about this
}
// Signal shutdown on the enclosing context--cannot wait, if we wait we WILL deadlock
GetContext()->SignalShutdown(false);
}
// Run loop is over, time to clean up
DoRunLoopCleanup(pusher.Pop());
// Clear our reference tracker, which will notify anyone who is asleep and also maybe
// will destroy the entire underlying context.
refTracker.reset();
}
void BasicThread::DoRunLoopCleanup(std::shared_ptr<CoreContext>&& ctxt)
{
// Take a copy of our state condition shared pointer while we still hold a reference to
// ourselves. This is the only member out of our collection of members that we actually
// need to hold a reference to.
auto state = m_state;
// Notify everyone that we're completed:
boost::lock_guard<boost::mutex> lk(state->m_lock);
m_stop = true;
m_completed = true;
m_running = false;
// Perform a manual notification of teardown listeners
NotifyTeardownListeners();
// No longer running, we MUST release the thread pointer to ensure proper teardown order
state->m_thisThread.detach();
// Release our hold on the context. After this point, we have to be VERY CAREFUL that we
// don't try to refer to any of our own member variables, because our own object may have
// already gone out of scope. [this] is potentially dangling.
ctxt.reset();
// Notify other threads that we are done. At this point, any held references that might
// still exist are held by entities other than ourselves.
state->m_stateCondition.notify_all();
}
void BasicThread::WaitForStateUpdate(const std::function<bool()>& fn) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
m_state->m_stateCondition.wait(lk, fn);
}
void BasicThread::PerformStatusUpdate(const std::function<void()>& fn) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
fn();
m_state->m_stateCondition.notify_all();
}
bool BasicThread::ShouldStop(void) const {
shared_ptr<CoreContext> context = ContextMember::GetContext();
return m_stop || !context || context->IsShutdown();
}
bool BasicThread::IsRunning(void) const {
boost::lock_guard<boost::mutex> lk(m_state->m_lock);
return m_running;
}
void BasicThread::ThreadSleep(long millisecond) {
boost::this_thread::sleep(boost::posix_time::milliseconds(millisecond));
}
bool BasicThread::Start(std::shared_ptr<Object> outstanding) {
std::shared_ptr<CoreContext> context = m_context.lock();
if(!context)
return false;
{
boost::lock_guard<boost::mutex> lk(m_state->m_lock);
if(m_running)
// Already running, short-circuit
return true;
// Currently running:
m_running = true;
m_state->m_stateCondition.notify_all();
}
// Kick off a thread and return here
MoveOnly<std::shared_ptr<Object>> out(std::move(outstanding));
m_state->m_thisThread = boost::thread(
[this, out] {
this->DoRun(std::move(out.value));
}
);
return true;
}
void BasicThread::Wait(void) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
m_state->m_stateCondition.wait(
lk,
[this]() {return this->m_completed; }
);
}
bool BasicThread::WaitFor(boost::chrono::nanoseconds duration) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
return m_state->m_stateCondition.wait_for(
lk,
duration,
[this]() {return this->m_completed; }
);
}
template<class TimeType>
bool BasicThread::WaitUntil(TimeType timepoint) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
return m_state->m_stateCondition.wait_until(
lk,
timepoint,
[this]() {return this->m_completed; }
);
}
void BasicThread::Stop(bool graceful) {
// Trivial return check:
if(m_stop)
return;
// Perform initial stop:
m_stop = true;
OnStop();
m_state->m_stateCondition.notify_all();
}
void BasicThread::ForceCoreThreadReidentify(void) {
AutoGlobalContext global;
global->EnumerateChildContexts(
[](std::shared_ptr<CoreContext> ctxt) {
auto threadListCpy = ctxt->CopyBasicThreadList();
for(auto q = threadListCpy.begin(); q != threadListCpy.end(); q++) {
(**q).SetCurrentThreadName();
}
}
);
}
void ForceCoreThreadReidentify(void) {
BasicThread::ForceCoreThreadReidentify();
}
<commit_msg>BasicThread should return early on its WaitForStateUpdate call<commit_after>#include "stdafx.h"
#include "BasicThread.h"
#include "Autowired.h"
#include "BasicThreadStateBlock.h"
#include "fast_pointer_cast.h"
#include "move_only.h"
#include <boost/thread.hpp>
// Explicit instantiation of supported time point types:
template<> bool BasicThread::WaitUntil(boost::chrono::high_resolution_clock::time_point);
template<> bool BasicThread::WaitUntil(boost::chrono::system_clock::time_point);
BasicThread::BasicThread(const char* pName):
ContextMember(pName),
m_priority(ThreadPriority::Default),
m_state(std::make_shared<BasicThreadStateBlock>()),
m_stop(false),
m_running(false),
m_completed(false)
{}
boost::mutex& BasicThread::GetLock(void) {
return m_state->m_lock;
}
void BasicThread::DoRun(std::shared_ptr<Object>&& refTracker) {
assert(m_running);
// Make our own session current before we do anything else:
CurrentContextPusher pusher(GetContext());
// Set the thread name no matter what:
if(GetName())
SetCurrentThreadName();
// Now we wait for the thread to be good to go:
try {
Run();
}
catch(dispatch_aborted_exception&) {
// Okay, this is fine, a dispatcher is terminating--this is a normal way to
// end a dispatcher loop.
}
catch(...) {
try {
// Ask that the enclosing context filter this exception, if possible:
GetContext()->FilterException();
}
catch(...) {
// Generic exception, unhandled, we can't do anything about this
}
// Signal shutdown on the enclosing context--cannot wait, if we wait we WILL deadlock
GetContext()->SignalShutdown(false);
}
// Run loop is over, time to clean up
DoRunLoopCleanup(pusher.Pop());
// Clear our reference tracker, which will notify anyone who is asleep and also maybe
// will destroy the entire underlying context.
refTracker.reset();
}
void BasicThread::DoRunLoopCleanup(std::shared_ptr<CoreContext>&& ctxt)
{
// Take a copy of our state condition shared pointer while we still hold a reference to
// ourselves. This is the only member out of our collection of members that we actually
// need to hold a reference to.
auto state = m_state;
// Notify everyone that we're completed:
boost::lock_guard<boost::mutex> lk(state->m_lock);
m_stop = true;
m_completed = true;
m_running = false;
// Perform a manual notification of teardown listeners
NotifyTeardownListeners();
// No longer running, we MUST release the thread pointer to ensure proper teardown order
state->m_thisThread.detach();
// Release our hold on the context. After this point, we have to be VERY CAREFUL that we
// don't try to refer to any of our own member variables, because our own object may have
// already gone out of scope. [this] is potentially dangling.
ctxt.reset();
// Notify other threads that we are done. At this point, any held references that might
// still exist are held by entities other than ourselves.
state->m_stateCondition.notify_all();
}
void BasicThread::WaitForStateUpdate(const std::function<bool()>& fn) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
m_state->m_stateCondition.wait(
lk,
[&fn, this] {
return fn() || ShouldStop();
}
);
if(ShouldStop())
throw dispatch_aborted_exception();
}
void BasicThread::PerformStatusUpdate(const std::function<void()>& fn) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
fn();
m_state->m_stateCondition.notify_all();
}
bool BasicThread::ShouldStop(void) const {
shared_ptr<CoreContext> context = ContextMember::GetContext();
return m_stop || !context || context->IsShutdown();
}
bool BasicThread::IsRunning(void) const {
boost::lock_guard<boost::mutex> lk(m_state->m_lock);
return m_running;
}
void BasicThread::ThreadSleep(long millisecond) {
boost::this_thread::sleep(boost::posix_time::milliseconds(millisecond));
}
bool BasicThread::Start(std::shared_ptr<Object> outstanding) {
std::shared_ptr<CoreContext> context = m_context.lock();
if(!context)
return false;
{
boost::lock_guard<boost::mutex> lk(m_state->m_lock);
if(m_running)
// Already running, short-circuit
return true;
// Currently running:
m_running = true;
m_state->m_stateCondition.notify_all();
}
// Kick off a thread and return here
MoveOnly<std::shared_ptr<Object>> out(std::move(outstanding));
m_state->m_thisThread = boost::thread(
[this, out] {
this->DoRun(std::move(out.value));
}
);
return true;
}
void BasicThread::Wait(void) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
m_state->m_stateCondition.wait(
lk,
[this]() {return this->m_completed; }
);
}
bool BasicThread::WaitFor(boost::chrono::nanoseconds duration) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
return m_state->m_stateCondition.wait_for(
lk,
duration,
[this]() {return this->m_completed; }
);
}
template<class TimeType>
bool BasicThread::WaitUntil(TimeType timepoint) {
boost::unique_lock<boost::mutex> lk(m_state->m_lock);
return m_state->m_stateCondition.wait_until(
lk,
timepoint,
[this]() {return this->m_completed; }
);
}
void BasicThread::Stop(bool graceful) {
// Trivial return check:
if(m_stop)
return;
// Perform initial stop:
m_stop = true;
OnStop();
m_state->m_stateCondition.notify_all();
}
void BasicThread::ForceCoreThreadReidentify(void) {
AutoGlobalContext global;
global->EnumerateChildContexts(
[](std::shared_ptr<CoreContext> ctxt) {
auto threadListCpy = ctxt->CopyBasicThreadList();
for(auto q = threadListCpy.begin(); q != threadListCpy.end(); q++) {
(**q).SetCurrentThreadName();
}
}
);
}
void ForceCoreThreadReidentify(void) {
BasicThread::ForceCoreThreadReidentify();
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2013 BMW Group
* Author: Manfred Bathelt (manfred.bathelt@bmw.de)
* Author: Juergen Gehring (juergen.gehring@bmw.de)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef _GLIBCXX_USE_NANOSLEEP
#define _GLIBCXX_USE_NANOSLEEP
#endif
#include <CommonAPI/DBus/DBusInputStream.h>
#include <CommonAPI/DBus/DBusMessage.h>
#include <CommonAPI/DBus/DBusProxy.h>
#include <CommonAPI/DBus/DBusConnection.h>
#include <CommonAPI/DBus/DBusStubAdapter.h>
#include <CommonAPI/DBus/DBusUtils.h>
#include <commonapi/tests/TestInterfaceDBusProxy.h>
#include <commonapi/tests/TestInterfaceDBusStubAdapter.h>
#include <commonapi/tests/TestInterfaceStubDefault.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
static const std::string commonApiAddress = "local:CommonAPI.DBus.tests.DBusProxyTestInterface:CommonAPI.DBus.tests.DBusProxyTestService";
static const std::string commonApiServiceName = "CommonAPI.DBus.tests.DBusProxyTest";
static const std::string interfaceName = "CommonAPI.DBus.tests.DBusProxyTestInterface";
static const std::string busName = "CommonAPI.DBus.tests.DBusProxyTestService";
static const std::string objectPath = "/CommonAPI/DBus/tests/DBusProxyTestService";
class ProxyTest: public ::testing::Test {
protected:
virtual void TearDown() {
proxyDBusConnection_->disconnect();
stubAdapter_.reset();
if (stubDBusConnection_) {
if (stubDBusConnection_->isConnected()) {
stubDBusConnection_->releaseServiceName(busName);
stubDBusConnection_->disconnect();
}
stubDBusConnection_.reset();
}
}
void SetUp() {
proxyDBusConnection_ = CommonAPI::DBus::DBusConnection::getSessionBus();
ASSERT_TRUE(proxyDBusConnection_->connect());
proxy_ = std::make_shared<commonapi::tests::TestInterfaceDBusProxy>(
commonApiAddress,
interfaceName,
busName,
objectPath,
proxyDBusConnection_);
}
void registerTestStub() {
stubDBusConnection_ = CommonAPI::DBus::DBusConnection::getSessionBus();
ASSERT_TRUE(stubDBusConnection_->connect());
ASSERT_TRUE(stubDBusConnection_->requestServiceNameAndBlock(busName));
auto stubDefault = std::make_shared<commonapi::tests::TestInterfaceStubDefault>();
stubAdapter_ = std::make_shared<commonapi::tests::TestInterfaceDBusStubAdapter>(
commonApiAddress,
interfaceName,
busName,
objectPath,
stubDBusConnection_,
stubDefault);
stubAdapter_->init();
}
void proxyRegisterForAvailabilityStatus() {
proxyAvailabilityStatus_ = CommonAPI::AvailabilityStatus::UNKNOWN;
proxy_->getProxyStatusEvent().subscribe([&](const CommonAPI::AvailabilityStatus& availabilityStatus) {
std::cout << "Proxy AvailabilityStatus changed to " << (int) availabilityStatus << std::endl;
proxyAvailabilityStatus_ = availabilityStatus;
});
}
bool proxyWaitForAvailabilityStatus(const CommonAPI::AvailabilityStatus& availabilityStatus) const {
std::chrono::milliseconds loopWaitDuration(100);
if (proxyAvailabilityStatus_ == availabilityStatus)
return true;
for (int i = 0; i < 10; i++) {
std::this_thread::sleep_for(loopWaitDuration);
if (proxyAvailabilityStatus_ == availabilityStatus)
return true;
}
return false;
}
std::shared_ptr<CommonAPI::DBus::DBusConnection> proxyDBusConnection_;
std::shared_ptr<commonapi::tests::TestInterfaceDBusProxy> proxy_;
CommonAPI::AvailabilityStatus proxyAvailabilityStatus_;
std::shared_ptr<CommonAPI::DBus::DBusConnection> stubDBusConnection_;
std::shared_ptr<commonapi::tests::TestInterfaceDBusStubAdapter> stubAdapter_;
};
TEST_F(ProxyTest, HasCorrectConnectionName) {
std::string actualName = proxy_->getDBusBusName();
EXPECT_EQ(busName, actualName);
}
TEST_F(ProxyTest, HasCorrectObjectPath) {
std::string actualPath = proxy_->getDBusObjectPath();
EXPECT_EQ(objectPath, actualPath);
}
TEST_F(ProxyTest, HasCorrectInterfaceName) {
std::string actualName = proxy_->getInterfaceName();
EXPECT_EQ(interfaceName, actualName);
}
TEST_F(ProxyTest, IsNotAvailable) {
bool isAvailable = proxy_->isAvailable();
EXPECT_FALSE(isAvailable);
}
TEST_F(ProxyTest, ServiceRegistry) {
std::shared_ptr<CommonAPI::DBus::DBusProxyConnection> connection = proxy_->getDBusConnection();
auto registry = connection->getDBusServiceRegistry();
ASSERT_FALSE(!registry);
}
TEST_F(ProxyTest, DBusProxyStatusEventBeforeServiceIsRegistered) {
proxyRegisterForAvailabilityStatus();
ASSERT_NE(proxyAvailabilityStatus_, CommonAPI::AvailabilityStatus::AVAILABLE);
registerTestStub();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::AVAILABLE));
stubDBusConnection_->disconnect();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::NOT_AVAILABLE));
}
TEST_F(ProxyTest, DBusProxyStatusEventAfterServiceIsRegistered) {
proxyDBusConnection_->disconnect();
registerTestStub();
ASSERT_TRUE(proxyDBusConnection_->connect());
proxyRegisterForAvailabilityStatus();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::AVAILABLE));
stubDBusConnection_->disconnect();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::NOT_AVAILABLE));
}
TEST_F(ProxyTest, ServiceStatus) {
proxyDBusConnection_->requestServiceNameAndBlock(busName);
std::shared_ptr<commonapi::tests::TestInterfaceStubDefault> stubDefault = std::make_shared<commonapi::tests::TestInterfaceStubDefault>();
std::shared_ptr<commonapi::tests::TestInterfaceDBusStubAdapter> stubAdapter = std::make_shared<commonapi::tests::TestInterfaceDBusStubAdapter>(
commonApiAddress,
interfaceName,
busName,
objectPath,
proxyDBusConnection_,
stubDefault);
stubAdapter->init();
auto testConnection = CommonAPI::DBus::DBusConnection::getSessionBus();
testConnection->connect();
std::vector<std::string> actuallyAvailableServices;
actuallyAvailableServices = testConnection->getDBusServiceRegistry()->getAvailableServiceInstances(commonApiServiceName,
"local");
auto found = std::find(actuallyAvailableServices.begin(), actuallyAvailableServices.end(), commonApiAddress);
ASSERT_TRUE(actuallyAvailableServices.begin() != actuallyAvailableServices.end());
ASSERT_TRUE(found != actuallyAvailableServices.end());
testConnection->disconnect();
}
TEST_F(ProxyTest, IsAvailableBlocking) {
std::shared_ptr<commonapi::tests::TestInterfaceStubDefault> stubDefault = std::make_shared<commonapi::tests::TestInterfaceStubDefault>();
std::shared_ptr<commonapi::tests::TestInterfaceDBusStubAdapter> stubAdapter = std::make_shared<commonapi::tests::TestInterfaceDBusStubAdapter>(
commonApiAddress,
interfaceName,
busName,
objectPath,
proxyDBusConnection_,
stubDefault);
stubAdapter->init();
bool registered = proxyDBusConnection_->requestServiceNameAndBlock(busName);
bool isAvailable = proxy_->isAvailableBlocking();
EXPECT_EQ(registered, isAvailable);
}
TEST_F(ProxyTest, HasNecessaryAttributesAndEvents) {
CommonAPI::InterfaceVersionAttribute& versionAttribute = (proxy_->getInterfaceVersionAttribute());
CommonAPI::ProxyStatusEvent& statusEvent = (proxy_->getProxyStatusEvent());
}
TEST_F(ProxyTest, IsConnected) {
ASSERT_TRUE(proxy_->getDBusConnection()->isConnected());
}
TEST_F(ProxyTest, TestInterfaceVersionAttribute) {
CommonAPI::InterfaceVersionAttribute& versionAttribute = proxy_->getInterfaceVersionAttribute();
CommonAPI::Version version;
CommonAPI::CallStatus status = versionAttribute.getValue(version);
ASSERT_EQ(CommonAPI::CallStatus::NOT_AVAILABLE, status);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Added Test for Proxies: Async Callbacks should be called even if the proxy is marked as "NOT_AVAILABLE"<commit_after>/* Copyright (C) 2013 BMW Group
* Author: Manfred Bathelt (manfred.bathelt@bmw.de)
* Author: Juergen Gehring (juergen.gehring@bmw.de)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef _GLIBCXX_USE_NANOSLEEP
#define _GLIBCXX_USE_NANOSLEEP
#endif
#include <CommonAPI/DBus/DBusInputStream.h>
#include <CommonAPI/DBus/DBusMessage.h>
#include <CommonAPI/DBus/DBusProxy.h>
#include <CommonAPI/DBus/DBusConnection.h>
#include <CommonAPI/DBus/DBusStubAdapter.h>
#include <CommonAPI/DBus/DBusUtils.h>
#include <commonapi/tests/TestInterfaceDBusProxy.h>
#include <commonapi/tests/TestInterfaceDBusStubAdapter.h>
#include <commonapi/tests/TestInterfaceStubDefault.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
static const std::string commonApiAddress = "local:CommonAPI.DBus.tests.DBusProxyTestInterface:CommonAPI.DBus.tests.DBusProxyTestService";
static const std::string commonApiServiceName = "CommonAPI.DBus.tests.DBusProxyTest";
static const std::string interfaceName = "CommonAPI.DBus.tests.DBusProxyTestInterface";
static const std::string busName = "CommonAPI.DBus.tests.DBusProxyTestService";
static const std::string objectPath = "/CommonAPI/DBus/tests/DBusProxyTestService";
class ProxyTest: public ::testing::Test {
protected:
virtual void TearDown() {
proxyDBusConnection_->disconnect();
stubAdapter_.reset();
if (stubDBusConnection_) {
if (stubDBusConnection_->isConnected()) {
stubDBusConnection_->releaseServiceName(busName);
stubDBusConnection_->disconnect();
}
stubDBusConnection_.reset();
}
}
void SetUp() {
proxyDBusConnection_ = CommonAPI::DBus::DBusConnection::getSessionBus();
ASSERT_TRUE(proxyDBusConnection_->connect());
proxy_ = std::make_shared<commonapi::tests::TestInterfaceDBusProxy>(
commonApiAddress,
interfaceName,
busName,
objectPath,
proxyDBusConnection_);
}
void registerTestStub() {
stubDBusConnection_ = CommonAPI::DBus::DBusConnection::getSessionBus();
ASSERT_TRUE(stubDBusConnection_->connect());
ASSERT_TRUE(stubDBusConnection_->requestServiceNameAndBlock(busName));
auto stubDefault = std::make_shared<commonapi::tests::TestInterfaceStubDefault>();
stubAdapter_ = std::make_shared<commonapi::tests::TestInterfaceDBusStubAdapter>(
commonApiAddress,
interfaceName,
busName,
objectPath,
stubDBusConnection_,
stubDefault);
stubAdapter_->init();
}
void proxyRegisterForAvailabilityStatus() {
proxyAvailabilityStatus_ = CommonAPI::AvailabilityStatus::UNKNOWN;
proxy_->getProxyStatusEvent().subscribe([&](const CommonAPI::AvailabilityStatus& availabilityStatus) {
std::cout << "Proxy AvailabilityStatus changed to " << (int) availabilityStatus << std::endl;
proxyAvailabilityStatus_ = availabilityStatus;
});
}
bool proxyWaitForAvailabilityStatus(const CommonAPI::AvailabilityStatus& availabilityStatus) const {
std::chrono::milliseconds loopWaitDuration(100);
if (proxyAvailabilityStatus_ == availabilityStatus)
return true;
for (int i = 0; i < 10; i++) {
std::this_thread::sleep_for(loopWaitDuration);
if (proxyAvailabilityStatus_ == availabilityStatus)
return true;
}
return false;
}
std::shared_ptr<CommonAPI::DBus::DBusConnection> proxyDBusConnection_;
std::shared_ptr<commonapi::tests::TestInterfaceDBusProxy> proxy_;
CommonAPI::AvailabilityStatus proxyAvailabilityStatus_;
std::shared_ptr<CommonAPI::DBus::DBusConnection> stubDBusConnection_;
std::shared_ptr<commonapi::tests::TestInterfaceDBusStubAdapter> stubAdapter_;
};
TEST_F(ProxyTest, HasCorrectConnectionName) {
std::string actualName = proxy_->getDBusBusName();
EXPECT_EQ(busName, actualName);
}
TEST_F(ProxyTest, HasCorrectObjectPath) {
std::string actualPath = proxy_->getDBusObjectPath();
EXPECT_EQ(objectPath, actualPath);
}
TEST_F(ProxyTest, HasCorrectInterfaceName) {
std::string actualName = proxy_->getInterfaceName();
EXPECT_EQ(interfaceName, actualName);
}
TEST_F(ProxyTest, IsNotAvailable) {
bool isAvailable = proxy_->isAvailable();
EXPECT_FALSE(isAvailable);
}
TEST_F(ProxyTest, ServiceRegistry) {
std::shared_ptr<CommonAPI::DBus::DBusProxyConnection> connection = proxy_->getDBusConnection();
auto registry = connection->getDBusServiceRegistry();
ASSERT_FALSE(!registry);
}
TEST_F(ProxyTest, DBusProxyStatusEventBeforeServiceIsRegistered) {
proxyRegisterForAvailabilityStatus();
ASSERT_NE(proxyAvailabilityStatus_, CommonAPI::AvailabilityStatus::AVAILABLE);
registerTestStub();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::AVAILABLE));
stubDBusConnection_->disconnect();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::NOT_AVAILABLE));
}
TEST_F(ProxyTest, DBusProxyStatusEventAfterServiceIsRegistered) {
proxyDBusConnection_->disconnect();
registerTestStub();
ASSERT_TRUE(proxyDBusConnection_->connect());
proxyRegisterForAvailabilityStatus();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::AVAILABLE));
stubDBusConnection_->disconnect();
ASSERT_TRUE(proxyWaitForAvailabilityStatus(CommonAPI::AvailabilityStatus::NOT_AVAILABLE));
}
TEST_F(ProxyTest, ServiceStatus) {
proxyDBusConnection_->requestServiceNameAndBlock(busName);
std::shared_ptr<commonapi::tests::TestInterfaceStubDefault> stubDefault = std::make_shared<commonapi::tests::TestInterfaceStubDefault>();
std::shared_ptr<commonapi::tests::TestInterfaceDBusStubAdapter> stubAdapter = std::make_shared<commonapi::tests::TestInterfaceDBusStubAdapter>(
commonApiAddress,
interfaceName,
busName,
objectPath,
proxyDBusConnection_,
stubDefault);
stubAdapter->init();
auto testConnection = CommonAPI::DBus::DBusConnection::getSessionBus();
testConnection->connect();
std::vector<std::string> actuallyAvailableServices;
actuallyAvailableServices = testConnection->getDBusServiceRegistry()->getAvailableServiceInstances(commonApiServiceName,
"local");
auto found = std::find(actuallyAvailableServices.begin(), actuallyAvailableServices.end(), commonApiAddress);
ASSERT_TRUE(actuallyAvailableServices.begin() != actuallyAvailableServices.end());
ASSERT_TRUE(found != actuallyAvailableServices.end());
testConnection->disconnect();
}
TEST_F(ProxyTest, IsAvailableBlocking) {
std::shared_ptr<commonapi::tests::TestInterfaceStubDefault> stubDefault = std::make_shared<commonapi::tests::TestInterfaceStubDefault>();
std::shared_ptr<commonapi::tests::TestInterfaceDBusStubAdapter> stubAdapter = std::make_shared<commonapi::tests::TestInterfaceDBusStubAdapter>(
commonApiAddress,
interfaceName,
busName,
objectPath,
proxyDBusConnection_,
stubDefault);
stubAdapter->init();
bool registered = proxyDBusConnection_->requestServiceNameAndBlock(busName);
bool isAvailable = proxy_->isAvailableBlocking();
EXPECT_EQ(registered, isAvailable);
}
TEST_F(ProxyTest, HasNecessaryAttributesAndEvents) {
CommonAPI::InterfaceVersionAttribute& versionAttribute = (proxy_->getInterfaceVersionAttribute());
CommonAPI::ProxyStatusEvent& statusEvent = (proxy_->getProxyStatusEvent());
}
TEST_F(ProxyTest, IsConnected) {
ASSERT_TRUE(proxy_->getDBusConnection()->isConnected());
}
TEST_F(ProxyTest, TestInterfaceVersionAttribute) {
CommonAPI::InterfaceVersionAttribute& versionAttribute = proxy_->getInterfaceVersionAttribute();
CommonAPI::Version version;
CommonAPI::CallStatus status = versionAttribute.getValue(version);
ASSERT_EQ(CommonAPI::CallStatus::NOT_AVAILABLE, status);
}
TEST_F(ProxyTest, AsyncCallbacksAreCalledIfServiceNotAvailable) {
commonapi::tests::DerivedTypeCollection::TestEnumExtended2 testInputStruct;
commonapi::tests::DerivedTypeCollection::TestMap testInputMap;
bool wasCalled = false;
proxy_->testDerivedTypeMethodAsync(testInputStruct, testInputMap, [&] (const CommonAPI::CallStatus& callStatus,
const commonapi::tests::DerivedTypeCollection::TestEnumExtended2&,
const commonapi::tests::DerivedTypeCollection::TestMap&) {
ASSERT_EQ(callStatus, CommonAPI::CallStatus::NOT_AVAILABLE);
wasCalled = true;
}
);
sleep(1);
ASSERT_TRUE(wasCalled);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2016 ZNC, see the NOTICE file for details.
*
* 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 <znc/User.h>
#include <znc/IRCNetwork.h>
using std::vector;
#define MESSAGE "Your account has been disabled. Contact your administrator."
class CBlockUser : public CModule {
public:
MODCONSTRUCTOR(CBlockUser) {
AddHelpCommand();
AddCommand("List", static_cast<CModCommand::ModCmdFunc>(
&CBlockUser::OnListCommand),
"", "List blocked users");
AddCommand("Block", static_cast<CModCommand::ModCmdFunc>(
&CBlockUser::OnBlockCommand),
"<user>", "Block a user");
AddCommand("Unblock", static_cast<CModCommand::ModCmdFunc>(
&CBlockUser::OnUnblockCommand),
"<user>", "Unblock a user");
}
~CBlockUser() override {}
bool OnLoad(const CString& sArgs, CString& sMessage) override {
VCString vArgs;
VCString::iterator it;
MCString::iterator it2;
// Load saved settings
for (it2 = BeginNV(); it2 != EndNV(); ++it2) {
// Ignore errors
Block(it2->first);
}
// Parse arguments, each argument is a user name to block
sArgs.Split(" ", vArgs, false);
for (it = vArgs.begin(); it != vArgs.end(); ++it) {
if (!Block(*it)) {
sMessage = "Could not block [" + *it + "]";
return false;
}
}
return true;
}
EModRet OnLoginAttempt(std::shared_ptr<CAuthBase> Auth) override {
if (IsBlocked(Auth->GetUsername())) {
Auth->RefuseLogin(MESSAGE);
return HALT;
}
return CONTINUE;
}
void OnModCommand(const CString& sCommand) override {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
} else {
HandleCommand(sCommand);
}
}
void OnListCommand(const CString& sCommand) {
CTable Table;
MCString::iterator it;
Table.AddColumn("Blocked user");
for (it = BeginNV(); it != EndNV(); ++it) {
Table.AddRow();
Table.SetCell("Blocked user", it->first);
}
if (PutModule(Table) == 0) PutModule("No users blocked");
}
void OnBlockCommand(const CString& sCommand) {
CString sUser = sCommand.Token(1, true);
if (sUser.empty()) {
PutModule("Usage: Block <user>");
return;
}
if (GetUser()->GetUserName().Equals(sUser)) {
PutModule("You can't block yourself");
return;
}
if (Block(sUser))
PutModule("Blocked [" + sUser + "]");
else
PutModule("Could not block [" + sUser + "] (misspelled?)");
}
void OnUnblockCommand(const CString& sCommand) {
CString sUser = sCommand.Token(1, true);
if (sUser.empty()) {
PutModule("Usage: Unblock <user>");
return;
}
if (DelNV(sUser))
PutModule("Unblocked [" + sUser + "]");
else
PutModule("This user is not blocked");
}
bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName,
CTemplate& Tmpl) override {
if (sPageName == "webadmin/user" && WebSock.GetSession()->IsAdmin()) {
CString sAction = Tmpl["WebadminAction"];
if (sAction == "display") {
Tmpl["Blocked"] = CString(IsBlocked(Tmpl["Username"]));
Tmpl["Self"] = CString(Tmpl["Username"].Equals(
WebSock.GetSession()->GetUser()->GetUserName()));
return true;
}
if (sAction == "change" &&
WebSock.GetParam("embed_blockuser_presented").ToBool()) {
if (Tmpl["Username"].Equals(
WebSock.GetSession()->GetUser()->GetUserName()) &&
WebSock.GetParam("embed_blockuser_block").ToBool()) {
WebSock.GetSession()->AddError("You can't block yourself");
} else if (WebSock.GetParam("embed_blockuser_block").ToBool()) {
if (!WebSock.GetParam("embed_blockuser_old").ToBool()) {
if (Block(Tmpl["Username"])) {
WebSock.GetSession()->AddSuccess(
"Blocked [" + Tmpl["Username"] + "]");
} else {
WebSock.GetSession()->AddError(
"Couldn't block [" + Tmpl["Username"] + "]");
}
}
} else if (WebSock.GetParam("embed_blockuser_old").ToBool()) {
if (DelNV(Tmpl["Username"])) {
WebSock.GetSession()->AddSuccess(
"Unblocked [" + Tmpl["Username"] + "]");
} else {
WebSock.GetSession()->AddError(
"User [" + Tmpl["Username"] + "is not blocked");
}
}
return true;
}
}
return false;
}
private:
bool IsBlocked(const CString& sUser) {
MCString::iterator it;
for (it = BeginNV(); it != EndNV(); ++it) {
if (sUser == it->first) {
return true;
}
}
return false;
}
bool Block(const CString& sUser) {
CUser* pUser = CZNC::Get().FindUser(sUser);
if (!pUser) return false;
// Disconnect all clients
vector<CClient*> vpClients = pUser->GetAllClients();
vector<CClient*>::iterator it;
for (it = vpClients.begin(); it != vpClients.end(); ++it) {
(*it)->PutStatusNotice(MESSAGE);
(*it)->Close(Csock::CLT_AFTERWRITE);
}
// Disconnect all networks from irc
vector<CIRCNetwork*> vNetworks = pUser->GetNetworks();
for (vector<CIRCNetwork*>::iterator it2 = vNetworks.begin();
it2 != vNetworks.end(); ++it2) {
(*it2)->SetIRCConnectEnabled(false);
}
SetNV(pUser->GetUserName(), "");
return true;
}
};
template <>
void TModInfo<CBlockUser>(CModInfo& Info) {
Info.SetWikiPage("blockuser");
Info.SetHasArgs(true);
Info.SetArgsHelpText(
"Enter one or more user names. Separate them by spaces.");
}
GLOBALMODULEDEFS(CBlockUser, "Block certain users from logging in.")
<commit_msg>Adding some comments to blockuser module (#1380)<commit_after>/*
* Copyright (C) 2004-2016 ZNC, see the NOTICE file for details.
*
* 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 <znc/User.h>
#include <znc/IRCNetwork.h>
using std::vector;
#define MESSAGE "Your account has been disabled. Contact your administrator."
class CBlockUser : public CModule {
public:
MODCONSTRUCTOR(CBlockUser) {
AddHelpCommand();
AddCommand("List", static_cast<CModCommand::ModCmdFunc>(
&CBlockUser::OnListCommand),
"", "List blocked users");
AddCommand("Block", static_cast<CModCommand::ModCmdFunc>(
&CBlockUser::OnBlockCommand),
"<user>", "Block a user");
AddCommand("Unblock", static_cast<CModCommand::ModCmdFunc>(
&CBlockUser::OnUnblockCommand),
"<user>", "Unblock a user");
}
~CBlockUser() override {}
bool OnLoad(const CString& sArgs, CString& sMessage) override {
VCString vArgs;
VCString::iterator it;
MCString::iterator it2;
// Load saved settings
for (it2 = BeginNV(); it2 != EndNV(); ++it2) {
// Ignore errors
Block(it2->first);
}
// Parse arguments, each argument is a user name to block
sArgs.Split(" ", vArgs, false);
for (it = vArgs.begin(); it != vArgs.end(); ++it) {
if (!Block(*it)) {
sMessage = "Could not block [" + *it + "]";
return false;
}
}
return true;
}
/* If a user is on the blocked list and tries to log in, displays - MESSAGE
and stops their log in attempt.*/
EModRet OnLoginAttempt(std::shared_ptr<CAuthBase> Auth) override {
if (IsBlocked(Auth->GetUsername())) {
Auth->RefuseLogin(MESSAGE);
return HALT;
}
return CONTINUE;
}
void OnModCommand(const CString& sCommand) override {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
} else {
HandleCommand(sCommand);
}
}
// Displays all blocked users as a list.
void OnListCommand(const CString& sCommand) {
CTable Table;
MCString::iterator it;
Table.AddColumn("Blocked user");
for (it = BeginNV(); it != EndNV(); ++it) {
Table.AddRow();
Table.SetCell("Blocked user", it->first);
}
if (PutModule(Table) == 0) PutModule("No users blocked");
}
/* Blocks a user if possible(ie not self, not already blocked).
Displays an error message if not possible. */
void OnBlockCommand(const CString& sCommand) {
CString sUser = sCommand.Token(1, true);
if (sUser.empty()) {
PutModule("Usage: Block <user>");
return;
}
if (GetUser()->GetUserName().Equals(sUser)) {
PutModule("You can't block yourself");
return;
}
if (Block(sUser))
PutModule("Blocked [" + sUser + "]");
else
PutModule("Could not block [" + sUser + "] (misspelled?)");
}
// Unblocks a user from the blocked list.
void OnUnblockCommand(const CString& sCommand) {
CString sUser = sCommand.Token(1, true);
if (sUser.empty()) {
PutModule("Usage: Unblock <user>");
return;
}
if (DelNV(sUser))
PutModule("Unblocked [" + sUser + "]");
else
PutModule("This user is not blocked");
}
// Provides GUI to configure this module by adding a widget to user page in webadmin.
bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName,
CTemplate& Tmpl) override {
if (sPageName == "webadmin/user" && WebSock.GetSession()->IsAdmin()) {
CString sAction = Tmpl["WebadminAction"];
if (sAction == "display") {
Tmpl["Blocked"] = CString(IsBlocked(Tmpl["Username"]));
Tmpl["Self"] = CString(Tmpl["Username"].Equals(
WebSock.GetSession()->GetUser()->GetUserName()));
return true;
}
if (sAction == "change" &&
WebSock.GetParam("embed_blockuser_presented").ToBool()) {
if (Tmpl["Username"].Equals(
WebSock.GetSession()->GetUser()->GetUserName()) &&
WebSock.GetParam("embed_blockuser_block").ToBool()) {
WebSock.GetSession()->AddError("You can't block yourself");
} else if (WebSock.GetParam("embed_blockuser_block").ToBool()) {
if (!WebSock.GetParam("embed_blockuser_old").ToBool()) {
if (Block(Tmpl["Username"])) {
WebSock.GetSession()->AddSuccess(
"Blocked [" + Tmpl["Username"] + "]");
} else {
WebSock.GetSession()->AddError(
"Couldn't block [" + Tmpl["Username"] + "]");
}
}
} else if (WebSock.GetParam("embed_blockuser_old").ToBool()) {
if (DelNV(Tmpl["Username"])) {
WebSock.GetSession()->AddSuccess(
"Unblocked [" + Tmpl["Username"] + "]");
} else {
WebSock.GetSession()->AddError(
"User [" + Tmpl["Username"] + "is not blocked");
}
}
return true;
}
}
return false;
}
private:
/* Iterates through all blocked users and returns true if the specified user (sUser)
is blocked, else returns false.*/
bool IsBlocked(const CString& sUser) {
MCString::iterator it;
for (it = BeginNV(); it != EndNV(); ++it) {
if (sUser == it->first) {
return true;
}
}
return false;
}
bool Block(const CString& sUser) {
CUser* pUser = CZNC::Get().FindUser(sUser);
if (!pUser) return false;
// Disconnect all clients
vector<CClient*> vpClients = pUser->GetAllClients();
vector<CClient*>::iterator it;
for (it = vpClients.begin(); it != vpClients.end(); ++it) {
(*it)->PutStatusNotice(MESSAGE);
(*it)->Close(Csock::CLT_AFTERWRITE);
}
// Disconnect all networks from irc
vector<CIRCNetwork*> vNetworks = pUser->GetNetworks();
for (vector<CIRCNetwork*>::iterator it2 = vNetworks.begin();
it2 != vNetworks.end(); ++it2) {
(*it2)->SetIRCConnectEnabled(false);
}
SetNV(pUser->GetUserName(), "");
return true;
}
};
template <>
void TModInfo<CBlockUser>(CModInfo& Info) {
Info.SetWikiPage("blockuser");
Info.SetHasArgs(true);
Info.SetArgsHelpText(
"Enter one or more user names. Separate them by spaces.");
}
GLOBALMODULEDEFS(CBlockUser, "Block certain users from logging in.")
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/blocked_popup_container.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "gfx/rect.h"
// static
const size_t BlockedPopupContainer::kImpossibleNumberOfPopups = 30;
struct BlockedPopupContainer::BlockedPopup {
BlockedPopup(TabContents* tab_contents,
const gfx::Rect& bounds)
: tab_contents(tab_contents), bounds(bounds) {
}
TabContents* tab_contents;
gfx::Rect bounds;
};
BlockedPopupContainer::BlockedPopupContainer(TabContents* owner)
: owner_(owner) {
}
void BlockedPopupContainer::AddTabContents(TabContents* tab_contents,
const gfx::Rect& bounds) {
if (blocked_popups_.size() == (kImpossibleNumberOfPopups - 1)) {
delete tab_contents;
LOG(INFO) << "Warning: Renderer is sending more popups to us than should "
"be possible. Renderer compromised?";
return;
}
blocked_popups_.push_back(BlockedPopup(tab_contents, bounds));
tab_contents->set_delegate(this);
if (blocked_popups_.size() == 1)
owner_->PopupNotificationVisibilityChanged(true);
}
void BlockedPopupContainer::LaunchPopupForContents(TabContents* tab_contents) {
// Open the popup.
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
if (i->tab_contents == tab_contents) {
tab_contents->set_delegate(NULL);
owner_->AddNewContents(tab_contents, NEW_POPUP, i->bounds, true);
blocked_popups_.erase(i);
break;
}
}
if (blocked_popups_.empty())
Destroy();
}
size_t BlockedPopupContainer::GetBlockedPopupCount() const {
return blocked_popups_.size();
}
void BlockedPopupContainer::GetBlockedContents(
BlockedContents* blocked_contents) const {
DCHECK(blocked_contents);
for (BlockedPopups::const_iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i)
blocked_contents->push_back(i->tab_contents);
}
void BlockedPopupContainer::Destroy() {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
TabContents* tab_contents = i->tab_contents;
tab_contents->set_delegate(NULL);
delete tab_contents;
}
blocked_popups_.clear();
owner_->WillCloseBlockedPopupContainer(this);
delete this;
}
// Overridden from TabContentsDelegate:
void BlockedPopupContainer::OpenURLFromTab(TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
owner_->OpenURL(url, referrer, disposition, transition);
}
void BlockedPopupContainer::AddNewContents(TabContents* source,
TabContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_position,
bool user_gesture) {
owner_->AddNewContents(new_contents, disposition, initial_position,
user_gesture);
}
void BlockedPopupContainer::CloseContents(TabContents* source) {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
TabContents* tab_contents = i->tab_contents;
if (tab_contents == source) {
tab_contents->set_delegate(NULL);
blocked_popups_.erase(i);
delete tab_contents;
break;
}
}
}
void BlockedPopupContainer::MoveContents(TabContents* source,
const gfx::Rect& new_bounds) {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
if (i->tab_contents == source) {
i->bounds = new_bounds;
break;
}
}
}
bool BlockedPopupContainer::IsPopup(const TabContents* source) const {
return true;
}
TabContents* BlockedPopupContainer::GetConstrainingContents(
TabContents* source) {
return owner_;
}
<commit_msg>Fix browser hang when blocking hulu pop-out<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/blocked_popup_container.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "gfx/rect.h"
// static
const size_t BlockedPopupContainer::kImpossibleNumberOfPopups = 30;
struct BlockedPopupContainer::BlockedPopup {
BlockedPopup(TabContents* tab_contents,
const gfx::Rect& bounds)
: tab_contents(tab_contents), bounds(bounds) {
}
TabContents* tab_contents;
gfx::Rect bounds;
};
BlockedPopupContainer::BlockedPopupContainer(TabContents* owner)
: owner_(owner) {
}
void BlockedPopupContainer::AddTabContents(TabContents* tab_contents,
const gfx::Rect& bounds) {
if (blocked_popups_.size() == (kImpossibleNumberOfPopups - 1)) {
delete tab_contents;
LOG(INFO) << "Warning: Renderer is sending more popups to us than should "
"be possible. Renderer compromised?";
return;
}
// BUG:52754 Super hack time. If we supress a popup that has flash 10.1
// playing a movie, it cannot handle being zero-sized: an unending series
// of divide by zero exceptions are thrown (and ignored) inside the flash
// in the UI thread thereby hanging the plugin and in turn hanging us.
tab_contents->view()->SizeContents(gfx::Size(10, 10));
blocked_popups_.push_back(BlockedPopup(tab_contents, bounds));
tab_contents->set_delegate(this);
if (blocked_popups_.size() == 1)
owner_->PopupNotificationVisibilityChanged(true);
}
void BlockedPopupContainer::LaunchPopupForContents(TabContents* tab_contents) {
// Open the popup.
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
if (i->tab_contents == tab_contents) {
tab_contents->set_delegate(NULL);
owner_->AddNewContents(tab_contents, NEW_POPUP, i->bounds, true);
blocked_popups_.erase(i);
break;
}
}
if (blocked_popups_.empty())
Destroy();
}
size_t BlockedPopupContainer::GetBlockedPopupCount() const {
return blocked_popups_.size();
}
void BlockedPopupContainer::GetBlockedContents(
BlockedContents* blocked_contents) const {
DCHECK(blocked_contents);
for (BlockedPopups::const_iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i)
blocked_contents->push_back(i->tab_contents);
}
void BlockedPopupContainer::Destroy() {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
TabContents* tab_contents = i->tab_contents;
tab_contents->set_delegate(NULL);
delete tab_contents;
}
blocked_popups_.clear();
owner_->WillCloseBlockedPopupContainer(this);
delete this;
}
// Overridden from TabContentsDelegate:
void BlockedPopupContainer::OpenURLFromTab(TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
owner_->OpenURL(url, referrer, disposition, transition);
}
void BlockedPopupContainer::AddNewContents(TabContents* source,
TabContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_position,
bool user_gesture) {
owner_->AddNewContents(new_contents, disposition, initial_position,
user_gesture);
}
void BlockedPopupContainer::CloseContents(TabContents* source) {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
TabContents* tab_contents = i->tab_contents;
if (tab_contents == source) {
tab_contents->set_delegate(NULL);
blocked_popups_.erase(i);
delete tab_contents;
break;
}
}
}
void BlockedPopupContainer::MoveContents(TabContents* source,
const gfx::Rect& new_bounds) {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
if (i->tab_contents == source) {
i->bounds = new_bounds;
break;
}
}
}
bool BlockedPopupContainer::IsPopup(const TabContents* source) const {
return true;
}
TabContents* BlockedPopupContainer::GetConstrainingContents(
TabContents* source) {
return owner_;
}
<|endoftext|> |
<commit_before>#include "marian.h"
#include "translator/beam_search.h"
#include "translator/translator.h"
int main(int argc, char** argv) {
using namespace marian;
auto options = New<Config>(argc, argv, ConfigMode::translating);
auto task = New<TranslateLoopMultiGPU<BeamSearch>>(options);
boost::timer::cpu_timer timer;
for(std::string line; std::getline(std::cin, line);) {
timer.start();
for(auto& output : task->run({line}))
std::cout << output << std::endl;
LOG(info)->info("Search took: {}", timer.format(5, "%ws"));
}
return 0;
}
<commit_msg>Add simple server application<commit_after>#include "marian.h"
#include "translator/beam_search.h"
#include "translator/translator.h"
#include "3rd_party/simple-websocket-server/server_ws.hpp"
typedef SimpleWeb::SocketServer<SimpleWeb::WS> WsServer;
int main(int argc, char** argv) {
using namespace marian;
auto options = New<Config>(argc, argv, ConfigMode::translating);
auto task = New<TranslateLoopMultiGPU<BeamSearch>>(options);
WsServer server_;
server_.config.port = 1234;
auto &echo = server_.endpoint["^/translate/?$"];
echo.on_message = [&task](std::shared_ptr<WsServer::Connection> connection,
std::shared_ptr<WsServer::Message> message) {
auto message_str = message->string();
std::cout << "Server: Message received: \"" << message_str << "\" from "
<< connection.get() << std::endl;
std::cout << "Server: Sending message \"" << message_str << "\" to "
<< connection.get() << std::endl;
auto send_stream = std::make_shared<WsServer::SendStream>();
boost::timer::cpu_timer timer;
for(auto& transl : task->run({message_str})) {
*send_stream << transl << std::endl;
}
LOG(info)->info("Search took: {}", timer.format(5, "%ws"));
// connection->send is an asynchronous function
connection->send(send_stream, [](const SimpleWeb::error_code &ec) {
if(ec) {
std::cout << "Server: Error sending message. " <<
// Error Codes for error code meanings:
// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html
"Error: " << ec << ", error message: " << ec.message() << std::endl;
}
});
// Alternatively, using a convenience function:
// connection->send(message_str, [](const SimpleWeb::error_code & /*ec*/) {
// /*handle error*/ });
};
echo.on_open = [](std::shared_ptr<WsServer::Connection> connection) {
std::cout << "Server: Opened connection " << connection.get() << std::endl;
};
// See RFC 6455 7.4.1. for status codes
echo.on_close = [](std::shared_ptr<WsServer::Connection> connection,
int status,
const std::string & /*reason*/) {
std::cout << "Server: Closed connection " << connection.get()
<< " with status code " << status << std::endl;
};
// Error Codes for error code meanings
// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html,
echo.on_error = [](std::shared_ptr<WsServer::Connection> connection,
const SimpleWeb::error_code &ec) {
std::cout << "Server: Error in connection " << connection.get() << ". "
<< "Error: " << ec << ", error message: " << ec.message()
<< std::endl;
};
std::thread server_thread([&server_]() {
LOG(info)->info("Server started");
server_.start();
});
server_thread.join();
return 0;
}
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdarg.h>
#include <stdint.h>
#include <gmock/gmock.h>
#include <list>
#include <string>
#include <mesos/resources.hpp>
#include <stout/gtest.hpp>
#include "master/allocator/sorter/drf/sorter.hpp"
#include "tests/mesos.hpp"
using mesos::internal::master::allocator::DRFSorter;
using std::list;
using std::string;
namespace mesos {
namespace internal {
namespace tests {
TEST(SorterTest, DRFSorter)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
Resources totalResources = Resources::parse("cpus:100;mem:100").get();
sorter.add(slaveId, totalResources);
sorter.add("a");
Resources aResources = Resources::parse("cpus:5;mem:5").get();
sorter.allocated("a", slaveId, aResources);
Resources bResources = Resources::parse("cpus:6;mem:6").get();
sorter.add("b");
sorter.allocated("b", slaveId, bResources);
// shares: a = .05, b = .06
EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());
Resources cResources = Resources::parse("cpus:1;mem:1").get();
sorter.add("c");
sorter.allocated("c", slaveId, cResources);
Resources dResources = Resources::parse("cpus:3;mem:1").get();
sorter.add("d");
sorter.allocated("d", slaveId, dResources);
// shares: a = .05, b = .06, c = .01, d = .03
EXPECT_EQ(list<string>({"c", "d", "a", "b"}), sorter.sort());
sorter.remove("a");
Resources bUnallocated = Resources::parse("cpus:4;mem:4").get();
sorter.unallocated("b", slaveId, bUnallocated);
// shares: b = .02, c = .01, d = .03
EXPECT_EQ(list<string>({"c", "b", "d"}), sorter.sort());
Resources eResources = Resources::parse("cpus:1;mem:5").get();
sorter.add("e");
sorter.allocated("e", slaveId, eResources);
Resources removedResources = Resources::parse("cpus:50;mem:0").get();
sorter.remove(slaveId, removedResources);
// total resources is now cpus = 50, mem = 100
// shares: b = .04, c = .02, d = .06, e = .05
EXPECT_EQ(list<string>({"c", "b", "e", "d"}), sorter.sort());
Resources addedResources = Resources::parse("cpus:0;mem:100").get();
sorter.add(slaveId, addedResources);
// total resources is now cpus = 50, mem = 200
Resources fResources = Resources::parse("cpus:5;mem:1").get();
sorter.add("f");
sorter.allocated("f", slaveId, fResources);
Resources cResources2 = Resources::parse("cpus:0;mem:15").get();
sorter.allocated("c", slaveId, cResources2);
// shares: b = .04, c = .08, d = .06, e = .025, f = .1
EXPECT_EQ(list<string>({"e", "b", "d", "c", "f"}), sorter.sort());
EXPECT_TRUE(sorter.contains("b"));
EXPECT_FALSE(sorter.contains("a"));
EXPECT_EQ(sorter.count(), 5);
sorter.deactivate("d");
EXPECT_TRUE(sorter.contains("d"));
EXPECT_EQ(list<string>({"e", "b", "c", "f"}), sorter.sort());
EXPECT_EQ(sorter.count(), 5);
sorter.activate("d");
EXPECT_EQ(list<string>({"e", "b", "d", "c", "f"}), sorter.sort());
}
TEST(SorterTest, WDRFSorter)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add(slaveId, Resources::parse("cpus:100;mem:100").get());
sorter.add("a");
sorter.allocated("a", slaveId, Resources::parse("cpus:5;mem:5").get());
sorter.add("b", 2);
sorter.allocated("b", slaveId, Resources::parse("cpus:6;mem:6").get());
// shares: a = .05, b = .03
EXPECT_EQ(list<string>({"b", "a"}), sorter.sort());
sorter.add("c");
sorter.allocated("c", slaveId, Resources::parse("cpus:4;mem:4").get());
// shares: a = .05, b = .03, c = .04
EXPECT_EQ(list<string>({"b", "c", "a"}), sorter.sort());
sorter.add("d", 10);
sorter.allocated("d", slaveId, Resources::parse("cpus:10;mem:20").get());
// shares: a = .05, b = .03, c = .04, d = .02
EXPECT_EQ(list<string>({"d", "b", "c", "a"}), sorter.sort());
sorter.remove("b");
EXPECT_EQ(list<string>({"d", "c", "a"}), sorter.sort());
sorter.allocated("d", slaveId, Resources::parse("cpus:10;mem:25").get());
// shares: a = .05, c = .04, d = .045
EXPECT_EQ(list<string>({"c", "d", "a"}), sorter.sort());
sorter.add("e", .1);
sorter.allocated("e", slaveId, Resources::parse("cpus:1;mem:1").get());
// shares: a = .05, c = .04, d = .045, e = .1
EXPECT_EQ(list<string>({"c", "d", "a", "e"}), sorter.sort());
sorter.remove("a");
EXPECT_EQ(list<string>({"c", "d", "e"}), sorter.sort());
}
// Some resources are split across multiple resource objects (e.g.
// persistent volumes). This test ensures that the shares for these
// are accounted correctly.
TEST(SorterTest, SplitResourceShares)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
Resource disk1 = Resources::parse("disk", "5", "*").get();
disk1.mutable_disk()->mutable_persistence()->set_id("ID2");
disk1.mutable_disk()->mutable_volume()->set_container_path("data");
Resource disk2 = Resources::parse("disk", "5", "*").get();
disk2.mutable_disk()->mutable_persistence()->set_id("ID2");
disk2.mutable_disk()->mutable_volume()->set_container_path("data");
sorter.add(
slaveId,
Resources::parse("cpus:100;mem:100;disk:95").get() + disk1 + disk2);
// Now, allocate resources to "a" and "b". Note that "b" will have
// more disk if the shares are accounted correctly!
sorter.allocated(
"a", slaveId, Resources::parse("cpus:9;mem:9;disk:9").get());
sorter.allocated(
"b", slaveId, Resources::parse("cpus:9;mem:9").get() + disk1 + disk2);
EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());
}
TEST(SorterTest, UpdateAllocation)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
sorter.add(slaveId, Resources::parse("cpus:10;mem:10;disk:10").get());
sorter.allocated(
"a", slaveId, Resources::parse("cpus:10;mem:10;disk:10").get());
// Construct an offer operation.
Resource volume = Resources::parse("disk", "5", "*").get();
volume.mutable_disk()->mutable_persistence()->set_id("ID");
volume.mutable_disk()->mutable_volume()->set_container_path("data");
// Compute the updated allocation.
Resources oldAllocation = sorter.allocation("a")[slaveId];
Try<Resources> newAllocation = oldAllocation.apply(CREATE(volume));
ASSERT_SOME(newAllocation);
// Update the resources for the client.
sorter.update("a", slaveId, oldAllocation, newAllocation.get());
hashmap<SlaveID, Resources> allocation = sorter.allocation("a");
EXPECT_EQ(1u, allocation.size());
EXPECT_EQ(newAllocation.get(), allocation[slaveId]);
}
// We aggregate resources from multiple slaves into the sorter.
// Since non-scalar resources don't aggregate well across slaves,
// we need to keep track of the SlaveIDs of the resources. This
// tests that no resources vanish in the process of aggregation
// by inspecting the result of 'allocation'.
TEST(SorterTest, MultipleSlaves)
{
DRFSorter sorter;
SlaveID slaveA;
slaveA.set_value("slaveA");
SlaveID slaveB;
slaveB.set_value("slaveB");
sorter.add("framework");
Resources slaveResources =
Resources::parse("cpus:2;mem:512;ports:[31000-32000]").get();
sorter.add(slaveA, slaveResources);
sorter.add(slaveB, slaveResources);
sorter.allocated("framework", slaveA, slaveResources);
sorter.allocated("framework", slaveB, slaveResources);
hashmap<SlaveID, Resources> allocation = sorter.allocation("framework");
EXPECT_EQ(2u, allocation.size());
EXPECT_EQ(slaveResources, allocation[slaveA]);
EXPECT_EQ(slaveResources, allocation[slaveB]);
}
// We aggregate resources from multiple slaves into the sorter.
// Since non-scalar resources don't aggregate well across slaves,
// we need to keep track of the SlaveIDs of the resources.
// This tests that no resources vanish in the process of aggregation
// by performing a updates from unreserved to reserved resources.
TEST(SorterTest, MultipleSlaveUpdates)
{
DRFSorter sorter;
SlaveID slaveA;
slaveA.set_value("slaveA");
SlaveID slaveB;
slaveB.set_value("slaveB");
sorter.add("framework");
Resources slaveResources =
Resources::parse("cpus:2;mem:512;disk:10;ports:[31000-32000]").get();
sorter.add(slaveA, slaveResources);
sorter.add(slaveB, slaveResources);
sorter.allocated("framework", slaveA, slaveResources);
sorter.allocated("framework", slaveB, slaveResources);
// Construct an offer operation.
Resource volume = Resources::parse("disk", "5", "*").get();
volume.mutable_disk()->mutable_persistence()->set_id("ID");
volume.mutable_disk()->mutable_volume()->set_container_path("data");
// Compute the updated allocation.
Try<Resources> newAllocation = slaveResources.apply(CREATE(volume));
ASSERT_SOME(newAllocation);
// Update the resources for the client.
sorter.update("framework", slaveA, slaveResources, newAllocation.get());
sorter.update("framework", slaveB, slaveResources, newAllocation.get());
hashmap<SlaveID, Resources> allocation = sorter.allocation("framework");
EXPECT_EQ(2u, allocation.size());
EXPECT_EQ(newAllocation.get(), allocation[slaveA]);
EXPECT_EQ(newAllocation.get(), allocation[slaveB]);
}
// This test verifies that when the total pool of resources is updated
// the sorting order of clients reflects the new total.
TEST(SorterTest, UpdateTotal)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
sorter.add(slaveId, Resources::parse("cpus:10;mem:100").get());
// Dominant share of "a" is 0.2 (cpus).
sorter.allocated(
"a", slaveId, Resources::parse("cpus:2;mem:1").get());
// Dominant share of "b" is 0.1 (cpus).
sorter.allocated(
"b", slaveId, Resources::parse("cpus:1;mem:2").get());
list<string> sorted = sorter.sort();
ASSERT_EQ(2, sorted.size());
EXPECT_EQ("b", sorted.front());
EXPECT_EQ("a", sorted.back());
// Update the total resources.
sorter.update(slaveId, Resources::parse("cpus:100;mem:10").get());
// Now the dominant share of "a" is 0.1 (mem) and "b" is 0.2 (mem),
// which should change the sort order.
sorted = sorter.sort();
ASSERT_EQ(2, sorted.size());
EXPECT_EQ("a", sorted.front());
EXPECT_EQ("b", sorted.back());
}
// This test verifies that revocable resources are properly accounted
// for in the DRF sorter.
TEST(SorterTest, RevocableResources)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
// Create a total resource pool of 10 revocable cpus and 10 cpus and
// 10 MB mem.
Resource revocable = Resources::parse("cpus", "10", "*").get();
revocable.mutable_revocable();
Resources total = Resources::parse("cpus:10;mem:100").get() + revocable;
sorter.add(slaveId, revocable);
// Dominant share of "a" is 0.1 (cpus).
Resources a = Resources::parse("cpus:2;mem:1").get();
sorter.allocated("a", slaveId, a);
// Dominant share of "b" is 0.5 (cpus).
revocable = Resources::parse("cpus", "9", "*").get();
revocable.mutable_revocable();
Resources b = Resources::parse("cpus:1;mem:1").get() + revocable;
sorter.allocated("b", slaveId, b);
// Check that the allocations are correct.
ASSERT_EQ(a, sorter.allocation("a")[slaveId]);
ASSERT_EQ(b, sorter.allocation("b")[slaveId]);
// Check that the sort is correct.
list<string> sorted = sorter.sort();
ASSERT_EQ(2, sorted.size());
EXPECT_EQ("a", sorted.front());
EXPECT_EQ("b", sorted.back());
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Minor signed comparison fix in sorter tests.<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdarg.h>
#include <stdint.h>
#include <gmock/gmock.h>
#include <list>
#include <string>
#include <mesos/resources.hpp>
#include <stout/gtest.hpp>
#include "master/allocator/sorter/drf/sorter.hpp"
#include "tests/mesos.hpp"
using mesos::internal::master::allocator::DRFSorter;
using std::list;
using std::string;
namespace mesos {
namespace internal {
namespace tests {
TEST(SorterTest, DRFSorter)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
Resources totalResources = Resources::parse("cpus:100;mem:100").get();
sorter.add(slaveId, totalResources);
sorter.add("a");
Resources aResources = Resources::parse("cpus:5;mem:5").get();
sorter.allocated("a", slaveId, aResources);
Resources bResources = Resources::parse("cpus:6;mem:6").get();
sorter.add("b");
sorter.allocated("b", slaveId, bResources);
// shares: a = .05, b = .06
EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());
Resources cResources = Resources::parse("cpus:1;mem:1").get();
sorter.add("c");
sorter.allocated("c", slaveId, cResources);
Resources dResources = Resources::parse("cpus:3;mem:1").get();
sorter.add("d");
sorter.allocated("d", slaveId, dResources);
// shares: a = .05, b = .06, c = .01, d = .03
EXPECT_EQ(list<string>({"c", "d", "a", "b"}), sorter.sort());
sorter.remove("a");
Resources bUnallocated = Resources::parse("cpus:4;mem:4").get();
sorter.unallocated("b", slaveId, bUnallocated);
// shares: b = .02, c = .01, d = .03
EXPECT_EQ(list<string>({"c", "b", "d"}), sorter.sort());
Resources eResources = Resources::parse("cpus:1;mem:5").get();
sorter.add("e");
sorter.allocated("e", slaveId, eResources);
Resources removedResources = Resources::parse("cpus:50;mem:0").get();
sorter.remove(slaveId, removedResources);
// total resources is now cpus = 50, mem = 100
// shares: b = .04, c = .02, d = .06, e = .05
EXPECT_EQ(list<string>({"c", "b", "e", "d"}), sorter.sort());
Resources addedResources = Resources::parse("cpus:0;mem:100").get();
sorter.add(slaveId, addedResources);
// total resources is now cpus = 50, mem = 200
Resources fResources = Resources::parse("cpus:5;mem:1").get();
sorter.add("f");
sorter.allocated("f", slaveId, fResources);
Resources cResources2 = Resources::parse("cpus:0;mem:15").get();
sorter.allocated("c", slaveId, cResources2);
// shares: b = .04, c = .08, d = .06, e = .025, f = .1
EXPECT_EQ(list<string>({"e", "b", "d", "c", "f"}), sorter.sort());
EXPECT_TRUE(sorter.contains("b"));
EXPECT_FALSE(sorter.contains("a"));
EXPECT_EQ(sorter.count(), 5);
sorter.deactivate("d");
EXPECT_TRUE(sorter.contains("d"));
EXPECT_EQ(list<string>({"e", "b", "c", "f"}), sorter.sort());
EXPECT_EQ(sorter.count(), 5);
sorter.activate("d");
EXPECT_EQ(list<string>({"e", "b", "d", "c", "f"}), sorter.sort());
}
TEST(SorterTest, WDRFSorter)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add(slaveId, Resources::parse("cpus:100;mem:100").get());
sorter.add("a");
sorter.allocated("a", slaveId, Resources::parse("cpus:5;mem:5").get());
sorter.add("b", 2);
sorter.allocated("b", slaveId, Resources::parse("cpus:6;mem:6").get());
// shares: a = .05, b = .03
EXPECT_EQ(list<string>({"b", "a"}), sorter.sort());
sorter.add("c");
sorter.allocated("c", slaveId, Resources::parse("cpus:4;mem:4").get());
// shares: a = .05, b = .03, c = .04
EXPECT_EQ(list<string>({"b", "c", "a"}), sorter.sort());
sorter.add("d", 10);
sorter.allocated("d", slaveId, Resources::parse("cpus:10;mem:20").get());
// shares: a = .05, b = .03, c = .04, d = .02
EXPECT_EQ(list<string>({"d", "b", "c", "a"}), sorter.sort());
sorter.remove("b");
EXPECT_EQ(list<string>({"d", "c", "a"}), sorter.sort());
sorter.allocated("d", slaveId, Resources::parse("cpus:10;mem:25").get());
// shares: a = .05, c = .04, d = .045
EXPECT_EQ(list<string>({"c", "d", "a"}), sorter.sort());
sorter.add("e", .1);
sorter.allocated("e", slaveId, Resources::parse("cpus:1;mem:1").get());
// shares: a = .05, c = .04, d = .045, e = .1
EXPECT_EQ(list<string>({"c", "d", "a", "e"}), sorter.sort());
sorter.remove("a");
EXPECT_EQ(list<string>({"c", "d", "e"}), sorter.sort());
}
// Some resources are split across multiple resource objects (e.g.
// persistent volumes). This test ensures that the shares for these
// are accounted correctly.
TEST(SorterTest, SplitResourceShares)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
Resource disk1 = Resources::parse("disk", "5", "*").get();
disk1.mutable_disk()->mutable_persistence()->set_id("ID2");
disk1.mutable_disk()->mutable_volume()->set_container_path("data");
Resource disk2 = Resources::parse("disk", "5", "*").get();
disk2.mutable_disk()->mutable_persistence()->set_id("ID2");
disk2.mutable_disk()->mutable_volume()->set_container_path("data");
sorter.add(
slaveId,
Resources::parse("cpus:100;mem:100;disk:95").get() + disk1 + disk2);
// Now, allocate resources to "a" and "b". Note that "b" will have
// more disk if the shares are accounted correctly!
sorter.allocated(
"a", slaveId, Resources::parse("cpus:9;mem:9;disk:9").get());
sorter.allocated(
"b", slaveId, Resources::parse("cpus:9;mem:9").get() + disk1 + disk2);
EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());
}
TEST(SorterTest, UpdateAllocation)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
sorter.add(slaveId, Resources::parse("cpus:10;mem:10;disk:10").get());
sorter.allocated(
"a", slaveId, Resources::parse("cpus:10;mem:10;disk:10").get());
// Construct an offer operation.
Resource volume = Resources::parse("disk", "5", "*").get();
volume.mutable_disk()->mutable_persistence()->set_id("ID");
volume.mutable_disk()->mutable_volume()->set_container_path("data");
// Compute the updated allocation.
Resources oldAllocation = sorter.allocation("a")[slaveId];
Try<Resources> newAllocation = oldAllocation.apply(CREATE(volume));
ASSERT_SOME(newAllocation);
// Update the resources for the client.
sorter.update("a", slaveId, oldAllocation, newAllocation.get());
hashmap<SlaveID, Resources> allocation = sorter.allocation("a");
EXPECT_EQ(1u, allocation.size());
EXPECT_EQ(newAllocation.get(), allocation[slaveId]);
}
// We aggregate resources from multiple slaves into the sorter.
// Since non-scalar resources don't aggregate well across slaves,
// we need to keep track of the SlaveIDs of the resources. This
// tests that no resources vanish in the process of aggregation
// by inspecting the result of 'allocation'.
TEST(SorterTest, MultipleSlaves)
{
DRFSorter sorter;
SlaveID slaveA;
slaveA.set_value("slaveA");
SlaveID slaveB;
slaveB.set_value("slaveB");
sorter.add("framework");
Resources slaveResources =
Resources::parse("cpus:2;mem:512;ports:[31000-32000]").get();
sorter.add(slaveA, slaveResources);
sorter.add(slaveB, slaveResources);
sorter.allocated("framework", slaveA, slaveResources);
sorter.allocated("framework", slaveB, slaveResources);
hashmap<SlaveID, Resources> allocation = sorter.allocation("framework");
EXPECT_EQ(2u, allocation.size());
EXPECT_EQ(slaveResources, allocation[slaveA]);
EXPECT_EQ(slaveResources, allocation[slaveB]);
}
// We aggregate resources from multiple slaves into the sorter.
// Since non-scalar resources don't aggregate well across slaves,
// we need to keep track of the SlaveIDs of the resources.
// This tests that no resources vanish in the process of aggregation
// by performing a updates from unreserved to reserved resources.
TEST(SorterTest, MultipleSlaveUpdates)
{
DRFSorter sorter;
SlaveID slaveA;
slaveA.set_value("slaveA");
SlaveID slaveB;
slaveB.set_value("slaveB");
sorter.add("framework");
Resources slaveResources =
Resources::parse("cpus:2;mem:512;disk:10;ports:[31000-32000]").get();
sorter.add(slaveA, slaveResources);
sorter.add(slaveB, slaveResources);
sorter.allocated("framework", slaveA, slaveResources);
sorter.allocated("framework", slaveB, slaveResources);
// Construct an offer operation.
Resource volume = Resources::parse("disk", "5", "*").get();
volume.mutable_disk()->mutable_persistence()->set_id("ID");
volume.mutable_disk()->mutable_volume()->set_container_path("data");
// Compute the updated allocation.
Try<Resources> newAllocation = slaveResources.apply(CREATE(volume));
ASSERT_SOME(newAllocation);
// Update the resources for the client.
sorter.update("framework", slaveA, slaveResources, newAllocation.get());
sorter.update("framework", slaveB, slaveResources, newAllocation.get());
hashmap<SlaveID, Resources> allocation = sorter.allocation("framework");
EXPECT_EQ(2u, allocation.size());
EXPECT_EQ(newAllocation.get(), allocation[slaveA]);
EXPECT_EQ(newAllocation.get(), allocation[slaveB]);
}
// This test verifies that when the total pool of resources is updated
// the sorting order of clients reflects the new total.
TEST(SorterTest, UpdateTotal)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
sorter.add(slaveId, Resources::parse("cpus:10;mem:100").get());
// Dominant share of "a" is 0.2 (cpus).
sorter.allocated(
"a", slaveId, Resources::parse("cpus:2;mem:1").get());
// Dominant share of "b" is 0.1 (cpus).
sorter.allocated(
"b", slaveId, Resources::parse("cpus:1;mem:2").get());
list<string> sorted = sorter.sort();
ASSERT_EQ(2u, sorted.size());
EXPECT_EQ("b", sorted.front());
EXPECT_EQ("a", sorted.back());
// Update the total resources.
sorter.update(slaveId, Resources::parse("cpus:100;mem:10").get());
// Now the dominant share of "a" is 0.1 (mem) and "b" is 0.2 (mem),
// which should change the sort order.
sorted = sorter.sort();
ASSERT_EQ(2u, sorted.size());
EXPECT_EQ("a", sorted.front());
EXPECT_EQ("b", sorted.back());
}
// This test verifies that revocable resources are properly accounted
// for in the DRF sorter.
TEST(SorterTest, RevocableResources)
{
DRFSorter sorter;
SlaveID slaveId;
slaveId.set_value("slaveId");
sorter.add("a");
sorter.add("b");
// Create a total resource pool of 10 revocable cpus and 10 cpus and
// 10 MB mem.
Resource revocable = Resources::parse("cpus", "10", "*").get();
revocable.mutable_revocable();
Resources total = Resources::parse("cpus:10;mem:100").get() + revocable;
sorter.add(slaveId, revocable);
// Dominant share of "a" is 0.1 (cpus).
Resources a = Resources::parse("cpus:2;mem:1").get();
sorter.allocated("a", slaveId, a);
// Dominant share of "b" is 0.5 (cpus).
revocable = Resources::parse("cpus", "9", "*").get();
revocable.mutable_revocable();
Resources b = Resources::parse("cpus:1;mem:1").get() + revocable;
sorter.allocated("b", slaveId, b);
// Check that the allocations are correct.
ASSERT_EQ(a, sorter.allocation("a")[slaveId]);
ASSERT_EQ(b, sorter.allocation("b")[slaveId]);
// Check that the sort is correct.
list<string> sorted = sorter.sort();
ASSERT_EQ(2u, sorted.size());
EXPECT_EQ("a", sorted.front());
EXPECT_EQ("b", sorted.back());
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|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/blocked_popup_container.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/notification_service.h"
// static
BlockedPopupContainer* BlockedPopupContainer::Create(
TabContents* owner, Profile* profile) {
BlockedPopupContainer* container =
new BlockedPopupContainer(owner, profile->GetPrefs());
// TODO(port): This ifdef goes away once Mac peeps write a Cocoa
// implementation of BlockedPopupContainerView.
#if defined(OS_WIN) || defined(OS_LINUX)
BlockedPopupContainerView* view =
BlockedPopupContainerView::Create(container);
container->set_view(view);
#endif
return container;
}
// static
void BlockedPopupContainer::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterListPref(prefs::kPopupWhitelistedHosts);
}
void BlockedPopupContainer::AddTabContents(TabContents* tab_contents,
const gfx::Rect& bounds,
const std::string& host) {
// Show whitelisted popups immediately.
bool whitelisted = !!whitelist_.count(host);
if (whitelisted)
owner_->AddNewContents(tab_contents, NEW_POPUP, bounds, true, GURL());
if (has_been_dismissed_) {
// Don't want to show any other UI.
if (!whitelisted)
delete tab_contents; // Discard blocked popups entirely.
return;
}
if (whitelisted) {
// Listen for this popup's destruction, so if the user closes it manually,
// we'll know to stop caring about it.
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab_contents));
unblocked_popups_[tab_contents] = host;
} else {
if (blocked_popups_.size() >= kImpossibleNumberOfPopups) {
delete tab_contents;
LOG(INFO) << "Warning: Renderer is sending more popups to us than should "
"be possible. Renderer compromised?";
return;
}
blocked_popups_.push_back(BlockedPopup(tab_contents, bounds, host));
tab_contents->set_delegate(this);
}
PopupHosts::const_iterator i(popup_hosts_.find(host));
if (i == popup_hosts_.end())
popup_hosts_[host] = whitelisted;
else
DCHECK_EQ(whitelisted, i->second);
UpdateView();
view_->ShowView();
owner_->PopupNotificationVisibilityChanged(true);
}
void BlockedPopupContainer::LaunchPopupAtIndex(size_t index) {
if (index >= blocked_popups_.size())
return;
// Open the popup.
BlockedPopups::iterator i(blocked_popups_.begin() + index);
TabContents* tab_contents = i->tab_contents;
tab_contents->set_delegate(NULL);
owner_->AddNewContents(tab_contents, NEW_POPUP, i->bounds, true, GURL());
const std::string& host = i->host;
if (!host.empty()) {
// Listen for this popup's destruction, so if the user closes it manually,
// we'll know to stop caring about it.
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab_contents));
// Add the popup to the unblocked list. (Do this before the below call!)
unblocked_popups_[tab_contents] = i->host;
}
// Remove the popup from the blocked list.
EraseDataForPopupAndUpdateUI(i);
}
size_t BlockedPopupContainer::GetBlockedPopupCount() const {
return blocked_popups_.size();
}
bool BlockedPopupContainer::IsHostWhitelisted(size_t index) const {
PopupHosts::const_iterator i(ConvertHostIndexToIterator(index));
return (i == popup_hosts_.end()) ? false : i->second;
}
void BlockedPopupContainer::ToggleWhitelistingForHost(size_t index) {
PopupHosts::const_iterator i(ConvertHostIndexToIterator(index));
const std::string& host = i->first;
bool should_whitelist = !i->second;
popup_hosts_[host] = should_whitelist;
ListValue* whitelist_pref =
prefs_->GetMutableList(prefs::kPopupWhitelistedHosts);
if (should_whitelist) {
whitelist_.insert(host);
whitelist_pref->Append(new StringValue(host));
// Open the popups in order.
for (size_t j = 0; j < blocked_popups_.size();) {
if (blocked_popups_[j].host == host)
LaunchPopupAtIndex(j); // This shifts the rest of the entries down.
else
++j;
}
} else {
// Remove from whitelist.
whitelist_.erase(host);
StringValue host_as_string(host);
whitelist_pref->Remove(host_as_string);
for (UnblockedPopups::iterator i(unblocked_popups_.begin());
i != unblocked_popups_.end(); ) {
TabContents* tab_contents = i->first;
TabContentsDelegate* delegate = tab_contents->delegate();
if ((i->second == host) && delegate->IsPopup(tab_contents)) {
// Convert the popup back into a blocked popup.
delegate->DetachContents(tab_contents);
tab_contents->set_delegate(this);
// Add the popup to the blocked list. (Do this before the below call!)
gfx::Rect bounds;
tab_contents->GetContainerBounds(&bounds);
blocked_popups_.push_back(BlockedPopup(tab_contents, bounds, host));
// Remove the popup from the unblocked list.
UnblockedPopups::iterator to_erase = i;
++i;
EraseDataForPopupAndUpdateUI(to_erase);
} else {
++i;
}
}
}
}
void BlockedPopupContainer::CloseAll() {
ClearData();
HideSelf();
}
void BlockedPopupContainer::Destroy() {
view_->Destroy();
ClearData();
GetConstrainingContents(NULL)->WillCloseBlockedPopupContainer(this);
delete this;
}
void BlockedPopupContainer::RepositionBlockedPopupContainer() {
view_->SetPosition();
}
TabContents* BlockedPopupContainer::GetTabContentsAt(size_t index) const {
return blocked_popups_[index].tab_contents;
}
std::vector<std::string> BlockedPopupContainer::GetHosts() const {
std::vector<std::string> hosts;
for (PopupHosts::const_iterator i(popup_hosts_.begin());
i != popup_hosts_.end(); ++i)
hosts.push_back(i->first);
return hosts;
}
// Overridden from TabContentsDelegate:
void BlockedPopupContainer::OpenURLFromTab(TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
owner_->OpenURL(url, referrer, disposition, transition);
}
void BlockedPopupContainer::AddNewContents(TabContents* source,
TabContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_position,
bool user_gesture) {
owner_->AddNewContents(new_contents, disposition, initial_position,
user_gesture, GURL());
}
void BlockedPopupContainer::CloseContents(TabContents* source) {
for (BlockedPopups::iterator it = blocked_popups_.begin();
it != blocked_popups_.end(); ++it) {
TabContents* tab_contents = it->tab_contents;
if (tab_contents == source) {
tab_contents->set_delegate(NULL);
EraseDataForPopupAndUpdateUI(it);
delete tab_contents;
break;
}
}
}
void BlockedPopupContainer::MoveContents(TabContents* source,
const gfx::Rect& new_bounds) {
for (BlockedPopups::iterator it = blocked_popups_.begin();
it != blocked_popups_.end(); ++it) {
if (it->tab_contents == source) {
it->bounds = new_bounds;
break;
}
}
}
bool BlockedPopupContainer::IsPopup(TabContents* source) {
return true;
}
TabContents* BlockedPopupContainer::GetConstrainingContents(
TabContents* source) {
return owner_;
}
ExtensionFunctionDispatcher* BlockedPopupContainer::
CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host,
const std::string& extension_id) {
return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id);
}
void BlockedPopupContainer::HideSelf() {
view_->HideView();
owner_->PopupNotificationVisibilityChanged(false);
}
void BlockedPopupContainer::ClearData() {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
TabContents* tab_contents = i->tab_contents;
tab_contents->set_delegate(NULL);
delete tab_contents;
}
blocked_popups_.clear();
registrar_.RemoveAll();
unblocked_popups_.clear();
popup_hosts_.clear();
}
BlockedPopupContainer::PopupHosts::const_iterator
BlockedPopupContainer::ConvertHostIndexToIterator(size_t index) const {
if (index >= popup_hosts_.size())
return popup_hosts_.end();
// If only there was a std::map::const_iterator::operator +=() ...
PopupHosts::const_iterator i(popup_hosts_.begin());
for (size_t j = 0; j < index; ++j)
++i;
return i;
}
void BlockedPopupContainer::EraseDataForPopupAndUpdateUI(
BlockedPopups::iterator i) {
// Erase the host if this is the last popup for that host.
const std::string& host = i->host;
if (!host.empty()) {
bool should_erase_host = true;
for (BlockedPopups::const_iterator j(blocked_popups_.begin());
j != blocked_popups_.end(); ++j) {
if ((j != i) && (j->host == host)) {
should_erase_host = false;
break;
}
}
if (should_erase_host) {
for (UnblockedPopups::const_iterator j(unblocked_popups_.begin());
j != unblocked_popups_.end(); ++j) {
if (j->second == host) {
should_erase_host = false;
break;
}
}
if (should_erase_host)
popup_hosts_.erase(host);
}
}
// Erase the popup and update the UI.
blocked_popups_.erase(i);
UpdateView();
}
void BlockedPopupContainer::EraseDataForPopupAndUpdateUI(
UnblockedPopups::iterator i) {
// Stop listening for this popup's destruction.
registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(i->first));
// Erase the host if this is the last popup for that host.
const std::string& host = i->second;
if (!host.empty()) {
bool should_erase_host = true;
for (UnblockedPopups::const_iterator j(unblocked_popups_.begin());
j != unblocked_popups_.end(); ++j) {
if ((j != i) && (j->second == host)) {
should_erase_host = false;
break;
}
}
if (should_erase_host) {
for (BlockedPopups::const_iterator j(blocked_popups_.begin());
j != blocked_popups_.end(); ++j) {
if (j->host == host) {
should_erase_host = false;
break;
}
}
if (should_erase_host)
popup_hosts_.erase(host);
}
}
// Erase the popup and update the UI.
unblocked_popups_.erase(i);
UpdateView();
}
// private:
BlockedPopupContainer::BlockedPopupContainer(TabContents* owner,
PrefService* prefs)
: owner_(owner),
prefs_(prefs),
has_been_dismissed_(false) {
// Copy whitelist pref into local member that's easier to use.
const ListValue* whitelist_pref =
prefs_->GetList(prefs::kPopupWhitelistedHosts);
// Careful: The returned value could be NULL if the pref has never been set.
if (whitelist_pref != NULL) {
for (ListValue::const_iterator i(whitelist_pref->begin());
i != whitelist_pref->end(); ++i) {
std::string host;
(*i)->GetAsString(&host);
whitelist_.insert(host);
}
}
}
void BlockedPopupContainer::UpdateView() {
if (blocked_popups_.empty() && unblocked_popups_.empty())
HideSelf();
else
view_->UpdateLabel();
}
void BlockedPopupContainer::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
TabContents* tab_contents = Source<TabContents>(source).ptr();
UnblockedPopups::iterator i(unblocked_popups_.find(tab_contents));
DCHECK(i != unblocked_popups_.end());
EraseDataForPopupAndUpdateUI(i);
}
<commit_msg>Coverity: Initialize member view_ to NULL in constructor.<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/blocked_popup_container.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/notification_service.h"
// static
BlockedPopupContainer* BlockedPopupContainer::Create(
TabContents* owner, Profile* profile) {
BlockedPopupContainer* container =
new BlockedPopupContainer(owner, profile->GetPrefs());
// TODO(port): This ifdef goes away once Mac peeps write a Cocoa
// implementation of BlockedPopupContainerView.
#if defined(OS_WIN) || defined(OS_LINUX)
BlockedPopupContainerView* view =
BlockedPopupContainerView::Create(container);
container->set_view(view);
#endif
return container;
}
// static
void BlockedPopupContainer::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterListPref(prefs::kPopupWhitelistedHosts);
}
void BlockedPopupContainer::AddTabContents(TabContents* tab_contents,
const gfx::Rect& bounds,
const std::string& host) {
// Show whitelisted popups immediately.
bool whitelisted = !!whitelist_.count(host);
if (whitelisted)
owner_->AddNewContents(tab_contents, NEW_POPUP, bounds, true, GURL());
if (has_been_dismissed_) {
// Don't want to show any other UI.
if (!whitelisted)
delete tab_contents; // Discard blocked popups entirely.
return;
}
if (whitelisted) {
// Listen for this popup's destruction, so if the user closes it manually,
// we'll know to stop caring about it.
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab_contents));
unblocked_popups_[tab_contents] = host;
} else {
if (blocked_popups_.size() >= kImpossibleNumberOfPopups) {
delete tab_contents;
LOG(INFO) << "Warning: Renderer is sending more popups to us than should "
"be possible. Renderer compromised?";
return;
}
blocked_popups_.push_back(BlockedPopup(tab_contents, bounds, host));
tab_contents->set_delegate(this);
}
PopupHosts::const_iterator i(popup_hosts_.find(host));
if (i == popup_hosts_.end())
popup_hosts_[host] = whitelisted;
else
DCHECK_EQ(whitelisted, i->second);
UpdateView();
view_->ShowView();
owner_->PopupNotificationVisibilityChanged(true);
}
void BlockedPopupContainer::LaunchPopupAtIndex(size_t index) {
if (index >= blocked_popups_.size())
return;
// Open the popup.
BlockedPopups::iterator i(blocked_popups_.begin() + index);
TabContents* tab_contents = i->tab_contents;
tab_contents->set_delegate(NULL);
owner_->AddNewContents(tab_contents, NEW_POPUP, i->bounds, true, GURL());
const std::string& host = i->host;
if (!host.empty()) {
// Listen for this popup's destruction, so if the user closes it manually,
// we'll know to stop caring about it.
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab_contents));
// Add the popup to the unblocked list. (Do this before the below call!)
unblocked_popups_[tab_contents] = i->host;
}
// Remove the popup from the blocked list.
EraseDataForPopupAndUpdateUI(i);
}
size_t BlockedPopupContainer::GetBlockedPopupCount() const {
return blocked_popups_.size();
}
bool BlockedPopupContainer::IsHostWhitelisted(size_t index) const {
PopupHosts::const_iterator i(ConvertHostIndexToIterator(index));
return (i == popup_hosts_.end()) ? false : i->second;
}
void BlockedPopupContainer::ToggleWhitelistingForHost(size_t index) {
PopupHosts::const_iterator i(ConvertHostIndexToIterator(index));
const std::string& host = i->first;
bool should_whitelist = !i->second;
popup_hosts_[host] = should_whitelist;
ListValue* whitelist_pref =
prefs_->GetMutableList(prefs::kPopupWhitelistedHosts);
if (should_whitelist) {
whitelist_.insert(host);
whitelist_pref->Append(new StringValue(host));
// Open the popups in order.
for (size_t j = 0; j < blocked_popups_.size();) {
if (blocked_popups_[j].host == host)
LaunchPopupAtIndex(j); // This shifts the rest of the entries down.
else
++j;
}
} else {
// Remove from whitelist.
whitelist_.erase(host);
StringValue host_as_string(host);
whitelist_pref->Remove(host_as_string);
for (UnblockedPopups::iterator i(unblocked_popups_.begin());
i != unblocked_popups_.end(); ) {
TabContents* tab_contents = i->first;
TabContentsDelegate* delegate = tab_contents->delegate();
if ((i->second == host) && delegate->IsPopup(tab_contents)) {
// Convert the popup back into a blocked popup.
delegate->DetachContents(tab_contents);
tab_contents->set_delegate(this);
// Add the popup to the blocked list. (Do this before the below call!)
gfx::Rect bounds;
tab_contents->GetContainerBounds(&bounds);
blocked_popups_.push_back(BlockedPopup(tab_contents, bounds, host));
// Remove the popup from the unblocked list.
UnblockedPopups::iterator to_erase = i;
++i;
EraseDataForPopupAndUpdateUI(to_erase);
} else {
++i;
}
}
}
}
void BlockedPopupContainer::CloseAll() {
ClearData();
HideSelf();
}
void BlockedPopupContainer::Destroy() {
view_->Destroy();
ClearData();
GetConstrainingContents(NULL)->WillCloseBlockedPopupContainer(this);
delete this;
}
void BlockedPopupContainer::RepositionBlockedPopupContainer() {
view_->SetPosition();
}
TabContents* BlockedPopupContainer::GetTabContentsAt(size_t index) const {
return blocked_popups_[index].tab_contents;
}
std::vector<std::string> BlockedPopupContainer::GetHosts() const {
std::vector<std::string> hosts;
for (PopupHosts::const_iterator i(popup_hosts_.begin());
i != popup_hosts_.end(); ++i)
hosts.push_back(i->first);
return hosts;
}
// Overridden from TabContentsDelegate:
void BlockedPopupContainer::OpenURLFromTab(TabContents* source,
const GURL& url,
const GURL& referrer,
WindowOpenDisposition disposition,
PageTransition::Type transition) {
owner_->OpenURL(url, referrer, disposition, transition);
}
void BlockedPopupContainer::AddNewContents(TabContents* source,
TabContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_position,
bool user_gesture) {
owner_->AddNewContents(new_contents, disposition, initial_position,
user_gesture, GURL());
}
void BlockedPopupContainer::CloseContents(TabContents* source) {
for (BlockedPopups::iterator it = blocked_popups_.begin();
it != blocked_popups_.end(); ++it) {
TabContents* tab_contents = it->tab_contents;
if (tab_contents == source) {
tab_contents->set_delegate(NULL);
EraseDataForPopupAndUpdateUI(it);
delete tab_contents;
break;
}
}
}
void BlockedPopupContainer::MoveContents(TabContents* source,
const gfx::Rect& new_bounds) {
for (BlockedPopups::iterator it = blocked_popups_.begin();
it != blocked_popups_.end(); ++it) {
if (it->tab_contents == source) {
it->bounds = new_bounds;
break;
}
}
}
bool BlockedPopupContainer::IsPopup(TabContents* source) {
return true;
}
TabContents* BlockedPopupContainer::GetConstrainingContents(
TabContents* source) {
return owner_;
}
ExtensionFunctionDispatcher* BlockedPopupContainer::
CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host,
const std::string& extension_id) {
return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id);
}
void BlockedPopupContainer::HideSelf() {
view_->HideView();
owner_->PopupNotificationVisibilityChanged(false);
}
void BlockedPopupContainer::ClearData() {
for (BlockedPopups::iterator i(blocked_popups_.begin());
i != blocked_popups_.end(); ++i) {
TabContents* tab_contents = i->tab_contents;
tab_contents->set_delegate(NULL);
delete tab_contents;
}
blocked_popups_.clear();
registrar_.RemoveAll();
unblocked_popups_.clear();
popup_hosts_.clear();
}
BlockedPopupContainer::PopupHosts::const_iterator
BlockedPopupContainer::ConvertHostIndexToIterator(size_t index) const {
if (index >= popup_hosts_.size())
return popup_hosts_.end();
// If only there was a std::map::const_iterator::operator +=() ...
PopupHosts::const_iterator i(popup_hosts_.begin());
for (size_t j = 0; j < index; ++j)
++i;
return i;
}
void BlockedPopupContainer::EraseDataForPopupAndUpdateUI(
BlockedPopups::iterator i) {
// Erase the host if this is the last popup for that host.
const std::string& host = i->host;
if (!host.empty()) {
bool should_erase_host = true;
for (BlockedPopups::const_iterator j(blocked_popups_.begin());
j != blocked_popups_.end(); ++j) {
if ((j != i) && (j->host == host)) {
should_erase_host = false;
break;
}
}
if (should_erase_host) {
for (UnblockedPopups::const_iterator j(unblocked_popups_.begin());
j != unblocked_popups_.end(); ++j) {
if (j->second == host) {
should_erase_host = false;
break;
}
}
if (should_erase_host)
popup_hosts_.erase(host);
}
}
// Erase the popup and update the UI.
blocked_popups_.erase(i);
UpdateView();
}
void BlockedPopupContainer::EraseDataForPopupAndUpdateUI(
UnblockedPopups::iterator i) {
// Stop listening for this popup's destruction.
registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(i->first));
// Erase the host if this is the last popup for that host.
const std::string& host = i->second;
if (!host.empty()) {
bool should_erase_host = true;
for (UnblockedPopups::const_iterator j(unblocked_popups_.begin());
j != unblocked_popups_.end(); ++j) {
if ((j != i) && (j->second == host)) {
should_erase_host = false;
break;
}
}
if (should_erase_host) {
for (BlockedPopups::const_iterator j(blocked_popups_.begin());
j != blocked_popups_.end(); ++j) {
if (j->host == host) {
should_erase_host = false;
break;
}
}
if (should_erase_host)
popup_hosts_.erase(host);
}
}
// Erase the popup and update the UI.
unblocked_popups_.erase(i);
UpdateView();
}
// private:
BlockedPopupContainer::BlockedPopupContainer(TabContents* owner,
PrefService* prefs)
: owner_(owner),
prefs_(prefs),
has_been_dismissed_(false),
view_(NULL) {
// Copy whitelist pref into local member that's easier to use.
const ListValue* whitelist_pref =
prefs_->GetList(prefs::kPopupWhitelistedHosts);
// Careful: The returned value could be NULL if the pref has never been set.
if (whitelist_pref != NULL) {
for (ListValue::const_iterator i(whitelist_pref->begin());
i != whitelist_pref->end(); ++i) {
std::string host;
(*i)->GetAsString(&host);
whitelist_.insert(host);
}
}
}
void BlockedPopupContainer::UpdateView() {
if (blocked_popups_.empty() && unblocked_popups_.empty())
HideSelf();
else
view_->UpdateLabel();
}
void BlockedPopupContainer::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
TabContents* tab_contents = Source<TabContents>(source).ptr();
UnblockedPopups::iterator i(unblocked_popups_.find(tab_contents));
DCHECK(i != unblocked_popups_.end());
EraseDataForPopupAndUpdateUI(i);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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 <string>
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/download/save_package.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/ui_test_utils.h"
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests");
class BrowserEncodingTest : public UITest {
protected:
BrowserEncodingTest() : UITest() {}
// Make sure the content of the page are as expected
// after override or auto-detect
void CheckFile(const FilePath& generated_file,
const FilePath& expected_result_file,
bool check_equal) {
FilePath expected_result_filepath = ui_test_utils::GetTestFilePath(
FilePath(kTestDir), expected_result_file);
ASSERT_TRUE(file_util::PathExists(expected_result_filepath));
WaitForGeneratedFileAndCheck(generated_file,
expected_result_filepath,
true, // We do care whether they are equal.
check_equal,
true); // Delete the generated file when done.
}
virtual void SetUp() {
UITest::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
save_dir_ = temp_dir_.path();
temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files");
}
ScopedTempDir temp_dir_;
FilePath save_dir_;
FilePath temp_sub_resource_dir_;
};
// TODO(jnd): 1. Some encodings are missing here. It'll be added later. See
// http://crbug.com/13306.
// 2. Add more files with multiple encoding name variants for each canonical
// encoding name). Webkit layout tests cover some, but testing in the UI test is
// also necessary.
TEST_F(BrowserEncodingTest, TestEncodingAliasMapping) {
struct EncodingTestData {
const char* file_name;
const char* encoding_name;
};
const EncodingTestData kEncodingTestDatas[] = {
{ "Big5.html", "Big5" },
{ "EUC-JP.html", "EUC-JP" },
{ "gb18030.html", "gb18030" },
{ "iso-8859-1.html", "ISO-8859-1" },
{ "ISO-8859-2.html", "ISO-8859-2" },
{ "ISO-8859-4.html", "ISO-8859-4" },
{ "ISO-8859-5.html", "ISO-8859-5" },
{ "ISO-8859-6.html", "ISO-8859-6" },
{ "ISO-8859-7.html", "ISO-8859-7" },
{ "ISO-8859-8.html", "ISO-8859-8" },
{ "ISO-8859-13.html", "ISO-8859-13" },
{ "ISO-8859-15.html", "ISO-8859-15" },
{ "KOI8-R.html", "KOI8-R" },
{ "KOI8-U.html", "KOI8-U" },
{ "macintosh.html", "macintosh" },
{ "Shift-JIS.html", "Shift_JIS" },
{ "US-ASCII.html", "ISO-8859-1" }, // http://crbug.com/15801
{ "UTF-8.html", "UTF-8" },
{ "UTF-16LE.html", "UTF-16LE" },
{ "windows-874.html", "windows-874" },
{ "windows-949.html", "windows-949" },
{ "windows-1250.html", "windows-1250" },
{ "windows-1251.html", "windows-1251" },
{ "windows-1252.html", "windows-1252" },
{ "windows-1253.html", "windows-1253" },
{ "windows-1254.html", "windows-1254" },
{ "windows-1255.html", "windows-1255" },
{ "windows-1256.html", "windows-1256" },
{ "windows-1257.html", "windows-1257" },
{ "windows-1258.html", "windows-1258" }
};
const char* const kAliasTestDir = "alias_mapping";
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir);
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(
kEncodingTestDatas[i].file_name);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(test_file_path));
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kEncodingTestDatas[i].encoding_name);
}
}
TEST_F(BrowserEncodingTest, TestOverrideEncoding) {
const char* const kTestFileName = "gb18030_with_iso88591_meta.html";
const char* const kExpectedFileName =
"expected_gb18030_saved_from_iso88591_meta.html";
const char* const kOverrideTestDir = "user_override";
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir);
test_dir_path = test_dir_path.AppendASCII(kTestFileName);
GURL url = URLRequestMockHTTPJob::GetMockUrl(test_dir_path);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->NavigateToURL(url));
WaitUntilTabCount(1);
// Get the encoding declared in the page.
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-1");
// Override the encoding to "gb18030".
int64 last_nav_time = 0;
EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
EXPECT_TRUE(tab_proxy->OverrideEncoding("gb18030"));
EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));
// Re-get the encoding of page. It should be gb18030.
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "gb18030");
// Dump the page, the content of dump page should be identical to the
// expected result file.
FilePath full_file_name = save_dir_.AppendASCII(kTestFileName);
// We save the page as way of complete HTML file, which requires a directory
// name to save sub resources in it. Although this test file does not have
// sub resources, but the directory name is still required.
EXPECT_TRUE(tab_proxy->SavePage(full_file_name, temp_sub_resource_dir_,
SavePackage::SAVE_AS_COMPLETE_HTML));
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
FilePath expected_file_name = FilePath().AppendASCII(kOverrideTestDir);
expected_file_name = expected_file_name.AppendASCII(kExpectedFileName);
CheckFile(full_file_name, expected_file_name, true);
}
// The following encodings are excluded from the auto-detection test because
// it's a known issue that the current encoding detector does not detect them:
// ISO-8859-4
// ISO-8859-13
// KOI8-U
// macintosh
// windows-874
// windows-1252
// windows-1253
// windows-1257
// windows-1258
// For Hebrew, the expected encoding value is ISO-8859-8-I. See
// http://crbug.com/2927 for more details.
// FLAKY: see http://crbug.com/44666
TEST_F(BrowserEncodingTest, FLAKY_TestEncodingAutoDetect) {
struct EncodingAutoDetectTestData {
const char* test_file_name; // File name of test data.
const char* expected_result; // File name of expected results.
const char* expected_encoding; // expected encoding.
};
const EncodingAutoDetectTestData kTestDatas[] = {
{ "Big5_with_no_encoding_specified.html",
"expected_Big5_saved_from_no_encoding_specified.html",
"Big5" },
{ "gb18030_with_no_encoding_specified.html",
"expected_gb18030_saved_from_no_encoding_specified.html",
"gb18030" },
{ "iso-8859-1_with_no_encoding_specified.html",
"expected_iso-8859-1_saved_from_no_encoding_specified.html",
"ISO-8859-1" },
{ "ISO-8859-5_with_no_encoding_specified.html",
"expected_ISO-8859-5_saved_from_no_encoding_specified.html",
"ISO-8859-5" },
{ "ISO-8859-6_with_no_encoding_specified.html",
"expected_ISO-8859-6_saved_from_no_encoding_specified.html",
"ISO-8859-6" },
{ "ISO-8859-7_with_no_encoding_specified.html",
"expected_ISO-8859-7_saved_from_no_encoding_specified.html",
"ISO-8859-7" },
{ "ISO-8859-8_with_no_encoding_specified.html",
"expected_ISO-8859-8_saved_from_no_encoding_specified.html",
"ISO-8859-8-I" },
{ "KOI8-R_with_no_encoding_specified.html",
"expected_KOI8-R_saved_from_no_encoding_specified.html",
"KOI8-R" },
{ "Shift-JIS_with_no_encoding_specified.html",
"expected_Shift-JIS_saved_from_no_encoding_specified.html",
"Shift_JIS" },
{ "UTF-8_with_no_encoding_specified.html",
"expected_UTF-8_saved_from_no_encoding_specified.html",
"UTF-8" },
{ "windows-949_with_no_encoding_specified.html",
"expected_windows-949_saved_from_no_encoding_specified.html",
"windows-949" },
{ "windows-1251_with_no_encoding_specified.html",
"expected_windows-1251_saved_from_no_encoding_specified.html",
"windows-1251" },
{ "windows-1254_with_no_encoding_specified.html",
"expected_windows-1254_saved_from_no_encoding_specified.html",
"windows-1254" },
{ "windows-1255_with_no_encoding_specified.html",
"expected_windows-1255_saved_from_no_encoding_specified.html",
"windows-1255" },
{ "windows-1256_with_no_encoding_specified.html",
"expected_windows-1256_saved_from_no_encoding_specified.html",
"windows-1256" }
};
const char* const kAutoDetectDir = "auto_detect";
// Directory of the files of expected results.
const char* const kExpectedResultDir = "expected_results";
// Full path of saved file. full_file_name = save_dir_ + file_name[i];
FilePath full_saved_file_name;
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir);
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Set the default charset to one of encodings not supported by the current
// auto-detector (Please refer to the above comments) to make sure we
// incorrectly decode the page. Now we use ISO-8859-4.
ASSERT_TRUE(browser->SetStringPreference(prefs::kDefaultCharset,
L"ISO-8859-4"));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas);i++) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name);
GURL url =
URLRequestMockHTTPJob::GetMockUrl(test_file_path);
ASSERT_TRUE(tab->NavigateToURL(url));
// Disable auto detect if it is on.
EXPECT_TRUE(
browser->SetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
false));
EXPECT_TRUE(tab->Reload());
// Get the encoding used for the page, it must be the default charset we
// just set.
std::string encoding;
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-4");
// Enable the encoding auto detection.
EXPECT_TRUE(browser->SetBooleanPreference(
prefs::kWebKitUsesUniversalDetector, true));
EXPECT_TRUE(tab->Reload());
// Re-get the encoding of page. It should return the real encoding now.
bool encoding_auto_detect = false;
EXPECT_TRUE(
browser->GetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
&encoding_auto_detect));
EXPECT_TRUE(encoding_auto_detect);
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kTestDatas[i].expected_encoding);
// Dump the page, the content of dump page should be equal with our expect
// result file.
full_saved_file_name = save_dir_.AppendASCII(kTestDatas[i].test_file_name);
// Full path of expect result file.
FilePath expected_result_file_name = FilePath().AppendASCII(kAutoDetectDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kExpectedResultDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kTestDatas[i].expected_result);
EXPECT_TRUE(tab->SavePage(full_saved_file_name, temp_sub_resource_dir_,
SavePackage::SAVE_AS_COMPLETE_HTML));
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
CheckFile(full_saved_file_name, expected_result_file_name, true);
}
}
<commit_msg>Marking BrowserEncodingTest.TestOverrideEncoding as FLAKY.<commit_after>// Copyright (c) 2006-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 <string>
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/download/save_package.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/ui_test_utils.h"
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests");
class BrowserEncodingTest : public UITest {
protected:
BrowserEncodingTest() : UITest() {}
// Make sure the content of the page are as expected
// after override or auto-detect
void CheckFile(const FilePath& generated_file,
const FilePath& expected_result_file,
bool check_equal) {
FilePath expected_result_filepath = ui_test_utils::GetTestFilePath(
FilePath(kTestDir), expected_result_file);
ASSERT_TRUE(file_util::PathExists(expected_result_filepath));
WaitForGeneratedFileAndCheck(generated_file,
expected_result_filepath,
true, // We do care whether they are equal.
check_equal,
true); // Delete the generated file when done.
}
virtual void SetUp() {
UITest::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
save_dir_ = temp_dir_.path();
temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files");
}
ScopedTempDir temp_dir_;
FilePath save_dir_;
FilePath temp_sub_resource_dir_;
};
// TODO(jnd): 1. Some encodings are missing here. It'll be added later. See
// http://crbug.com/13306.
// 2. Add more files with multiple encoding name variants for each canonical
// encoding name). Webkit layout tests cover some, but testing in the UI test is
// also necessary.
TEST_F(BrowserEncodingTest, TestEncodingAliasMapping) {
struct EncodingTestData {
const char* file_name;
const char* encoding_name;
};
const EncodingTestData kEncodingTestDatas[] = {
{ "Big5.html", "Big5" },
{ "EUC-JP.html", "EUC-JP" },
{ "gb18030.html", "gb18030" },
{ "iso-8859-1.html", "ISO-8859-1" },
{ "ISO-8859-2.html", "ISO-8859-2" },
{ "ISO-8859-4.html", "ISO-8859-4" },
{ "ISO-8859-5.html", "ISO-8859-5" },
{ "ISO-8859-6.html", "ISO-8859-6" },
{ "ISO-8859-7.html", "ISO-8859-7" },
{ "ISO-8859-8.html", "ISO-8859-8" },
{ "ISO-8859-13.html", "ISO-8859-13" },
{ "ISO-8859-15.html", "ISO-8859-15" },
{ "KOI8-R.html", "KOI8-R" },
{ "KOI8-U.html", "KOI8-U" },
{ "macintosh.html", "macintosh" },
{ "Shift-JIS.html", "Shift_JIS" },
{ "US-ASCII.html", "ISO-8859-1" }, // http://crbug.com/15801
{ "UTF-8.html", "UTF-8" },
{ "UTF-16LE.html", "UTF-16LE" },
{ "windows-874.html", "windows-874" },
{ "windows-949.html", "windows-949" },
{ "windows-1250.html", "windows-1250" },
{ "windows-1251.html", "windows-1251" },
{ "windows-1252.html", "windows-1252" },
{ "windows-1253.html", "windows-1253" },
{ "windows-1254.html", "windows-1254" },
{ "windows-1255.html", "windows-1255" },
{ "windows-1256.html", "windows-1256" },
{ "windows-1257.html", "windows-1257" },
{ "windows-1258.html", "windows-1258" }
};
const char* const kAliasTestDir = "alias_mapping";
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir);
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(
kEncodingTestDatas[i].file_name);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(test_file_path));
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kEncodingTestDatas[i].encoding_name);
}
}
// Marked as flaky: see http://crbug.com/44668
TEST_F(BrowserEncodingTest, FLAKY_TestOverrideEncoding) {
const char* const kTestFileName = "gb18030_with_iso88591_meta.html";
const char* const kExpectedFileName =
"expected_gb18030_saved_from_iso88591_meta.html";
const char* const kOverrideTestDir = "user_override";
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir);
test_dir_path = test_dir_path.AppendASCII(kTestFileName);
GURL url = URLRequestMockHTTPJob::GetMockUrl(test_dir_path);
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->NavigateToURL(url));
WaitUntilTabCount(1);
// Get the encoding declared in the page.
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-1");
// Override the encoding to "gb18030".
int64 last_nav_time = 0;
EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
EXPECT_TRUE(tab_proxy->OverrideEncoding("gb18030"));
EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));
// Re-get the encoding of page. It should be gb18030.
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "gb18030");
// Dump the page, the content of dump page should be identical to the
// expected result file.
FilePath full_file_name = save_dir_.AppendASCII(kTestFileName);
// We save the page as way of complete HTML file, which requires a directory
// name to save sub resources in it. Although this test file does not have
// sub resources, but the directory name is still required.
EXPECT_TRUE(tab_proxy->SavePage(full_file_name, temp_sub_resource_dir_,
SavePackage::SAVE_AS_COMPLETE_HTML));
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
FilePath expected_file_name = FilePath().AppendASCII(kOverrideTestDir);
expected_file_name = expected_file_name.AppendASCII(kExpectedFileName);
CheckFile(full_file_name, expected_file_name, true);
}
// The following encodings are excluded from the auto-detection test because
// it's a known issue that the current encoding detector does not detect them:
// ISO-8859-4
// ISO-8859-13
// KOI8-U
// macintosh
// windows-874
// windows-1252
// windows-1253
// windows-1257
// windows-1258
// For Hebrew, the expected encoding value is ISO-8859-8-I. See
// http://crbug.com/2927 for more details.
// FLAKY: see http://crbug.com/44666
TEST_F(BrowserEncodingTest, FLAKY_TestEncodingAutoDetect) {
struct EncodingAutoDetectTestData {
const char* test_file_name; // File name of test data.
const char* expected_result; // File name of expected results.
const char* expected_encoding; // expected encoding.
};
const EncodingAutoDetectTestData kTestDatas[] = {
{ "Big5_with_no_encoding_specified.html",
"expected_Big5_saved_from_no_encoding_specified.html",
"Big5" },
{ "gb18030_with_no_encoding_specified.html",
"expected_gb18030_saved_from_no_encoding_specified.html",
"gb18030" },
{ "iso-8859-1_with_no_encoding_specified.html",
"expected_iso-8859-1_saved_from_no_encoding_specified.html",
"ISO-8859-1" },
{ "ISO-8859-5_with_no_encoding_specified.html",
"expected_ISO-8859-5_saved_from_no_encoding_specified.html",
"ISO-8859-5" },
{ "ISO-8859-6_with_no_encoding_specified.html",
"expected_ISO-8859-6_saved_from_no_encoding_specified.html",
"ISO-8859-6" },
{ "ISO-8859-7_with_no_encoding_specified.html",
"expected_ISO-8859-7_saved_from_no_encoding_specified.html",
"ISO-8859-7" },
{ "ISO-8859-8_with_no_encoding_specified.html",
"expected_ISO-8859-8_saved_from_no_encoding_specified.html",
"ISO-8859-8-I" },
{ "KOI8-R_with_no_encoding_specified.html",
"expected_KOI8-R_saved_from_no_encoding_specified.html",
"KOI8-R" },
{ "Shift-JIS_with_no_encoding_specified.html",
"expected_Shift-JIS_saved_from_no_encoding_specified.html",
"Shift_JIS" },
{ "UTF-8_with_no_encoding_specified.html",
"expected_UTF-8_saved_from_no_encoding_specified.html",
"UTF-8" },
{ "windows-949_with_no_encoding_specified.html",
"expected_windows-949_saved_from_no_encoding_specified.html",
"windows-949" },
{ "windows-1251_with_no_encoding_specified.html",
"expected_windows-1251_saved_from_no_encoding_specified.html",
"windows-1251" },
{ "windows-1254_with_no_encoding_specified.html",
"expected_windows-1254_saved_from_no_encoding_specified.html",
"windows-1254" },
{ "windows-1255_with_no_encoding_specified.html",
"expected_windows-1255_saved_from_no_encoding_specified.html",
"windows-1255" },
{ "windows-1256_with_no_encoding_specified.html",
"expected_windows-1256_saved_from_no_encoding_specified.html",
"windows-1256" }
};
const char* const kAutoDetectDir = "auto_detect";
// Directory of the files of expected results.
const char* const kExpectedResultDir = "expected_results";
// Full path of saved file. full_file_name = save_dir_ + file_name[i];
FilePath full_saved_file_name;
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir);
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Set the default charset to one of encodings not supported by the current
// auto-detector (Please refer to the above comments) to make sure we
// incorrectly decode the page. Now we use ISO-8859-4.
ASSERT_TRUE(browser->SetStringPreference(prefs::kDefaultCharset,
L"ISO-8859-4"));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas);i++) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name);
GURL url =
URLRequestMockHTTPJob::GetMockUrl(test_file_path);
ASSERT_TRUE(tab->NavigateToURL(url));
// Disable auto detect if it is on.
EXPECT_TRUE(
browser->SetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
false));
EXPECT_TRUE(tab->Reload());
// Get the encoding used for the page, it must be the default charset we
// just set.
std::string encoding;
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-4");
// Enable the encoding auto detection.
EXPECT_TRUE(browser->SetBooleanPreference(
prefs::kWebKitUsesUniversalDetector, true));
EXPECT_TRUE(tab->Reload());
// Re-get the encoding of page. It should return the real encoding now.
bool encoding_auto_detect = false;
EXPECT_TRUE(
browser->GetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
&encoding_auto_detect));
EXPECT_TRUE(encoding_auto_detect);
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kTestDatas[i].expected_encoding);
// Dump the page, the content of dump page should be equal with our expect
// result file.
full_saved_file_name = save_dir_.AppendASCII(kTestDatas[i].test_file_name);
// Full path of expect result file.
FilePath expected_result_file_name = FilePath().AppendASCII(kAutoDetectDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kExpectedResultDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kTestDatas[i].expected_result);
EXPECT_TRUE(tab->SavePage(full_saved_file_name, temp_sub_resource_dir_,
SavePackage::SAVE_AS_COMPLETE_HTML));
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
CheckFile(full_saved_file_name, expected_result_file_name, true);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* TIGHTDB CONFIDENTIAL
* __________________
*
* [2011] - [2012] TightDB Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of TightDB Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to TightDB Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from TightDB Incorporated.
*
**************************************************************************/
#ifndef TIGHTDB_EXCEPTIONS_HPP
#define TIGHTDB_EXCEPTIONS_HPP
#include <stdexcept>
#include <tightdb/util/features.h>
namespace tightdb {
class Exception: public std::exception {
public:
/// message() returns the error description without version info.
virtual const char* message() const TIGHTDB_NOEXCEPT_OR_NOTHROW = 0;
/// version() returns the version of the TightDB library that threw this exception.
const char* version() const TIGHTDB_NOEXCEPT_OR_NOTHROW;
};
class RuntimeError: public std::runtime_error {
public:
/// RuntimeError prepends the contents of TIGHTDB_VER_CHUNK to the message,
/// so that what() will contain information about the library version.
/// Call message()
RuntimeError(const std::string& message);
RuntimeError(const RuntimeError& other);
/// message() returns the error description without embedded release info.
/// Default implementation has the precondition that what() returns a string
/// that is prepended with the current release version.
/// FIXME: Declare what() final (C++11) to secure the precondition.
virtual const char* message() const TIGHTDB_NOEXCEPT_OR_NOTHROW;
/// version() returns the version of the TightDB library that threw this exception.
const char* version() const TIGHTDB_NOEXCEPT_OR_NOTHROW;
};
class ExceptionWithVersionInWhat: public Exception {
public:
/// CAUTION: Deriving from this class means you guarantee that the string
/// returned from what() contains TIGHTDB_VER_CHUNK + one space at the beginning.
const char* message() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Thrown by various functions to indicate that a specified table does not
/// exist.
class NoSuchTable: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Thrown by various functions to indicate that a specified table name is
/// already in use.
class TableNameInUse: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
// Thrown by functions that require a table to **not** be the target of link
// columns, unless those link columns are part of the table itself.
class CrossTableLinkTarget: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Thrown by various functions to indicate that the dynamic type of a table
/// does not match a particular other table type (dynamic or static).
class DescriptorMismatch: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Reports errors that are a consequence of faulty logic within the program,
/// such as violating logical preconditions or class invariants, and can be
/// easily predicted.
class LogicError: public ExceptionWithVersionInWhat {
public:
enum error_kind {
string_too_big,
binary_too_big,
table_name_too_long,
column_name_too_long,
table_index_out_of_range,
row_index_out_of_range,
column_index_out_of_range,
/// Indicates that an argument has a value that is illegal in combination
/// with another argument, or with the state of an involved object.
illegal_combination,
/// Indicates a data type mismatch, such as when `Table::find_pkey_int()` is
/// called and the type of the primary key is not `type_Int`.
type_mismatch,
/// Indicates that an involved table is of the wrong kind, i.e., if it is a
/// subtable, and the function requires a root table.
wrong_kind_of_table,
/// Indicates that an involved accessor is was detached, i.e., was not
/// attached to an underlying object.
detached_accessor,
// Indicates that an involved column lacks a search index.
no_search_index,
// Indicates that an involved table lacks a primary key.
no_primary_key,
// Indicates that an attempt was made to add a primary key to a table that
// already had a primary key.
has_primary_key,
/// Indicates that a modification was attempted that would have produced a
/// duplicate primary value.
unique_constraint_violation
};
LogicError(error_kind message);
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
static const char* get_message_for_error(error_kind) TIGHTDB_NOEXCEPT_OR_NOTHROW;
private:
const char* m_message;
};
// Implementation:
inline LogicError::LogicError(LogicError::error_kind kind):
m_message(get_message_for_error(kind))
{
}
inline const char* LogicError::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW
{
return m_message;
}
} // namespace tightdb
#endif // TIGHTDB_EXCEPTIONS_HPP
<commit_msg>removed stray comment<commit_after>/*************************************************************************
*
* TIGHTDB CONFIDENTIAL
* __________________
*
* [2011] - [2012] TightDB Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of TightDB Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to TightDB Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from TightDB Incorporated.
*
**************************************************************************/
#ifndef TIGHTDB_EXCEPTIONS_HPP
#define TIGHTDB_EXCEPTIONS_HPP
#include <stdexcept>
#include <tightdb/util/features.h>
namespace tightdb {
class Exception: public std::exception {
public:
/// message() returns the error description without version info.
virtual const char* message() const TIGHTDB_NOEXCEPT_OR_NOTHROW = 0;
/// version() returns the version of the TightDB library that threw this exception.
const char* version() const TIGHTDB_NOEXCEPT_OR_NOTHROW;
};
class RuntimeError: public std::runtime_error {
public:
/// RuntimeError prepends the contents of TIGHTDB_VER_CHUNK to the message,
/// so that what() will contain information about the library version.
RuntimeError(const std::string& message);
RuntimeError(const RuntimeError& other);
/// message() returns the error description without embedded release info.
/// Default implementation has the precondition that what() returns a string
/// that is prepended with the current release version.
/// FIXME: Declare what() final (C++11) to secure the precondition.
virtual const char* message() const TIGHTDB_NOEXCEPT_OR_NOTHROW;
/// version() returns the version of the TightDB library that threw this exception.
const char* version() const TIGHTDB_NOEXCEPT_OR_NOTHROW;
};
class ExceptionWithVersionInWhat: public Exception {
public:
/// CAUTION: Deriving from this class means you guarantee that the string
/// returned from what() contains TIGHTDB_VER_CHUNK + one space at the beginning.
const char* message() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Thrown by various functions to indicate that a specified table does not
/// exist.
class NoSuchTable: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Thrown by various functions to indicate that a specified table name is
/// already in use.
class TableNameInUse: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
// Thrown by functions that require a table to **not** be the target of link
// columns, unless those link columns are part of the table itself.
class CrossTableLinkTarget: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Thrown by various functions to indicate that the dynamic type of a table
/// does not match a particular other table type (dynamic or static).
class DescriptorMismatch: public ExceptionWithVersionInWhat {
public:
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
};
/// Reports errors that are a consequence of faulty logic within the program,
/// such as violating logical preconditions or class invariants, and can be
/// easily predicted.
class LogicError: public ExceptionWithVersionInWhat {
public:
enum error_kind {
string_too_big,
binary_too_big,
table_name_too_long,
column_name_too_long,
table_index_out_of_range,
row_index_out_of_range,
column_index_out_of_range,
/// Indicates that an argument has a value that is illegal in combination
/// with another argument, or with the state of an involved object.
illegal_combination,
/// Indicates a data type mismatch, such as when `Table::find_pkey_int()` is
/// called and the type of the primary key is not `type_Int`.
type_mismatch,
/// Indicates that an involved table is of the wrong kind, i.e., if it is a
/// subtable, and the function requires a root table.
wrong_kind_of_table,
/// Indicates that an involved accessor is was detached, i.e., was not
/// attached to an underlying object.
detached_accessor,
// Indicates that an involved column lacks a search index.
no_search_index,
// Indicates that an involved table lacks a primary key.
no_primary_key,
// Indicates that an attempt was made to add a primary key to a table that
// already had a primary key.
has_primary_key,
/// Indicates that a modification was attempted that would have produced a
/// duplicate primary value.
unique_constraint_violation
};
LogicError(error_kind message);
const char* what() const TIGHTDB_NOEXCEPT_OR_NOTHROW TIGHTDB_OVERRIDE;
static const char* get_message_for_error(error_kind) TIGHTDB_NOEXCEPT_OR_NOTHROW;
private:
const char* m_message;
};
// Implementation:
inline LogicError::LogicError(LogicError::error_kind kind):
m_message(get_message_for_error(kind))
{
}
inline const char* LogicError::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW
{
return m_message;
}
} // namespace tightdb
#endif // TIGHTDB_EXCEPTIONS_HPP
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <stdexcept>
#include <GL/glew.h>
#include <visionaray/detail/platform.h>
#if defined(VSNRAY_OS_DARWIN)
#include <AvailabilityMacros.h>
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#else // VSNRAY_OS_DARWIN
#if defined(VSNRAY_OS_WIN32)
#include <windows.h>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#endif
#include <GL/gl.h>
#include <GL/glut.h>
#ifdef FREEGLUT
#include <GL/freeglut_ext.h>
#endif
#endif
#include "input/keyboard.h"
#include "input/mouse.h"
#include "viewer_glut.h"
using namespace visionaray;
struct viewer_glut::impl
{
static viewer_glut* viewer;
static mouse::button down_button;
static int win_id;
impl(viewer_glut* instance);
void init(
int argc,
char** argv,
std::string window_title,
bool full_screen,
int width,
int height
);
static void close_func();
static void display_func();
static void idle_func();
static void keyboard_func(unsigned char key, int, int);
static void keyboard_up_func(unsigned char key, int, int);
static void motion_func(int x, int y);
static void mouse_func(int button, int state, int x, int y);
static void passive_motion_func(int x, int y);
static void reshape_func(int w, int h);
static void special_func(int key, int, int);
static void special_up_func(int key, int, int);
};
viewer_glut* viewer_glut::impl::viewer = nullptr;
mouse::button viewer_glut::impl::down_button = mouse::NoButton;
int viewer_glut::impl::win_id = 0;
//-------------------------------------------------------------------------------------------------
// Private implementation methods
//-------------------------------------------------------------------------------------------------
viewer_glut::impl::impl(viewer_glut* instance)
{
viewer_glut::impl::viewer = instance;
}
//-------------------------------------------------------------------------------------------------
// Init GLUT
//
void viewer_glut::impl::init(
int argc,
char** argv,
std::string window_title,
bool full_screen,
int width,
int height
)
{
glutInit(&argc, argv);
glutInitDisplayMode(/*GLUT_3_2_CORE_PROFILE |*/ GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(width, height);
win_id = glutCreateWindow(window_title.c_str());
if (full_screen)
{
glutFullScreen();
}
glutDisplayFunc(display_func);
glutIdleFunc(idle_func);
glutKeyboardFunc(keyboard_func);
glutKeyboardUpFunc(keyboard_up_func);
glutMotionFunc(motion_func);
glutMouseFunc(mouse_func);
glutPassiveMotionFunc(passive_motion_func);
glutReshapeFunc(reshape_func);
glutSpecialFunc(special_func);
glutSpecialUpFunc(special_up_func);
#ifdef FREEGLUT
glutCloseFunc(close_func);
#else
atexit(close_func);
#endif
if (glewInit() != GLEW_OK)
{
throw std::runtime_error("glewInit() failed");
}
}
//-------------------------------------------------------------------------------------------------
// Dispatch to virtual event handlers
//
void viewer_glut::impl::close_func()
{
viewer->on_close();
}
void viewer_glut::impl::display_func()
{
viewer->on_display();
glutSwapBuffers();
}
void viewer_glut::impl::idle_func()
{
viewer->on_idle();
}
void viewer_glut::impl::motion_func(int x, int y)
{
mouse::pos p = { x, y };
mouse_event event(
mouse::Move,
p,
down_button,
keyboard::NoKey
);
viewer->on_mouse_move(event);
}
void viewer_glut::impl::keyboard_func(unsigned char key, int, int)
{
auto k = keyboard::map_glut_key(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_press( key_event(keyboard::KeyPress, k, m) );
}
void viewer_glut::impl::keyboard_up_func(unsigned char key, int, int)
{
auto k = keyboard::map_glut_key(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_release( key_event(keyboard::KeyRelease, k, m) );
}
void viewer_glut::impl::mouse_func(int button, int state, int x, int y)
{
mouse::pos p = { x, y };
auto b = mouse::map_glut_button(button);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
if (state == GLUT_DOWN)
{
viewer->on_mouse_down( mouse_event(mouse::ButtonDown, p, b, m) );
down_button = b;
}
else if (state == GLUT_UP)
{
viewer->on_mouse_up( mouse_event(mouse::ButtonUp, p, b, m) );
down_button = mouse::NoButton;
}
}
void viewer_glut::impl::passive_motion_func(int x, int y)
{
mouse::pos p = { x, y };
mouse_event event(
mouse::Move,
p,
mouse::NoButton,
keyboard::NoKey
);
viewer->on_mouse_move(event);
}
void viewer_glut::impl::reshape_func(int w, int h)
{
viewer->on_resize(w, h);
}
void viewer_glut::impl::special_func(int key, int, int)
{
auto k = keyboard::map_glut_special(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_press( key_event(keyboard::KeyPress, k, m) );
}
void viewer_glut::impl::special_up_func(int key, int, int)
{
auto k = keyboard::map_glut_special(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_release( key_event(keyboard::KeyRelease, k, m) );
}
//-------------------------------------------------------------------------------------------------
// Public interface
//
viewer_glut::viewer_glut(
int width,
int height,
std::string window_title
)
: viewer_base(width, height, window_title)
, impl_(new impl(this))
{
}
viewer_glut::~viewer_glut()
{
}
void viewer_glut::init(int argc, char** argv)
{
viewer_base::init(argc, argv);
impl_->init(argc, argv, window_title(), full_screen(), width(), height());
}
void viewer_glut::event_loop()
{
glutMainLoop();
}
void viewer_glut::toggle_full_screen()
{
// OK to use statics, this is GLUT, anyway...
static int win_x = glutGet(GLUT_WINDOW_X);
static int win_y = glutGet(GLUT_WINDOW_Y);
static int width = glutGet(GLUT_WINDOW_WIDTH);
static int height = glutGet(GLUT_WINDOW_HEIGHT);
if (full_screen())
{
glutReshapeWindow( width, height );
glutPositionWindow( win_x, win_y );
}
else
{
win_x = glutGet(GLUT_WINDOW_X);
win_y = glutGet(GLUT_WINDOW_Y);
width = glutGet(GLUT_WINDOW_WIDTH);
height = glutGet(GLUT_WINDOW_HEIGHT);
glutFullScreen();
}
viewer_base::toggle_full_screen();
}
void viewer_glut::quit()
{
glutDestroyWindow(impl_->win_id);
#ifdef FREEGLUT
glutLeaveMainLoop();
viewer_base::quit();
#else
viewer_base::quit();
exit(EXIT_SUCCESS); // TODO
#endif
}
void viewer_glut::resize(int width, int height)
{
viewer_base::resize(width, height);
glutReshapeWindow(width, height);
}
//-------------------------------------------------------------------------------------------------
// Event handlers
//
void viewer_glut::on_idle()
{
glutPostRedisplay();
}
<commit_msg>Refactoring<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <stdexcept>
#include <GL/glew.h>
#include <visionaray/detail/platform.h>
#if defined(VSNRAY_OS_DARWIN)
#include <AvailabilityMacros.h>
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#else // VSNRAY_OS_DARWIN
#if defined(VSNRAY_OS_WIN32)
#include <windows.h>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#endif
#include <GL/gl.h>
#include <GL/glut.h>
#ifdef FREEGLUT
#include <GL/freeglut_ext.h>
#endif
#endif
#include "input/keyboard.h"
#include "input/mouse.h"
#include "viewer_glut.h"
using namespace visionaray;
struct viewer_glut::impl
{
static viewer_glut* viewer;
static mouse::button down_button;
static int win_id;
impl(viewer_glut* instance);
void init(
int argc,
char** argv,
std::string window_title,
bool full_screen,
int width,
int height
);
static void close_func();
static void display_func();
static void idle_func();
static void keyboard_func(unsigned char key, int, int);
static void keyboard_up_func(unsigned char key, int, int);
static void motion_func(int x, int y);
static void mouse_func(int button, int state, int x, int y);
static void passive_motion_func(int x, int y);
static void reshape_func(int w, int h);
static void special_func(int key, int, int);
static void special_up_func(int key, int, int);
};
viewer_glut* viewer_glut::impl::viewer = nullptr;
mouse::button viewer_glut::impl::down_button = mouse::NoButton;
int viewer_glut::impl::win_id = 0;
//-------------------------------------------------------------------------------------------------
// Private implementation methods
//-------------------------------------------------------------------------------------------------
viewer_glut::impl::impl(viewer_glut* instance)
{
viewer_glut::impl::viewer = instance;
}
//-------------------------------------------------------------------------------------------------
// Init GLUT
//
void viewer_glut::impl::init(
int argc,
char** argv,
std::string window_title,
bool full_screen,
int width,
int height
)
{
glutInit(&argc, argv);
glutInitDisplayMode(/*GLUT_3_2_CORE_PROFILE |*/ GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(width, height);
win_id = glutCreateWindow(window_title.c_str());
if (full_screen)
{
glutFullScreen();
}
glutDisplayFunc(display_func);
glutIdleFunc(idle_func);
glutKeyboardFunc(keyboard_func);
glutKeyboardUpFunc(keyboard_up_func);
glutMotionFunc(motion_func);
glutMouseFunc(mouse_func);
glutPassiveMotionFunc(passive_motion_func);
glutReshapeFunc(reshape_func);
glutSpecialFunc(special_func);
glutSpecialUpFunc(special_up_func);
#ifdef FREEGLUT
glutCloseFunc(close_func);
#else
atexit(close_func);
#endif
if (glewInit() != GLEW_OK)
{
throw std::runtime_error("glewInit() failed");
}
}
//-------------------------------------------------------------------------------------------------
// Dispatch to virtual event handlers
//
void viewer_glut::impl::close_func()
{
viewer->on_close();
}
void viewer_glut::impl::display_func()
{
viewer->on_display();
glutSwapBuffers();
}
void viewer_glut::impl::idle_func()
{
viewer->on_idle();
}
void viewer_glut::impl::keyboard_func(unsigned char key, int, int)
{
auto k = keyboard::map_glut_key(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_press( key_event(keyboard::KeyPress, k, m) );
}
void viewer_glut::impl::keyboard_up_func(unsigned char key, int, int)
{
auto k = keyboard::map_glut_key(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_release( key_event(keyboard::KeyRelease, k, m) );
}
void viewer_glut::impl::motion_func(int x, int y)
{
mouse::pos p = { x, y };
mouse_event event(
mouse::Move,
p,
down_button,
keyboard::NoKey
);
viewer->on_mouse_move(event);
}
void viewer_glut::impl::mouse_func(int button, int state, int x, int y)
{
mouse::pos p = { x, y };
auto b = mouse::map_glut_button(button);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
if (state == GLUT_DOWN)
{
viewer->on_mouse_down( mouse_event(mouse::ButtonDown, p, b, m) );
down_button = b;
}
else if (state == GLUT_UP)
{
viewer->on_mouse_up( mouse_event(mouse::ButtonUp, p, b, m) );
down_button = mouse::NoButton;
}
}
void viewer_glut::impl::passive_motion_func(int x, int y)
{
mouse::pos p = { x, y };
mouse_event event(
mouse::Move,
p,
mouse::NoButton,
keyboard::NoKey
);
viewer->on_mouse_move(event);
}
void viewer_glut::impl::reshape_func(int w, int h)
{
viewer->on_resize(w, h);
}
void viewer_glut::impl::special_func(int key, int, int)
{
auto k = keyboard::map_glut_special(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_press( key_event(keyboard::KeyPress, k, m) );
}
void viewer_glut::impl::special_up_func(int key, int, int)
{
auto k = keyboard::map_glut_special(key);
auto m = keyboard::map_glut_modifiers(glutGetModifiers());
viewer->on_key_release( key_event(keyboard::KeyRelease, k, m) );
}
//-------------------------------------------------------------------------------------------------
// Public interface
//
viewer_glut::viewer_glut(
int width,
int height,
std::string window_title
)
: viewer_base(width, height, window_title)
, impl_(new impl(this))
{
}
viewer_glut::~viewer_glut()
{
}
void viewer_glut::init(int argc, char** argv)
{
viewer_base::init(argc, argv);
impl_->init(argc, argv, window_title(), full_screen(), width(), height());
}
void viewer_glut::event_loop()
{
glutMainLoop();
}
void viewer_glut::toggle_full_screen()
{
// OK to use statics, this is GLUT, anyway...
static int win_x = glutGet(GLUT_WINDOW_X);
static int win_y = glutGet(GLUT_WINDOW_Y);
static int width = glutGet(GLUT_WINDOW_WIDTH);
static int height = glutGet(GLUT_WINDOW_HEIGHT);
if (full_screen())
{
glutReshapeWindow( width, height );
glutPositionWindow( win_x, win_y );
}
else
{
win_x = glutGet(GLUT_WINDOW_X);
win_y = glutGet(GLUT_WINDOW_Y);
width = glutGet(GLUT_WINDOW_WIDTH);
height = glutGet(GLUT_WINDOW_HEIGHT);
glutFullScreen();
}
viewer_base::toggle_full_screen();
}
void viewer_glut::quit()
{
glutDestroyWindow(impl_->win_id);
#ifdef FREEGLUT
glutLeaveMainLoop();
viewer_base::quit();
#else
viewer_base::quit();
exit(EXIT_SUCCESS); // TODO
#endif
}
void viewer_glut::resize(int width, int height)
{
viewer_base::resize(width, height);
glutReshapeWindow(width, height);
}
//-------------------------------------------------------------------------------------------------
// Event handlers
//
void viewer_glut::on_idle()
{
glutPostRedisplay();
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/trace/bufferpage.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2017 */
/* [+] 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 */
#include "bufferpage.H"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifndef __HOSTBOOT_RUNTIME
#include <kernel/pagemgr.H>
#endif
namespace TRACE
{
Entry* BufferPage::claimEntry(size_t i_size)
{
uint64_t l_usedSize = this->usedSize;
// Verify there is enough space.
while ((usedSize + i_size) < (PAGESIZE - sizeof(BufferPage)))
{
// Atomically attempt to claim i_size worth.
uint64_t newSize = l_usedSize + i_size;
if (!__sync_bool_compare_and_swap(&this->usedSize,
l_usedSize,
newSize))
{
// Failed race to atomically update.
// Re-read size, try again.
l_usedSize = this->usedSize;
continue;
}
// Successful at claiming an entry, return pointer to it.
return reinterpret_cast<Entry*>(&this->data[0] + l_usedSize);
}
return NULL;
}
BufferPage* BufferPage::allocate(bool i_common)
{
BufferPage* page = NULL;
#ifndef __HOSTBOOT_RUNTIME
page = reinterpret_cast<BufferPage*>(PageManager::allocatePage());
#else
page = reinterpret_cast<BufferPage*>(malloc(PAGESIZE));
#endif
memset(page, '\0', PAGESIZE);
if (i_common)
{
page->commonPage = 1;
}
return page;
}
void BufferPage::deallocate(BufferPage* i_page)
{
#ifndef __HOSTBOOT_RUNTIME
PageManager::freePage(i_page);
#else
if (i_page != nullptr)
{
free(i_page);
i_page = nullptr;
}
#endif
}
}
<commit_msg>Fix race condition in BufferPage allocation function<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/trace/bufferpage.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "bufferpage.H"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifndef __HOSTBOOT_RUNTIME
#include <kernel/pagemgr.H>
#endif
namespace TRACE
{
Entry* BufferPage::claimEntry(size_t i_size)
{
uint64_t l_usedSize = this->usedSize;
// Verify there is enough space.
while ((l_usedSize + i_size) < (PAGESIZE - sizeof(BufferPage)))
{
// Atomically attempt to claim i_size worth.
uint64_t newSize = l_usedSize + i_size;
if (!__sync_bool_compare_and_swap(&this->usedSize,
l_usedSize,
newSize))
{
// Failed race to atomically update.
// Re-read size, try again.
l_usedSize = this->usedSize;
continue;
}
// Successful at claiming an entry, return pointer to it.
return reinterpret_cast<Entry*>(&this->data[0] + l_usedSize);
}
return NULL;
}
BufferPage* BufferPage::allocate(bool i_common)
{
BufferPage* page = NULL;
#ifndef __HOSTBOOT_RUNTIME
page = reinterpret_cast<BufferPage*>(PageManager::allocatePage());
#else
page = reinterpret_cast<BufferPage*>(malloc(PAGESIZE));
#endif
memset(page, '\0', PAGESIZE);
if (i_common)
{
page->commonPage = 1;
}
return page;
}
void BufferPage::deallocate(BufferPage* i_page)
{
#ifndef __HOSTBOOT_RUNTIME
PageManager::freePage(i_page);
#else
if (i_page != nullptr)
{
free(i_page);
i_page = nullptr;
}
#endif
}
}
<|endoftext|> |
<commit_before>#include "BufferAccess.hpp"
#include "Error.hpp"
PyObject * MGLBufferAccess_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
MGLBufferAccess * self = (MGLBufferAccess *)type->tp_alloc(type, 0);
#ifdef MGL_VERBOSE
printf("MGLBufferAccess_tp_new %p\n", self);
#endif
if (self) {
}
return (PyObject *)self;
}
void MGLBufferAccess_tp_dealloc(MGLBufferAccess * self) {
#ifdef MGL_VERBOSE
printf("MGLBufferAccess_tp_dealloc %p\n", self);
#endif
MGLBufferAccess_Type.tp_free((PyObject *)self);
}
int MGLBufferAccess_tp_init(MGLBufferAccess * self, PyObject * args, PyObject * kwargs) {
MGLError_Set("cannot create mgl.BufferAccess manually");
return -1;
}
PyObject * MGLBufferAccess_open(MGLBufferAccess * self) {
if (self->ptr) {
MGLError_Set("already open");
return 0;
}
self->gl->BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
self->ptr = (char *)self->gl->MapBufferRange(GL_ARRAY_BUFFER, self->offset, self->size, self->access);
if (!self->ptr) {
MGLError_Set("cannot map the buffer");
return 0;
}
Py_RETURN_NONE;
}
PyObject * MGLBufferAccess_close(MGLBufferAccess * self) {
if (self->ptr) {
self->gl->UnmapBuffer(GL_ARRAY_BUFFER);
self->ptr = 0;
}
Py_RETURN_NONE;
}
PyObject * MGLBufferAccess_read(MGLBufferAccess * self, PyObject * args) {
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"II",
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
if (!self->ptr) {
MGLError_Set("the access object is not open");
return 0;
}
return PyBytes_FromStringAndSize(self->ptr + offset, size);
}
PyObject * MGLBufferAccess_read_into(MGLBufferAccess * self, PyObject * args) {
PyObject * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"OII",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
if (!self->ptr) {
MGLError_Set("the access object is not open");
return 0;
}
Py_buffer buffer_view;
int get_buffer = PyObject_GetBuffer(data, &buffer_view, PyBUF_WRITABLE);
if (get_buffer < 0) {
MGLError_Set("the buffer (%s) does not support buffer interface", Py_TYPE(data)->tp_name);
return 0;
}
if (buffer_view.len < size) {
MGLError_Set("the buffer is too small %d < %d", buffer_view.len, size);
PyBuffer_Release(&buffer_view);
return 0;
}
memcpy(buffer_view.buf, self->ptr + offset, size);
PyBuffer_Release(&buffer_view);
Py_RETURN_NONE;
}
PyObject * MGLBufferAccess_write(MGLBufferAccess * self, PyObject * args) {
const char * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"y#I",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (offset < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
if (!self->ptr) {
MGLError_Set("access objet is not open");
return 0;
}
memcpy(self->ptr + offset, data, size);
Py_RETURN_NONE;
}
PyMethodDef MGLBufferAccess_tp_methods[] = {
{"open", (PyCFunction)MGLBufferAccess_open, METH_NOARGS, 0},
{"close", (PyCFunction)MGLBufferAccess_close, METH_VARARGS, 0},
{"read", (PyCFunction)MGLBufferAccess_read, METH_VARARGS, 0},
{"read_into", (PyCFunction)MGLBufferAccess_read_into, METH_VARARGS, 0},
{"write", (PyCFunction)MGLBufferAccess_write, METH_VARARGS, 0},
{0},
};
PyObject * MGLBufferAccess_get_offset(MGLBufferAccess * self) {
return PyLong_FromLong(self->offset);
}
PyObject * MGLBufferAccess_get_size(MGLBufferAccess * self) {
return PyLong_FromLong(self->size);
}
PyObject * MGLBufferAccess_get_readonly(MGLBufferAccess * self) {
return PyBool_FromLong(!(self->access & GL_MAP_WRITE_BIT));
}
PyGetSetDef MGLBufferAccess_tp_getseters[] = {
{(char *)"offset", (getter)MGLBufferAccess_get_offset, 0, 0, 0},
{(char *)"size", (getter)MGLBufferAccess_get_size, 0, 0, 0},
{(char *)"readonly", (getter)MGLBufferAccess_get_readonly, 0, 0, 0},
{0},
};
PyTypeObject MGLBufferAccess_Type = {
PyVarObject_HEAD_INIT(0, 0)
"mgl.BufferAccess", // tp_name
sizeof(MGLBufferAccess), // tp_basicsize
0, // tp_itemsize
(destructor)MGLBufferAccess_tp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
0, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
MGLBufferAccess_tp_methods, // tp_methods
0, // tp_members
MGLBufferAccess_tp_getseters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)MGLBufferAccess_tp_init, // tp_init
0, // tp_alloc
MGLBufferAccess_tp_new, // tp_new
};
MGLBufferAccess * MGLBufferAccess_New() {
MGLBufferAccess * self = (MGLBufferAccess *)MGLBufferAccess_tp_new(&MGLBufferAccess_Type, 0, 0);
return self;
}
<commit_msg>buffer access read into<commit_after>#include "BufferAccess.hpp"
#include "Error.hpp"
PyObject * MGLBufferAccess_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
MGLBufferAccess * self = (MGLBufferAccess *)type->tp_alloc(type, 0);
#ifdef MGL_VERBOSE
printf("MGLBufferAccess_tp_new %p\n", self);
#endif
if (self) {
}
return (PyObject *)self;
}
void MGLBufferAccess_tp_dealloc(MGLBufferAccess * self) {
#ifdef MGL_VERBOSE
printf("MGLBufferAccess_tp_dealloc %p\n", self);
#endif
MGLBufferAccess_Type.tp_free((PyObject *)self);
}
int MGLBufferAccess_tp_init(MGLBufferAccess * self, PyObject * args, PyObject * kwargs) {
MGLError_Set("cannot create mgl.BufferAccess manually");
return -1;
}
PyObject * MGLBufferAccess_open(MGLBufferAccess * self) {
if (self->ptr) {
MGLError_Set("already open");
return 0;
}
self->gl->BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
self->ptr = (char *)self->gl->MapBufferRange(GL_ARRAY_BUFFER, self->offset, self->size, self->access);
if (!self->ptr) {
MGLError_Set("cannot map the buffer");
return 0;
}
Py_RETURN_NONE;
}
PyObject * MGLBufferAccess_close(MGLBufferAccess * self) {
if (self->ptr) {
self->gl->UnmapBuffer(GL_ARRAY_BUFFER);
self->ptr = 0;
}
Py_RETURN_NONE;
}
PyObject * MGLBufferAccess_read(MGLBufferAccess * self, PyObject * args) {
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"II",
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
if (!self->ptr) {
MGLError_Set("the access object is not open");
return 0;
}
return PyBytes_FromStringAndSize(self->ptr + offset, size);
}
PyObject * MGLBufferAccess_read_into(MGLBufferAccess * self, PyObject * args) {
PyObject * data;
int size;
int offset;
int write_offset;
int args_ok = PyArg_ParseTuple(
args,
"OIII",
&data,
&size,
&offset,
&write_offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
if (!self->ptr) {
MGLError_Set("the access object is not open");
return 0;
}
Py_buffer buffer_view;
int get_buffer = PyObject_GetBuffer(data, &buffer_view, PyBUF_WRITABLE);
if (get_buffer < 0) {
MGLError_Set("the buffer (%s) does not support buffer interface", Py_TYPE(data)->tp_name);
return 0;
}
if (buffer_view.len < write_offset + size) {
MGLError_Set("the buffer is too small");
PyBuffer_Release(&buffer_view);
return 0;
}
char * ptr = (char *)buffer_view.buf + write_offset;
memcpy(ptr, self->ptr + offset, size);
PyBuffer_Release(&buffer_view);
Py_RETURN_NONE;
}
PyObject * MGLBufferAccess_write(MGLBufferAccess * self, PyObject * args) {
const char * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"y#I",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (offset < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
if (!self->ptr) {
MGLError_Set("access objet is not open");
return 0;
}
memcpy(self->ptr + offset, data, size);
Py_RETURN_NONE;
}
PyMethodDef MGLBufferAccess_tp_methods[] = {
{"open", (PyCFunction)MGLBufferAccess_open, METH_NOARGS, 0},
{"close", (PyCFunction)MGLBufferAccess_close, METH_VARARGS, 0},
{"read", (PyCFunction)MGLBufferAccess_read, METH_VARARGS, 0},
{"read_into", (PyCFunction)MGLBufferAccess_read_into, METH_VARARGS, 0},
{"write", (PyCFunction)MGLBufferAccess_write, METH_VARARGS, 0},
{0},
};
PyObject * MGLBufferAccess_get_offset(MGLBufferAccess * self) {
return PyLong_FromLong(self->offset);
}
PyObject * MGLBufferAccess_get_size(MGLBufferAccess * self) {
return PyLong_FromLong(self->size);
}
PyObject * MGLBufferAccess_get_readonly(MGLBufferAccess * self) {
return PyBool_FromLong(!(self->access & GL_MAP_WRITE_BIT));
}
PyGetSetDef MGLBufferAccess_tp_getseters[] = {
{(char *)"offset", (getter)MGLBufferAccess_get_offset, 0, 0, 0},
{(char *)"size", (getter)MGLBufferAccess_get_size, 0, 0, 0},
{(char *)"readonly", (getter)MGLBufferAccess_get_readonly, 0, 0, 0},
{0},
};
PyTypeObject MGLBufferAccess_Type = {
PyVarObject_HEAD_INIT(0, 0)
"mgl.BufferAccess", // tp_name
sizeof(MGLBufferAccess), // tp_basicsize
0, // tp_itemsize
(destructor)MGLBufferAccess_tp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
0, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
MGLBufferAccess_tp_methods, // tp_methods
0, // tp_members
MGLBufferAccess_tp_getseters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)MGLBufferAccess_tp_init, // tp_init
0, // tp_alloc
MGLBufferAccess_tp_new, // tp_new
};
MGLBufferAccess * MGLBufferAccess_New() {
MGLBufferAccess * self = (MGLBufferAccess *)MGLBufferAccess_tp_new(&MGLBufferAccess_Type, 0, 0);
return self;
}
<|endoftext|> |
<commit_before>/*
* PCLTypeCaster.cpp
*
* Created on: Oct 7, 2011
* Author: Pinaki Sunil Banerjee
*/
#include "PCLTypecaster.h"
namespace BRICS_3D {
PCLTypecaster::PCLTypecaster() {}
PCLTypecaster::~PCLTypecaster() {}
void PCLTypecaster::convertToPCLDataType(pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloudPtr,
BRICS_3D::PointCloud3D* pointCloud3DPtr ){
//printf("[PCLTypeCaster]iNPUT cloud Size: %d \n", pointCloud3DPtr->getSize());
pclCloudPtr->width = pointCloud3DPtr->getSize();
pclCloudPtr->height = 1;
pclCloudPtr->points.resize( pclCloudPtr->width * pclCloudPtr->height );
for (unsigned int i =0 ; i<pointCloud3DPtr->getSize() ; i++){
pclCloudPtr->points[i].x = pointCloud3DPtr->getPointCloud()->data()[i].getX();
pclCloudPtr->points[i].y = pointCloud3DPtr->getPointCloud()->data()[i].getY();
pclCloudPtr->points[i].z = pointCloud3DPtr->getPointCloud()->data()[i].getZ();
}
//printf("[PCLTypeCaster]cONVERTED cloud Size: %d \n", pclCloudPtr->size());
}
void PCLTypecaster::convertToBRICS3DDataType(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pclCloudPtr,
BRICS_3D::PointCloud3D* pointCloud3DPtr ){
// //printf("[PCLTypeCaster]Input cloud Size: %d \n", pclCloudPtr->size());
for (unsigned int i =0 ; i < pclCloudPtr->size() ; i++){
pointCloud3DPtr->addPoint(ColoredPoint3D(new Point3D(pclCloudPtr->points[i].x,
pclCloudPtr->points[i].y, pclCloudPtr->points[i].z)));
}
// //printf("[PCLTypeCaster]Converted cloud Size: %d \n", pointCloud3DPtr->getSize());
}
void PCLTypecaster::convertToBRICS3DDataType(pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloudPtr,
BRICS_3D::PointCloud3D* pointCloud3DPtr ){
// pointCloud3DPtr->getPointCloud()->resize(pclCloudPtr->size());
for (unsigned int i =0 ; i < pclCloudPtr->size() ; i++){
pointCloud3DPtr->addPoint(ColoredPoint3D(new Point3D(pclCloudPtr->points[i].x,
pclCloudPtr->points[i].y, pclCloudPtr->points[i].z)));
}
}
void PCLTypecaster::convertToPCLDataType(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pclCloudPtr,
BRICS_3D::ColoredPointCloud3D* pointCloud3DPtr ){
BRICS_3D::ColorSpaceConvertor colorSpaceConvertor;
pclCloudPtr->width = pointCloud3DPtr->getSize();
pclCloudPtr->height = 1;
pclCloudPtr->points.resize( pclCloudPtr->width * pclCloudPtr->height );
float rgbVal24bit=0;
for (unsigned int i =0 ; i<pointCloud3DPtr->getSize() ; i++){
pclCloudPtr->points[i].x = pointCloud3DPtr->getPointCloud()->data()[i].getX();
pclCloudPtr->points[i].y = pointCloud3DPtr->getPointCloud()->data()[i].getY();
pclCloudPtr->points[i].z = pointCloud3DPtr->getPointCloud()->data()[i].getZ();
colorSpaceConvertor.rgbToRGB24Bit(&rgbVal24bit,
pointCloud3DPtr->getPointCloud()->data()[i].getR(),
pointCloud3DPtr->getPointCloud()->data()[i].getG(),
pointCloud3DPtr->getPointCloud()->data()[i].getB());
pclCloudPtr->points[i].rgb = rgbVal24bit;
}
}
void PCLTypecaster::convertToPCLDataType(pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloudPtr,
BRICS_3D::ColoredPointCloud3D* pointCloud3DPtr ){
pclCloudPtr->width = pointCloud3DPtr->getSize();
pclCloudPtr->height = 1;
pclCloudPtr->points.resize( pclCloudPtr->width * pclCloudPtr->height );
float rgbVal24bit=0;
for (unsigned int i =0 ; i<pointCloud3DPtr->getSize() ; i++){
pclCloudPtr->points[i].x = pointCloud3DPtr->getPointCloud()->data()[i].getX();
pclCloudPtr->points[i].y = pointCloud3DPtr->getPointCloud()->data()[i].getY();
pclCloudPtr->points[i].z = pointCloud3DPtr->getPointCloud()->data()[i].getZ();
}
}
void PCLTypecaster::convertToBRICS3DDataType(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pclCloudPtr,
BRICS_3D::ColoredPointCloud3D* pointCloud3DPtr ){
uint8_t r, g, b;
BRICS_3D::ColorSpaceConvertor colorSpaceConvertor;
uint32_t rgbVal;
unsigned char red, green, blue;
////printf("\n\n\tCHECKPOINT!!!\n");
for (unsigned int i =0 ; i < pclCloudPtr->size() ; i++){
rgbVal= *reinterpret_cast<int*>(&pclCloudPtr->points[i].rgb);
colorSpaceConvertor.rgb24bitToRGB(rgbVal, &r, &g, &b);
red= *reinterpret_cast<unsigned char*>(&r);
green= *reinterpret_cast<unsigned char*>(&g);
blue= *reinterpret_cast<unsigned char*>(&b);
pointCloud3DPtr->addPoint(new ColoredPoint3D(new Point3D(pclCloudPtr->points[i].x,
pclCloudPtr->points[i].y, pclCloudPtr->points[i].z), red, green, blue));
}
}
}
<commit_msg>modified the way points were added to colored list<commit_after>/*
* PCLTypeCaster.cpp
*
* Created on: Oct 7, 2011
* Author: Pinaki Sunil Banerjee
*/
#include "PCLTypecaster.h"
namespace BRICS_3D {
PCLTypecaster::PCLTypecaster() {}
PCLTypecaster::~PCLTypecaster() {}
void PCLTypecaster::convertToPCLDataType(pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloudPtr,
BRICS_3D::PointCloud3D* pointCloud3DPtr ){
pclCloudPtr->width = pointCloud3DPtr->getSize();
pclCloudPtr->height = 1;
pclCloudPtr->points.resize( pclCloudPtr->width * pclCloudPtr->height );
for (unsigned int i =0 ; i<pointCloud3DPtr->getSize() ; i++){
pclCloudPtr->points[i].x = pointCloud3DPtr->getPointCloud()->data()[i].getX();
pclCloudPtr->points[i].y = pointCloud3DPtr->getPointCloud()->data()[i].getY();
pclCloudPtr->points[i].z = pointCloud3DPtr->getPointCloud()->data()[i].getZ();
}
}
void PCLTypecaster::convertToBRICS3DDataType(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pclCloudPtr,
BRICS_3D::PointCloud3D* pointCloud3DPtr ){
pointCloud3DPtr->getPointCloud()->resize(pclCloudPtr->size());
for (unsigned int i =0 ; i < pclCloudPtr->size() ; i++){
pointCloud3DPtr->getPointCloud()->data()[i].setX(pclCloudPtr->points[i].x);
pointCloud3DPtr->getPointCloud()->data()[i].setY(pclCloudPtr->points[i].y);
pointCloud3DPtr->getPointCloud()->data()[i].setZ(pclCloudPtr->points[i].z);
// pointCloud3DPtr->addPoint(new Point3D(pclCloudPtr->points[i].x,
// pclCloudPtr->points[i].y, pclCloudPtr->points[i].z));
}
}
void PCLTypecaster::convertToBRICS3DDataType(pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloudPtr,
BRICS_3D::PointCloud3D* pointCloud3DPtr ){
pointCloud3DPtr->getPointCloud()->resize(pclCloudPtr->size());
for (unsigned int i =0 ; i < pclCloudPtr->size() ; i++){
pointCloud3DPtr->getPointCloud()->data()[i].setX(pclCloudPtr->points[i].x);
pointCloud3DPtr->getPointCloud()->data()[i].setY(pclCloudPtr->points[i].y);
pointCloud3DPtr->getPointCloud()->data()[i].setZ(pclCloudPtr->points[i].z);
// pointCloud3DPtr->addPoint(new Point3D(pclCloudPtr->points[i].x,
// pclCloudPtr->points[i].y, pclCloudPtr->points[i].z));
}
}
void PCLTypecaster::convertToPCLDataType(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pclCloudPtr,
BRICS_3D::ColoredPointCloud3D* pointCloud3DPtr ){
BRICS_3D::ColorSpaceConvertor colorSpaceConvertor;
pclCloudPtr->width = pointCloud3DPtr->getSize();
pclCloudPtr->height = 1;
pclCloudPtr->points.resize( pclCloudPtr->width * pclCloudPtr->height );
float rgbVal24bit=0;
for (unsigned int i =0 ; i<pointCloud3DPtr->getSize() ; i++){
pclCloudPtr->points[i].x = pointCloud3DPtr->getPointCloud()->data()[i].getX();
pclCloudPtr->points[i].y = pointCloud3DPtr->getPointCloud()->data()[i].getY();
pclCloudPtr->points[i].z = pointCloud3DPtr->getPointCloud()->data()[i].getZ();
colorSpaceConvertor.rgbToRGB24Bit(&rgbVal24bit,
pointCloud3DPtr->getPointCloud()->data()[i].getR(),
pointCloud3DPtr->getPointCloud()->data()[i].getG(),
pointCloud3DPtr->getPointCloud()->data()[i].getB());
pclCloudPtr->points[i].rgb = rgbVal24bit;
}
}
void PCLTypecaster::convertToPCLDataType(pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloudPtr,
BRICS_3D::ColoredPointCloud3D* pointCloud3DPtr ){
pclCloudPtr->width = pointCloud3DPtr->getSize();
pclCloudPtr->height = 1;
pclCloudPtr->points.resize( pclCloudPtr->width * pclCloudPtr->height );
for (unsigned int i =0 ; i<pointCloud3DPtr->getSize() ; i++){
pclCloudPtr->points[i].x = pointCloud3DPtr->getPointCloud()->data()[i].getX();
pclCloudPtr->points[i].y = pointCloud3DPtr->getPointCloud()->data()[i].getY();
pclCloudPtr->points[i].z = pointCloud3DPtr->getPointCloud()->data()[i].getZ();
}
}
void PCLTypecaster::convertToBRICS3DDataType(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pclCloudPtr,
BRICS_3D::ColoredPointCloud3D* pointCloud3DPtr ){
uint8_t r, g, b;
BRICS_3D::ColorSpaceConvertor colorSpaceConvertor;
uint32_t rgbVal;
unsigned char red, green, blue;
// printf("Input Cloud Size: %d", pclCloudPtr->size());
//FIXME Results into a memory leak
// pointCloud3DPtr->getPointCloud()->resize(pclCloudPtr->size());
for (unsigned int i =0 ; i < pclCloudPtr->size() ; i++){
rgbVal= *reinterpret_cast<int*>(&pclCloudPtr->points[i].rgb);
colorSpaceConvertor.rgb24bitToRGB(rgbVal, &r, &g, &b);
red= *reinterpret_cast<unsigned char*>(&r);
green= *reinterpret_cast<unsigned char*>(&g);
blue= *reinterpret_cast<unsigned char*>(&b);
Point3D* tmpPoint = new Point3D(pclCloudPtr->points[i].x, pclCloudPtr->points[i].y, pclCloudPtr->points[i].z);
ColoredPoint3D* tmpColoredPoint = new ColoredPoint3D(tmpPoint, red, green, blue);
pointCloud3DPtr->addPoint(tmpColoredPoint);
delete tmpPoint;
delete tmpColoredPoint;
// pointCloud3DPtr->getPointCloud()->data()[i].setX(pclCloudPtr->points[i].x);
// pointCloud3DPtr->getPointCloud()->data()[i].setY(pclCloudPtr->points[i].y);
// pointCloud3DPtr->getPointCloud()->data()[i].setZ(pclCloudPtr->points[i].z);
// pointCloud3DPtr->getPointCloud()->data()[i].setR(red);
// pointCloud3DPtr->getPointCloud()->data()[i].setG(blue);
// pointCloud3DPtr->getPointCloud()->data()[i].setB(green);
}
// printf("Output Cloud Size: %d", pointCloud3DPtr->getSize());
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/common/ipc_sync_channel.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/mock_render_process.h"
#include "chrome/renderer/render_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kThreadName[] = "render_thread_unittest";
class RenderThreadTest : public testing::Test {
public:
virtual void SetUp() {
MockProcess::GlobalInit();
// Need a MODE_SERVER to make MODE_CLIENTs (like a RenderThread) happy.
channel_ = new IPC::Channel(ASCIIToWide(kThreadName),
IPC::Channel::MODE_SERVER, NULL);
}
virtual void TearDown() {
message_loop_.RunAllPending();
delete channel_;
MockProcess::GlobalCleanup();
}
private:
MessageLoopForIO message_loop_;
IPC::Channel *channel_;
};
TEST_F(RenderThreadTest, TestGlobal) {
ASSERT_FALSE(g_render_thread);
{
RenderThread thread(ASCIIToWide(kThreadName));
ASSERT_TRUE(g_render_thread);
}
ASSERT_FALSE(g_render_thread);
}
TEST_F(RenderThreadTest, TestVisitedMsg) {
RenderThread thread(ASCIIToWide(kThreadName));
#if defined(OS_WIN)
IPC::Message* msg = new ViewMsg_VisitedLink_NewTable(NULL);
#elif defined(OS_POSIX)
IPC::Message* msg = new ViewMsg_VisitedLink_NewTable(
base::SharedMemoryHandle());
#endif
ASSERT_TRUE(msg);
// Message goes nowhere, but this confirms Init() has happened.
// Unusually (?), RenderThread() Start()s itself in it's constructor.
thread.Send(msg);
// No need to delete msg; per Message::Send() documentation, "The
// implementor takes ownership of the given Message regardless of
// whether or not this method succeeds."
}
} // namespace
<commit_msg>POSIX: TestVisitedMsg; use valid file descriptor (unit_tests fix)<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/common/ipc_sync_channel.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/mock_render_process.h"
#include "chrome/renderer/render_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kThreadName[] = "render_thread_unittest";
class RenderThreadTest : public testing::Test {
public:
virtual void SetUp() {
MockProcess::GlobalInit();
// Need a MODE_SERVER to make MODE_CLIENTs (like a RenderThread) happy.
channel_ = new IPC::Channel(ASCIIToWide(kThreadName),
IPC::Channel::MODE_SERVER, NULL);
}
virtual void TearDown() {
message_loop_.RunAllPending();
delete channel_;
MockProcess::GlobalCleanup();
}
private:
MessageLoopForIO message_loop_;
IPC::Channel *channel_;
};
TEST_F(RenderThreadTest, TestGlobal) {
ASSERT_FALSE(g_render_thread);
{
RenderThread thread(ASCIIToWide(kThreadName));
ASSERT_TRUE(g_render_thread);
}
ASSERT_FALSE(g_render_thread);
}
TEST_F(RenderThreadTest, TestVisitedMsg) {
RenderThread thread(ASCIIToWide(kThreadName));
#if defined(OS_WIN)
IPC::Message* msg = new ViewMsg_VisitedLink_NewTable(NULL);
#elif defined(OS_POSIX)
IPC::Message* msg = new ViewMsg_VisitedLink_NewTable(
base::SharedMemoryHandle(0, false));
#endif
ASSERT_TRUE(msg);
// Message goes nowhere, but this confirms Init() has happened.
// Unusually (?), RenderThread() Start()s itself in it's constructor.
thread.Send(msg);
// No need to delete msg; per Message::Send() documentation, "The
// implementor takes ownership of the given Message regardless of
// whether or not this method succeeds."
}
} // namespace
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 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/>.
*/
/*
* $Log$
* Revision 1.9 2000/06/26 20:30:04 jpolast
* check if initialized in Terminate() to stop access violations
* submitted by John_Roper@iOra.com
*
* Revision 1.8 2000/05/09 00:22:40 andyh
* Memory Cleanup. XMLPlatformUtils::Terminate() deletes all lazily
* allocated memory; memory leak checking tools will no longer report
* that leaks exist. (DOM GetElementsByTagID temporarily removed
* as part of this.)
*
* Revision 1.7 2000/03/24 19:50:29 roddey
* Clear the 'initialized' flag when the termination call is made. Probably
* not required technically, but...
*
* Revision 1.6 2000/03/02 19:54:44 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.5 2000/02/06 07:48:03 rahulj
* Year 2K copyright swat.
*
* Revision 1.4 2000/01/19 00:56:59 roddey
* Changes to get rid of dependence on old utils standard streams and to
* get rid of the fgLibLocation stuff.
*
* Revision 1.3 1999/12/18 00:18:10 roddey
* More changes to support the new, completely orthagonal support for
* intrinsic encodings.
*
* Revision 1.2 1999/12/15 19:41:28 roddey
* Support for the new transcoder system, where even intrinsic encodings are
* done via the same transcoder abstraction as external ones.
*
* Revision 1.1.1.1 1999/11/09 01:04:53 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:11 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLMsgLoader.hpp>
#include <util/Mutexes.hpp>
#include <util/PlatformUtils.hpp>
#include <util/RefVectorOf.hpp>
#include <util/TransService.hpp>
#include <util/XMLString.hpp>
#include <util/XMLNetAccessor.hpp>
#include <util/XMLUni.hpp>
// ---------------------------------------------------------------------------
// Local data members
//
// gSyncMutex
// This is a mutex that will be used to synchronize access to some of
// the static data of the platform utilities class and here locally.
// ---------------------------------------------------------------------------
static XMLMutex* gSyncMutex = 0;
static RefVectorOf<XMLDeleter>* gLazyData;
static bool gInitFlag = false;
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Static Data Members
// ---------------------------------------------------------------------------
XMLNetAccessor* XMLPlatformUtils::fgNetAccessor = 0;
XMLTransService* XMLPlatformUtils::fgTransService = 0;
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Init/term methods
// ---------------------------------------------------------------------------
void XMLPlatformUtils::Initialize()
{
//
// Make sure we haven't already been initialized. Note that this is not
// thread safe and is not intended for that. Its more for those COM
// like processes that cannot keep up with whether they have initialized
// us yet or not.
//
if (gInitFlag)
return;
gInitFlag = true;
// Create the local sync mutex
gSyncMutex = new XMLMutex;
// Create the array for saving lazily allocated objects to be deleted at termination
gLazyData= new RefVectorOf<XMLDeleter>(512);
//
// Call the platform init method, which is implemented in each of the
// per-platform implementation cpp files. This one does the very low
// level per-platform setup. It cannot use any XML util services at all,
// i.e. only native services.
//
platformInit();
//
// Ask the per-platform code to make the desired transcoding service for
// us to use. This call cannot throw any exceptions or do anything that
// cause any transcoding to happen. It should create the service and
// return it or zero if it cannot.
//
// This one also cannot use any utility services. It can only create a
// transcoding service object and return it.
//
// If we cannot make one, then we call panic to end the process.
//
fgTransService = makeTransService();
if (!fgTransService)
panic(Panic_NoTransService);
// Initialize the transcoder service
fgTransService->initTransService();
//
// Try to create a default local code page transcoder. This is the one
// that will be used internally by the XMLString class. If we cannot
// create one, then call the panic method.
//
XMLLCPTranscoder* defXCode = XMLPlatformUtils::fgTransService->makeNewLCPTranscoder();
if (!defXCode)
panic(Panic_NoDefTranscoder);
XMLString::initString(defXCode);
//
// Now lets ask the per-platform code to give us an instance of the type
// of network access implementation he wants to use. This can return
// a zero pointer if this platform doesn't want to support this.
//
fgNetAccessor = makeNetAccessor();
}
void XMLPlatformUtils::Terminate()
{
if (!gInitFlag)
return;
// Delete any net accessor that got installed
delete fgNetAccessor;
fgNetAccessor = 0;
//
// Call the method that cleans up the registered lazy eval objects.
// This is all higher level code which might try to report errors if
// they have problems, so we want to do this before we hose our
// fundamental bits and pieces.
//
cleanupLazyData();
//
// Call some other internal modules to give them a chance to clean up.
// Do the string class last in case something tries to use it during
// cleanup.
//
XMLString::termString();
// Clean up the the transcoding service
delete fgTransService;
fgTransService = 0;
// Clean up the sync mutex
delete gSyncMutex;
gSyncMutex = 0;
//
// And do platform termination. This cannot do use any XML services
// at all, it can only clean up local stuff. It it reports an error,
// it cannot use any XML exception or error reporting services.
//
platformTerm();
// And say we are no longer initialized
gInitFlag = false;
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Msg support methods
// ---------------------------------------------------------------------------
XMLMsgLoader* XMLPlatformUtils::loadMsgSet(const XMLCh* const msgDomain)
{
//
// Ask the platform support to load up the correct type of message
// loader for the indicated message set. We don't check here whether it
// works or not. That's their decision.
//
return loadAMsgSet(msgDomain);
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Lazy eval methods
// ---------------------------------------------------------------------------
void XMLPlatformUtils::registerLazyData(XMLDeleter* const deleter)
{
// Just add a copy of this object to the vector. MUST be synchronized
XMLMutexLock lock(gSyncMutex);
gLazyData->addElement(deleter);
}
void XMLPlatformUtils::cleanupLazyData()
{
//
// Loop through the vector and try to delete each object. Use a try
// block so that we don't fall out prematurely if one of them hoses.
// Note that we effectively do them in reverse order of their having
// been registered.
//
// Also, note that we don't synchronize here because this is happening
// during shutdown.
//
while (gLazyData->size())
{
try
{
gLazyData->removeLastElement();
}
catch(...)
{
// We don't try to report errors here, just fall through
}
}
delete gLazyData;
gLazyData = 0;
}
<commit_msg>use gInitFlag as a reference to the number of times Initialized was called. this way, the terminate routines are not invoked until all processes call Terminate() on the parser.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 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/>.
*/
/*
* $Log$
* Revision 1.10 2000/07/25 20:55:23 jpolast
* use gInitFlag as a reference to the number of times
* Initialized was called. this way, the terminate routines are
* not invoked until all processes call Terminate() on the parser.
*
* Revision 1.9 2000/06/26 20:30:04 jpolast
* check if initialized in Terminate() to stop access violations
* submitted by John_Roper@iOra.com
*
* Revision 1.8 2000/05/09 00:22:40 andyh
* Memory Cleanup. XMLPlatformUtils::Terminate() deletes all lazily
* allocated memory; memory leak checking tools will no longer report
* that leaks exist. (DOM GetElementsByTagID temporarily removed
* as part of this.)
*
* Revision 1.7 2000/03/24 19:50:29 roddey
* Clear the 'initialized' flag when the termination call is made. Probably
* not required technically, but...
*
* Revision 1.6 2000/03/02 19:54:44 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.5 2000/02/06 07:48:03 rahulj
* Year 2K copyright swat.
*
* Revision 1.4 2000/01/19 00:56:59 roddey
* Changes to get rid of dependence on old utils standard streams and to
* get rid of the fgLibLocation stuff.
*
* Revision 1.3 1999/12/18 00:18:10 roddey
* More changes to support the new, completely orthagonal support for
* intrinsic encodings.
*
* Revision 1.2 1999/12/15 19:41:28 roddey
* Support for the new transcoder system, where even intrinsic encodings are
* done via the same transcoder abstraction as external ones.
*
* Revision 1.1.1.1 1999/11/09 01:04:53 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:11 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLMsgLoader.hpp>
#include <util/Mutexes.hpp>
#include <util/PlatformUtils.hpp>
#include <util/RefVectorOf.hpp>
#include <util/TransService.hpp>
#include <util/XMLString.hpp>
#include <util/XMLNetAccessor.hpp>
#include <util/XMLUni.hpp>
// ---------------------------------------------------------------------------
// Local data members
//
// gSyncMutex
// This is a mutex that will be used to synchronize access to some of
// the static data of the platform utilities class and here locally.
// ---------------------------------------------------------------------------
static XMLMutex* gSyncMutex = 0;
static RefVectorOf<XMLDeleter>* gLazyData;
static short gInitFlag = 0;
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Static Data Members
// ---------------------------------------------------------------------------
XMLNetAccessor* XMLPlatformUtils::fgNetAccessor = 0;
XMLTransService* XMLPlatformUtils::fgTransService = 0;
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Init/term methods
// ---------------------------------------------------------------------------
void XMLPlatformUtils::Initialize()
{
//
// Make sure we haven't already been initialized. Note that this is not
// thread safe and is not intended for that. Its more for those COM
// like processes that cannot keep up with whether they have initialized
// us yet or not.
//
gInitFlag++;
if (gInitFlag > 1)
return;
// Create the local sync mutex
gSyncMutex = new XMLMutex;
// Create the array for saving lazily allocated objects to be deleted at termination
gLazyData= new RefVectorOf<XMLDeleter>(512);
//
// Call the platform init method, which is implemented in each of the
// per-platform implementation cpp files. This one does the very low
// level per-platform setup. It cannot use any XML util services at all,
// i.e. only native services.
//
platformInit();
//
// Ask the per-platform code to make the desired transcoding service for
// us to use. This call cannot throw any exceptions or do anything that
// cause any transcoding to happen. It should create the service and
// return it or zero if it cannot.
//
// This one also cannot use any utility services. It can only create a
// transcoding service object and return it.
//
// If we cannot make one, then we call panic to end the process.
//
fgTransService = makeTransService();
if (!fgTransService)
panic(Panic_NoTransService);
// Initialize the transcoder service
fgTransService->initTransService();
//
// Try to create a default local code page transcoder. This is the one
// that will be used internally by the XMLString class. If we cannot
// create one, then call the panic method.
//
XMLLCPTranscoder* defXCode = XMLPlatformUtils::fgTransService->makeNewLCPTranscoder();
if (!defXCode)
panic(Panic_NoDefTranscoder);
XMLString::initString(defXCode);
//
// Now lets ask the per-platform code to give us an instance of the type
// of network access implementation he wants to use. This can return
// a zero pointer if this platform doesn't want to support this.
//
fgNetAccessor = makeNetAccessor();
}
void XMLPlatformUtils::Terminate()
{
gInitFlag--;
if (gInitFlag > 0)
return;
// Delete any net accessor that got installed
delete fgNetAccessor;
fgNetAccessor = 0;
//
// Call the method that cleans up the registered lazy eval objects.
// This is all higher level code which might try to report errors if
// they have problems, so we want to do this before we hose our
// fundamental bits and pieces.
//
cleanupLazyData();
//
// Call some other internal modules to give them a chance to clean up.
// Do the string class last in case something tries to use it during
// cleanup.
//
XMLString::termString();
// Clean up the the transcoding service
delete fgTransService;
fgTransService = 0;
// Clean up the sync mutex
delete gSyncMutex;
gSyncMutex = 0;
//
// And do platform termination. This cannot do use any XML services
// at all, it can only clean up local stuff. It it reports an error,
// it cannot use any XML exception or error reporting services.
//
platformTerm();
// And say we are no longer initialized
gInitFlag = false;
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Msg support methods
// ---------------------------------------------------------------------------
XMLMsgLoader* XMLPlatformUtils::loadMsgSet(const XMLCh* const msgDomain)
{
//
// Ask the platform support to load up the correct type of message
// loader for the indicated message set. We don't check here whether it
// works or not. That's their decision.
//
return loadAMsgSet(msgDomain);
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Lazy eval methods
// ---------------------------------------------------------------------------
void XMLPlatformUtils::registerLazyData(XMLDeleter* const deleter)
{
// Just add a copy of this object to the vector. MUST be synchronized
XMLMutexLock lock(gSyncMutex);
gLazyData->addElement(deleter);
}
void XMLPlatformUtils::cleanupLazyData()
{
//
// Loop through the vector and try to delete each object. Use a try
// block so that we don't fall out prematurely if one of them hoses.
// Note that we effectively do them in reverse order of their having
// been registered.
//
// Also, note that we don't synchronize here because this is happening
// during shutdown.
//
while (gLazyData->size())
{
try
{
gLazyData->removeLastElement();
}
catch(...)
{
// We don't try to report errors here, just fall through
}
}
delete gLazyData;
gLazyData = 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c)2015 - 2018 Oasis LMF Limited
* 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 original author of this software 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: Ben Matharu email: ben.matharu@oasislmf.org
*/
#include <stdio.h>
#include <stdlib.h>
#if defined(_MSC_VER)
#include "../wingetopt/wingetopt.h"
#else
#include <unistd.h>
#endif
#include "../include/oasis.h"
char *progname;
namespace validateitems {
void doit();
}
#if !defined(_MSC_VER) && !defined(__MINGW32__)
void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
fprintf(stderr, "%s: Segment fault at address: %p\n", progname, si->si_addr);
exit(EXIT_FAILURE);
}
#endif
void help()
{
fprintf(stderr, "-h help\n-v version\n");
}
int main(int argc, char* argv[])
{
progname = argv[0];
int opt;
bool skipheader = false;
while ((opt = getopt(argc, argv, (char *) "svh")) != -1) {
switch (opt) {
case 's':
skipheader = true;
break;
case 'v':
fprintf(stderr, "%s : version: %s\n", argv[0], VERSION);
exit(EXIT_SUCCESS);
break;
case 'h':
default:
help();
exit(EXIT_FAILURE);
}
}
#if !defined(_MSC_VER) && !defined(__MINGW32__)
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfault_sigaction;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
#endif
try {
initstreams("", "");
validateitems::doit();
}
catch (std::bad_alloc) {
fprintf(stderr, "%s: Memory allocation failed\n", progname);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
<commit_msg>fix exitcode on help validateitems<commit_after>/*
* Copyright (c)2015 - 2018 Oasis LMF Limited
* 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 original author of this software 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: Ben Matharu email: ben.matharu@oasislmf.org
*/
#include <stdio.h>
#include <stdlib.h>
#if defined(_MSC_VER)
#include "../wingetopt/wingetopt.h"
#else
#include <unistd.h>
#endif
#include "../include/oasis.h"
char *progname;
namespace validateitems {
void doit();
}
#if !defined(_MSC_VER) && !defined(__MINGW32__)
void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
fprintf(stderr, "%s: Segment fault at address: %p\n", progname, si->si_addr);
exit(EXIT_FAILURE);
}
#endif
void help()
{
fprintf(stderr, "-h help\n-v version\n");
}
int main(int argc, char* argv[])
{
progname = argv[0];
int opt;
bool skipheader = false;
while ((opt = getopt(argc, argv, (char *) "svh")) != -1) {
switch (opt) {
case 's':
skipheader = true;
break;
case 'v':
fprintf(stderr, "%s : version: %s\n", argv[0], VERSION);
exit(EXIT_FAILURE);
break;
case 'h':
default:
help();
exit(EXIT_FAILURE);
}
}
#if !defined(_MSC_VER) && !defined(__MINGW32__)
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfault_sigaction;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
#endif
try {
initstreams("", "");
validateitems::doit();
}
catch (std::bad_alloc) {
fprintf(stderr, "%s: Memory allocation failed\n", progname);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "Communicator.hpp"
#include <ctime>
#include <iostream>
#include <string>
#include "api_application/Announce.h"
Communicator::Communicator(CvKinect *device, CvImageProcessor *analyzer):
device(device),
analyzer(analyzer),
initialized(false)
{
ros::NodeHandle n;
// Advertise myself to API
ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("announce");
api_application::Announce announce;
announce.request.type = 0; // 0 means camera module
if (announceClient.call(announce))
{
id = announce.response.id;
if (id == ~0 /* -1 */)
{
ROS_ERROR("Error! Got id -1");
exit(1);
}
else
{
ROS_INFO("Position module successfully announced. Got id %d", id);
}
}
else
{
ROS_ERROR("Error! Could not announce myself to API!");
exit(2);
}
// Services
std::stringstream ss;
ss << "InitializeCameraService" << id;
this->initializeCameraService = n.advertiseService(ss.str(), &Communicator::handleInitializeCameraService, this);
// Subscribers
this->pictureSendingActivationSubscriber = n.subscribe("PictureSendingActivation", 1, &Communicator::handlePictureSendingActivation, this);
this->calibrateCameraSubscriber = n.subscribe("CalibrateCamera", 100, &Communicator::handleCalibrateCamera, this);
this->cameraCalibrationDataSubscriber = n.subscribe("CameraCalibrationData", 4, &Communicator::handleCameraCalibrationData, this);
this->systemSubscriber = n.subscribe("System", 2, &Communicator::handleSystem, this);
// Publishers
this->picturePublisher = n.advertise<camera_application::Picture>("Picture", 1);
this->rawPositionPublisher = n.advertise<camera_application::RawPosition>("RawPosition", 1);
this->cameraCalibrationDataPublisher = n.advertise<camera_application::CameraCalibrationData>("CameraCalibrationData", 4);
// Listen to the camera.
device->addImageReceiver(this);
pictureNumber = 0;
pictureSendingActivated = false;
}
void Communicator::receiveImage(cv::Mat* image, long int time, int type)
{
if (pictureSendingActivated) {
camera_application::Picture::_image_type data;
for (size_t i = 0; i < (640 * 480 * 3); i++) {
data[i] = image->data[i];
}
this->sendPicture(data, (uint64_t)time, type);
}
delete image;
}
void Communicator::receiveTrackingData(cv::Scalar direction, int quadcopterId, long int time)
{
camera_application::RawPosition pos;
pos.ID = this->id;
pos.timestamp = time;
pos.xPosition = direction[0];
pos.yPosition = direction[1];
pos.quadcopterId = quadcopterId;
rawPositionPublisher.publish(pos);
}
void Communicator::calibrationFinished(cv::Mat* intrinsicsMatrix, cv::Mat* distortionCoefficients)
{
camera_application::CameraCalibrationData msg;
msg.createdByCamera = true;
for (int i = 0; i < 9; i++) {
msg.intrinsics[i] = intrinsicsMatrix->data[i];
}
for (int i = 0; i < 4; i++) {
msg.distortion[i] = distortionCoefficients->data[i];
}
cameraCalibrationDataPublisher.publish(msg);
analyzer->clearCalibrationImages();
}
void Communicator::sendPicture(camera_application::Picture::_image_type &data, uint64_t timestamp, int type)
{
camera_application::Picture msg;
msg.ID = this->id;
msg.imageNumber = pictureNumber++;
msg.timestamp = timestamp;
msg.image = data;
msg.calibrationImage = (type == 1);
this->picturePublisher.publish(msg);
}
bool Communicator::handleInitializeCameraService(
camera_application::InitializeCameraService::Request &req,
camera_application::InitializeCameraService::Response &res)
{
if (this->initialized) {
ROS_ERROR("initialize_camera called twice, ignoring.");
res.error = 1;
} else {
ROS_INFO("Initializing camera %u.", id);
this->initialized = true;
this->hsvColorRanges = req.hsvColorRanges;
this->quadCopterIds = req.quadCopterIds;
// Set quadcopters
for (int i = 0; i < this->quadCopterIds.size(); i++)
{
QuadcopterColor* color = new QuadcopterColor(hsvColorRanges[i * 2], hsvColorRanges[(i * 2) + 1], quadCopterIds[i]);
analyzer->addQuadcopter(color);
ROS_DEBUG("Added quadcopter: %s", color->toString().c_str());
}
res.error = 0;
}
return true;
}
void Communicator::handlePictureSendingActivation(
const camera_application::PictureSendingActivation::Ptr &msg)
{
if (msg->ID != this->id && msg->ID != 0)
return;
pictureSendingActivated = msg->active;
if (pictureSendingActivated) {
ROS_DEBUG("Picture sending activated");
} else {
ROS_DEBUG("Picture sending deactivated");
}
}
void Communicator::handleCalibrateCamera(
const camera_application::CalibrateCamera::Ptr &msg)
{
if (msg->ID == this->id) {
ROS_DEBUG("Received calibration order for me");
analyzer->startCalibration(msg->imageAmount, msg->imageDelay, msg->boardWidth, msg->boardHeight, msg->boardRectangleWidth, msg->boardRectangleHeight, this, this);
}
}
void Communicator::handleCameraCalibrationData(
const camera_application::CameraCalibrationData::Ptr &msg)
{
if (msg->ID == this->id && msg->createdByCamera == false) {
cv::Mat intrinsicsMatrix(cv::Size(3, 3), CV_64F);
cv::Mat distortionCoefficients(cv::Size(5, 1), CV_64F);
for (int i = 0; i < 9; i++) {
intrinsicsMatrix.data[i] = msg->intrinsics[i];
}
for (int i = 0; i < 4; i++) {
distortionCoefficients.data[i] = msg->distortion[i];
}
distortionCoefficients.data[4] = 0;
analyzer->setIntrinsicsMatrix(&intrinsicsMatrix);
analyzer->setDistortionCoefficients(&distortionCoefficients);
}
}
void Communicator::handleSystem(
const api_application::System::Ptr &msg)
{
if (msg->command == 1) {
// Start
analyzer->startTracking();
} else if (msg->command == 2) {
// Stop
analyzer->stopTracking();
ros::shutdown();
}
}<commit_msg>Changed output<commit_after>#include "Communicator.hpp"
#include <ctime>
#include <iostream>
#include <string>
#include "api_application/Announce.h"
Communicator::Communicator(CvKinect *device, CvImageProcessor *analyzer):
device(device),
analyzer(analyzer),
initialized(false)
{
ros::NodeHandle n;
// Advertise myself to API
ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("announce");
api_application::Announce announce;
announce.request.type = 0; // 0 means camera module
if (announceClient.call(announce))
{
id = announce.response.id;
if (id == ~0 /* -1 */)
{
ROS_ERROR("Error! Got id -1");
exit(1);
}
else
{
ROS_INFO("Camera module successfully announced. Got id %d", id);
}
}
else
{
ROS_ERROR("Error! Could not announce myself to API!");
exit(2);
}
// Services
std::stringstream ss;
ss << "InitializeCameraService" << id;
this->initializeCameraService = n.advertiseService(ss.str(), &Communicator::handleInitializeCameraService, this);
// Subscribers
this->pictureSendingActivationSubscriber = n.subscribe("PictureSendingActivation", 1, &Communicator::handlePictureSendingActivation, this);
this->calibrateCameraSubscriber = n.subscribe("CalibrateCamera", 100, &Communicator::handleCalibrateCamera, this);
this->cameraCalibrationDataSubscriber = n.subscribe("CameraCalibrationData", 4, &Communicator::handleCameraCalibrationData, this);
this->systemSubscriber = n.subscribe("System", 2, &Communicator::handleSystem, this);
// Publishers
this->picturePublisher = n.advertise<camera_application::Picture>("Picture", 1);
this->rawPositionPublisher = n.advertise<camera_application::RawPosition>("RawPosition", 1);
this->cameraCalibrationDataPublisher = n.advertise<camera_application::CameraCalibrationData>("CameraCalibrationData", 4);
// Listen to the camera.
device->addImageReceiver(this);
pictureNumber = 0;
pictureSendingActivated = false;
}
void Communicator::receiveImage(cv::Mat* image, long int time, int type)
{
if (pictureSendingActivated) {
camera_application::Picture::_image_type data;
for (size_t i = 0; i < (640 * 480 * 3); i++) {
data[i] = image->data[i];
}
this->sendPicture(data, (uint64_t)time, type);
}
delete image;
}
void Communicator::receiveTrackingData(cv::Scalar direction, int quadcopterId, long int time)
{
camera_application::RawPosition pos;
pos.ID = this->id;
pos.timestamp = time;
pos.xPosition = direction[0];
pos.yPosition = direction[1];
pos.quadcopterId = quadcopterId;
rawPositionPublisher.publish(pos);
}
void Communicator::calibrationFinished(cv::Mat* intrinsicsMatrix, cv::Mat* distortionCoefficients)
{
camera_application::CameraCalibrationData msg;
msg.createdByCamera = true;
for (int i = 0; i < 9; i++) {
msg.intrinsics[i] = intrinsicsMatrix->data[i];
}
for (int i = 0; i < 4; i++) {
msg.distortion[i] = distortionCoefficients->data[i];
}
cameraCalibrationDataPublisher.publish(msg);
analyzer->clearCalibrationImages();
}
void Communicator::sendPicture(camera_application::Picture::_image_type &data, uint64_t timestamp, int type)
{
camera_application::Picture msg;
msg.ID = this->id;
msg.imageNumber = pictureNumber++;
msg.timestamp = timestamp;
msg.image = data;
msg.calibrationImage = (type == 1);
this->picturePublisher.publish(msg);
}
bool Communicator::handleInitializeCameraService(
camera_application::InitializeCameraService::Request &req,
camera_application::InitializeCameraService::Response &res)
{
if (this->initialized) {
ROS_ERROR("initialize_camera called twice, ignoring.");
res.error = 1;
} else {
ROS_INFO("Initializing camera %u.", id);
this->initialized = true;
this->hsvColorRanges = req.hsvColorRanges;
this->quadCopterIds = req.quadCopterIds;
// Set quadcopters
for (int i = 0; i < this->quadCopterIds.size(); i++)
{
QuadcopterColor* color = new QuadcopterColor(hsvColorRanges[i * 2], hsvColorRanges[(i * 2) + 1], quadCopterIds[i]);
analyzer->addQuadcopter(color);
ROS_DEBUG("Added quadcopter: %s", color->toString().c_str());
}
res.error = 0;
}
return true;
}
void Communicator::handlePictureSendingActivation(
const camera_application::PictureSendingActivation::Ptr &msg)
{
if (msg->ID != this->id && msg->ID != 0)
return;
pictureSendingActivated = msg->active;
if (pictureSendingActivated) {
ROS_DEBUG("Picture sending activated");
} else {
ROS_DEBUG("Picture sending deactivated");
}
}
void Communicator::handleCalibrateCamera(
const camera_application::CalibrateCamera::Ptr &msg)
{
if (msg->ID == this->id) {
ROS_DEBUG("Received calibration order for me");
analyzer->startCalibration(msg->imageAmount, msg->imageDelay, msg->boardWidth, msg->boardHeight, msg->boardRectangleWidth, msg->boardRectangleHeight, this, this);
}
}
void Communicator::handleCameraCalibrationData(
const camera_application::CameraCalibrationData::Ptr &msg)
{
if (msg->ID == this->id && msg->createdByCamera == false) {
cv::Mat intrinsicsMatrix(cv::Size(3, 3), CV_64F);
cv::Mat distortionCoefficients(cv::Size(5, 1), CV_64F);
for (int i = 0; i < 9; i++) {
intrinsicsMatrix.data[i] = msg->intrinsics[i];
}
for (int i = 0; i < 4; i++) {
distortionCoefficients.data[i] = msg->distortion[i];
}
distortionCoefficients.data[4] = 0;
analyzer->setIntrinsicsMatrix(&intrinsicsMatrix);
analyzer->setDistortionCoefficients(&distortionCoefficients);
}
}
void Communicator::handleSystem(
const api_application::System::Ptr &msg)
{
if (msg->command == 1) {
// Start
analyzer->startTracking();
} else if (msg->command == 2) {
// Stop
analyzer->stopTracking();
ros::shutdown();
}
}<|endoftext|> |
<commit_before>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#include "infoware/cpu.hpp"
#include <cstdint>
#include <stdexcept>
#include <string>
iware::cpu::endianness_t iware::cpu::endianness() noexcept {
const std::uint16_t test = 0xFF00;
const auto result = *static_cast<const std::uint8_t*>(static_cast<const void*>(&test));
switch(result) {
case 0xFF:
return iware::cpu::endianness_t::little;
case 0x00:
return iware::cpu::endianness_t::little;
default:
throw std::domain_error(std::to_string(static_cast<unsigned int>(result)) + " is neither 0xFF nor 0x00");
}
}
<commit_msg>Throwing there is 100% WTF<commit_after>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#include "infoware/cpu.hpp"
#include <cstdint>
iware::cpu::endianness_t iware::cpu::endianness() noexcept {
const std::uint16_t test = 0xFF00;
const auto result = *static_cast<const std::uint8_t*>(static_cast<const void*>(&test));
if(result == 0xFF)
return iware::cpu::endianness_t::little;
else
return iware::cpu::endianness_t::little;
}
<|endoftext|> |
<commit_before>
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/sinks/msvc_sink.h>
#include "xdCore.hpp"
#include "Log.hpp"
using namespace XDay;
XDAY_API Logger GlobalLog("init.log", false);
Logger::Logger(const std::string& _logfile, bool coreInitialized) : LogFile(_logfile)
{
if (Core.FindParam(eParamNoLog))
{
nolog = true;
return;
}
if (Core.FindParam(eParamNoLogFlush))
nologflush = true;
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
if (!nologflush && coreInitialized)
sinks.push_back(std::make_shared<spdlog::sinks::simple_file_sink_mt>(Core.LogsPath.string() + LogFile, true));
#if defined(DEBUG) && defined(_MSC_VER)
sinks.push_back(std::make_shared<spdlog::sinks::msvc_sink_mt>());
#endif
spdlogger = std::make_shared<spdlog::logger>("X-Day Engine", begin(sinks), end(sinks));
spdlogger->set_pattern("[%T] [%l] %v");
spdlog::register_logger(spdlogger);
}
Logger::~Logger()
{
if (nolog)
return;
CloseLog();
}
// Used only in GlobalLog
void Logger::onCoreInitialized()
{
if (nolog || nologflush)
return;
CloseLog();
this->Logger::Logger("main.log", true);
}
void Logger::CloseLog()
{
if (nolog)
return;
if (!nologflush)
FlushLog();
spdlog::drop_all();
}
void Logger::FlushLog()
{
if (nologflush)
return;
spdlogger->flush();
}
<commit_msg>Set trace logger level for debug configuration<commit_after>
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/sinks/msvc_sink.h>
#include "xdCore.hpp"
#include "Log.hpp"
using namespace XDay;
XDAY_API Logger GlobalLog("init.log", false);
Logger::Logger(const std::string& _logfile, bool coreInitialized) : LogFile(_logfile)
{
if (Core.FindParam(eParamNoLog))
{
nolog = true;
return;
}
if (Core.FindParam(eParamNoLogFlush))
nologflush = true;
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
if (!nologflush && coreInitialized)
sinks.push_back(std::make_shared<spdlog::sinks::simple_file_sink_mt>(Core.LogsPath.string() + LogFile, true));
#if defined(DEBUG) && defined(_MSC_VER)
sinks.push_back(std::make_shared<spdlog::sinks::msvc_sink_mt>());
#endif
spdlogger = std::make_shared<spdlog::logger>("X-Day Engine", begin(sinks), end(sinks));
spdlogger->set_pattern("[%T] [%l] %v");
if (Core.isGlobalDebug())
spdlogger->set_level(spdlog::level::trace);
spdlog::register_logger(spdlogger);
}
Logger::~Logger()
{
if (nolog)
return;
CloseLog();
}
// Used only in GlobalLog
void Logger::onCoreInitialized()
{
if (nolog || nologflush)
return;
CloseLog();
this->Logger::Logger("main.log", true);
}
void Logger::CloseLog()
{
if (nolog)
return;
if (!nologflush)
FlushLog();
spdlog::drop_all();
}
void Logger::FlushLog()
{
if (nologflush)
return;
spdlogger->flush();
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/QName.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// QName: Constructors and Destructor
// ---------------------------------------------------------------------------
QName::QName(MemoryManager* const manager)
:fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(manager)
{
}
typedef JanitorMemFunCall<QName> CleanupType;
QName::QName( const XMLCh* const prefix
, const XMLCh* const localPart
, const unsigned int uriId
, MemoryManager* const manager)
:fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(manager)
{
CleanupType cleanup(this, &QName::cleanUp);
try
{
//
// Just call the local setters to set up everything. Too much
// work is required to replicate that functionality here.
//
setName(prefix, localPart, uriId);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
QName::QName( const XMLCh* const rawName
, const unsigned int uriId
, MemoryManager* const manager)
:fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(manager)
{
CleanupType cleanup(this, &QName::cleanUp);
try
{
//
// Just call the local setters to set up everything. Too much
// work is required to replicate that functionality here.
//
setName(rawName, uriId);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
QName::~QName()
{
cleanUp();
}
// ---------------------------------------------------------------------------
// QName: Copy Constructors
// ---------------------------------------------------------------------------
QName::QName(const QName& qname)
:XSerializable(qname)
,XMemory(qname)
,fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(qname.fMemoryManager)
{
unsigned int newLen;
newLen = XMLString::stringLen(qname.getLocalPart());
fLocalPartBufSz = newLen + 8;
fLocalPart = (XMLCh*) fMemoryManager->allocate
(
(fLocalPartBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fLocalPartBufSz + 1];
XMLString::moveChars(fLocalPart, qname.getLocalPart(), newLen + 1);
newLen = XMLString::stringLen(qname.getPrefix());
fPrefixBufSz = newLen + 8;
fPrefix = (XMLCh*) fMemoryManager->allocate
(
(fPrefixBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fPrefixBufSz + 1];
XMLString::moveChars(fPrefix, qname.getPrefix(), newLen + 1);
fURIId = qname.getURI();
}
// ---------------------------------------------------------------------------
// QName: Getter methods
// ---------------------------------------------------------------------------
const XMLCh* QName::getRawName() const
{
//
// If there is no buffer, or if there is but we've not faulted in the
// value yet, then we have to do that now.
//
if (!fRawName || !*fRawName)
{
//
// If we have a prefix, then do the prefix:name version. Else, its
// just the name.
//
if (*fPrefix)
{
//
// Calculate the worst case size buffer we will need. We use the
// current high water marks of the prefix and name buffers, so it
// might be a little wasteful of memory but we don't have to do
// string len operations on the two strings.
//
const unsigned int neededLen = fPrefixBufSz + fLocalPartBufSz + 1;
//
// If no buffer, or the current one is too small, then allocate one
// and get rid of any old one.
//
if (!fRawName || (neededLen > fRawNameBufSz))
{
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
((QName*)this)->fRawName = 0;
// We have to cast off the const'ness to do this
((QName*)this)->fRawNameBufSz = neededLen;
((QName*)this)->fRawName = (XMLCh*) fMemoryManager->allocate
(
(neededLen + 1) * sizeof(XMLCh)
); //new XMLCh[neededLen + 1];
// Make sure its initially empty
*fRawName = 0;
}
const unsigned int prefixLen = XMLString::stringLen(fPrefix);
XMLString::moveChars(fRawName, fPrefix, prefixLen);
fRawName[prefixLen] = chColon;
XMLString::copyString(&fRawName[prefixLen+1], fLocalPart);
}
else
{
return fLocalPart;
}
}
return fRawName;
}
XMLCh* QName::getRawName()
{
//
// If there is no buffer, or if there is but we've not faulted in the
// value yet, then we have to do that now.
//
if (!fRawName || !*fRawName)
{
//
// If we have a prefix, then do the prefix:name version. Else, its
// just the name.
//
if (*fPrefix)
{
//
// Calculate the worst case size buffer we will need. We use the
// current high water marks of the prefix and name buffers, so it
// might be a little wasteful of memory but we don't have to do
// string len operations on the two strings.
//
const unsigned int neededLen = fPrefixBufSz + fLocalPartBufSz + 1;
//
// If no buffer, or the current one is too small, then allocate one
// and get rid of any old one.
//
if (!fRawName || (neededLen > fRawNameBufSz))
{
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
fRawName = 0;
// We have to cast off the const'ness to do this
((QName*)this)->fRawNameBufSz = neededLen;
((QName*)this)->fRawName = (XMLCh*) fMemoryManager->allocate
(
(neededLen + 1) * sizeof(XMLCh)
); //new XMLCh[neededLen + 1];
// Make sure its initially empty
*fRawName = 0;
}
const unsigned int prefixLen = XMLString::stringLen(fPrefix);
XMLString::moveChars(fRawName, fPrefix, prefixLen);
fRawName[prefixLen] = chColon;
XMLString::copyString(&fRawName[prefixLen+1], fLocalPart);
}
else
{
return fLocalPart;
}
}
return fRawName;
}
// ---------------------------------------------------------------------------
// QName: Setter methods
// ---------------------------------------------------------------------------
void QName::setName(const XMLCh* const prefix
, const XMLCh* const localPart
, const unsigned int uriId)
{
setPrefix(prefix);
setLocalPart(localPart);
// And clean up any QName and leave it undone until/if asked for again
if (fRawName)
*fRawName = 0;
// And finally store the URI id parameter
fURIId = uriId;
}
void QName::setName(const XMLCh* const rawName
, const unsigned int uriId)
{
//set the rawName
unsigned int newLen = XMLString::stringLen(rawName);
//find out the prefix and localPart from the rawName
const int colonInd = XMLString::indexOf(rawName, chColon);
if (colonInd >= 0)
{
if (!fRawNameBufSz || (newLen > fRawNameBufSz))
{
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
fRawName = 0;
fRawNameBufSz = newLen + 8;
fRawName = (XMLCh*) fMemoryManager->allocate
(
(fRawNameBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fRawNameBufSz + 1];
}
XMLString::moveChars(fRawName, rawName, newLen + 1);
setNPrefix(rawName, colonInd);
}
else
{
// No colon, so we just have a name with no prefix
setPrefix(XMLUni::fgZeroLenString);
// And clean up any QName and leave it undone until/if asked for again
if (fRawName)
*fRawName = 0;
}
setNLocalPart(&rawName[colonInd+1], newLen-colonInd-1);
// And finally store the URI id parameter
fURIId = uriId;
}
void QName::setPrefix(const XMLCh* prefix)
{
setNPrefix(prefix, XMLString::stringLen(prefix));
}
void QName::setNPrefix(const XMLCh* prefix, const unsigned int newLen)
{
if (!fPrefixBufSz || (newLen > fPrefixBufSz))
{
fMemoryManager->deallocate(fPrefix); //delete [] fPrefix;
fPrefix = 0;
fPrefixBufSz = newLen + 8;
fPrefix = (XMLCh*) fMemoryManager->allocate
(
(fPrefixBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fPrefixBufSz + 1];
}
XMLString::moveChars(fPrefix, prefix, newLen);
fPrefix[newLen] = chNull;
}
void QName::setLocalPart(const XMLCh* localPart)
{
unsigned int newLen;
newLen = XMLString::stringLen(localPart);
if (!fLocalPartBufSz || (newLen > fLocalPartBufSz))
{
fMemoryManager->deallocate(fLocalPart); //delete [] fLocalPart;
fLocalPart = 0;
fLocalPartBufSz = newLen + 8;
fLocalPart = (XMLCh*) fMemoryManager->allocate
(
(fLocalPartBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fLocalPartBufSz + 1];
}
XMLString::moveChars(fLocalPart, localPart, newLen + 1);
}
void QName::setNLocalPart(const XMLCh* localPart, const unsigned int newLen)
{
if (!fLocalPartBufSz || (newLen > fLocalPartBufSz))
{
fMemoryManager->deallocate(fLocalPart); //delete [] fLocalPart;
fLocalPart = 0;
fLocalPartBufSz = newLen + 8;
fLocalPart = (XMLCh*) fMemoryManager->allocate
(
(fLocalPartBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fLocalPartBufSz + 1];
}
XMLString::moveChars(fLocalPart, localPart, newLen);
fLocalPart[newLen] = chNull;
}
void QName::setValues(const QName& qname)
{
setPrefix(qname.getPrefix());
setLocalPart(qname.getLocalPart());
setURI(qname.getURI());
}
// -----------------------------------------------------------------------
// comparison
// -----------------------------------------------------------------------
bool QName::operator==(const QName& qname) const
{
if (fURIId == 0) // null URI
return (XMLString::equals(getRawName(),qname.getRawName()));
return ((fURIId == qname.getURI()) &&
(XMLString::equals(fLocalPart, qname.getLocalPart())));
}
// ---------------------------------------------------------------------------
// QName: Private, helper methods
// ---------------------------------------------------------------------------
void QName::cleanUp()
{
fMemoryManager->deallocate(fLocalPart); //delete [] fLocalPart;
fMemoryManager->deallocate(fPrefix); //delete [] fPrefix;
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
fLocalPart = fPrefix = fRawName = 0;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(QName)
void QName::serialize(XSerializeEngine& serEng)
{
if (serEng.isStoring())
{
serEng.writeString(fPrefix, fPrefixBufSz, XSerializeEngine::toWriteBufferLen);
serEng.writeString(fLocalPart, fLocalPartBufSz, XSerializeEngine::toWriteBufferLen);
//do not serialize rawName
serEng<<fURIId;
}
else
{
int dataLen = 0;
serEng.readString(fPrefix, (int&)fPrefixBufSz, dataLen, XSerializeEngine::toReadBufferLen);
serEng.readString(fLocalPart, (int&)fLocalPartBufSz, dataLen, XSerializeEngine::toReadBufferLen);
//force raw name rebuilt
fRawNameBufSz = 0;
fRawName = 0;
serEng>>fURIId;
}
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Reuse existing method<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/QName.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// QName: Constructors and Destructor
// ---------------------------------------------------------------------------
QName::QName(MemoryManager* const manager)
:fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(manager)
{
}
typedef JanitorMemFunCall<QName> CleanupType;
QName::QName( const XMLCh* const prefix
, const XMLCh* const localPart
, const unsigned int uriId
, MemoryManager* const manager)
:fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(manager)
{
CleanupType cleanup(this, &QName::cleanUp);
try
{
//
// Just call the local setters to set up everything. Too much
// work is required to replicate that functionality here.
//
setName(prefix, localPart, uriId);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
QName::QName( const XMLCh* const rawName
, const unsigned int uriId
, MemoryManager* const manager)
:fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(manager)
{
CleanupType cleanup(this, &QName::cleanUp);
try
{
//
// Just call the local setters to set up everything. Too much
// work is required to replicate that functionality here.
//
setName(rawName, uriId);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
QName::~QName()
{
cleanUp();
}
// ---------------------------------------------------------------------------
// QName: Copy Constructors
// ---------------------------------------------------------------------------
QName::QName(const QName& qname)
:XSerializable(qname)
,XMemory(qname)
,fPrefixBufSz(0)
,fLocalPartBufSz(0)
,fRawNameBufSz(0)
,fURIId(0)
,fPrefix(0)
,fLocalPart(0)
,fRawName(0)
,fMemoryManager(qname.fMemoryManager)
{
unsigned int newLen;
newLen = XMLString::stringLen(qname.getLocalPart());
fLocalPartBufSz = newLen + 8;
fLocalPart = (XMLCh*) fMemoryManager->allocate
(
(fLocalPartBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fLocalPartBufSz + 1];
XMLString::moveChars(fLocalPart, qname.getLocalPart(), newLen + 1);
newLen = XMLString::stringLen(qname.getPrefix());
fPrefixBufSz = newLen + 8;
fPrefix = (XMLCh*) fMemoryManager->allocate
(
(fPrefixBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fPrefixBufSz + 1];
XMLString::moveChars(fPrefix, qname.getPrefix(), newLen + 1);
fURIId = qname.getURI();
}
// ---------------------------------------------------------------------------
// QName: Getter methods
// ---------------------------------------------------------------------------
const XMLCh* QName::getRawName() const
{
//
// If there is no buffer, or if there is but we've not faulted in the
// value yet, then we have to do that now.
//
if (!fRawName || !*fRawName)
{
//
// If we have a prefix, then do the prefix:name version. Else, its
// just the name.
//
if (*fPrefix)
{
//
// Calculate the worst case size buffer we will need. We use the
// current high water marks of the prefix and name buffers, so it
// might be a little wasteful of memory but we don't have to do
// string len operations on the two strings.
//
const unsigned int neededLen = fPrefixBufSz + fLocalPartBufSz + 1;
//
// If no buffer, or the current one is too small, then allocate one
// and get rid of any old one.
//
if (!fRawName || (neededLen > fRawNameBufSz))
{
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
((QName*)this)->fRawName = 0;
// We have to cast off the const'ness to do this
((QName*)this)->fRawNameBufSz = neededLen;
((QName*)this)->fRawName = (XMLCh*) fMemoryManager->allocate
(
(neededLen + 1) * sizeof(XMLCh)
); //new XMLCh[neededLen + 1];
// Make sure its initially empty
*fRawName = 0;
}
const unsigned int prefixLen = XMLString::stringLen(fPrefix);
XMLString::moveChars(fRawName, fPrefix, prefixLen);
fRawName[prefixLen] = chColon;
XMLString::copyString(&fRawName[prefixLen+1], fLocalPart);
}
else
{
return fLocalPart;
}
}
return fRawName;
}
XMLCh* QName::getRawName()
{
//
// If there is no buffer, or if there is but we've not faulted in the
// value yet, then we have to do that now.
//
if (!fRawName || !*fRawName)
{
//
// If we have a prefix, then do the prefix:name version. Else, its
// just the name.
//
if (*fPrefix)
{
//
// Calculate the worst case size buffer we will need. We use the
// current high water marks of the prefix and name buffers, so it
// might be a little wasteful of memory but we don't have to do
// string len operations on the two strings.
//
const unsigned int neededLen = fPrefixBufSz + fLocalPartBufSz + 1;
//
// If no buffer, or the current one is too small, then allocate one
// and get rid of any old one.
//
if (!fRawName || (neededLen > fRawNameBufSz))
{
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
fRawName = 0;
// We have to cast off the const'ness to do this
((QName*)this)->fRawNameBufSz = neededLen;
((QName*)this)->fRawName = (XMLCh*) fMemoryManager->allocate
(
(neededLen + 1) * sizeof(XMLCh)
); //new XMLCh[neededLen + 1];
// Make sure its initially empty
*fRawName = 0;
}
const unsigned int prefixLen = XMLString::stringLen(fPrefix);
XMLString::moveChars(fRawName, fPrefix, prefixLen);
fRawName[prefixLen] = chColon;
XMLString::copyString(&fRawName[prefixLen+1], fLocalPart);
}
else
{
return fLocalPart;
}
}
return fRawName;
}
// ---------------------------------------------------------------------------
// QName: Setter methods
// ---------------------------------------------------------------------------
void QName::setName(const XMLCh* const prefix
, const XMLCh* const localPart
, const unsigned int uriId)
{
setPrefix(prefix);
setLocalPart(localPart);
// And clean up any QName and leave it undone until/if asked for again
if (fRawName)
*fRawName = 0;
// And finally store the URI id parameter
fURIId = uriId;
}
void QName::setName(const XMLCh* const rawName
, const unsigned int uriId)
{
//set the rawName
unsigned int newLen = XMLString::stringLen(rawName);
//find out the prefix and localPart from the rawName
const int colonInd = XMLString::indexOf(rawName, chColon);
if (colonInd >= 0)
{
if (!fRawNameBufSz || (newLen > fRawNameBufSz))
{
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
fRawName = 0;
fRawNameBufSz = newLen + 8;
fRawName = (XMLCh*) fMemoryManager->allocate
(
(fRawNameBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fRawNameBufSz + 1];
}
XMLString::moveChars(fRawName, rawName, newLen + 1);
setNPrefix(rawName, colonInd);
}
else
{
// No colon, so we just have a name with no prefix
setPrefix(XMLUni::fgZeroLenString);
// And clean up any QName and leave it undone until/if asked for again
if (fRawName)
*fRawName = 0;
}
setNLocalPart(&rawName[colonInd+1], newLen-colonInd-1);
// And finally store the URI id parameter
fURIId = uriId;
}
void QName::setPrefix(const XMLCh* prefix)
{
setNPrefix(prefix, XMLString::stringLen(prefix));
}
void QName::setNPrefix(const XMLCh* prefix, const unsigned int newLen)
{
if (!fPrefixBufSz || (newLen > fPrefixBufSz))
{
fMemoryManager->deallocate(fPrefix); //delete [] fPrefix;
fPrefix = 0;
fPrefixBufSz = newLen + 8;
fPrefix = (XMLCh*) fMemoryManager->allocate
(
(fPrefixBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fPrefixBufSz + 1];
}
XMLString::moveChars(fPrefix, prefix, newLen);
fPrefix[newLen] = chNull;
}
void QName::setLocalPart(const XMLCh* localPart)
{
setNLocalPart(localPart, XMLString::stringLen(localPart));
}
void QName::setNLocalPart(const XMLCh* localPart, const unsigned int newLen)
{
if (!fLocalPartBufSz || (newLen > fLocalPartBufSz))
{
fMemoryManager->deallocate(fLocalPart); //delete [] fLocalPart;
fLocalPart = 0;
fLocalPartBufSz = newLen + 8;
fLocalPart = (XMLCh*) fMemoryManager->allocate
(
(fLocalPartBufSz + 1) * sizeof(XMLCh)
); //new XMLCh[fLocalPartBufSz + 1];
}
XMLString::moveChars(fLocalPart, localPart, newLen);
fLocalPart[newLen] = chNull;
}
void QName::setValues(const QName& qname)
{
setPrefix(qname.getPrefix());
setLocalPart(qname.getLocalPart());
setURI(qname.getURI());
}
// -----------------------------------------------------------------------
// comparison
// -----------------------------------------------------------------------
bool QName::operator==(const QName& qname) const
{
if (fURIId == 0) // null URI
return (XMLString::equals(getRawName(),qname.getRawName()));
return ((fURIId == qname.getURI()) &&
(XMLString::equals(fLocalPart, qname.getLocalPart())));
}
// ---------------------------------------------------------------------------
// QName: Private, helper methods
// ---------------------------------------------------------------------------
void QName::cleanUp()
{
fMemoryManager->deallocate(fLocalPart); //delete [] fLocalPart;
fMemoryManager->deallocate(fPrefix); //delete [] fPrefix;
fMemoryManager->deallocate(fRawName); //delete [] fRawName;
fLocalPart = fPrefix = fRawName = 0;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(QName)
void QName::serialize(XSerializeEngine& serEng)
{
if (serEng.isStoring())
{
serEng.writeString(fPrefix, fPrefixBufSz, XSerializeEngine::toWriteBufferLen);
serEng.writeString(fLocalPart, fLocalPartBufSz, XSerializeEngine::toWriteBufferLen);
//do not serialize rawName
serEng<<fURIId;
}
else
{
int dataLen = 0;
serEng.readString(fPrefix, (int&)fPrefixBufSz, dataLen, XSerializeEngine::toReadBufferLen);
serEng.readString(fLocalPart, (int&)fLocalPartBufSz, dataLen, XSerializeEngine::toReadBufferLen);
//force raw name rebuilt
fRawNameBufSz = 0;
fRawName = 0;
serEng>>fURIId;
}
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#include <cstring>
#include <limits>
#include <zorba/internal/unique_ptr.h>
#include "common/common.h"
#include "util/ascii_util.h"
#include "decimal.h"
#include "floatimpl.h"
#include "integer.h"
#include "numconversions.h"
using namespace std;
namespace zorba {
///////////////////////////////////////////////////////////////////////////////
Decimal::value_type const Decimal::round_precision_limit( 64 );
void Decimal::parse( char const *s, value_type *result, int parse_options ) {
if ( !*s )
throw invalid_argument( "empty string" );
s = ascii::trim_start_space( s );
char const *const first_non_ws = s;
if ( *s == '+' || *s == '-' )
++s;
while ( ascii::is_digit( *s ) )
++s;
if ( parse_options & parse_decimal ) {
if ( *s == '.' ) {
++s;
while ( ascii::is_digit( *s ) )
++s;
}
}
char const *first_trailing_ws = nullptr;
while ( ascii::is_space( *s ) ) {
if ( !first_trailing_ws )
first_trailing_ws = s;
++s;
}
if ( *s )
throw invalid_argument( BUILD_STRING( '"', *s, "\": invalid character" ) );
if ( first_trailing_ws ) {
ptrdiff_t const size = first_trailing_ws - first_non_ws;
char *const copy = ::strncpy( new char[ size + 1 ], first_non_ws, size );
copy[ size ] = '\0';
*result = copy;
delete[] copy;
} else
*result = first_non_ws;
}
/**
* Rounds .xxx9999xxx or .xxx000000xxx.
*/
void Decimal::reduce( char *s ) {
char *const dot = ::strrchr( s, '.' );
if ( !dot ) // not a floating-point number
return;
char *e = ::strpbrk( s, "eE" );
if ( !e )
e = s + ::strlen( s ); // eliminates special-case
char *digit = e - 1;
if ( ::strncmp( dot + 1, "9999", 3 ) == 0 ) {
// The "leading nines" case, e.g., 12.9999[34][E56]
::memmove( dot, e, strlen( e ) + 1 );
digit = dot - 1;
char const *const first = *s == '-' ? s + 1 : s;
while ( true ) {
if ( *digit == '9' ) {
*digit = '0';
if ( digit == first ) {
// slide to the right to insert a leading '1'
::memmove( digit + 1, digit, strlen( digit ) + 1 );
*digit = '1';
break;
}
--digit;
} else {
++digit[0]; // e.g., 12 => 13
break;
}
}
return;
}
if ( char *const nines = ::strstr( dot + 1, "9999" ) ) {
// The "in-the-middle nines" case, e.g., 12.349999[56][E78]
++nines[-1]; // e.g., .xxx19 => .xxx29
::memmove( nines, e, strlen( e ) + 1 );
return;
}
if ( char *const zeros = ::strstr( dot + 1, "000000" ) ) {
// The "zeros" case, e.g., 12.0000003, 12.340000005.
::memmove( zeros, e, strlen( e ) + 1 );
char *const last = s + ::strlen( s ) - 1;
if ( *last == '.' )
*last = '\0';
return;
}
}
////////// constructors ///////////////////////////////////////////////////////
Decimal::Decimal( long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
}
Decimal::Decimal( unsigned long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
}
Decimal::Decimal( unsigned long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
}
Decimal::Decimal( float f ) {
if ( f != f ||
f == std::numeric_limits<float>::infinity() ||
f == -std::numeric_limits<float>::infinity() )
throw invalid_argument( "float value = infinity" );
value_ = f;
}
Decimal::Decimal( double d ) {
if ( d != d ||
d == std::numeric_limits<double>::infinity() ||
d == -std::numeric_limits<double>::infinity() )
throw invalid_argument( "double value = infinity" );
value_ = d;
}
Decimal::Decimal( Double const &d ) {
if ( !d.isFinite() )
throw invalid_argument( "double value = infinity" );
value_ = d.getNumber();
}
Decimal::Decimal( Float const &f ) {
if ( !f.isFinite() )
throw invalid_argument( "float value = infinity" );
value_ = f.getNumber();
}
template<class T>
Decimal::Decimal( IntegerImpl<T> const &i ) : value_( i.itod() ) {
}
// instantiate Decimal-from-Integer constructors
template Decimal::Decimal( Integer const& );
template Decimal::Decimal( NegativeInteger const& );
template Decimal::Decimal( NonNegativeInteger const& );
template Decimal::Decimal( NonPositiveInteger const& );
template Decimal::Decimal( PositiveInteger const& );
////////// assignment operators ///////////////////////////////////////////////
Decimal& Decimal::operator=( long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
return *this;
}
Decimal& Decimal::operator=( unsigned long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
return *this;
}
template<class T>
Decimal& Decimal::operator=( IntegerImpl<T> const &i ) {
value_ = i.itod();
return *this;
}
template Decimal& Decimal::operator=( Integer const& );
template Decimal& Decimal::operator=( NegativeInteger const& );
template Decimal& Decimal::operator=( NonNegativeInteger const& );
template Decimal& Decimal::operator=( NonPositiveInteger const& );
template Decimal& Decimal::operator=( PositiveInteger const& );
Decimal& Decimal::operator=( Double const &d ) {
if ( !d.isFinite() )
throw invalid_argument( "not finite" );
value_ = d.getNumber();
return *this;
}
Decimal& Decimal::operator=( Float const &f ) {
if ( !f.isFinite() )
throw invalid_argument( "not finite" );
value_ = f.getNumber();
return *this;
}
////////// arithmetic operators ///////////////////////////////////////////////
#define ZORBA_INSTANTIATE(OP,I) \
template Decimal operator OP( Decimal const&, I const& )
#define ZORBA_DECIMAL_OP(OP) \
template<class T> inline \
Decimal operator OP( Decimal const &d, IntegerImpl<T> const &i ) { \
return d.value_ OP i.itod(); \
} \
ZORBA_INSTANTIATE(OP,Integer); \
ZORBA_INSTANTIATE(OP,NegativeInteger); \
ZORBA_INSTANTIATE(OP,NonNegativeInteger); \
ZORBA_INSTANTIATE(OP,NonPositiveInteger); \
ZORBA_INSTANTIATE(OP,PositiveInteger);
ZORBA_DECIMAL_OP(+);
ZORBA_DECIMAL_OP(-);
ZORBA_DECIMAL_OP(*);
ZORBA_DECIMAL_OP(/);
ZORBA_DECIMAL_OP(%);
#undef ZORBA_DECIMAL_OP
#undef ZORBA_INSTANTIATE
////////// relational operators ///////////////////////////////////////////////
#define ZORBA_INSTANTIATE(OP,I) \
template bool operator OP( Decimal const&, I const& )
#define ZORBA_DECIMAL_OP(OP) \
template<class T> inline \
bool operator OP( Decimal const &d, IntegerImpl<T> const &i ) { \
return d.value_ OP i.itod(); \
} \
ZORBA_INSTANTIATE( OP, Integer ); \
ZORBA_INSTANTIATE( OP, NegativeInteger ); \
ZORBA_INSTANTIATE( OP, NonNegativeInteger ); \
ZORBA_INSTANTIATE( OP, NonPositiveInteger ); \
ZORBA_INSTANTIATE( OP, PositiveInteger );
ZORBA_DECIMAL_OP(==);
ZORBA_DECIMAL_OP(!=);
ZORBA_DECIMAL_OP(< );
ZORBA_DECIMAL_OP(<=);
ZORBA_DECIMAL_OP(> );
ZORBA_DECIMAL_OP(>=);
#undef ZORBA_DECIMAL_OP
#undef ZORBA_INSTANTIATE
////////// math functions /////////////////////////////////////////////////////
Decimal Decimal::round() const {
return round( numeric_consts<xs_integer>::zero() );
}
template<class T>
Decimal Decimal::round( IntegerImpl<T> const &precision ) const {
return round2( value_, precision.itod() );
}
template Decimal Decimal::round( Integer const& ) const;
template Decimal Decimal::round( NegativeInteger const& ) const;
template Decimal Decimal::round( NonNegativeInteger const& ) const;
template Decimal Decimal::round( NonPositiveInteger const& ) const;
template Decimal Decimal::round( PositiveInteger const& ) const;
Decimal::value_type Decimal::round2( value_type const &v,
value_type const &precision ) {
if ( precision < -round_precision_limit )
return round2( v, -round_precision_limit );
if ( precision > round_precision_limit )
return round2( v, round_precision_limit );
value_type const exp( value_type(10).pow( precision ) );
value_type result( v * exp );
result += MAPM::get0_5();
result = result.floor();
result /= exp;
return result;
}
template<class T>
Decimal Decimal::roundHalfToEven( IntegerImpl<T> const &precision ) const {
return roundHalfToEven2( value_, precision.itod() );
}
template Decimal Decimal::roundHalfToEven( Integer const& ) const;
template Decimal Decimal::roundHalfToEven( NegativeInteger const& ) const;
template Decimal Decimal::roundHalfToEven( NonNegativeInteger const& ) const;
template Decimal Decimal::roundHalfToEven( NonPositiveInteger const& ) const;
template Decimal Decimal::roundHalfToEven( PositiveInteger const& ) const;
Decimal::value_type Decimal::roundHalfToEven2( value_type const &v,
value_type const &precision ) {
if ( precision < -round_precision_limit )
return roundHalfToEven2( v, -round_precision_limit );
if ( precision > round_precision_limit )
return roundHalfToEven2( v, round_precision_limit );
value_type const exp( value_type(10).pow( precision ) );
value_type result( v * exp );
bool const aHalfVal = (result - MAPM::get0_5()) == result.floor();
result += MAPM::get0_5();
result = result.floor();
if ( aHalfVal && result.is_odd() )
--result;
result /= exp;
return result;
}
////////// miscellaneous //////////////////////////////////////////////////////
size_t Decimal::alloc_size() const {
return value_.significant_digits();
}
uint32_t Decimal::hash( value_type const &value ) {
char buf[1024];
char *bufp = value.exponent() + 3 > 1024 ?
new char[ value.exponent() + 3 ] : buf;
if ( value.sign() < 0 ) {
if ( value >= MAPM::getMinInt64() ) {
// hash it as int64
value.toIntegerString( bufp );
stringstream ss( bufp );
int64_t n;
ss >> n;
assert( ss.eof() );
if ( bufp != buf )
delete[] bufp;
return static_cast<uint32_t>( n & 0xFFFFFFFF );
}
} else if ( value <= MAPM::getMaxUInt64() ) {
// hash it as uint64
value.toIntegerString( bufp );
stringstream ss( bufp );
uint64_t n;
ss >> n;
assert( ss.eof() );
if ( bufp != buf )
delete[] bufp;
return static_cast<uint32_t>( n & 0xFFFFFFFF );
}
// In all other cases, hash it as double
value.toFixPtString( bufp, ZORBA_FLOAT_POINT_PRECISION );
stringstream ss( bufp );
double n;
ss >> n;
assert( ss.eof() );
if ( bufp != buf )
delete[] bufp;
return static_cast<uint32_t>( n );
}
zstring Decimal::toString( value_type const &value, bool minusZero,
int precision ) {
char buf[ 2048 ];
if ( minusZero ) {
if ( value.sign() == 0 )
buf[0] = '-';
else
minusZero = false;
}
value.toFixPtString( buf + minusZero, precision );
//
// Note that in the canonical representation, the decimal point is required
// and there must be at least one digit to the right and one digit to the
// left of the decimal point (which may be 0).
//
if ( strchr( buf, '.' ) != 0 ) {
// remove trailing 0's
char *last = buf + strlen( buf );
while ( *--last == '0' )
*last = '\0';
if ( *last == '.' ) // remove '.' if no digits after it
*last = '\0';
}
if ( precision < ZORBA_FLOAT_POINT_PRECISION )
reduce( buf );
return buf;
}
///////////////////////////////////////////////////////////////////////////////
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Tweaks.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#include <cstring>
#include <limits>
#include <zorba/internal/unique_ptr.h>
#include "common/common.h"
#include "util/ascii_util.h"
#include "decimal.h"
#include "floatimpl.h"
#include "integer.h"
#include "numconversions.h"
using namespace std;
namespace zorba {
///////////////////////////////////////////////////////////////////////////////
Decimal::value_type const Decimal::round_precision_limit( 64 );
void Decimal::parse( char const *s, value_type *result, int parse_options ) {
if ( !*s )
throw invalid_argument( "empty string" );
s = ascii::trim_start_space( s );
char const *const first_non_ws = s;
if ( *s == '+' || *s == '-' )
++s;
while ( ascii::is_digit( *s ) )
++s;
if ( parse_options & parse_decimal ) {
if ( *s == '.' ) {
++s;
while ( ascii::is_digit( *s ) )
++s;
}
}
char const *first_trailing_ws = nullptr;
while ( ascii::is_space( *s ) ) {
if ( !first_trailing_ws )
first_trailing_ws = s;
++s;
}
if ( *s )
throw invalid_argument( BUILD_STRING( '"', *s, "\": invalid character" ) );
if ( first_trailing_ws ) {
ptrdiff_t const size = first_trailing_ws - first_non_ws;
char *const copy = ::strncpy( new char[ size + 1 ], first_non_ws, size );
copy[ size ] = '\0';
*result = copy;
delete[] copy;
} else
*result = first_non_ws;
}
/**
* Rounds .xxx9999xxx or .xxx000000xxx.
*/
void Decimal::reduce( char *s ) {
char *const dot = ::strrchr( s, '.' );
if ( !dot ) // not a floating-point number
return;
bool has_e = false;
char *e = ::strpbrk( s, "eE" );
if ( !e )
e = s + ::strlen( s ); // eliminates a special-case
else
has_e = true;
char *digit = e - 1;
if ( ::strncmp( dot + 1, "9999", 3 ) == 0 ) {
// The "leading nines" case, e.g., 12.9999[34][E56]
if ( has_e ) {
::memmove( dot + 2, e, strlen( e ) + 1 );
dot[1] = '0';
} else
::memmove( dot, e, strlen( e ) + 1 );
digit = dot - 1;
char const *const first = *s == '-' ? s + 1 : s;
while ( true ) {
if ( *digit == '9' ) {
*digit = '0';
if ( digit == first ) {
// slide to the right to insert a leading '1'
::memmove( digit + 1, digit, strlen( digit ) + 1 );
*digit = '1';
break;
}
--digit;
} else {
++digit[0]; // e.g., 12 => 13
break;
}
}
return;
}
if ( char *const nines = ::strstr( dot + 1, "9999" ) ) {
// The "in-the-middle nines" case, e.g., 12.349999[56][E78]
++nines[-1]; // e.g., .xxx19 => .xxx29
::memmove( nines, e, strlen( e ) + 1 );
return;
}
if ( char *zeros = ::strstr( dot + 1, "000000" ) ) {
// The "zeros" case, e.g., 12.0000003, 12.340000005.
if ( zeros[-1] == '.' ) // if leading zeros, leave one 0
++zeros;
::memmove( zeros, e, strlen( e ) + 1 );
return;
}
}
////////// constructors ///////////////////////////////////////////////////////
Decimal::Decimal( long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
}
Decimal::Decimal( unsigned long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
}
Decimal::Decimal( unsigned long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
}
Decimal::Decimal( float f ) {
if ( f != f ||
f == std::numeric_limits<float>::infinity() ||
f == -std::numeric_limits<float>::infinity() )
throw invalid_argument( "float value = infinity" );
value_ = f;
}
Decimal::Decimal( double d ) {
if ( d != d ||
d == std::numeric_limits<double>::infinity() ||
d == -std::numeric_limits<double>::infinity() )
throw invalid_argument( "double value = infinity" );
value_ = d;
}
Decimal::Decimal( Double const &d ) {
if ( !d.isFinite() )
throw invalid_argument( "double value = infinity" );
value_ = d.getNumber();
}
Decimal::Decimal( Float const &f ) {
if ( !f.isFinite() )
throw invalid_argument( "float value = infinity" );
value_ = f.getNumber();
}
template<class T>
Decimal::Decimal( IntegerImpl<T> const &i ) : value_( i.itod() ) {
}
// instantiate Decimal-from-Integer constructors
template Decimal::Decimal( Integer const& );
template Decimal::Decimal( NegativeInteger const& );
template Decimal::Decimal( NonNegativeInteger const& );
template Decimal::Decimal( NonPositiveInteger const& );
template Decimal::Decimal( PositiveInteger const& );
////////// assignment operators ///////////////////////////////////////////////
Decimal& Decimal::operator=( long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
return *this;
}
Decimal& Decimal::operator=( unsigned long long n ) {
ascii::itoa_buf_type buf;
value_ = ascii::itoa( n, buf );
return *this;
}
template<class T>
Decimal& Decimal::operator=( IntegerImpl<T> const &i ) {
value_ = i.itod();
return *this;
}
template Decimal& Decimal::operator=( Integer const& );
template Decimal& Decimal::operator=( NegativeInteger const& );
template Decimal& Decimal::operator=( NonNegativeInteger const& );
template Decimal& Decimal::operator=( NonPositiveInteger const& );
template Decimal& Decimal::operator=( PositiveInteger const& );
Decimal& Decimal::operator=( Double const &d ) {
if ( !d.isFinite() )
throw invalid_argument( "not finite" );
value_ = d.getNumber();
return *this;
}
Decimal& Decimal::operator=( Float const &f ) {
if ( !f.isFinite() )
throw invalid_argument( "not finite" );
value_ = f.getNumber();
return *this;
}
////////// arithmetic operators ///////////////////////////////////////////////
#define ZORBA_INSTANTIATE(OP,I) \
template Decimal operator OP( Decimal const&, I const& )
#define ZORBA_DECIMAL_OP(OP) \
template<class T> inline \
Decimal operator OP( Decimal const &d, IntegerImpl<T> const &i ) { \
return d.value_ OP i.itod(); \
} \
ZORBA_INSTANTIATE(OP,Integer); \
ZORBA_INSTANTIATE(OP,NegativeInteger); \
ZORBA_INSTANTIATE(OP,NonNegativeInteger); \
ZORBA_INSTANTIATE(OP,NonPositiveInteger); \
ZORBA_INSTANTIATE(OP,PositiveInteger);
ZORBA_DECIMAL_OP(+);
ZORBA_DECIMAL_OP(-);
ZORBA_DECIMAL_OP(*);
ZORBA_DECIMAL_OP(/);
ZORBA_DECIMAL_OP(%);
#undef ZORBA_DECIMAL_OP
#undef ZORBA_INSTANTIATE
////////// relational operators ///////////////////////////////////////////////
#define ZORBA_INSTANTIATE(OP,I) \
template bool operator OP( Decimal const&, I const& )
#define ZORBA_DECIMAL_OP(OP) \
template<class T> inline \
bool operator OP( Decimal const &d, IntegerImpl<T> const &i ) { \
return d.value_ OP i.itod(); \
} \
ZORBA_INSTANTIATE( OP, Integer ); \
ZORBA_INSTANTIATE( OP, NegativeInteger ); \
ZORBA_INSTANTIATE( OP, NonNegativeInteger ); \
ZORBA_INSTANTIATE( OP, NonPositiveInteger ); \
ZORBA_INSTANTIATE( OP, PositiveInteger );
ZORBA_DECIMAL_OP(==);
ZORBA_DECIMAL_OP(!=);
ZORBA_DECIMAL_OP(< );
ZORBA_DECIMAL_OP(<=);
ZORBA_DECIMAL_OP(> );
ZORBA_DECIMAL_OP(>=);
#undef ZORBA_DECIMAL_OP
#undef ZORBA_INSTANTIATE
////////// math functions /////////////////////////////////////////////////////
Decimal Decimal::round() const {
return round( numeric_consts<xs_integer>::zero() );
}
template<class T>
Decimal Decimal::round( IntegerImpl<T> const &precision ) const {
return round2( value_, precision.itod() );
}
template Decimal Decimal::round( Integer const& ) const;
template Decimal Decimal::round( NegativeInteger const& ) const;
template Decimal Decimal::round( NonNegativeInteger const& ) const;
template Decimal Decimal::round( NonPositiveInteger const& ) const;
template Decimal Decimal::round( PositiveInteger const& ) const;
Decimal::value_type Decimal::round2( value_type const &v,
value_type const &precision ) {
if ( precision < -round_precision_limit )
return round2( v, -round_precision_limit );
if ( precision > round_precision_limit )
return round2( v, round_precision_limit );
value_type const exp( value_type(10).pow( precision ) );
value_type result( v * exp );
result += MAPM::get0_5();
result = result.floor();
result /= exp;
return result;
}
template<class T>
Decimal Decimal::roundHalfToEven( IntegerImpl<T> const &precision ) const {
return roundHalfToEven2( value_, precision.itod() );
}
template Decimal Decimal::roundHalfToEven( Integer const& ) const;
template Decimal Decimal::roundHalfToEven( NegativeInteger const& ) const;
template Decimal Decimal::roundHalfToEven( NonNegativeInteger const& ) const;
template Decimal Decimal::roundHalfToEven( NonPositiveInteger const& ) const;
template Decimal Decimal::roundHalfToEven( PositiveInteger const& ) const;
Decimal::value_type Decimal::roundHalfToEven2( value_type const &v,
value_type const &precision ) {
if ( precision < -round_precision_limit )
return roundHalfToEven2( v, -round_precision_limit );
if ( precision > round_precision_limit )
return roundHalfToEven2( v, round_precision_limit );
value_type const exp( value_type(10).pow( precision ) );
value_type result( v * exp );
bool const aHalfVal = (result - MAPM::get0_5()) == result.floor();
result += MAPM::get0_5();
result = result.floor();
if ( aHalfVal && result.is_odd() )
--result;
result /= exp;
return result;
}
////////// miscellaneous //////////////////////////////////////////////////////
size_t Decimal::alloc_size() const {
return value_.significant_digits();
}
uint32_t Decimal::hash( value_type const &value ) {
char buf[1024];
char *bufp = value.exponent() + 3 > 1024 ?
new char[ value.exponent() + 3 ] : buf;
if ( value.sign() < 0 ) {
if ( value >= MAPM::getMinInt64() ) {
// hash it as int64
value.toIntegerString( bufp );
stringstream ss( bufp );
int64_t n;
ss >> n;
assert( ss.eof() );
if ( bufp != buf )
delete[] bufp;
return static_cast<uint32_t>( n & 0xFFFFFFFF );
}
} else if ( value <= MAPM::getMaxUInt64() ) {
// hash it as uint64
value.toIntegerString( bufp );
stringstream ss( bufp );
uint64_t n;
ss >> n;
assert( ss.eof() );
if ( bufp != buf )
delete[] bufp;
return static_cast<uint32_t>( n & 0xFFFFFFFF );
}
// In all other cases, hash it as double
value.toFixPtString( bufp, ZORBA_FLOAT_POINT_PRECISION );
stringstream ss( bufp );
double n;
ss >> n;
assert( ss.eof() );
if ( bufp != buf )
delete[] bufp;
return static_cast<uint32_t>( n );
}
zstring Decimal::toString( value_type const &value, bool minusZero,
int precision ) {
char buf[ 2048 ];
if ( minusZero ) {
if ( value.sign() == 0 )
buf[0] = '-';
else
minusZero = false;
}
value.toFixPtString( buf + minusZero, precision );
//
// Note that in the canonical representation, the decimal point is required
// and there must be at least one digit to the right and one digit to the
// left of the decimal point (which may be 0).
//
if ( strchr( buf, '.' ) != 0 ) {
// remove trailing 0's
char *last = buf + strlen( buf );
while ( *--last == '0' )
*last = '\0';
if ( *last == '.' ) // remove '.' if no digits after it
*last = '\0';
}
if ( precision < ZORBA_FLOAT_POINT_PRECISION )
reduce( buf );
return buf;
}
///////////////////////////////////////////////////////////////////////////////
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|> |
<commit_before>// MenuItem.hh for FbTk - Fluxbox Toolkit
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// 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.
// $Id: MenuItem.hh,v 1.1 2003/01/12 17:06:07 fluxgen Exp $
#ifndef FBTK_MENUITEM_HH
#define FBTK_MENUITEM_HH
#include "RefCount.hh"
#include "Command.hh"
#include <string>
namespace FbTk {
class Menu;
/// An interface for a menu item in Menu
class MenuItem {
public:
MenuItem(
const char *label)
: m_label(label ? label : ""),
m_submenu(0),
m_enabled(true),
m_selected(false)
{ }
/// create a menu item with a specific command to be executed on click
MenuItem(const char *label, RefCount<Command> &cmd):
m_label(label ? label : ""),
m_submenu(0),
m_command(cmd),
m_enabled(true),
m_selected(false) {
}
MenuItem(const char *label, Menu *submenu)
: m_label(label ? label : "")
, m_submenu(submenu)
, m_enabled(true)
, m_selected(false)
{ }
virtual ~MenuItem() { }
virtual void setSelected(bool selected) { m_selected = selected; }
virtual void setEnabled(bool enabled) { m_enabled = enabled; }
virtual void setLabel(const char *label) { m_label = (label ? label : ""); }
Menu *submenu() { return m_submenu; }
/**
@name accessors
*/
//@{
virtual const std::string &label() const { return m_label; }
const Menu *submenu() const { return m_submenu; }
virtual bool isEnabled() const { return m_enabled; }
virtual bool isSelected() const { return m_selected; }
/**
Called when the item was clicked with a specific button
@param button the button number
@param time the time stamp
*/
virtual void click(int button, int time);
RefCount<Command> &command() { return m_command; }
const RefCount<Command> &command() const { return m_command; }
//@}
private:
std::string m_label; ///< label of this item
Menu *m_submenu; ///< a submenu, 0 if we don't have one
RefCount<Command> m_command; ///< command to be executed
bool m_enabled, m_selected;
};
};// end namespace FbTk
#endif // FBTK_MENUITEM_HH
<commit_msg>we might want to change command once the object is created<commit_after>// MenuItem.hh for FbTk - Fluxbox Toolkit
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// 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.
// $Id: MenuItem.hh,v 1.2 2003/02/17 12:28:06 fluxgen Exp $
#ifndef FBTK_MENUITEM_HH
#define FBTK_MENUITEM_HH
#include "RefCount.hh"
#include "Command.hh"
#include <string>
namespace FbTk {
class Menu;
/// An interface for a menu item in Menu
class MenuItem {
public:
MenuItem(
const char *label)
: m_label(label ? label : ""),
m_submenu(0),
m_enabled(true),
m_selected(false)
{ }
/// create a menu item with a specific command to be executed on click
MenuItem(const char *label, RefCount<Command> &cmd):
m_label(label ? label : ""),
m_submenu(0),
m_command(cmd),
m_enabled(true),
m_selected(false) {
}
MenuItem(const char *label, Menu *submenu)
: m_label(label ? label : "")
, m_submenu(submenu)
, m_enabled(true)
, m_selected(false)
{ }
virtual ~MenuItem() { }
void setCommand(RefCount<Command> &cmd) { m_command = cmd; }
virtual void setSelected(bool selected) { m_selected = selected; }
virtual void setEnabled(bool enabled) { m_enabled = enabled; }
virtual void setLabel(const char *label) { m_label = (label ? label : ""); }
Menu *submenu() { return m_submenu; }
/**
@name accessors
*/
//@{
virtual const std::string &label() const { return m_label; }
const Menu *submenu() const { return m_submenu; }
virtual bool isEnabled() const { return m_enabled; }
virtual bool isSelected() const { return m_selected; }
/**
Called when the item was clicked with a specific button
@param button the button number
@param time the time stamp
*/
virtual void click(int button, int time);
RefCount<Command> &command() { return m_command; }
const RefCount<Command> &command() const { return m_command; }
//@}
private:
std::string m_label; ///< label of this item
Menu *m_submenu; ///< a submenu, 0 if we don't have one
RefCount<Command> m_command; ///< command to be executed
bool m_enabled, m_selected;
};
};// end namespace FbTk
#endif // FBTK_MENUITEM_HH
<|endoftext|> |
<commit_before>/*
* FileAppender.cpp
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "log4cpp/Portability.hh"
#include "log4cpp/OstringStream.hh"
#ifdef LOG4CPP_HAVE_IO_H
# include <io.h>
#endif
#ifdef LOG4CPP_HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log4cpp/FileAppender.hh"
#include "log4cpp/Category.hh"
namespace log4cpp {
FileAppender::FileAppender(const std::string& name,
const std::string& fileName) :
LayoutAppender(name),
_fileName(fileName) {
_fd = ::open(_fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 00644);
}
FileAppender::FileAppender(const std::string& name, int fd) :
LayoutAppender(name),
_fileName(""),
_fd(fd) {
}
FileAppender::~FileAppender() {
close();
}
void FileAppender::close() {
::close(_fd);
}
void FileAppender::_append(const LoggingEvent& event) {
std::string message(_getLayout().format(event));
if (!::write(_fd, message.data(), message.length())) {
// XXX help! help!
}
}
bool FileAppender::reopen() {
if (_fileName != "") {
int fd = ::open(_fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 00644);
if (fd < 0)
return false;
else {
int oldfd = _fd;
_fd = fd;
::close(oldfd);
return true;
}
} else {
return true;
}
}
}
<commit_msg>Add some OpenVMS specific parameters when opening a file. The changes allow other users to perform a type/continuous on the log file, a unix equivalent of tail -f.<commit_after>/*
* FileAppender.cpp
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "log4cpp/Portability.hh"
#include "log4cpp/OstringStream.hh"
#ifdef LOG4CPP_HAVE_IO_H
# include <io.h>
#endif
#ifdef LOG4CPP_HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log4cpp/FileAppender.hh"
#include "log4cpp/Category.hh"
namespace log4cpp {
FileAppender::FileAppender(const std::string& name,
const std::string& fileName) :
LayoutAppender(name),
_fileName(fileName) {
#if defined(__OPENVMS__)
// shr=get, File Sharing Options, Allow users to read
// ctx=rec, Force record mode access
// rop=rea, Record-processing options, Locks record for a read operation for this process, while allowing other accessors to read the record.
_fd = ::open(_fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 00644, "shr=get","ctx=rec","rop=rea");
#else
_fd = ::open(_fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 00644);
#endif
}
FileAppender::FileAppender(const std::string& name, int fd) :
LayoutAppender(name),
_fileName(""),
_fd(fd) {
}
FileAppender::~FileAppender() {
close();
}
void FileAppender::close() {
::close(_fd);
}
void FileAppender::_append(const LoggingEvent& event) {
std::string message(_getLayout().format(event));
if (!::write(_fd, message.data(), message.length())) {
// XXX help! help!
}
}
bool FileAppender::reopen() {
if (_fileName != "") {
int fd = ::open(_fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 00644);
if (fd < 0)
return false;
else {
int oldfd = _fd;
_fd = fd;
::close(oldfd);
return true;
}
} else {
return true;
}
}
}
<|endoftext|> |
<commit_before>// tOleInPlaceSite.cpp: implementation of the tOleInPlaceSite class.
//
//////////////////////////////////////////////////////////////////////
#include "tOleInPlaceSite.h"
#include "tOleHandler.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BOOL g_fSwitchingActive=FALSE;
/*
* tOleInPlaceSite::tOleInPlaceSite
* tOleInPlaceSite::~tOleInPlaceSite
*
* Parameters (Constructor):
* pTen PCTenant of the tenant we're in.
* pUnkOuter LPUNKNOWN to which we delegate.
*/
tOleInPlaceSite::tOleInPlaceSite(class tOleHandler *pTen
, LPUNKNOWN pUnkOuter)
{
m_cRef=0;
m_pTen=pTen;
m_pUnkOuter=pUnkOuter;
m_oleinplaceframe = new tOleInPlaceFrame(m_pTen->m_hWnd);
return;
}
tOleInPlaceSite::~tOleInPlaceSite(void)
{
return;
}
/*
* tOleInPlaceSite::QueryInterface
* tOleInPlaceSite::AddRef
* tOleInPlaceSite::Release
*
* Purpose:
* IUnknown members for tOleInPlaceSite object.
*/
STDMETHODIMP tOleInPlaceSite::QueryInterface(REFIID riid
, LPVOID *ppv)
{
return m_pUnkOuter->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::AddRef(void)
{
++m_cRef;
return m_pUnkOuter->AddRef();
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::Release(void)
{
--m_cRef;
return m_pUnkOuter->Release();
}
/*
* tOleInPlaceActiveObject::GetWindow
*
* Purpose:
* Retrieves the handle of the window associated with the object
* on which this interface is implemented.
*
* Parameters:
* phWnd HWND * in which to store the window handle.
*
* Return Value:
* HRESULT NOERROR if successful, E_FAIL if there is no
* window.
*/
STDMETHODIMP tOleInPlaceSite::GetWindow(HWND *phWnd)
{
*phWnd=m_pTen->m_hWnd;
return NOERROR;
}
/*
* tOleInPlaceActiveObject::ContextSensitiveHelp
*
* Purpose:
* Instructs the object on which this interface is implemented to
* enter or leave a context-sensitive help mode.
*
* Parameters:
* fEnterMode BOOL TRUE to enter the mode, FALSE otherwise.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::ContextSensitiveHelp
(BOOL fEnterMode)
{
return E_NOTIMPL;
}
/*
* tOleInPlaceSite::CanInPlaceActivate
*
* Purpose:
* Answers the server whether or not we can currently in-place
* activate its object. By implementing this interface we say
* that we support in-place activation, but through this function
* we indicate whether the object can currently be activated
* in-place. Iconic aspects, for example, cannot, meaning we
* return S_FALSE.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR if we can in-place activate the object
* in this site, S_FALSE if not.
*/
STDMETHODIMP tOleInPlaceSite::CanInPlaceActivate(void)
{
if (DVASPECT_CONTENT!=m_pTen->m_fe.dwAspect)
return ResultFromScode(S_FALSE);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceActivate
*
* Purpose:
* Informs the container that an object is being activated in-place
* such that the container can prepare appropriately. The
* container does not, however, make any user interface changes at
* this point. See OnUIActivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
//m_pIOleIPObject is our in-place flag.
m_pTen->m_pObj->QueryInterface(IID_IOleInPlaceObject
, (PPVOID)&m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceDeactivate
*
* Purpose:
* Notifies the container that the object has deactivated itself
* from an in-place state. Opposite of OnInPlaceActivate. The
* container does not change any UI at this point.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceDeactivate(void)
{
/*
* Since we don't have an Undo command, we can tell the object
* right away to discard its Undo state.
*/
m_pTen->Activate(OLEIVERB_DISCARDUNDOSTATE, NULL);
ReleaseInterface(m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIActivate
*
* Purpose:
* Informs the container that the object is going to start munging
* around with user interface, like replacing the menu. The
* container should remove any relevant UI in preparation.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
/*
* Change the currently selected tenant in the page. This
* will UIDeactivate the currently UI Active tenant.
*/
g_fSwitchingActive=TRUE;
//m_pTen->m_pPG->m_pPageCur->SwitchActiveTenant(m_pTen);
g_fSwitchingActive=FALSE;
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIDeactivate
*
* Purpose:
* Informs the container that the object is deactivating its
* in-place user interface at which time the container may
* reinstate its own. Opposite of OnUIActivate.
*
* Parameters:
* fUndoable BOOL indicating if the object will actually
* perform an Undo if the container calls
* ReactivateAndUndo.
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIDeactivate(BOOL fUndoable)
{
MSG msg;
/*
* Ignore this notification if we're switching between
* multiple active objects.
*/
if (g_fSwitchingActive)
return NOERROR;
//If in shutdown (NULL storage), don't check messages.
/* if (NULL==m_pTen->m_pIStorage)
{
g_pFR->ReinstateUI();
return NOERROR;
}*/
//If there's a pending double-click, delay showing our UI
/* if (!PeekMessage(&msg, pDoc->Window(), WM_LBUTTONDBLCLK
, WM_LBUTTONDBLCLK, PM_NOREMOVE | PM_NOYIELD))
{
//Turn everything back on.
g_pFR->ReinstateUI();
}
else*/
return NOERROR;
}
/*
* tOleInPlaceSite::DeactivateAndUndo
*
* Purpose:
* If immediately after activation the object does an Undo, the
* action being undone is the activation itself, and this call
* informs the container that this is, in fact, what happened.
* The container should call IOleInPlaceObject::UIDeactivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DeactivateAndUndo(void)
{
//CHAPTER24MOD
/*
* Note that we don't pay attention to the locking
* from IOleControlSite::LockInPlaceActive since only
* the object calls this function and should know
* that it's going to be deactivated.
*/
//End CHAPTER24MOD
m_pTen->m_pIOleIPObject->InPlaceDeactivate();
return NOERROR;
}
/*
* tOleInPlaceSite::DiscardUndoState
*
* Purpose:
* Informs the container that something happened in the object
* that means the container should discard any undo information
* it currently maintains for the object.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DiscardUndoState(void)
{
return ResultFromScode(E_NOTIMPL);
}
/*
* tOleInPlaceSite::GetWindowContext
*
* Purpose:
* Provides an in-place object with pointers to the frame and
* document level in-place interfaces (IOleInPlaceFrame and
* IOleInPlaceUIWindow) such that the object can do border
* negotiation and so forth. Also requests the position and
* clipping rectangles of the object in the container and a
* pointer to an OLEINPLACEFRAME info structure which contains
* accelerator information.
*
* Note that the two interfaces this call returns are not
* available through QueryInterface on IOleInPlaceSite since they
* live with the frame and document, but not the site.
*
* Parameters:
* ppIIPFrame LPOLEINPLACEFRAME * in which to return the
* AddRef'd pointer to the container's
* IOleInPlaceFrame.
* ppIIPUIWindow LPOLEINPLACEUIWINDOW * in which to return
* the AddRef'd pointer to the container document's
* IOleInPlaceUIWindow.
* prcPos LPRECT in which to store the object's position.
* prcClip LPRECT in which to store the object's visible
* region.
* pFI LPOLEINPLACEFRAMEINFO to fill with accelerator
* stuff.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::GetWindowContext
(LPOLEINPLACEFRAME *ppIIPFrame, LPOLEINPLACEUIWINDOW
*ppIIPUIWindow, LPRECT prcPos, LPRECT prcClip
, LPOLEINPLACEFRAMEINFO pFI)
{
RECTL rcl;
*ppIIPUIWindow=NULL;
*ppIIPFrame=m_oleinplaceframe;
m_oleinplaceframe->AddRef();
GetClientRect(m_pTen->m_hWnd, prcPos);
GetClientRect(m_pTen->m_hWnd, prcClip);
/* *ppIIPFrame=(LPOLEINPLACEFRAME)g_pFR;
g_pFR->AddRef();*/
/* if (NULL!=pDoc)
{
pDoc->QueryInterface(IID_IOleInPlaceUIWindow
, (PPVOID)ppIIPUIWindow);
}*/
//Now get the rectangles and frame information.
/*m_pTen->RectGet(&rcl, TRUE);
RECTFROMRECTL(*prcPos, rcl);
0
//Include scroll position here.
OffsetRect(prcPos, -(int)m_pTen->m_pPG->m_xPos
, -(int)m_pTen->m_pPG->m_yPos);
SetRect(prcClip, 0, 0, 32767, 32767);
*/
pFI->cb=sizeof(OLEINPLACEFRAMEINFO);
pFI->fMDIApp=FALSE;
pFI->hwndFrame=m_pTen->m_hWnd;
pFI->haccel=NULL;
pFI->cAccelEntries=0;
return NOERROR;
}
/*
* tOleInPlaceSite::Scroll
*
* Purpose:
* Asks the container to scroll the document, and thus the object,
* by the given amounts in the sz parameter.
*
* Parameters:
* sz SIZE containing signed horizontal and vertical
* extents by which the container should scroll.
* These are in device units.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::Scroll(SIZE sz)
{
/*int x, y;
x=m_pTen->m_pPG->m_xPos+sz.cx;
y=m_pTen->m_pPG->m_yPos+sz.cy;
SendScrollPosition(m_pTen->m_hWnd, WM_HSCROLL, x);
SendScrollPosition(m_pTen->m_hWnd, WM_VSCROLL, y);*/
return NOERROR;
}
/*
* tOleInPlaceSite::OnPosRectChange
*
* Purpose:
* Informs the container that the in-place object was resized.
* The container must call IOleInPlaceObject::SetObjectRects.
* This does not change the site's rectangle in any case.
*
* Parameters:
* prcPos LPCRECT containing the new size of the object.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::OnPosRectChange(LPCRECT prcPos)
{
if (NULL!=prcPos)
m_pTen->m_rcPos=*prcPos;
m_pTen->UpdateInPlaceObjectRects(prcPos, FALSE);
return NOERROR;
}
<commit_msg>Fixed: object position in IupOleControl.<commit_after>// tOleInPlaceSite.cpp: implementation of the tOleInPlaceSite class.
//
//////////////////////////////////////////////////////////////////////
#include "tOleInPlaceSite.h"
#include "tOleHandler.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BOOL g_fSwitchingActive=FALSE;
/*
* tOleInPlaceSite::tOleInPlaceSite
* tOleInPlaceSite::~tOleInPlaceSite
*
* Parameters (Constructor):
* pTen PCTenant of the tenant we're in.
* pUnkOuter LPUNKNOWN to which we delegate.
*/
tOleInPlaceSite::tOleInPlaceSite(class tOleHandler *pTen
, LPUNKNOWN pUnkOuter)
{
m_cRef=0;
m_pTen=pTen;
m_pUnkOuter=pUnkOuter;
m_oleinplaceframe = new tOleInPlaceFrame(m_pTen->m_hWnd);
return;
}
tOleInPlaceSite::~tOleInPlaceSite(void)
{
return;
}
/*
* tOleInPlaceSite::QueryInterface
* tOleInPlaceSite::AddRef
* tOleInPlaceSite::Release
*
* Purpose:
* IUnknown members for tOleInPlaceSite object.
*/
STDMETHODIMP tOleInPlaceSite::QueryInterface(REFIID riid
, LPVOID *ppv)
{
return m_pUnkOuter->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::AddRef(void)
{
++m_cRef;
return m_pUnkOuter->AddRef();
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::Release(void)
{
--m_cRef;
return m_pUnkOuter->Release();
}
/*
* tOleInPlaceActiveObject::GetWindow
*
* Purpose:
* Retrieves the handle of the window associated with the object
* on which this interface is implemented.
*
* Parameters:
* phWnd HWND * in which to store the window handle.
*
* Return Value:
* HRESULT NOERROR if successful, E_FAIL if there is no
* window.
*/
STDMETHODIMP tOleInPlaceSite::GetWindow(HWND *phWnd)
{
*phWnd=m_pTen->m_hWnd;
return NOERROR;
}
/*
* tOleInPlaceActiveObject::ContextSensitiveHelp
*
* Purpose:
* Instructs the object on which this interface is implemented to
* enter or leave a context-sensitive help mode.
*
* Parameters:
* fEnterMode BOOL TRUE to enter the mode, FALSE otherwise.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::ContextSensitiveHelp
(BOOL fEnterMode)
{
return E_NOTIMPL;
}
/*
* tOleInPlaceSite::CanInPlaceActivate
*
* Purpose:
* Answers the server whether or not we can currently in-place
* activate its object. By implementing this interface we say
* that we support in-place activation, but through this function
* we indicate whether the object can currently be activated
* in-place. Iconic aspects, for example, cannot, meaning we
* return S_FALSE.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR if we can in-place activate the object
* in this site, S_FALSE if not.
*/
STDMETHODIMP tOleInPlaceSite::CanInPlaceActivate(void)
{
if (DVASPECT_CONTENT!=m_pTen->m_fe.dwAspect)
return ResultFromScode(S_FALSE);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceActivate
*
* Purpose:
* Informs the container that an object is being activated in-place
* such that the container can prepare appropriately. The
* container does not, however, make any user interface changes at
* this point. See OnUIActivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
//m_pIOleIPObject is our in-place flag.
m_pTen->m_pObj->QueryInterface(IID_IOleInPlaceObject
, (PPVOID)&m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceDeactivate
*
* Purpose:
* Notifies the container that the object has deactivated itself
* from an in-place state. Opposite of OnInPlaceActivate. The
* container does not change any UI at this point.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceDeactivate(void)
{
/*
* Since we don't have an Undo command, we can tell the object
* right away to discard its Undo state.
*/
m_pTen->Activate(OLEIVERB_DISCARDUNDOSTATE, NULL);
ReleaseInterface(m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIActivate
*
* Purpose:
* Informs the container that the object is going to start munging
* around with user interface, like replacing the menu. The
* container should remove any relevant UI in preparation.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
/*
* Change the currently selected tenant in the page. This
* will UIDeactivate the currently UI Active tenant.
*/
g_fSwitchingActive=TRUE;
//m_pTen->m_pPG->m_pPageCur->SwitchActiveTenant(m_pTen);
g_fSwitchingActive=FALSE;
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIDeactivate
*
* Purpose:
* Informs the container that the object is deactivating its
* in-place user interface at which time the container may
* reinstate its own. Opposite of OnUIActivate.
*
* Parameters:
* fUndoable BOOL indicating if the object will actually
* perform an Undo if the container calls
* ReactivateAndUndo.
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIDeactivate(BOOL fUndoable)
{
MSG msg;
/*
* Ignore this notification if we're switching between
* multiple active objects.
*/
if (g_fSwitchingActive)
return NOERROR;
//If in shutdown (NULL storage), don't check messages.
/* if (NULL==m_pTen->m_pIStorage)
{
g_pFR->ReinstateUI();
return NOERROR;
}*/
//If there's a pending double-click, delay showing our UI
/* if (!PeekMessage(&msg, pDoc->Window(), WM_LBUTTONDBLCLK
, WM_LBUTTONDBLCLK, PM_NOREMOVE | PM_NOYIELD))
{
//Turn everything back on.
g_pFR->ReinstateUI();
}
else*/
return NOERROR;
}
/*
* tOleInPlaceSite::DeactivateAndUndo
*
* Purpose:
* If immediately after activation the object does an Undo, the
* action being undone is the activation itself, and this call
* informs the container that this is, in fact, what happened.
* The container should call IOleInPlaceObject::UIDeactivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DeactivateAndUndo(void)
{
//CHAPTER24MOD
/*
* Note that we don't pay attention to the locking
* from IOleControlSite::LockInPlaceActive since only
* the object calls this function and should know
* that it's going to be deactivated.
*/
//End CHAPTER24MOD
m_pTen->m_pIOleIPObject->InPlaceDeactivate();
return NOERROR;
}
/*
* tOleInPlaceSite::DiscardUndoState
*
* Purpose:
* Informs the container that something happened in the object
* that means the container should discard any undo information
* it currently maintains for the object.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DiscardUndoState(void)
{
return ResultFromScode(E_NOTIMPL);
}
/*
* tOleInPlaceSite::GetWindowContext
*
* Purpose:
* Provides an in-place object with pointers to the frame and
* document level in-place interfaces (IOleInPlaceFrame and
* IOleInPlaceUIWindow) such that the object can do border
* negotiation and so forth. Also requests the position and
* clipping rectangles of the object in the container and a
* pointer to an OLEINPLACEFRAME info structure which contains
* accelerator information.
*
* Note that the two interfaces this call returns are not
* available through QueryInterface on IOleInPlaceSite since they
* live with the frame and document, but not the site.
*
* Parameters:
* ppIIPFrame LPOLEINPLACEFRAME * in which to return the
* AddRef'd pointer to the container's
* IOleInPlaceFrame.
* ppIIPUIWindow LPOLEINPLACEUIWINDOW * in which to return
* the AddRef'd pointer to the container document's
* IOleInPlaceUIWindow.
* prcPos LPRECT in which to store the object's position.
* prcClip LPRECT in which to store the object's visible
* region.
* pFI LPOLEINPLACEFRAMEINFO to fill with accelerator
* stuff.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::GetWindowContext
(LPOLEINPLACEFRAME *ppIIPFrame, LPOLEINPLACEUIWINDOW
*ppIIPUIWindow, LPRECT prcPos, LPRECT prcClip
, LPOLEINPLACEFRAMEINFO pFI)
{
RECTL rcl;
*ppIIPUIWindow=NULL;
*ppIIPFrame=m_oleinplaceframe;
m_oleinplaceframe->AddRef();
GetClientRect(m_pTen->m_hWnd, prcPos);
GetClientRect(m_pTen->m_hWnd, prcClip);
/* *ppIIPFrame=(LPOLEINPLACEFRAME)g_pFR;
g_pFR->AddRef();*/
/* if (NULL!=pDoc)
{
pDoc->QueryInterface(IID_IOleInPlaceUIWindow
, (PPVOID)ppIIPUIWindow);
}*/
//Now get the rectangles and frame information.
/*m_pTen->RectGet(&rcl, TRUE);
RECTFROMRECTL(*prcPos, rcl);
0
//Include scroll position here.
OffsetRect(prcPos, -(int)m_pTen->m_pPG->m_xPos
, -(int)m_pTen->m_pPG->m_yPos);
SetRect(prcClip, 0, 0, 32767, 32767);
*/
pFI->cb=sizeof(OLEINPLACEFRAMEINFO);
pFI->fMDIApp=FALSE;
pFI->hwndFrame=m_pTen->m_hWnd;
pFI->haccel=NULL;
pFI->cAccelEntries=0;
return NOERROR;
}
/*
* tOleInPlaceSite::Scroll
*
* Purpose:
* Asks the container to scroll the document, and thus the object,
* by the given amounts in the sz parameter.
*
* Parameters:
* sz SIZE containing signed horizontal and vertical
* extents by which the container should scroll.
* These are in device units.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::Scroll(SIZE sz)
{
/*int x, y;
x=m_pTen->m_pPG->m_xPos+sz.cx;
y=m_pTen->m_pPG->m_yPos+sz.cy;
SendScrollPosition(m_pTen->m_hWnd, WM_HSCROLL, x);
SendScrollPosition(m_pTen->m_hWnd, WM_VSCROLL, y);*/
return NOERROR;
}
/*
* tOleInPlaceSite::OnPosRectChange
*
* Purpose:
* Informs the container that the in-place object was resized.
* The container must call IOleInPlaceObject::SetObjectRects.
* This does not change the site's rectangle in any case.
*
* Parameters:
* prcPos LPCRECT containing the new size of the object.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::OnPosRectChange(LPCRECT prcPos)
{
if (NULL!=prcPos)
{
// This change was necessary because some controls were not working, and being positioned in a wrong place.
// Contribution by Kommit
LPRECT pPos = (LPRECT)prcPos; // convert the const pointer to non-const pointer to modify it's member values.
pPos->right -= pPos->left;
pPos->bottom -= pPos->top;
pPos->left = 0;
pPos->top = 0;
m_pTen->m_rcPos=*prcPos;
}
m_pTen->UpdateInPlaceObjectRects(prcPos, FALSE);
return NOERROR;
}
<|endoftext|> |
<commit_before>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "Datastore.h"
#include "GroupPool.h"
#include "NebulaLog.h"
const char * Datastore::table = "datastore_pool";
const char * Datastore::db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * Datastore::db_bootstrap =
"CREATE TABLE IF NOT EXISTS datastore_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ************************************************************************ */
/* Datastore :: Constructor/Destructor */
/* ************************************************************************ */
Datastore::Datastore(int id,
DatastoreTemplate* ds_template):
PoolObjectSQL(id,DATASTORE,"",-1,-1,"","",table),
ObjectCollection("IMAGES"),
type(""),
base_path("")
{
if (ds_template != 0)
{
obj_template = ds_template;
}
else
{
obj_template = new DatastoreTemplate;
}
}
/* ************************************************************************ */
/* Datastore :: Database Access Functions */
/* ************************************************************************ */
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Datastore::insert(SqlDB *db, string& error_str)
{
int rc;
// ---------------------------------------------------------------------
// Check default datastore attributes
// ---------------------------------------------------------------------
erase_template_attribute("NAME", name);
// NAME is checked in DatastorePool::allocate
erase_template_attribute("TYPE", type);
if ( type.empty() == true )
{
goto error_type;
}
erase_template_attribute("BASE_PATH", base_path);
if ( base_path.empty() == true )
{
goto error_base_path;
}
//--------------------------------------------------------------------------
// Insert the Datastore
//--------------------------------------------------------------------------
rc = insert_replace(db, false, error_str);
return rc;
error_type:
error_str = "No NAME in template.";
goto error_common;
error_base_path:
error_str = "No BASE_PATH in template.";
goto error_common;
error_common:
NebulaLog::log("DATASTORE", Log::ERROR, error_str);
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Datastore::insert_replace(SqlDB *db, bool replace, string& error_str)
{
ostringstream oss;
int rc;
string xml_body;
char * sql_name;
char * sql_xml;
// Set the owner and group to oneadmin
set_user(0, "");
set_group(GroupPool::ONEADMIN_ID, GroupPool::ONEADMIN_NAME);
// Update the Datastore
sql_name = db->escape_str(name.c_str());
if ( sql_name == 0 )
{
goto error_name;
}
sql_xml = db->escape_str(to_xml(xml_body).c_str());
if ( sql_xml == 0 )
{
goto error_body;
}
if ( validate_xml(sql_xml) != 0 )
{
goto error_xml;
}
if ( replace )
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<<table <<" ("<< db_names <<") VALUES ("
<< oid << ","
<< "'" << sql_name << "',"
<< "'" << sql_xml << "',"
<< uid << ","
<< gid << ","
<< owner_u << ","
<< group_u << ","
<< other_u << ")";
rc = db->exec(oss);
db->free_str(sql_name);
db->free_str(sql_xml);
return rc;
error_xml:
db->free_str(sql_name);
db->free_str(sql_xml);
error_str = "Error transforming the Datastore to XML.";
goto error_common;
error_body:
db->free_str(sql_name);
goto error_generic;
error_name:
goto error_generic;
error_generic:
error_str = "Error inserting Datastore in DB.";
error_common:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Datastore::to_xml(string& xml) const
{
ostringstream oss;
string collection_xml;
ObjectCollection::to_xml(collection_xml);
oss <<
"<DATASTORE>" <<
"<ID>" << oid << "</ID>" <<
"<NAME>" << name << "</NAME>" <<
"<TYPE>" << type << "</TYPE>" <<
"<BASE_PATH>" << base_path << "</BASE_PATH>" <<
collection_xml <<
"</DATASTORE>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Datastore::from_xml(const string& xml)
{
int rc = 0;
vector<xmlNodePtr> content;
// Initialize the internal XML object
update_from_str(xml);
// Get class base attributes
rc += xpath(oid, "/DATASTORE/ID", -1);
rc += xpath(name, "/DATASTORE/NAME", "not_found");
rc += xpath(type, "/DATASTORE/TYPE", "not_found");
rc += xpath(base_path, "/DATASTORE/BASE_PATH", "not_found");
// Set the owner and group to oneadmin
set_user(0, "");
set_group(GroupPool::ONEADMIN_ID, GroupPool::ONEADMIN_NAME);
// Get associated classes
ObjectXML::get_nodes("/DATASTORE/IMAGES", content);
if (content.empty())
{
return -1;
}
// Set of IDs
rc += ObjectCollection::from_xml_node(content[0]);
ObjectXML::free_nodes(content);
if (rc != 0)
{
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
<commit_msg>Feature #1112: Fix error message for missing TYPE in datastore creation<commit_after>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "Datastore.h"
#include "GroupPool.h"
#include "NebulaLog.h"
const char * Datastore::table = "datastore_pool";
const char * Datastore::db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * Datastore::db_bootstrap =
"CREATE TABLE IF NOT EXISTS datastore_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ************************************************************************ */
/* Datastore :: Constructor/Destructor */
/* ************************************************************************ */
Datastore::Datastore(int id,
DatastoreTemplate* ds_template):
PoolObjectSQL(id,DATASTORE,"",-1,-1,"","",table),
ObjectCollection("IMAGES"),
type(""),
base_path("")
{
if (ds_template != 0)
{
obj_template = ds_template;
}
else
{
obj_template = new DatastoreTemplate;
}
}
/* ************************************************************************ */
/* Datastore :: Database Access Functions */
/* ************************************************************************ */
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Datastore::insert(SqlDB *db, string& error_str)
{
int rc;
// ---------------------------------------------------------------------
// Check default datastore attributes
// ---------------------------------------------------------------------
erase_template_attribute("NAME", name);
// NAME is checked in DatastorePool::allocate
erase_template_attribute("TYPE", type);
if ( type.empty() == true )
{
goto error_type;
}
erase_template_attribute("BASE_PATH", base_path);
if ( base_path.empty() == true )
{
goto error_base_path;
}
//--------------------------------------------------------------------------
// Insert the Datastore
//--------------------------------------------------------------------------
rc = insert_replace(db, false, error_str);
return rc;
error_type:
error_str = "No TYPE in template.";
goto error_common;
error_base_path:
error_str = "No BASE_PATH in template.";
goto error_common;
error_common:
NebulaLog::log("DATASTORE", Log::ERROR, error_str);
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Datastore::insert_replace(SqlDB *db, bool replace, string& error_str)
{
ostringstream oss;
int rc;
string xml_body;
char * sql_name;
char * sql_xml;
// Set the owner and group to oneadmin
set_user(0, "");
set_group(GroupPool::ONEADMIN_ID, GroupPool::ONEADMIN_NAME);
// Update the Datastore
sql_name = db->escape_str(name.c_str());
if ( sql_name == 0 )
{
goto error_name;
}
sql_xml = db->escape_str(to_xml(xml_body).c_str());
if ( sql_xml == 0 )
{
goto error_body;
}
if ( validate_xml(sql_xml) != 0 )
{
goto error_xml;
}
if ( replace )
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<<table <<" ("<< db_names <<") VALUES ("
<< oid << ","
<< "'" << sql_name << "',"
<< "'" << sql_xml << "',"
<< uid << ","
<< gid << ","
<< owner_u << ","
<< group_u << ","
<< other_u << ")";
rc = db->exec(oss);
db->free_str(sql_name);
db->free_str(sql_xml);
return rc;
error_xml:
db->free_str(sql_name);
db->free_str(sql_xml);
error_str = "Error transforming the Datastore to XML.";
goto error_common;
error_body:
db->free_str(sql_name);
goto error_generic;
error_name:
goto error_generic;
error_generic:
error_str = "Error inserting Datastore in DB.";
error_common:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Datastore::to_xml(string& xml) const
{
ostringstream oss;
string collection_xml;
ObjectCollection::to_xml(collection_xml);
oss <<
"<DATASTORE>" <<
"<ID>" << oid << "</ID>" <<
"<NAME>" << name << "</NAME>" <<
"<TYPE>" << type << "</TYPE>" <<
"<BASE_PATH>" << base_path << "</BASE_PATH>" <<
collection_xml <<
"</DATASTORE>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Datastore::from_xml(const string& xml)
{
int rc = 0;
vector<xmlNodePtr> content;
// Initialize the internal XML object
update_from_str(xml);
// Get class base attributes
rc += xpath(oid, "/DATASTORE/ID", -1);
rc += xpath(name, "/DATASTORE/NAME", "not_found");
rc += xpath(type, "/DATASTORE/TYPE", "not_found");
rc += xpath(base_path, "/DATASTORE/BASE_PATH", "not_found");
// Set the owner and group to oneadmin
set_user(0, "");
set_group(GroupPool::ONEADMIN_ID, GroupPool::ONEADMIN_NAME);
// Get associated classes
ObjectXML::get_nodes("/DATASTORE/IMAGES", content);
if (content.empty())
{
return -1;
}
// Set of IDs
rc += ObjectCollection::from_xml_node(content[0]);
ObjectXML::free_nodes(content);
if (rc != 0)
{
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
<|endoftext|> |
<commit_before>#ifndef SF_BASE_TYPES_HPP_INCLUDED
#define SF_BASE_TYPES_HPP_INCLUDED SF_BASE_TYPES_HPP_INCLUDED
#include <luabind/object.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
typedef sf::Vector2<lua_Number> LuaVec2;
typedef sf::Vector3<lua_Number> LuaVec3;
typedef sf::Rect<lua_Number> LuaRect;
namespace luaSfGeo {
extern char const* const libname;
template <typename T>
struct Traits;
template <>
struct Traits<LuaVec2>
{
static char const* const mtName;
static char const* const expName;
static void const* const mmtKey;
};
template <>
struct Traits<LuaVec3>
{
static char const* const mtName;
static char const* const expName;
static void const* const mmtKey;
};
template <>
struct Traits<LuaRect>
{
static char const* const mtName;
static char const* const expName;
static void const* const mmtKey;
};
template <typename T>
T* to(lua_State* L, int idx)
{
return static_cast<T*>(luaL_checkudata(L, idx, Traits<T>::mtName));
}
template <typename T>
T* optTo(lua_State* L, int idx)
{
return static_cast<T*>(luaL_testudata(L, idx, Traits<T>::mtName));
}
template <typename T>
T* push(lua_State* L, T const& v)
{
T* newvec = static_cast<T*>(
lua_newuserdata(L, sizeof(T)));
new (newvec) T(v);
luaL_setmetatable(L, Traits<T>::mtName);
return newvec;
}
} // namespace luaSfGeo
namespace luabind {
#define CONVERTER(luat, cppt) \
template<typename T> \
struct default_converter<cppt<T>>: \
public native_converter_base<cppt<T>> { \
static int compute_score(lua_State* L, int index) \
{ \
if (luaL_testudata(L, index, luaSfGeo::Traits<luat>::mtName)) \
return 1; \
return -1; \
} \
cppt<T> from(lua_State* L, int index) \
{ \
assert(luaL_testudata(L, index, luaSfGeo::Traits<luat>::mtName)); \
return static_cast<cppt<T>>( \
*static_cast<luat*>(lua_touserdata(L, index))); \
} \
void to(lua_State* L, cppt<T> const& x) \
{ \
luaSfGeo::push<luat>(L, static_cast<luat>(x)); \
} \
}; \
template <typename T> \
struct default_converter<cppt<T> const&> \
: default_converter<cppt<T>> { };
CONVERTER(LuaVec2, sf::Vector2)
CONVERTER(LuaVec3, sf::Vector3)
CONVERTER(LuaRect, sf::Rect)
#undef CONVERTER
// sf::String <-> Lua converter (see luabind/detail/policy.hpp:741)
template <>
struct default_converter<sf::String>
: native_converter_base<sf::String>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TSTRING ? 0 : -1;
}
sf::String from(lua_State* L, int index)
{
return sf::String(lua_tostring(L, index));
}
void to(lua_State* L, sf::String const& value)
{
std::string const s(value);
lua_pushlstring(L, s.data(), s.size());
}
};
template <>
struct default_converter<sf::String const>
: default_converter<sf::String>
{};
template <>
struct default_converter<sf::String const&>
: default_converter<sf::String>
{};
} // namespace luabind
#endif
<commit_msg>Lua <-> sf::String: Assume UTF-8 Lua-Strings.<commit_after>#ifndef SF_BASE_TYPES_HPP_INCLUDED
#define SF_BASE_TYPES_HPP_INCLUDED SF_BASE_TYPES_HPP_INCLUDED
#include <luabind/object.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#include <boost/locale/encoding_utf.hpp>
typedef sf::Vector2<lua_Number> LuaVec2;
typedef sf::Vector3<lua_Number> LuaVec3;
typedef sf::Rect<lua_Number> LuaRect;
namespace luaSfGeo {
extern char const* const libname;
template <typename T>
struct Traits;
template <>
struct Traits<LuaVec2>
{
static char const* const mtName;
static char const* const expName;
static void const* const mmtKey;
};
template <>
struct Traits<LuaVec3>
{
static char const* const mtName;
static char const* const expName;
static void const* const mmtKey;
};
template <>
struct Traits<LuaRect>
{
static char const* const mtName;
static char const* const expName;
static void const* const mmtKey;
};
template <typename T>
T* to(lua_State* L, int idx)
{
return static_cast<T*>(luaL_checkudata(L, idx, Traits<T>::mtName));
}
template <typename T>
T* optTo(lua_State* L, int idx)
{
return static_cast<T*>(luaL_testudata(L, idx, Traits<T>::mtName));
}
template <typename T>
T* push(lua_State* L, T const& v)
{
T* newvec = static_cast<T*>(
lua_newuserdata(L, sizeof(T)));
new (newvec) T(v);
luaL_setmetatable(L, Traits<T>::mtName);
return newvec;
}
} // namespace luaSfGeo
namespace luabind {
#define CONVERTER(luat, cppt) \
template<typename T> \
struct default_converter<cppt<T>>: \
public native_converter_base<cppt<T>> { \
static int compute_score(lua_State* L, int index) \
{ \
if (luaL_testudata(L, index, luaSfGeo::Traits<luat>::mtName)) \
return 1; \
return -1; \
} \
cppt<T> from(lua_State* L, int index) \
{ \
assert(luaL_testudata(L, index, luaSfGeo::Traits<luat>::mtName)); \
return static_cast<cppt<T>>( \
*static_cast<luat*>(lua_touserdata(L, index))); \
} \
void to(lua_State* L, cppt<T> const& x) \
{ \
luaSfGeo::push<luat>(L, static_cast<luat>(x)); \
} \
}; \
template <typename T> \
struct default_converter<cppt<T> const&> \
: default_converter<cppt<T>> { };
CONVERTER(LuaVec2, sf::Vector2)
CONVERTER(LuaVec3, sf::Vector3)
CONVERTER(LuaRect, sf::Rect)
#undef CONVERTER
// sf::String <-> Lua converter (see luabind/detail/policy.hpp:741)
template <>
struct default_converter<sf::String>
: native_converter_base<sf::String>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TSTRING ? 0 : -1;
}
sf::String from(lua_State* L, int index)
{
return sf::String(boost::locale::conv::utf_to_utf<sf::Uint32>(
lua_tostring(L, index)));
}
void to(lua_State* L, sf::String const& value)
{
std::string const s(
boost::locale::conv::utf_to_utf<char>(
value.getData(), value.getData() + value.getSize()));
lua_pushlstring(L, s.data(), s.size());
}
};
template <>
struct default_converter<sf::String const>
: default_converter<sf::String>
{};
template <>
struct default_converter<sf::String const&>
: default_converter<sf::String>
{};
} // namespace luabind
#endif
<|endoftext|> |
<commit_before>%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%
$header
$includes
$beginSlotsClass
$slot=5,1,0|baudRateChanged( qint32 baudRate, QSerialPort::Directions dir )
$slot=5,1,0|dataBitsChanged( QSerialPort::DataBits dataBits )
$slot=5,1,0|parityChanged( QSerialPort::Parity parity )
$slot=5,1,0|stopBitsChanged( QSerialPort::StopBits stopBits )
$slot=5,1,0|flowControlChanged( QSerialPort::FlowControl flow )
$slot=5,1,0|dataErrorPolicyChanged( QSerialPort::DataErrorPolicy policy )
$slot=5,1,0|dataTerminalReadyChanged( bool set )
$slot=5,1,0|requestToSendChanged( bool set )
$slot=5,1,0|error( QSerialPort::SerialPortError serialPortError )
$slot=5,1,0|settingsRestoredOnCloseChanged( bool restore )
$endSlotsClass
<commit_msg>QtSerialPort: data for code generation updated<commit_after>%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%
$header
$includes=5,1,0
$beginSlotsClass
$slot=5,1,0|baudRateChanged( qint32 baudRate, QSerialPort::Directions dir )
$slot=5,1,0|dataBitsChanged( QSerialPort::DataBits dataBits )
$slot=5,1,0|parityChanged( QSerialPort::Parity parity )
$slot=5,1,0|stopBitsChanged( QSerialPort::StopBits stopBits )
$slot=5,1,0|flowControlChanged( QSerialPort::FlowControl flow )
$slot=5,1,0|dataErrorPolicyChanged( QSerialPort::DataErrorPolicy policy )
$slot=5,1,0|dataTerminalReadyChanged( bool set )
$slot=5,1,0|requestToSendChanged( bool set )
$slot=5,1,0|error( QSerialPort::SerialPortError serialPortError )
$slot=5,1,0|settingsRestoredOnCloseChanged( bool restore )
$endSlotsClass
<|endoftext|> |
<commit_before>#include "core/imageops.h"
#include <iostream>
#include "core/image.h"
#include "core/palette.h"
namespace euphoria::core
{
Table<char>
ImageToStringTable(const Image& img, const std::vector<ImageMapAction>& map)
{
auto pal = Palette::Empty("");
for(const auto m: map)
{
pal.colors.push_back(m.from_color);
}
auto ret = Table<char>::FromWidthHeight(
img.GetWidth(), img.GetHeight(), ' ');
ret.SetAll([&pal, &map, &img](int x, int y) {
const auto p = img.GetPixel(x, y);
const auto index = pal.GetIndexClosest(Rgbi {p.r, p.g, p.b});
return map[index].to;
});
return ret;
}
Table<char>
ImageToStringTableExact(
const Image& img,
const std::vector<ImageMapAction>& map, char missing)
{
auto find_match = [&](const Rgbi& c) -> char
{
for(const auto& m: map)
{
if(m.from_color == c)
{
return m.to;
}
}
return missing;
};
auto ret = Table<char>::FromWidthHeight(
img.GetWidth(), img.GetHeight(), ' ');
ret.SetAll([&](int x, int y) {
const auto p = img.GetPixel(x, y);
const auto c = Rgbi {p.r, p.g, p.b};
const auto r = find_match(c);
return r;
});
return ret;
}
Table<char>
ImageToStringTable(const Image& img, bool shorter)
{
auto ret = Table<char>::FromWidthHeight(
img.GetWidth(), img.GetHeight(), ' ');
ret.SetAll([shorter, &img](int x, int y) {
// http://paulbourke.net/dataformats/asciiart/
const std::string characters
= shorter ? " .:-=+*#%@"
: "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
const auto p = 1.0f - rgb(img.GetPixel(x, y)).r;
const auto index = Floori(p * (characters.size() - 1));
return characters[index];
});
return ret;
}
std::vector<std::string>
ToStrings(const Table<char>& table)
{
std::vector<std::string> ret;
for(int r = 0; r < table.Height(); r += 1)
{
std::stringstream ss;
for(int c = 0; c < table.Width(); c += 1)
{
ss << table.Value(c, r);
}
ret.insert(ret.begin(), ss.str());
}
return ret;
}
} // namespace euphoria::core
<commit_msg>added todo<commit_after>#include "core/imageops.h"
#include <iostream>
#include "core/image.h"
#include "core/palette.h"
namespace euphoria::core
{
Table<char>
ImageToStringTable(const Image& img, const std::vector<ImageMapAction>& map)
{
auto pal = Palette::Empty("");
for(const auto m: map)
{
pal.colors.push_back(m.from_color);
}
auto ret = Table<char>::FromWidthHeight(
img.GetWidth(), img.GetHeight(), ' ');
ret.SetAll([&pal, &map, &img](int x, int y) {
const auto p = img.GetPixel(x, y);
const auto index = pal.GetIndexClosest(Rgbi {p.r, p.g, p.b});
return map[index].to;
});
return ret;
}
Table<char>
ImageToStringTableExact(
const Image& img,
const std::vector<ImageMapAction>& map, char missing)
{
auto find_match = [&](const Rgbi& c) -> char
{
for(const auto& m: map)
{
if(m.from_color == c)
{
return m.to;
}
}
return missing;
};
auto ret = Table<char>::FromWidthHeight(
img.GetWidth(), img.GetHeight(), ' ');
ret.SetAll([&](int x, int y) {
const auto p = img.GetPixel(x, y);
const auto c = Rgbi {p.r, p.g, p.b};
const auto r = find_match(c);
return r;
});
return ret;
}
Table<char>
ImageToStringTable(const Image& img, bool shorter)
{
// todo(Gustav): use grayscale function from imagefiler
auto ret = Table<char>::FromWidthHeight(
img.GetWidth(), img.GetHeight(), ' ');
ret.SetAll([shorter, &img](int x, int y) {
// http://paulbourke.net/dataformats/asciiart/
const std::string characters
= shorter ? " .:-=+*#%@"
: "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
const auto p = 1.0f - rgb(img.GetPixel(x, y)).r;
const auto index = Floori(p * (characters.size() - 1));
return characters[index];
});
return ret;
}
std::vector<std::string>
ToStrings(const Table<char>& table)
{
std::vector<std::string> ret;
for(int r = 0; r < table.Height(); r += 1)
{
std::stringstream ss;
for(int c = 0; c < table.Width(); c += 1)
{
ss << table.Value(c, r);
}
ret.insert(ret.begin(), ss.str());
}
return ret;
}
} // namespace euphoria::core
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "LRUCache.hxx"
TEST(LRUCache, InsertPair)
{
LRUCache<int, std::string, 3> cache;
auto pairResult = cache.insert(std::make_pair<int, std::string>(1, "1"));
EXPECT_EQ(std::string("1"), pairResult.first->second->second);
EXPECT_TRUE(pairResult.second);
EXPECT_EQ(1, cache.size());
pairResult = cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_EQ(std::string("2"), pairResult.first->second->second);
EXPECT_TRUE(pairResult.second);
pairResult = cache.insert(std::make_pair<int, std::string>(3, "3"));
EXPECT_EQ(std::string("3"), pairResult.first->second->second);
EXPECT_TRUE(pairResult.second);
EXPECT_EQ(3, cache.size());
// Reaching limit
pairResult = cache.insert(std::make_pair<int, std::string>(4, "4"));
EXPECT_EQ(std::string("4"), pairResult.first->second->second);
EXPECT_TRUE(pairResult.second);
EXPECT_EQ(3, cache.size());
// Trying to insert another value with previous key
pairResult = cache.insert(std::make_pair<int, std::string>(4, "42"));
EXPECT_EQ(std::string("4"), pairResult.first->second->second);
EXPECT_FALSE(pairResult.second);
EXPECT_EQ(3, cache.size());
}
TEST(LRUCache, Exists)
{
LRUCache<int, std::string, 2> cache;
const auto firstKey = 1;
const auto secondKey = 2;
const auto thirdKey = 3;
const auto firstValue = std::string("1");
const auto secondValue = std::string("2");
cache.insert(std::make_pair(firstKey, firstValue));
cache.insert(std::make_pair(secondKey, secondValue));
EXPECT_TRUE(cache.exists(firstKey));
EXPECT_TRUE(cache.exists(secondKey));
EXPECT_FALSE(cache.exists(thirdKey));
}
TEST(LRUCache, Count)
{
LRUCache<int, std::string, 2> cache;
const auto firstKey = 1;
const auto secondKey = 2;
const auto thirdKey = 3;
const auto firstValue = std::string("1");
const auto secondValue = std::string("2");
cache.insert(std::make_pair(firstKey, firstValue));
cache.insert(std::make_pair(secondKey, secondValue));
EXPECT_EQ(1, cache.count(firstKey));
EXPECT_EQ(1, cache.count(secondKey));
EXPECT_EQ(0, cache.count(thirdKey));
}
TEST(LRUCache, Size)
{
LRUCache<int, std::string, 2> cache;
EXPECT_EQ(0, cache.size());
cache.insert(std::make_pair<int, std::string>(1, "1"));
EXPECT_EQ(1, cache.size());
cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_EQ(2, cache.size());
}
TEST(LRUCache, Empty)
{
LRUCache<int, std::string, 1> cache;
EXPECT_TRUE(cache.empty());
cache.insert(std::make_pair<int, std::string>(1, "1"));
EXPECT_FALSE(cache.empty());
cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_FALSE(cache.empty());
}
TEST(LRUCache, Clear)
{
LRUCache<int, std::string, 2> cache;
cache.insert(std::make_pair<int, std::string>(1, "1"));
cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_EQ(2, cache.size());
cache.clear();
EXPECT_TRUE(cache.empty());
}
TEST(LRUCache, BracketOperatorLValue)
{
LRUCache<std::string, std::string, 5> cache;
const auto firstKey = std::string("answer to life the universe and everything");
const auto firstValue = std::string("42");
const auto secondKey = std::string("where's north ?");
cache.insert(std::make_pair(firstKey, firstValue));
// Element does exist
auto& value = cache[firstKey];
EXPECT_EQ(firstValue, value);
// Element that does not exist
auto& defaultValue = cache[secondKey];
EXPECT_EQ(std::string(), defaultValue);
}
TEST(LRUCache, BracketOperatorRValue)
{
LRUCache<std::string, std::string, 5> cache;
const char* const firstKey = "answer to life the universe and everything";
const char* const firstValue = "42";
const char* const secondKey = "where's north ?";
// Element does exist
cache.insert(std::make_pair(std::string(firstKey), std::string(firstValue)));
auto& value = cache[std::string(firstKey)];
EXPECT_EQ(std::string(firstValue), value);
// Element that does not exist
auto& defaultValue = cache[std::string(secondKey)];
EXPECT_EQ(std::string(), defaultValue);
}<commit_msg>Adapt unit tests<commit_after>#include <gtest/gtest.h>
#include "LRUCache.hxx"
TEST(LRUCache, InsertPair)
{
LRUCache<int, std::string, 3> cache;
auto pairResult = cache.insert(std::make_pair<int, std::string>(1, "1"));
EXPECT_EQ(std::string("1"), pairResult.first->second);
EXPECT_TRUE(pairResult.second);
EXPECT_EQ(1, cache.size());
pairResult = cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_EQ(std::string("2"), pairResult.first->second);
EXPECT_TRUE(pairResult.second);
pairResult = cache.insert(std::make_pair<int, std::string>(3, "3"));
EXPECT_EQ(std::string("3"), pairResult.first->second);
EXPECT_TRUE(pairResult.second);
EXPECT_EQ(3, cache.size());
// Reaching limit
pairResult = cache.insert(std::make_pair<int, std::string>(4, "4"));
EXPECT_EQ(std::string("4"), pairResult.first->second);
EXPECT_TRUE(pairResult.second);
EXPECT_EQ(3, cache.size());
// Trying to insert another value with previous key
pairResult = cache.insert(std::make_pair<int, std::string>(4, "42"));
EXPECT_EQ(std::string("4"), pairResult.first->second);
EXPECT_FALSE(pairResult.second);
EXPECT_EQ(3, cache.size());
}
TEST(LRUCache, Find)
{
LRUCache<int, std::string, 2> cache;
const auto firstKey = 1;
const auto secondKey = 2;
const auto thirdKey = 3;
const auto firstValue = std::string("1");
const auto secondValue = std::string("2");
cache.insert(std::make_pair(firstKey, firstValue));
cache.insert(std::make_pair(secondKey, secondValue));
auto firstResult = cache.find(firstKey);
auto secondResult = cache.find(secondKey);
auto thirdResult = cache.find(thirdKey);
EXPECT_TRUE(firstResult.second);
EXPECT_EQ(firstKey, firstResult.first->first);
EXPECT_EQ(firstValue, firstResult.first->second);
EXPECT_TRUE(secondResult.second);
EXPECT_EQ(secondKey, secondResult.first->first);
EXPECT_EQ(secondValue, secondResult.first->second);
EXPECT_FALSE(thirdResult.second);
}
TEST(LRUCache, Count)
{
LRUCache<int, std::string, 2> cache;
const auto firstKey = 1;
const auto secondKey = 2;
const auto thirdKey = 3;
const auto firstValue = std::string("1");
const auto secondValue = std::string("2");
cache.insert(std::make_pair(firstKey, firstValue));
cache.insert(std::make_pair(secondKey, secondValue));
EXPECT_EQ(1, cache.count(firstKey));
EXPECT_EQ(1, cache.count(secondKey));
EXPECT_EQ(0, cache.count(thirdKey));
}
TEST(LRUCache, Size)
{
LRUCache<int, std::string, 2> cache;
EXPECT_EQ(0, cache.size());
cache.insert(std::make_pair<int, std::string>(1, "1"));
EXPECT_EQ(1, cache.size());
cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_EQ(2, cache.size());
}
TEST(LRUCache, Empty)
{
LRUCache<int, std::string, 1> cache;
EXPECT_TRUE(cache.empty());
cache.insert(std::make_pair<int, std::string>(1, "1"));
EXPECT_FALSE(cache.empty());
cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_FALSE(cache.empty());
}
TEST(LRUCache, Clear)
{
LRUCache<int, std::string, 2> cache;
cache.insert(std::make_pair<int, std::string>(1, "1"));
cache.insert(std::make_pair<int, std::string>(2, "2"));
EXPECT_EQ(2, cache.size());
cache.clear();
EXPECT_TRUE(cache.empty());
}
TEST(LRUCache, BracketOperatorLValue)
{
LRUCache<std::string, std::string, 5> cache;
const auto firstKey = std::string("answer to life the universe and everything");
const auto firstValue = std::string("42");
const auto secondKey = std::string("where's north ?");
cache.insert(std::make_pair(firstKey, firstValue));
// Element does exist
auto& value = cache[firstKey];
EXPECT_EQ(firstValue, value);
// Element that does not exist
auto& defaultValue = cache[secondKey];
EXPECT_EQ(std::string(), defaultValue);
}
TEST(LRUCache, BracketOperatorRValue)
{
LRUCache<std::string, std::string, 5> cache;
const char* const firstKey = "answer to life the universe and everything";
const char* const firstValue = "42";
const char* const secondKey = "where's north ?";
// Element does exist
cache.insert(std::make_pair(std::string(firstKey), std::string(firstValue)));
auto& value = cache[std::string(firstKey)];
EXPECT_EQ(std::string(firstValue), value);
// Element that does not exist
auto& defaultValue = cache[std::string(secondKey)];
EXPECT_EQ(std::string(), defaultValue);
}<|endoftext|> |
<commit_before>// Module: Log4CPLUS
// File: threads.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/threads.h>
#include <exception>
#include <sstream>
#include <stdexcept>
#include <errno.h>
#include <time.h>
#ifdef LOG4CPLUS_USE_PTHREADS
# include <sched.h>
#endif
using namespace log4cplus::helpers;
#ifndef LOG4CPLUS_SINGLE_THREADED
LOG4CPLUS_MUTEX_PTR_DECLARE
log4cplus::thread::createNewMutex()
{
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_mutex_t* m = new pthread_mutex_t();
pthread_mutex_init(m, NULL);
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
CRITICAL_SECTION* m = new CRITICAL_SECTION();
InitializeCriticalSection(m);
#endif
return m;
}
void
log4cplus::thread::deleteMutex(LOG4CPLUS_MUTEX_PTR_DECLARE m)
{
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_mutex_destroy(m);
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
DeleteCriticalSection(m);
#endif
delete m;
}
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_key_t*
log4cplus::thread::createPthreadKey()
{
pthread_key_t* key = new pthread_key_t();
pthread_key_create(key, NULL);
return key;
}
#endif
log4cplus::thread::Guard::~Guard()
{
try {
LOG4CPLUS_MUTEX_UNLOCK( _mutex );
}
catch(exception& e) {
helpers::getLogLog().error(std::string("**** Guard::~Guard() exception: ") + e.what());
throw;
}
catch(...) {
helpers::getLogLog().error("**** Guard::~Guard() exception!!!!");
throw;
}
}
void
log4cplus::thread::yield()
{
#ifdef LOG4CPLUS_USE_PTHREADS
sched_yield();
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
Sleep(0);
#endif
}
#define MILLIS_TO_NANOS 1000000
#define SEC_TO_MILLIS 1000
#define MAX_SLEEP_SECONDS (DWORD)4294966 // (2**32-2)/1000
void
log4cplus::thread::sleep(unsigned long secs, unsigned long nanosecs)
{
#ifdef LOG4CPLUS_USE_PTHREADS
timespec sleep_time = { secs, nanosecs };
timespec remain;
while (nanosleep(&sleep_time, &remain)) {
if (errno == EINTR) {
sleep_time.tv_sec = remain.tv_sec;
sleep_time.tv_nsec = remain.tv_nsec;
continue;
}
else {
return;
}
}
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
DWORD nano_millis = nanosecs / static_cast<unsigned long>(MILLIS_TO_NANOS);
if (secs <= MAX_SLEEP_SECONDS) {
Sleep((secs * SEC_TO_MILLIS) + nano_millis);
return;
}
DWORD no_of_max_sleeps = secs / MAX_SLEEP_SECONDS;
for(DWORD i = 0; i < no_of_max_sleeps; i++) {
Sleep(MAX_SLEEP_SECONDS * 1000);
}
Sleep((secs % MAX_SLEEP_SECONDS) * SEC_TO_MILLIS + nano_millis);
#endif
}
#ifdef LOG4CPLUS_USE_PTHREADS
void*
log4cplus::thread::threadStartFunc(void* arg)
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
DWORD WINAPI
log4cplus::thread::threadStartFunc(LPVOID arg)
#endif
{
if(arg == NULL) {
getLogLog().error("log4cplus::thread::threadStartFunc()- arg is NULL");
}
else {
AbstractThread* thread = static_cast<AbstractThread*>(arg);
try {
log4cplus::helpers::SharedObjectPtr<AbstractThread> ptr(thread);
thread->run();
}
catch(...) {
// TODO --> Log
}
thread->running = false;
}
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_exit(NULL);
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
return NULL;
#endif
}
log4cplus::thread::AbstractThread::AbstractThread()
: running(false)
{
}
log4cplus::thread::AbstractThread::~AbstractThread()
{
}
void
log4cplus::thread::AbstractThread::start()
{
running = true;
#ifdef LOG4CPLUS_USE_PTHREADS
if( pthread_create(&threadId, NULL, threadStartFunc, this) ) {
throw std::runtime_error("Thread creation was not successful");
}
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
HANDLE h = CreateThread(NULL, 0, threadStartFunc, (LPVOID)this, 0, &threadId);
CloseHandle(h);
#endif
}
#endif // LOG4CPLUS_SINGLE_THREADED
<commit_msg>Fixed a compilation error on gcc 3.2 compilers.<commit_after>// Module: Log4CPLUS
// File: threads.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/threads.h>
#include <exception>
#include <sstream>
#include <stdexcept>
#include <errno.h>
#include <time.h>
#ifdef LOG4CPLUS_USE_PTHREADS
# include <sched.h>
#endif
using namespace log4cplus::helpers;
#ifndef LOG4CPLUS_SINGLE_THREADED
LOG4CPLUS_MUTEX_PTR_DECLARE
log4cplus::thread::createNewMutex()
{
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_mutex_t* m = new pthread_mutex_t();
pthread_mutex_init(m, NULL);
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
CRITICAL_SECTION* m = new CRITICAL_SECTION();
InitializeCriticalSection(m);
#endif
return m;
}
void
log4cplus::thread::deleteMutex(LOG4CPLUS_MUTEX_PTR_DECLARE m)
{
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_mutex_destroy(m);
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
DeleteCriticalSection(m);
#endif
delete m;
}
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_key_t*
log4cplus::thread::createPthreadKey()
{
pthread_key_t* key = new pthread_key_t();
pthread_key_create(key, NULL);
return key;
}
#endif
log4cplus::thread::Guard::~Guard()
{
try {
LOG4CPLUS_MUTEX_UNLOCK( _mutex );
}
catch(std::exception& e) {
helpers::getLogLog().error(std::string("**** Guard::~Guard() exception: ") + e.what());
throw;
}
catch(...) {
helpers::getLogLog().error("**** Guard::~Guard() exception!!!!");
throw;
}
}
void
log4cplus::thread::yield()
{
#ifdef LOG4CPLUS_USE_PTHREADS
sched_yield();
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
Sleep(0);
#endif
}
#define MILLIS_TO_NANOS 1000000
#define SEC_TO_MILLIS 1000
#define MAX_SLEEP_SECONDS (DWORD)4294966 // (2**32-2)/1000
void
log4cplus::thread::sleep(unsigned long secs, unsigned long nanosecs)
{
#ifdef LOG4CPLUS_USE_PTHREADS
timespec sleep_time = { secs, nanosecs };
timespec remain;
while (nanosleep(&sleep_time, &remain)) {
if (errno == EINTR) {
sleep_time.tv_sec = remain.tv_sec;
sleep_time.tv_nsec = remain.tv_nsec;
continue;
}
else {
return;
}
}
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
DWORD nano_millis = nanosecs / static_cast<unsigned long>(MILLIS_TO_NANOS);
if (secs <= MAX_SLEEP_SECONDS) {
Sleep((secs * SEC_TO_MILLIS) + nano_millis);
return;
}
DWORD no_of_max_sleeps = secs / MAX_SLEEP_SECONDS;
for(DWORD i = 0; i < no_of_max_sleeps; i++) {
Sleep(MAX_SLEEP_SECONDS * 1000);
}
Sleep((secs % MAX_SLEEP_SECONDS) * SEC_TO_MILLIS + nano_millis);
#endif
}
#ifdef LOG4CPLUS_USE_PTHREADS
void*
log4cplus::thread::threadStartFunc(void* arg)
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
DWORD WINAPI
log4cplus::thread::threadStartFunc(LPVOID arg)
#endif
{
if(arg == NULL) {
getLogLog().error("log4cplus::thread::threadStartFunc()- arg is NULL");
}
else {
AbstractThread* thread = static_cast<AbstractThread*>(arg);
try {
log4cplus::helpers::SharedObjectPtr<AbstractThread> ptr(thread);
thread->run();
}
catch(...) {
// TODO --> Log
}
thread->running = false;
}
#ifdef LOG4CPLUS_USE_PTHREADS
pthread_exit(NULL);
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
return NULL;
#endif
}
log4cplus::thread::AbstractThread::AbstractThread()
: running(false)
{
}
log4cplus::thread::AbstractThread::~AbstractThread()
{
}
void
log4cplus::thread::AbstractThread::start()
{
running = true;
#ifdef LOG4CPLUS_USE_PTHREADS
if( pthread_create(&threadId, NULL, threadStartFunc, this) ) {
throw std::runtime_error("Thread creation was not successful");
}
#endif
#ifdef LOG4CPLUS_USE_WIN32_THREADS
HANDLE h = CreateThread(NULL, 0, threadStartFunc, (LPVOID)this, 0, &threadId);
CloseHandle(h);
#endif
}
#endif // LOG4CPLUS_SINGLE_THREADED
<|endoftext|> |
<commit_before>#pragma once
#include "util.cpp"
/*
struct Cluster {
int rx, cy, id;
vector<pair<int, int>> cells;
};
struct Balloon {
int id, cluster_id;
vector<int> r, c, h;
};
struct Input {
int r, c, a, l, v, b, t, rs, cs;
vector<Cluster> clusters;
vector<Ballon> balloon;
vector<int> cell_x;
vector<int> cell_y;
vector<vector<vector<int>>> movement_x;
vector<vector<vector<int>>> movement_y;
};
struct Coord {
int r, c, h;
};
void bfs(Input &input, vector<Coord> path) {
while (!q.empty()) {
Coord cur = q.front();
path.insert()
if (cur.r >= input.r || cur.r < 0) {
cur.r =
}
}
}*/
void pathfinding(Input& input, int balloon, int r, int c, int delta) {
//TODO fill me
queue<Coord> q;
Coord start;
start.r = input.balloons[balloon].r.back();
start.c = input.balloons[balloon].c.back();
start.h = input.balloons[balloon].h.back();
q.push(start);
input.balloons[balloon].h.push_back(1);
input.balloons[balloon].r.push_back(r+input.movement_r[r][c][1])
input.balloons[balloons.c.push_back(c+input.movement_c[r][c][1]);
//bfs(input,q);
}
<commit_msg>stupid pathfinding<commit_after>#pragma once
#include "util.cpp"
/*
struct Cluster {
int rx, cy, id;
vector<pair<int, int>> cells;
};
struct Balloon {
int id, cluster_id;
vector<int> r, c, h;
};
struct Input {
int r, c, a, l, v, b, t, rs, cs;
vector<Cluster> clusters;
vector<Ballon> balloon;
vector<int> cell_x;
vector<int> cell_y;
vector<vector<vector<int>>> movement_x;
vector<vector<vector<int>>> movement_y;
};
struct Coord {
int r, c, h;
};
void bfs(Input &input, vector<Coord> path) {
while (!q.empty()) {
Coord cur = q.front();
path.insert()
if (cur.r >= input.r || cur.r < 0) {
cur.r =
}
}
}*/
void pathfinding(Input& input, int balloon, int r, int c, int delta) {
//TODO fill me
//queue<Coord> q;
//Coord start;
int rr = input.balloons[balloon].r.back();
int cc = input.balloons[balloon].c.back();
//int hh = input.balloons[balloon].h.back();
//q.push(start);
input.balloons[balloon].h.push_back(1);
input.balloons[balloon].r.push_back(r+input.movement_r[rr][cc][1]);
input.balloons[balloon].c.push_back(c+input.movement_c[rr][cc][1]);
//bfs(input,q);
}
<|endoftext|> |
<commit_before>/* MStringArray - Dynamic Array of MString objects
Copyright (C) 2001 Jesse L. Lovelace (jllovela@eos.ncsu.edu)
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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <fstream.h>
#include "MStringArray.h"
#include "MString.h"
class MArrayNode {
public:
MArrayNode(MString string, MArrayNode* link = 0) {MLink_Forward = link; MInfo = string;}
MArrayNode *MLink_Forward;
MString MInfo;
};
static void deallocate(MArrayNode* p)
{
MArrayNode* tmp;
while (p) {
tmp = p;
p = p->MLink_Forward;
delete tmp;
}
}
static MArrayNode* findTail(MArrayNode * startPointer) {
MArrayNode * tmp=startPointer;
while (tmp) {
if (!tmp->MLink_Forward)
return tmp;
tmp = tmp->MLink_Forward;
}
return startPointer;
}
static MArrayNode* copy(MArrayNode* p, MArrayNode*& tailNode)
{
MArrayNode* head = 0;
MArrayNode* tail = 0;
while(p) {
if (!head)
head = tail = new MArrayNode(p->MInfo);
else {
tail->MLink_Forward = new MArrayNode(p->MInfo);
tail = tail->MLink_Forward;
}
p = p->MLink_Forward;
}
tailNode = tail;
return head;
}
MArrayNode* MStringArray::GetPointerAt(int nIndex) {
MArrayNode* tmp = headMNode;
for (int i = 0; (i < nIndex); i++) {
if (NULL == tmp)
return NULL;
tmp = tmp->MLink_Forward;
}
return tmp;
}
MStringArray::~MStringArray() {
deallocate(headMNode);
headMNode = tailMNode = NULL;
}
MStringArray::MStringArray() {
headMNode = tailMNode = NULL;
}
MStringArray::MStringArray(const MStringArray& arraySrc) {
headMNode = copy(arraySrc.headMNode, tailMNode);
}
MStringArray::MStringArray(const MString& stringSrc) {
headMNode = tailMNode = new MArrayNode(stringSrc);
}
const MStringArray& MStringArray::operator = (const MStringArray& arraySrc) {
if (this != &arraySrc) {
deallocate(headMNode);
headMNode = tailMNode = NULL;
headMNode = copy(arraySrc.headMNode, tailMNode);
}
return *this;
}
int MStringArray::GetSize() const {
int count = 0;
if (headMNode==NULL)
return count;
MArrayNode *tmp = headMNode;
while(tmp) {
count++;
tmp = tmp->MLink_Forward;
}
return count;
}
int MStringArray::GetUpperBound() const {
return (GetSize() - 1);
}
void MStringArray::SetSize(int nNewSize, int nGrowBy) {
if (nNewSize < 0)
return;
//UNFINISHED FUNCTION
//nGrowBy unreferenced formal param
}
void MStringArray::FreeExtra() {
//UNFINISHED FUNCTION
}
void MStringArray::RemoveAll() {
deallocate(headMNode);
headMNode = tailMNode = NULL;
}
void MStringArray::test() {
MArrayNode *tmp = headMNode;
int count = 0;
cout << "Head = " << headMNode << endl;
while (tmp)
{
cout << "Index(" << count++ << ") " << tmp->MInfo << " " << tmp->MLink_Forward << endl;
tmp = tmp->MLink_Forward;
}
cout << "Tail = " << tailMNode << endl;
cout << "GetSize = " << GetSize() << endl;
}
MString MStringArray::GetAt(int nIndex) const {
MString tmpStr;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
void MStringArray::SetAt(int nIndex, const MString &newElement) {
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
tmp->MInfo = newElement;
}
void MStringArray::SetAt(int nIndex, char newString[]) {
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
tmp->MInfo = newString;
}
MString& MStringArray::ElementAt(int nIndex) {
MString* tmpStr = NULL;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return *tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
// const MString* MStringArray::GetData() const;
// MString* MStringArray::GetData();
void MStringArray::SetAtGrow(int nIndex, const MString &newElement) {
//Not written yet
}
void MStringArray::SetAtGrow(int nIndex, char newString[]) {
//Not written yet
}
int MStringArray::Add(const MString &newElement) {
InsertAt(GetSize(), newElement);
return GetUpperBound();
}
int MStringArray::Add(char newString[]) { //works
InsertAt(GetSize(), newString);
return GetUpperBound();
}
int MStringArray::Append(const MStringArray &src) { //works
InsertAt(GetSize(), src);
return GetSize();
}
void MStringArray::Copy(const MStringArray &src) {
headMNode = copy(src.headMNode, tailMNode);
}
void MStringArray::InsertAt(int nIndex, const MString &newElement, int nCount) { //works
//MFC Uses pointer to MString,
int length = GetSize();
if ((nCount == 0) || (nIndex < 0))
return;
if (length == 0) { //if size is zero
headMNode = tailMNode = new MArrayNode(newElement);
return;
}
if (nIndex == length) {//if just adding to end, use tailMNode
for (int a = 0; a < nCount; a++) {
tailMNode->MLink_Forward = new MArrayNode(newElement);
tailMNode = tailMNode->MLink_Forward;
}
return;
}
if (nIndex == 0) {
headMNode = new MArrayNode(newElement, headMNode);
MArrayNode* tmp = headMNode;
for (int i = 1; i < nCount; i++) {
tmp->MLink_Forward = new MArrayNode(newElement, tmp->MLink_Forward);
tmp = tmp->MLink_Forward;
}
return;
}
if (nIndex > (length - 1)) {//if space between new element and old ones,
// pad with null MStrings
for (int adds = nIndex; nIndex > GetSize(); adds++) {
MString tmpStr;
Add(tmpStr);
}
for (int other = 0; other < nCount; other++) {
Add(newElement);
}
return;
}
// if inserting in the middle somewhere
MArrayNode * tmp = headMNode;
for (int k = 0; k < (nIndex - 1); k++) { //go to index you want to insert infront of.
tmp = tmp->MLink_Forward;
}
for (int w = 0; w < nCount; w++) {
tmp->MLink_Forward = new MArrayNode(newElement, tmp->MLink_Forward);
tmp = tmp->MLink_Forward;
}
return;
}
void MStringArray::InsertAt(int nStartIndex, MStringArray pNewArray){ //works
int size = pNewArray.GetSize();
for (int i = 0; i < size; i++)
InsertAt(nStartIndex++, pNewArray.GetAt(i)); //sloppy jesse, don't use GetAt
}
void MStringArray::InsertAt(int nIndex, char newString[], int nCount) {
MString tmp(newString);
InsertAt(nIndex, tmp, nCount);
return;
}
void MStringArray::RemoveAt(int nIndex, int nCount) {
int length = GetSize();
if ((length < 1) || (nIndex > length) || (nCount < 1))
return;
if (nCount > (length - nIndex))
nCount = (length - nIndex);
if (0 == nIndex) {
MArrayNode* first = headMNode;
MArrayNode* last = GetPointerAt((nIndex + nCount)-1);
if (last->MLink_Forward) {
headMNode = last->MLink_Forward;
last->MLink_Forward = NULL;
deallocate(first);
}
else {
headMNode = NULL;
deallocate(first);
}
}
else {
MArrayNode* toHead = GetPointerAt(nIndex - 1);
MArrayNode* first = GetPointerAt(nIndex);
MArrayNode* last = GetPointerAt((nCount + nIndex) - 1);
if (last->MLink_Forward) {
if (last->MLink_Forward->MLink_Forward) {
toHead->MLink_Forward = last->MLink_Forward;
last->MLink_Forward = NULL;
deallocate(first);
}
else {
toHead->MLink_Forward=last->MLink_Forward;
last->MLink_Forward = NULL;
deallocate(first);
}
}
else {
toHead->MLink_Forward = NULL;
deallocate(first);
}
}
tailMNode = findTail(headMNode);
}
MString& MStringArray::operator[](int nIndex) {
MString* tmpStr = NULL;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return *tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
MString MStringArray::operator[](int nIndex) const {
MString tmpStr;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
//New functions:
void MStringArray::Split(MString stringToSplit, char ch, int nStartIndex, int insertAt){
MStringArray tmpArray;
MString tmpString;
int place = nStartIndex,
nextFind = stringToSplit.Find(ch, place);
while (nextFind >= 0) {
tmpString = stringToSplit.Mid(place, nextFind - place);
tmpString.Trim(ch);
cout << tmpString << endl;
cout << "place = " << place << endl;
tmpArray.Add(tmpString);
tmpString.Empty();
place = nextFind + 1;
nextFind = stringToSplit.Find(ch, place);
cout << "place = " << place << endl;
}
tmpString = stringToSplit.Right(stringToSplit.GetLength() - place);
//get the last word and add
// it
tmpString.Trim(ch);
if (!tmpString.IsEmpty()) {
tmpArray.Add(tmpString);
tmpString.Empty();
}
InsertAt(insertAt, tmpArray);
}
<commit_msg>Fixed gcc compile error.<commit_after>/* MStringArray - Dynamic Array of MString objects
Copyright (C) 2001-2004 Jesse L. Lovelace (jllovela@eos.ncsu.edu)
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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <fstream.h>
#include <iostream.h>
#include "MStringArray.h"
#include "MString.h"
class MArrayNode {
public:
MArrayNode(MString string, MArrayNode* link = 0) {MLink_Forward = link; MInfo = string;}
MArrayNode *MLink_Forward;
MString MInfo;
};
static void deallocate(MArrayNode* p)
{
MArrayNode* tmp;
while (p) {
tmp = p;
p = p->MLink_Forward;
delete tmp;
}
}
static MArrayNode* findTail(MArrayNode * startPointer) {
MArrayNode * tmp=startPointer;
while (tmp) {
if (!tmp->MLink_Forward)
return tmp;
tmp = tmp->MLink_Forward;
}
return startPointer;
}
static MArrayNode* copy(MArrayNode* p, MArrayNode*& tailNode)
{
MArrayNode* head = 0;
MArrayNode* tail = 0;
while(p) {
if (!head)
head = tail = new MArrayNode(p->MInfo);
else {
tail->MLink_Forward = new MArrayNode(p->MInfo);
tail = tail->MLink_Forward;
}
p = p->MLink_Forward;
}
tailNode = tail;
return head;
}
MArrayNode* MStringArray::GetPointerAt(int nIndex) {
MArrayNode* tmp = headMNode;
for (int i = 0; (i < nIndex); i++) {
if (NULL == tmp)
return NULL;
tmp = tmp->MLink_Forward;
}
return tmp;
}
MStringArray::~MStringArray() {
deallocate(headMNode);
headMNode = tailMNode = NULL;
}
MStringArray::MStringArray() {
headMNode = tailMNode = NULL;
}
MStringArray::MStringArray(const MStringArray& arraySrc) {
headMNode = copy(arraySrc.headMNode, tailMNode);
}
MStringArray::MStringArray(const MString& stringSrc) {
headMNode = tailMNode = new MArrayNode(stringSrc);
}
const MStringArray& MStringArray::operator = (const MStringArray& arraySrc) {
if (this != &arraySrc) {
deallocate(headMNode);
headMNode = tailMNode = NULL;
headMNode = copy(arraySrc.headMNode, tailMNode);
}
return *this;
}
int MStringArray::GetSize() const {
int count = 0;
if (headMNode==NULL)
return count;
MArrayNode *tmp = headMNode;
while(tmp) {
count++;
tmp = tmp->MLink_Forward;
}
return count;
}
int MStringArray::GetUpperBound() const {
return (GetSize() - 1);
}
void MStringArray::SetSize(int nNewSize, int nGrowBy) {
if (nNewSize < 0)
return;
//UNFINISHED FUNCTION
//nGrowBy unreferenced formal param
}
void MStringArray::FreeExtra() {
//UNFINISHED FUNCTION
}
void MStringArray::RemoveAll() {
deallocate(headMNode);
headMNode = tailMNode = NULL;
}
void MStringArray::test() {
MArrayNode *tmp = headMNode;
int count = 0;
cout << "Head = " << headMNode << endl;
while (tmp)
{
cout << "Index(" << count++ << ") " << tmp->MInfo << " " << tmp->MLink_Forward << endl;
tmp = tmp->MLink_Forward;
}
cout << "Tail = " << tailMNode << endl;
cout << "GetSize = " << GetSize() << endl;
}
MString MStringArray::GetAt(int nIndex) const {
MString tmpStr;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
void MStringArray::SetAt(int nIndex, const MString &newElement) {
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
tmp->MInfo = newElement;
}
void MStringArray::SetAt(int nIndex, char newString[]) {
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
tmp->MInfo = newString;
}
MString& MStringArray::ElementAt(int nIndex) {
MString* tmpStr = NULL;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return *tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
// const MString* MStringArray::GetData() const;
// MString* MStringArray::GetData();
void MStringArray::SetAtGrow(int nIndex, const MString &newElement) {
//Not written yet
}
void MStringArray::SetAtGrow(int nIndex, char newString[]) {
//Not written yet
}
int MStringArray::Add(const MString &newElement) {
InsertAt(GetSize(), newElement);
return GetUpperBound();
}
int MStringArray::Add(char newString[]) { //works
InsertAt(GetSize(), newString);
return GetUpperBound();
}
int MStringArray::Append(const MStringArray &src) { //works
InsertAt(GetSize(), src);
return GetSize();
}
void MStringArray::Copy(const MStringArray &src) {
headMNode = copy(src.headMNode, tailMNode);
}
void MStringArray::InsertAt(int nIndex, const MString &newElement, int nCount) { //works
//MFC Uses pointer to MString,
int length = GetSize();
if ((nCount == 0) || (nIndex < 0))
return;
if (length == 0) { //if size is zero
headMNode = tailMNode = new MArrayNode(newElement);
return;
}
if (nIndex == length) {//if just adding to end, use tailMNode
for (int a = 0; a < nCount; a++) {
tailMNode->MLink_Forward = new MArrayNode(newElement);
tailMNode = tailMNode->MLink_Forward;
}
return;
}
if (nIndex == 0) {
headMNode = new MArrayNode(newElement, headMNode);
MArrayNode* tmp = headMNode;
for (int i = 1; i < nCount; i++) {
tmp->MLink_Forward = new MArrayNode(newElement, tmp->MLink_Forward);
tmp = tmp->MLink_Forward;
}
return;
}
if (nIndex > (length - 1)) {//if space between new element and old ones,
// pad with null MStrings
for (int adds = nIndex; nIndex > GetSize(); adds++) {
MString tmpStr;
Add(tmpStr);
}
for (int other = 0; other < nCount; other++) {
Add(newElement);
}
return;
}
// if inserting in the middle somewhere
MArrayNode * tmp = headMNode;
for (int k = 0; k < (nIndex - 1); k++) { //go to index you want to insert infront of.
tmp = tmp->MLink_Forward;
}
for (int w = 0; w < nCount; w++) {
tmp->MLink_Forward = new MArrayNode(newElement, tmp->MLink_Forward);
tmp = tmp->MLink_Forward;
}
return;
}
void MStringArray::InsertAt(int nStartIndex, MStringArray pNewArray){ //works
int size = pNewArray.GetSize();
for (int i = 0; i < size; i++)
InsertAt(nStartIndex++, pNewArray.GetAt(i)); //sloppy jesse, don't use GetAt
}
void MStringArray::InsertAt(int nIndex, char newString[], int nCount) {
MString tmp(newString);
InsertAt(nIndex, tmp, nCount);
return;
}
void MStringArray::RemoveAt(int nIndex, int nCount) {
int length = GetSize();
if ((length < 1) || (nIndex > length) || (nCount < 1))
return;
if (nCount > (length - nIndex))
nCount = (length - nIndex);
if (0 == nIndex) {
MArrayNode* first = headMNode;
MArrayNode* last = GetPointerAt((nIndex + nCount)-1);
if (last->MLink_Forward) {
headMNode = last->MLink_Forward;
last->MLink_Forward = NULL;
deallocate(first);
}
else {
headMNode = NULL;
deallocate(first);
}
}
else {
MArrayNode* toHead = GetPointerAt(nIndex - 1);
MArrayNode* first = GetPointerAt(nIndex);
MArrayNode* last = GetPointerAt((nCount + nIndex) - 1);
if (last->MLink_Forward) {
if (last->MLink_Forward->MLink_Forward) {
toHead->MLink_Forward = last->MLink_Forward;
last->MLink_Forward = NULL;
deallocate(first);
}
else {
toHead->MLink_Forward=last->MLink_Forward;
last->MLink_Forward = NULL;
deallocate(first);
}
}
else {
toHead->MLink_Forward = NULL;
deallocate(first);
}
}
tailMNode = findTail(headMNode);
}
MString& MStringArray::operator[](int nIndex) {
MString* tmpStr = NULL;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return *tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
MString MStringArray::operator[](int nIndex) const {
MString tmpStr;
if ((nIndex < 0) || (nIndex > GetUpperBound()))
return tmpStr; //return's null MString if the nIndex is to big or small.
MArrayNode* tmp = headMNode;
for (int i = 0; i < nIndex; i++)
tmp=tmp->MLink_Forward;
return tmp->MInfo;
}
//New functions:
void MStringArray::Split(MString stringToSplit, char ch, int nStartIndex, int insertAt){
MStringArray tmpArray;
MString tmpString;
int place = nStartIndex,
nextFind = stringToSplit.Find(ch, place);
while (nextFind >= 0) {
tmpString = stringToSplit.Mid(place, nextFind - place);
tmpString.Trim(ch);
cout << tmpString << endl;
cout << "place = " << place << endl;
tmpArray.Add(tmpString);
tmpString.Empty();
place = nextFind + 1;
nextFind = stringToSplit.Find(ch, place);
cout << "place = " << place << endl;
}
tmpString = stringToSplit.Right(stringToSplit.GetLength() - place);
//get the last word and add
// it
tmpString.Trim(ch);
if (!tmpString.IsEmpty()) {
tmpArray.Add(tmpString);
tmpString.Empty();
}
InsertAt(insertAt, tmpArray);
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include "StateSpace.h"
#include "Action.h"
#include "PriorityQueue.h"
#include "State.h"
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
Action * selectAction(PriorityQueue<Action *,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, Action & action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(std::time(NULL));
//create pointers to the possible actions as well as a pointer to hold the chosen action
Action* chosen_action;
Action* actions[2];
actions[0]=new Action(FORWARD);
actions[1]=new Action(BACKWARD);
//create a priority queue to copy to all the state space priority queues
PriorityQueue<Action*,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(actions[0],0);
initiator_queue.enqueueWithPriority(actions[1],0);
//create the state space
StateSpace space(100,50,initiator_queue);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
current_state.theta=getAngle();
current_state.theta_dot=getVelocity();
current_state.robot_state=chosen_action.action;
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
old_state=current_state;
chosen_action=selectAction(space[current_state]);
chosen_action.execute();
}
delete actions[0];
delete actions[1];
return 1;
}
double temperature()
{
return std::time(NULL);
}
//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
Action * selectAction(PriorityQueue<Action *,double>& a_queue)
{
typedef PriorityQueue<Action *,double> PQ;
typedef std::vector< std::pair<Action *, double> > Vec_Pair;
typedef std::pair<Action *, double> Pair;
double sum= 0;
int i = 0;
int size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(std::vector< std::pair<int, double> >::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()/ (RAND_MAX));
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return NULL; //note that this line should never be reached
}
void updateQ(StateSpace & space, Action & action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[current_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
<commit_msg>An error was detected which threatened the security of the robot<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include "StateSpace.h"
#include "Action.h"
#include "PriorityQueue.h"
#include "State.h"
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
Action * selectAction(PriorityQueue<Action *,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, Action & action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(std::time(NULL));
//create pointers to the possible actions as well as a pointer to hold the chosen action
Action* chosen_action;
Action* actions[2];
actions[0]=new Action(FORWARD);
actions[1]=new Action(BACKWARD);
//create a priority queue to copy to all the state space priority queues
PriorityQueue<Action*,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(actions[0],0);
initiator_queue.enqueueWithPriority(actions[1],0);
//create the state space
StateSpace space(100,50,initiator_queue);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
current_state.theta=getAngle();
current_state.theta_dot=getVelocity();
current_state.robot_state=chosen_action.action;
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
old_state=current_state;
chosen_action=selectAction(space[current_state]);
chosen_action.execute();
}
delete actions[0];
delete actions[1];
return 1;
}
double temperature()
{
return std::time(NULL);
}
//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
Action * selectAction(PriorityQueue<Action *,double>& a_queue)
{
typedef PriorityQueue<Action *,double> PQ;
typedef std::vector< std::pair<Action *, double> > Vec_Pair;
typedef std::pair<Action *, double> Pair;
double sum= 0;
int i = 0;
int size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(std::vector< std::pair<int, double> >::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()/ (RAND_MAX));
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return NULL; //note that this line should never be reached
}
void updateQ(StateSpace & space, Action * action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[current_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>
*
* 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 "directoryprovider.h"
#include <QtGui/QDesktopServices>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QSettings>
using namespace MulaCore;
MULA_DEFINE_SINGLETON( DirectoryProvider )
DirectoryProvider::DirectoryProvider( QObject* parent )
{
m_userDataPath = QDesktopServices::storageLocation( QDesktopServices::DataLocation );
m_userDataPath.remove( QCoreApplication::organizationName() + "/" + QCoreApplication::applicationName() );
m_userDataPath.append( "mula/" );
//Define standard dirs Mula recommends
m_userDirs["data"] = QDir::fromNativeSeparators( m_userDataPath + "data" );
//Create standard dirs Mula recommends
QDir dir;
foreach( const QString& dirPath, m_userDirs )
{
dir.mkpath( dirPath );
}
}
QString DirectoryProvider::installPrefix() const
{
#ifdef Q_OS_WIN
QSettings *settings;
if (MULA_ARCHITECTURE == "32")
settings = new QSettings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Mula\\Mula-" + MULA_VERSION_STRING + "\\", QSettings::NativeFormat);
else if (MULA_ARCHITECTURE == "64")
settings = new QSettings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Mula\\Mula-" + MULA_VERSION_STRING + "\\", QSettings::NativeFormat);
QString installPath = settings->value("Default").toString();
delete settings;
return installPath.isEmpty() ? MULA_INSTALL_PREFIX : installPath;
#else
return MULA_INSTALL_PREFIX;
#endif
}
QString DirectoryProvider::dataDirectory() const
{
return installPrefix() + "/" + MULA_SHARE_INSTALL_DIR;
}
QString DirectoryProvider::libDirectory() const
{
return installPrefix() + "/" + MULA_LIB_INSTALL_DIR;
}
QString DirectoryProvider::userDirectory( const QString& name )
{
if( !m_userDirs.contains( name ) )
{
QString path = QDir::fromNativeSeparators( m_userDataPath + name );
m_userDirs[name] = path;
QDir dir;
dir.mkpath( path );
}
return m_userDirs[name];
}
#include "directoryprovider.moc"
<commit_msg>Set the parent of the DirectoryProvider singleton properly<commit_after>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>
*
* 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 "directoryprovider.h"
#include <QtGui/QDesktopServices>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QSettings>
using namespace MulaCore;
MULA_DEFINE_SINGLETON( DirectoryProvider )
DirectoryProvider::DirectoryProvider( QObject* parent )
: MulaCore::Singleton< MulaCore::DirectoryProvider >( parent )
{
m_userDataPath = QDesktopServices::storageLocation( QDesktopServices::DataLocation );
m_userDataPath.remove( QCoreApplication::organizationName() + "/" + QCoreApplication::applicationName() );
m_userDataPath.append( "mula/" );
//Define standard dirs Mula recommends
m_userDirs["data"] = QDir::fromNativeSeparators( m_userDataPath + "data" );
//Create standard dirs Mula recommends
QDir dir;
foreach( const QString& dirPath, m_userDirs )
{
dir.mkpath( dirPath );
}
}
QString DirectoryProvider::installPrefix() const
{
#ifdef Q_OS_WIN
QSettings *settings;
if (MULA_ARCHITECTURE == "32")
settings = new QSettings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Mula\\Mula-" + MULA_VERSION_STRING + "\\", QSettings::NativeFormat);
else if (MULA_ARCHITECTURE == "64")
settings = new QSettings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Mula\\Mula-" + MULA_VERSION_STRING + "\\", QSettings::NativeFormat);
QString installPath = settings->value("Default").toString();
delete settings;
return installPath.isEmpty() ? MULA_INSTALL_PREFIX : installPath;
#else
return MULA_INSTALL_PREFIX;
#endif
}
QString DirectoryProvider::dataDirectory() const
{
return installPrefix() + "/" + MULA_SHARE_INSTALL_DIR;
}
QString DirectoryProvider::libDirectory() const
{
return installPrefix() + "/" + MULA_LIB_INSTALL_DIR;
}
QString DirectoryProvider::userDirectory( const QString& name )
{
if( !m_userDirs.contains( name ) )
{
QString path = QDir::fromNativeSeparators( m_userDataPath + name );
m_userDirs[name] = path;
QDir dir;
dir.mkpath( path );
}
return m_userDirs[name];
}
#include "directoryprovider.moc"
<|endoftext|> |
<commit_before>// Copyright (c) 2013-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 <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/un.h>
#include <pthread.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "portal.h"
#include "sock_utils.h"
static struct {
struct memrequest req;
unsigned int pnum;
int valid;
int inflight;
} head;
static int sockfd;
static struct memresponse respitem;
static int dma_fd = -1;
static sem_t dma_waiting;
static pthread_mutex_t socket_mutex;
static int trace_port;// = 1;
extern "C" {
void initPortal(unsigned long id){
static int once = 1;
if (once) {
sem_init(&dma_waiting, 0, 0);
pthread_mutex_init(&socket_mutex, NULL);
bsim_wait_for_connect(&sockfd);
}
once = 0;
}
void interruptLevel(uint32_t ivalue){
static int last_level;
int temp;
if (ivalue != last_level) {
last_level = ivalue;
printf("%s: %d\n", __FUNCTION__, ivalue);
pthread_mutex_lock(&socket_mutex);
temp = respitem.portal;
respitem.portal = MAGIC_PORTAL_FOR_SENDING_INTERRUPT;
respitem.data = ivalue;
bsim_ctrl_send(sockfd, &respitem);
respitem.portal = temp;
pthread_mutex_unlock(&socket_mutex);
}
}
int pareff_fd(int *fd)
{
sem_wait(&dma_waiting);
*fd = dma_fd;
dma_fd = -1;
return 0;
}
bool processReq32(uint32_t rr){
if (!head.valid){
int rv = bsim_ctrl_recv(sockfd, &head.req);
if(rv > 0){
//fprintf(stderr, "recv size %d\n", rv);
assert(rv == sizeof(memrequest));
respitem.portal = head.req.portal;
if (head.req.portal == MAGIC_PORTAL_FOR_SENDING_FD) {
dma_fd = head.req.data;
sem_post(&dma_waiting);
return 0;
}
head.valid = 1;
head.inflight = 1;
head.req.addr = (unsigned int *)(((long) head.req.addr) | head.req.portal << 16);
if(trace_port)
fprintf(stderr, "processr p=%d w=%d, a=%lx, d=%x:",
head.req.portal, head.req.write_flag, (long)head.req.addr, head.req.data);
}
}
return head.valid && head.inflight == 1 && head.req.write_flag == rr;
}
long processAddr32(int rr){
if(trace_port)
fprintf(stderr, " addr");
head.inflight = 0;
return (long)head.req.addr;
}
unsigned int writeData32(){
if(trace_port)
fprintf(stderr, " write\n");
head.valid = 0;
return head.req.data;
}
void readData32(unsigned int x){
if(trace_port)
fprintf(stderr, " read\n");
head.valid = 0;
pthread_mutex_lock(&socket_mutex);
respitem.data = x;
bsim_ctrl_send(sockfd, &respitem);
pthread_mutex_unlock(&socket_mutex);
}
}
<commit_msg>cleanup bsim value tracing<commit_after>// Copyright (c) 2013-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 <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/un.h>
#include <pthread.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "portal.h"
#include "sock_utils.h"
static struct {
struct memrequest req;
unsigned int pnum;
int valid;
int inflight;
} head;
static int sockfd;
static struct memresponse respitem;
static int dma_fd = -1;
static sem_t dma_waiting;
static pthread_mutex_t socket_mutex;
static int trace_port;// = 1;
extern "C" {
void initPortal(unsigned long id){
static int once = 1;
if (once) {
sem_init(&dma_waiting, 0, 0);
pthread_mutex_init(&socket_mutex, NULL);
bsim_wait_for_connect(&sockfd);
}
once = 0;
}
void interruptLevel(uint32_t ivalue){
static int last_level;
int temp;
if (ivalue != last_level) {
last_level = ivalue;
printf("%s: %d\n", __FUNCTION__, ivalue);
pthread_mutex_lock(&socket_mutex);
temp = respitem.portal;
respitem.portal = MAGIC_PORTAL_FOR_SENDING_INTERRUPT;
respitem.data = ivalue;
bsim_ctrl_send(sockfd, &respitem);
respitem.portal = temp;
pthread_mutex_unlock(&socket_mutex);
}
}
int pareff_fd(int *fd)
{
sem_wait(&dma_waiting);
*fd = dma_fd;
dma_fd = -1;
return 0;
}
bool processReq32(uint32_t rr){
if (!head.valid){
int rv = bsim_ctrl_recv(sockfd, &head.req);
if(rv > 0){
//fprintf(stderr, "recv size %d\n", rv);
assert(rv == sizeof(memrequest));
respitem.portal = head.req.portal;
if (head.req.portal == MAGIC_PORTAL_FOR_SENDING_FD) {
dma_fd = head.req.data;
sem_post(&dma_waiting);
return 0;
}
head.valid = 1;
head.inflight = 1;
head.req.addr = (unsigned int *)(((long) head.req.addr) | head.req.portal << 16);
if(trace_port)
fprintf(stderr, "processr p=%d w=%d, a=%8lx, d=%8x:",
head.req.portal, head.req.write_flag, (long)head.req.addr, head.req.data);
}
}
return head.valid && head.inflight == 1 && head.req.write_flag == rr;
}
long processAddr32(int rr){
if(trace_port)
fprintf(stderr, " addr");
head.inflight = 0;
return (long)head.req.addr;
}
unsigned int writeData32(){
if(trace_port)
fprintf(stderr, " write\n");
head.valid = 0;
return head.req.data;
}
void readData32(unsigned int x){
if(trace_port)
fprintf(stderr, " read\n");
head.valid = 0;
pthread_mutex_lock(&socket_mutex);
respitem.data = x;
bsim_ctrl_send(sockfd, &respitem);
pthread_mutex_unlock(&socket_mutex);
}
}
<|endoftext|> |
<commit_before>#include "sqlite3.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "character_tokenizer.h"
#ifdef __cplusplus
}
#endif
#define DEBUGMSGRED(msg) cout << "\033[0;31m" << msg << "\033[0m" << endl;
#define DEBUGMSGGREEN(msg) cout << "\033[0;32m" << msg << "\033[0m" << endl;
#define DEBUGMSGBROWN(msg) cout << "\033[0;33m" << msg << "\033[0m" << endl;
#define DEBUGMSGCYAN(msg) cout << "\033[0;36m" << msg << "\033[0m" << endl;
#define DEBUGMSG(msg) cout << msg << endl;
#define DEBUGMSGN(msg) cout << msg;
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
//int db;
class SQLite3Command
{
public:
SQLite3Command()
{
db = NULL;
}
~SQLite3Command()
{
sqlite3_free(db);
}
struct EXEC_RESULT
{
vector<string> colsName;
vector< vector<string> > records;
};
inline static void show_table(const vector< vector<string> > &data)
{
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data[i].size(); j++) {
DEBUGMSGN(data[i][j] << "\t\033[0;33m|\033[0m")
}
DEBUGMSG("");
}
}
int open(const string &path)
{
return open(path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
}
int open(const string &path, int flag, const char *szVfs)
{
int ret;
ret = sqlite3_open_v2(path.c_str(), &db, flag, szVfs);
if (ret) {
DEBUGMSGRED("[SQLite3DB open error] @ sqlite3_open_v2")
return ret;
}
ret = registerCharacterTokenizer();
if (ret) {
DEBUGMSGRED("[SQLite3DB open error] @ registerCharacterTokenizer")
return ret;
}
return ret;
}
int exec(const string &cmd)
{
return exec(cmd, 0, 0);
}
static int _execDefaultCallback(void *data, int argc, char **cols, char **colsName)
{
EXEC_RESULT *result = (EXEC_RESULT*) data;
result->records.push_back(vector<string>());
for (int i = 0; i < argc; i++) {
int pos = result->records.size() - 1;
if (pos == 0) {
result->colsName.push_back(colsName[i]);
}
result->records[pos].push_back(cols[i]);
}
return 0;
}
int exec(const string &cmd, vector< vector<string> > &data)
{
int ret;
EXEC_RESULT result;
char *errMsg = NULL;
ret = sqlite3_exec(db, cmd.c_str(), _execDefaultCallback, &result, &errMsg);
if (ret != SQLITE_OK) {
cmdFailed("exec", cmd, errMsg);
return ret;
}
data.clear();
// use '<=' instead of '<' for colsName
for (int i = 0; i <= result.records.size(); i++) {
data.push_back(vector<string>());
}
for (int i = 0; i < result.colsName.size(); i++) {
data[0].push_back(result.colsName[i]);
}
for (int i = 0; i < result.records.size(); i++) {
for (int j = 0; j < result.records[i].size(); j++) {
data[i+1].push_back(result.records[i][j]);
}
}
return ret;
}
int exec_and_show(const string &cmd)
{
int ret;
vector< vector<string> > data;
ret = exec(cmd, data);
if (ret) {
return ret;
}
DEBUGMSG("exec_and_show")
show_table(data);
return ret;
}
int exec(const string &cmd, int (*callback)(void*,int,char**,char**), void* data)
{
int ret;
char *errMsg = NULL;
ret = sqlite3_exec(db, cmd.c_str(), callback, data, &errMsg);
if (errMsg != NULL) {
cmdFailed("exec", cmd, errMsg);
return ret;
}
return 0;
}
/*
execf will not use reference.
because 'va_start' has undefined behavior with reference types.
*/
int execf(vector< vector<string> > *data, const string cmd, ...)
{
int ret;
va_list argv;
char *szSQL;
va_start(argv, cmd);
szSQL = sqlite3_vmprintf(cmd.c_str(), argv);
ret = exec(string(szSQL), *data);
sqlite3_free(szSQL);
return ret;
}
/*
execf without vector< vector<string> > data
*/
int execf_cmd_only(const string cmd, ...)
{
int ret;
va_list argv;
char *szSQL;
va_start(argv, cmd);
szSQL = sqlite3_vmprintf(cmd.c_str(), argv);
ret = exec(string(szSQL));
sqlite3_free(szSQL);
return ret;
}
int get_table(const string &query, int &rows, int &cols, vector< vector<string> > &result)
{
char **result_tmp;
int ret;
ret = get_table(query, rows, cols, result_tmp);
if (ret) {
return ret;
}
result.clear();
for (int i = 0; i <= rows; ++i) {
vector<string> tmp;
result.push_back(tmp);
for (int j = 0; j < cols; ++j) {
result[i].push_back(result_tmp[i*cols+j]);
}
}
return 0;
}
int get_table(const string &query, vector< vector<string> > &result)
{
int ret, rows, cols;
ret = get_table(query, rows, cols, result);
if (ret) {
return ret;
}
return 0;
}
int get_table_and_show(const string &query)
{
int ret, rows, cols;
vector< vector<string> > result;
ret = get_table(query, rows, cols, result);
if (ret) {
return ret;
}
DEBUGMSG("get_table_and_show " << rows << " " << cols)
show_table(result);
return 0;
}
int get_table(const string &query, int &rows, int &cols, char **&result)
{
char *errMsg = NULL;
sqlite3_get_table(db, query.c_str(), &result, &rows, &cols, &errMsg);
if (errMsg != NULL) {
cmdFailed("get_table", query, errMsg);
return 1;
}
return 0;
}
sqlite3 *getDB()
{
return db;
}
private:
sqlite3 *db;
int registerTokenizer(
sqlite3 *db,
const char *zName,
const sqlite3_tokenizer_module *p
){
int rc;
sqlite3_stmt *pStmt;
const char *zSql = "SELECT fts3_tokenizer(?, ?)";
rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
if( rc!=SQLITE_OK ){
return rc;
}
sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
sqlite3_step(pStmt);
return sqlite3_finalize(pStmt);
}
int registerCharacterTokenizer()
{
int ret;
const string tokenName = "character";
const sqlite3_tokenizer_module *ptr;
get_character_tokenizer_module(&ptr);
ret = registerTokenizer(db, tokenName.c_str(), ptr);
if (ret) {
DEBUGMSGRED("[SQLite3DB init error] can't register character tokenizer")
}
return ret;
}
inline void cmdFailed(const string &tag, const string &cmd, char *errMsg)
{
DEBUGMSGBROWN(">>> " << cmd)
DEBUGMSGRED("[SQLite3DB " << tag << " failed] " << errMsg)
sqlite3_free(errMsg);
}
};
int main()
{
SQLite3Command PG;
SQLite3Command *ptr = new SQLite3Command();
delete ptr;
vector< vector<string> > tmp;
PG.open("example.db");
PG.exec("asdf");
PG.get_table_and_show("SELECT * from note");
PG.execf_cmd_only("sjaksdf %Q %Q %d", "asdf", "ffff", 1234);
DEBUGMSGGREEN("=== result of INSERT")
PG.execf(&tmp, "INSERT INTO note VALUES(%Q, %Q);", "Insert Test", "Insert Content");
PG.show_table(tmp);
DEBUGMSGGREEN("=== result of SELECT")
PG.execf(&tmp, "SELECT * from note");
PG.show_table(tmp);
//PG.exec_and_show("select * from note");
DEBUGMSGRED("Red test")
DEBUGMSGGREEN("Green test")
DEBUGMSGBROWN("Brown test")
DEBUGMSGCYAN("Cyan test")
}<commit_msg>add constructor<commit_after>#include "sqlite3.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "character_tokenizer.h"
#ifdef __cplusplus
}
#endif
#define DEBUGMSGRED(msg) cout << "\033[0;31m" << msg << "\033[0m" << endl;
#define DEBUGMSGGREEN(msg) cout << "\033[0;32m" << msg << "\033[0m" << endl;
#define DEBUGMSGBROWN(msg) cout << "\033[0;33m" << msg << "\033[0m" << endl;
#define DEBUGMSGCYAN(msg) cout << "\033[0;36m" << msg << "\033[0m" << endl;
#define DEBUGMSG(msg) cout << msg << endl;
#define DEBUGMSGN(msg) cout << msg;
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
//int db;
class SQLite3Command
{
public:
SQLite3Command()
{
db = NULL;
}
~SQLite3Command()
{
sqlite3_free(db);
}
struct EXEC_RESULT
{
vector<string> colsName;
vector< vector<string> > records;
};
inline static void show_table(const vector< vector<string> > &data)
{
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data[i].size(); j++) {
DEBUGMSGN(data[i][j] << "\t\033[0;33m|\033[0m")
}
DEBUGMSG("");
}
}
int open(const string &path)
{
return open(path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
}
int open(const string &path, int flag, const char *szVfs)
{
int ret;
ret = sqlite3_open_v2(path.c_str(), &db, flag, szVfs);
if (ret) {
DEBUGMSGRED("[SQLite3DB open error] @ sqlite3_open_v2")
return ret;
}
ret = registerCharacterTokenizer();
if (ret) {
DEBUGMSGRED("[SQLite3DB open error] @ registerCharacterTokenizer")
return ret;
}
return ret;
}
int exec(const string &cmd)
{
return exec(cmd, 0, 0);
}
static int _execDefaultCallback(void *pData, int argc, char **cols, char **colsName)
{
EXEC_RESULT *result = (EXEC_RESULT*) pData;
result->records.push_back(vector<string>());
for (int i = 0; i < argc; i++) {
int pos = result->records.size() - 1;
if (pos == 0) {
result->colsName.push_back(colsName[i]);
}
result->records[pos].push_back(cols[i]);
}
return 0;
}
int exec(const string &cmd, vector< vector<string> > &data)
{
int ret;
EXEC_RESULT result;
char *errMsg = NULL;
ret = sqlite3_exec(db, cmd.c_str(), _execDefaultCallback, &result, &errMsg);
if (ret != SQLITE_OK) {
cmdFailed("exec", cmd, errMsg);
return ret;
}
data.clear();
// use '<=' instead of '<' for colsName
for (int i = 0; i <= result.records.size(); i++) {
data.push_back(vector<string>());
}
for (int i = 0; i < result.colsName.size(); i++) {
data[0].push_back(result.colsName[i]);
}
for (int i = 0; i < result.records.size(); i++) {
for (int j = 0; j < result.records[i].size(); j++) {
data[i+1].push_back(result.records[i][j]);
}
}
return ret;
}
int exec_and_show(const string &cmd)
{
int ret;
vector< vector<string> > data;
ret = exec(cmd, data);
if (ret) {
return ret;
}
DEBUGMSG("exec_and_show")
show_table(data);
return ret;
}
int exec(const string &cmd, int (*callback)(void*,int,char**,char**), void* data)
{
int ret;
char *errMsg = NULL;
ret = sqlite3_exec(db, cmd.c_str(), callback, data, &errMsg);
if (errMsg != NULL) {
cmdFailed("exec", cmd, errMsg);
return ret;
}
return 0;
}
/*
execf will not use reference.
because 'va_start' has undefined behavior with reference types.
*/
int execf(vector< vector<string> > *data, const string cmd, ...)
{
int ret;
va_list argv;
char *szSQL;
va_start(argv, cmd);
szSQL = sqlite3_vmprintf(cmd.c_str(), argv);
ret = exec(string(szSQL), *data);
sqlite3_free(szSQL);
return ret;
}
/*
execf without vector< vector<string> > data
*/
int execf_cmd_only(const string cmd, ...)
{
int ret;
va_list argv;
char *szSQL;
va_start(argv, cmd);
szSQL = sqlite3_vmprintf(cmd.c_str(), argv);
ret = exec(string(szSQL));
sqlite3_free(szSQL);
return ret;
}
int get_table(const string &query, int &rows, int &cols, vector< vector<string> > &result)
{
char **result_tmp;
int ret;
ret = get_table(query, rows, cols, result_tmp);
if (ret) {
return ret;
}
result.clear();
for (int i = 0; i <= rows; ++i) {
vector<string> tmp;
result.push_back(tmp);
for (int j = 0; j < cols; ++j) {
result[i].push_back(result_tmp[i*cols+j]);
}
}
return 0;
}
int get_table(const string &query, vector< vector<string> > &result)
{
int ret, rows, cols;
ret = get_table(query, rows, cols, result);
if (ret) {
return ret;
}
return 0;
}
int get_table_and_show(const string &query)
{
int ret, rows, cols;
vector< vector<string> > result;
ret = get_table(query, rows, cols, result);
if (ret) {
return ret;
}
DEBUGMSG("get_table_and_show " << rows << " " << cols)
show_table(result);
return 0;
}
int get_table(const string &query, int &rows, int &cols, char **&result)
{
char *errMsg = NULL;
sqlite3_get_table(db, query.c_str(), &result, &rows, &cols, &errMsg);
if (errMsg != NULL) {
cmdFailed("get_table", query, errMsg);
return 1;
}
return 0;
}
sqlite3 *getDB()
{
return db;
}
private:
sqlite3 *db;
int registerTokenizer(
sqlite3 *db,
const char *zName,
const sqlite3_tokenizer_module *p
){
int rc;
sqlite3_stmt *pStmt;
const char *zSql = "SELECT fts3_tokenizer(?, ?)";
rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
if( rc!=SQLITE_OK ){
return rc;
}
sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
sqlite3_step(pStmt);
return sqlite3_finalize(pStmt);
}
int registerCharacterTokenizer()
{
int ret;
const string tokenName = "character";
const sqlite3_tokenizer_module *ptr;
get_character_tokenizer_module(&ptr);
ret = registerTokenizer(db, tokenName.c_str(), ptr);
if (ret) {
DEBUGMSGRED("[SQLite3DB init error] can't register character tokenizer")
}
return ret;
}
inline void cmdFailed(const string &tag, const string &cmd, char *errMsg)
{
DEBUGMSGBROWN(">>> " << cmd)
DEBUGMSGRED("[SQLite3DB " << tag << " failed] " << errMsg)
sqlite3_free(errMsg);
}
};
int main()
{
SQLite3Command PG;
SQLite3Command *ptr = new SQLite3Command();
delete ptr;
vector< vector<string> > tmp;
PG.open("example.db");
PG.exec("asdf");
PG.get_table_and_show("SELECT * from note");
PG.execf_cmd_only("sjaksdf %Q %Q %d", "asdf", "ffff", 1234);
DEBUGMSGGREEN("=== result of INSERT")
PG.execf(&tmp, "INSERT INTO note VALUES(%Q, %Q);", "Insert Test", "Insert Content");
PG.show_table(tmp);
DEBUGMSGGREEN("=== result of SELECT")
PG.execf(&tmp, "SELECT * from note");
PG.show_table(tmp);
//PG.exec_and_show("select * from note");
DEBUGMSGRED("Red test")
DEBUGMSGGREEN("Green test")
DEBUGMSGBROWN("Brown test")
DEBUGMSGCYAN("Cyan test")
}<|endoftext|> |
<commit_before>/*
* Copyright 2016 Marcus Soll
*
* 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 "global.h"
#include "randomvocabulary.h"
#include "simpleinterface.h"
#include "trainer.h"
#include "settingsproxy.h"
#include "fileutils.h"
#include "csvhandle.h"
#include <QtQuick>
#include <sailfishapp.h>
bool create_new_db();
bool test_and_update_db();
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationName("harbour-vocabulary");
QCoreApplication::setApplicationName("harbour-vocabulary");
// Register QML types
qmlRegisterType<Trainer>("harbour.vocabulary.Trainer", 1, 0, "Trainer");
qmlRegisterType<SettingsProxy>("harbour.vocabulary.SettingsProxy", 1, 0, "SettingsProxy");
qmlRegisterType<CSVHandle>("harbour.vocabulary.CSVHandle", 1, 0, "CSVHandle");
// Connect to DB
QString path = QString(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
QDir dir(path);
if(!dir.exists())
{
DEBUG("Creating directory" << path);
dir.mkpath(path);
}
path.append("/database.sqlite3");
QFile file(path);
bool exists = file.exists();
database.setDatabaseName(path);
if(!database.open())
{
DEBUG(database.lastError().text());
FATAL("Can not open database.sqlite3");
}
if(!exists)
{
if(!create_new_db())
{
database.close();
file.remove();
FATAL("Can't create database.sqlite3");
}
}
else
{
if(!test_and_update_db())
{
database.close();
file.remove();
FATAL("Can't read/update database.sqlite3");
}
}
// Add classes to QQuickView
QGuiApplication *app = SailfishApp::application(argc,argv);
QQuickView *view = SailfishApp::createView();
RandomVocabulary random_vocabulary;
SimpleInterface simple_interface;
FileUtils file_utils;
view->rootContext()->setContextProperty("random_vocabulary", &random_vocabulary);
view->rootContext()->setContextProperty("simple_interface", &simple_interface);
view->rootContext()->setContextProperty("file_utils", &file_utils);
// Start application
view->setSource(SailfishApp::pathTo("qml/harbour-vocabulary.qml"));
view->show();
int return_value = app->exec();
database.close();
return return_value;
}
bool create_new_db()
{
DEBUG("Creating database");
QSqlQuery query(database);
QStringList operations;
operations.append("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)");
operations.append("CREATE TABLE vocabulary (word TEXT PRIMARY KEY, translation TEXT, priority INT)");
operations.append("INSERT INTO meta VALUES ('version', '1')");
foreach(QString s, operations)
{
if(!query.exec(s))
{
QString error = s.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
}
return true;
}
bool test_and_update_db()
{
QSqlQuery query(database);
QStringList operations;
QString s = QString("SELECT value FROM meta WHERE key='version'");
if(!query.exec(s))
{
QString error = s.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
if(!query.isSelect())
{
QString error = s.append(": No SELECT");
CRITICAL(error);
return false;
}
if(!query.next())
{
WARNING("No metadata 'version'");
return false;
}
switch(query.value(0).toInt())
{
// Upgrade settings
case 1:
DEBUG("Database version: 1");
return true;
break;
// For later usage
for(QStringList::const_iterator s = operations.cbegin(); s != operations.cend(); ++s)
{
if(!query.exec(*s))
{
QString error = *s;
error.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
}
DEBUG("Upgrade complete");
default:
WARNING("Unknown database version");
return false;
break;
}
}
<commit_msg>Added routine to simplify all words in database<commit_after>/*
* Copyright 2016 Marcus Soll
*
* 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 "global.h"
#include "randomvocabulary.h"
#include "simpleinterface.h"
#include "trainer.h"
#include "settingsproxy.h"
#include "fileutils.h"
#include "csvhandle.h"
#include <QtQuick>
#include <sailfishapp.h>
bool create_new_db();
bool test_and_update_db();
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationName("harbour-vocabulary");
QCoreApplication::setApplicationName("harbour-vocabulary");
// Register QML types
qmlRegisterType<Trainer>("harbour.vocabulary.Trainer", 1, 0, "Trainer");
qmlRegisterType<SettingsProxy>("harbour.vocabulary.SettingsProxy", 1, 0, "SettingsProxy");
qmlRegisterType<CSVHandle>("harbour.vocabulary.CSVHandle", 1, 0, "CSVHandle");
// Connect to DB
QString path = QString(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
QDir dir(path);
if(!dir.exists())
{
DEBUG("Creating directory" << path);
dir.mkpath(path);
}
path.append("/database.sqlite3");
QFile file(path);
bool exists = file.exists();
database.setDatabaseName(path);
if(!database.open())
{
DEBUG(database.lastError().text());
FATAL("Can not open database.sqlite3");
}
if(!exists)
{
if(!create_new_db())
{
database.close();
file.remove();
FATAL("Can't create database.sqlite3");
}
}
else
{
if(!test_and_update_db())
{
database.close();
file.remove();
FATAL("Can't read/update database.sqlite3");
}
}
// Add classes to QQuickView
QGuiApplication *app = SailfishApp::application(argc,argv);
QQuickView *view = SailfishApp::createView();
RandomVocabulary random_vocabulary;
SimpleInterface simple_interface;
FileUtils file_utils;
view->rootContext()->setContextProperty("random_vocabulary", &random_vocabulary);
view->rootContext()->setContextProperty("simple_interface", &simple_interface);
view->rootContext()->setContextProperty("file_utils", &file_utils);
// Start application
view->setSource(SailfishApp::pathTo("qml/harbour-vocabulary.qml"));
view->show();
int return_value = app->exec();
database.close();
return return_value;
}
bool create_new_db()
{
DEBUG("Creating database");
QSqlQuery query(database);
QStringList operations;
operations.append("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)");
operations.append("CREATE TABLE vocabulary (word TEXT PRIMARY KEY, translation TEXT, priority INT)");
operations.append("INSERT INTO meta VALUES ('version', '2')");
foreach(QString s, operations)
{
if(!query.exec(s))
{
QString error = s.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
}
return true;
}
bool test_and_update_db()
{
QSqlQuery query(database);
QStringList operations;
QString s = QString("SELECT value FROM meta WHERE key='version'");
if(!query.exec(s))
{
QString error = s.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
if(!query.isSelect())
{
QString error = s.append(": No SELECT");
CRITICAL(error);
return false;
}
if(!query.next())
{
WARNING("No metadata 'version'");
return false;
}
switch(query.value(0).toInt())
{
// Upgrade settings
case 1:
DEBUG("Database upgrade: 1 -> 2");
/*
* This database update simplifies all words contained in the database.
* It is needed because the old CSV import did not simplify.
*/
{
QStringList to_update;
s = "SELECT word FROM vocabulary";
query.clear();
query.prepare(s);
if(!query.exec())
{
QString error = s.append(": ").append(query.lastError().text());
WARNING(error);
return false;
}
if(!query.isSelect())
{
QString error = s.append(": No select");
WARNING(error);
return false;
}
while(query.next())
{
QString word = query.value(0).toString();
if(word.simplified() != word)
{
to_update << word;
}
}
for(QStringList::iterator i = to_update.begin(); i != to_update.end(); ++i)
{
s = "UPDATE OR IGNORE vocabulary SET word=? WHERE word=?";
query.clear();
query.prepare(s);
query.addBindValue((*i).simplified());
query.addBindValue(*i);
if(!query.exec())
{
QString error = s.append(": ").append(query.lastError().text());
WARNING(error);
}
}
query.clear();
s = "UPDATE meta SET value=2 WHERE key='version'";
if(!query.exec(s))
{
QString error = s.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
}
case 2:
DEBUG("Database version: 1");
return true;
break;
// For later usage
for(QStringList::const_iterator s = operations.cbegin(); s != operations.cend(); ++s)
{
if(!query.exec(*s))
{
QString error = *s;
error.append(": ").append(query.lastError().text());
CRITICAL(error);
return false;
}
}
DEBUG("Upgrade complete");
default:
WARNING("Unknown database version");
return false;
break;
}
}
<|endoftext|> |
<commit_before>#ifndef IMPL_AX_SYSTEM_HPP
#define IMPL_AX_SYSTEM_HPP
#include <cstddef>
#include <stdexcept>
#include <memory>
#include <functional>
#include <array>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include "prelude.hpp"
#include "string.hpp"
#include "vector.hpp"
#include "option.hpp"
#include "address.hpp"
#include "addressable.hpp"
#include "castable.hpp"
#include "eventable.hpp"
namespace ax
{
class entity;
class system;
using system_ptr = std::shared_ptr<ax::system>;
class world;
// A component in an entity-component-system.
struct component
{
CONSTRAINT(component);
bool active;
};
// A component that includes the address of the containing entity so that related components can be found.
struct composite_component : public ax::component
{
CONSTRAINT(composite_component);
ax::address address;
};
// The common data of an entity stored as a component.
struct entity_component : public ax::component
{
std::unordered_map<ax::name, ax::component*> components;
};
// A component that store multiple of the same type of component.
template<typename T, typename A, std::size_t N>
struct multi_component : public ax::component
{
CONSTRAINT(multi_component);
constexpr void static_check() { CONSTRAIN(T, component); }
ax::vector<T, A, N> components;
};
// A transform component.
// NOTE: of course, we'd instead use math library types in here.
struct transform : public ax::component
{
float x_pos;
float y_pos;
float rotation;
};
// A system in an entity-component-system.
class system : public ax::castable
{
public:
CONSTRAINT(system);
system(ax::world& world) : world(world) { }
virtual ~system() = default;
virtual ax::component& add_component(const ax::address& address) = 0;
virtual bool remove_component(const ax::address& address) = 0;
virtual ax::component* try_get_component(const ax::address& address) = 0;
virtual void update(int mode = 0) = 0;
protected:
ENABLE_CAST(ax::system, ax::castable);
ax::world& world;
};
template<typename T>
class system_t : public ax::system
{
public:
CONSTRAINT(system_t);
using component_t = T;
template<typename T> using reify = ax::system_t<T>;
system_t(std::size_t capacity = 128)
{
CONSTRAIN(T, ax::component);
components.reserve(capacity);
component_map.reserve(capacity);
}
T& add_component(const ax::address& address, const T& component)
{
if (free_list.empty())
{
components.push_back(component);
VAR& component_found = components.back();
component_found.active = false;
return component_found;
}
else
{
VAL index = free_list.front();
free_list.pop();
std::insert_or_assign(component_map, address, index);
VAR& component_found = components.at(index);
component_found = component;
component_found.active = true; // ensure active after assignment
return component_found;
}
}
T& add_component(const ax::address& address) override
{
return ax::system_t<T>::add_component(address, T());
}
bool remove_component(const ax::address& address) override
{
VAL index_iter = component_map.find(address);
if (index_iter != component_map.end())
{
VAL index = index_iter->second;
free_list.push(index);
VAR& component = components.at(index);
component.active = false;
component_map.erase(address);
return true;
}
return false;
}
T* try_get_component(const ax::address& address) override
{
VAL index_iter = component_map.find(address);
if (index_iter != component_map.end())
{
VAL index = index_iter->second;
return &components.at(index);
}
return nullptr;
}
void update(int mode) override
{
for (VAR& component : components)
{
update_component(component, mode);
}
}
virtual void update_component(T& component, int mode) = 0;
protected:
ENABLE_CAST(ax::system_t<T>, ax::system);
ax::vector<T> components;
std::unordered_map<ax::address, std::size_t> component_map;
std::queue<std::size_t> free_list;
};
template<typename S, typename A, std::size_t N>
class multi_system_t final : public ax::system_t<ax::multi_component<typename S::component_t, A, N>>
{
public:
CONSTRAINT(multi_system_t);
using component_t = typename S::component_t;
using multi_component_t = typename ax::multi_component<component_t, A, N>;
template<typename S, typename A, std::size_t N> using reify = ax::multi_system_t<S, A, N>;
multi_system_t(S& system) : system(system) { }
void update_component(multi_component_t& multicomponent, int mode) override
{
CONSTRAIN(S, ax::system_t<component_t>);
for (VAR& component : multi_component.components)
{
system.update_component(component, mode);
}
}
protected:
using multi_system_s_a_n = ax::multi_system_t<S, A, N>;
ENABLE_CAST(multi_system_s_a_n, ax::system_t<component_t>);
S& system;
};
// The world that contains the entity-component-system, event system, and other mixins.
// Uses function members because the type is not meant to be inherited.
class world final : public ax::eventable<ax::world>
{
public:
world(
std::function<void(ax::world& world)> initialize_systems_impl,
std::function<void(ax::world& world)> update_systems_impl,
std::function<void(ax::world& world)> clean_up_systems_impl);
template<typename T>
T* try_add_component(const ax::name& system_name, const ax::address& address, const T& component = T())
{
VAL& entities_iter = systems.find("entities");
if (entities_iter != systems.end())
{
VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);
VAR* entity_opt = entities->try_get_component(address);
if (entity_opt)
{
VAL& system_iter = systems.find(system_name);
if (system_iter != systems.end())
{
VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);
VAR& result = system->add_component(address, component);
std::insert_or_assign(entity_opt->components, system_name, &result);
return &result;
}
}
}
return nullptr;
}
template<typename T>
T* try_get_component(const ax::name& system_name, const ax::address& address)
{
VAL& entities_iter = systems.find("entities");
if (entities_iter != systems.end())
{
VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);
VAR* entity_opt = entities->try_get_component(address);
if (entity_opt)
{
VAL& system_iter = systems.find(system_name);
if (system_iter != systems.end())
{
VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);
return system->try_get_component(address);
}
}
}
return nullptr;
}
ax::transform* try_get_transform(const ax::address& address);
ax::entity_component* try_get_entity(const ax::address& address);
bool entity_exists(const ax::address& address);
ax::component* try_add_component(const ax::name& system_name, const ax::address& address);
bool try_remove_component(const ax::name& system_name, const ax::address& address);
ax::entity create_entity(const ax::address& address);
bool destroy_entity(const ax::address& address);
ax::system_ptr try_add_system(const ax::name& name, ax::system_ptr system);
bool remove_system(const ax::name& name);
void initialize_systems();
void update_systems();
void clean_up_systems();
private:
ax::entity_component* try_add_entity(const ax::address& address);
bool try_remove_entity(const ax::address& address);
std::unordered_map<ax::name, std::shared_ptr<ax::system>> systems;
std::function<void(ax::world& world)> initialize_systems_impl;
std::function<void(ax::world& world)> update_systems_impl;
std::function<void(ax::world& world)> clean_up_systems_impl;
};
// A handle to an entity in an entity-component-system.
class entity final : public ax::addressable
{
public:
entity(const ax::entity& other) = default;
entity(ax::entity&& other) = default;
ax::entity& operator=(const ax::entity& other) = default;
ax::entity& operator=(ax::entity&& other) = default;
entity(const ax::address& address, ax::world& world) : ax::addressable(address), world(world) { }
template<typename T>
const T* try_get_component(const ax::name& name) const { return world.try_get_component<T>(name, get_address()); }
template<typename T>
T* try_get_component(const ax::name& name) { return world.try_get_component<T>(name, get_address()); }
template<typename T>
const T& get_component(const ax::name& name) const { return *try_get_component<T>(name); }
template<typename T>
T& get_component(const ax::name& name)
{
VAR* component_opt = *try_get_component<T>(name);
if (component_opt) return *component_opt;
throw std::runtime_error("No component "_s + name.to_string() + " found at address " + get_address().to_string());
}
ax::transform& get_transform() const { return *world.try_get_transform(get_address()); }
ax::transform& set_transform(const ax::transform& transform) { return get_transform() = transform; }
float get_x_pos() const { return get_transform().x_pos; }
float set_x_pos(float value) { return get_transform().x_pos = value; }
float get_y_pos() const { return get_transform().y_pos; }
float set_y_pos(float value) { return get_transform().y_pos = value; }
float get_rotation() const { return get_transform().rotation; }
float set_rotation(float value) { return get_transform().rotation = value; }
bool exists() const { return world.entity_exists(get_address()); }
private:
ax::world& world;
};
}
#endif
<commit_msg>Fixed clang errors.<commit_after>#ifndef IMPL_AX_SYSTEM_HPP
#define IMPL_AX_SYSTEM_HPP
#include <cstddef>
#include <stdexcept>
#include <memory>
#include <functional>
#include <array>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include "prelude.hpp"
#include "string.hpp"
#include "vector.hpp"
#include "option.hpp"
#include "address.hpp"
#include "addressable.hpp"
#include "castable.hpp"
#include "eventable.hpp"
namespace ax
{
class entity;
class system;
using system_ptr = std::shared_ptr<ax::system>;
class world;
// A component in an entity-component-system.
struct component
{
CONSTRAINT(component);
bool active;
};
// A component that includes the address of the containing entity so that related components can be found.
struct composite_component : public ax::component
{
CONSTRAINT(composite_component);
ax::address address;
};
// The common data of an entity stored as a component.
struct entity_component : public ax::component
{
std::unordered_map<ax::name, ax::component*> components;
};
// A component that store multiple of the same type of component.
template<typename T, typename A, std::size_t N>
struct multi_component : public ax::component
{
CONSTRAINT(multi_component);
constexpr void static_check() { CONSTRAIN(T, component); }
ax::vector<T, A, N> components;
};
// A transform component.
// NOTE: of course, we'd instead use math library types in here.
struct transform : public ax::component
{
float x_pos;
float y_pos;
float rotation;
};
// A system in an entity-component-system.
class system : public ax::castable
{
public:
CONSTRAINT(system);
system(ax::world& world) : world(world) { }
virtual ~system() = default;
virtual ax::component& add_component(const ax::address& address) = 0;
virtual bool remove_component(const ax::address& address) = 0;
virtual ax::component* try_get_component(const ax::address& address) = 0;
virtual void update(int mode = 0) = 0;
protected:
ENABLE_CAST(ax::system, ax::castable);
ax::world& world;
};
template<typename T>
class system_t : public ax::system
{
public:
CONSTRAINT(system_t);
using component_t = T;
template<typename T2> using reify = ax::system_t<T2>;
system_t(std::size_t capacity = 128)
{
CONSTRAIN(T, ax::component);
components.reserve(capacity);
component_map.reserve(capacity);
}
T& add_component(const ax::address& address, const T& component)
{
if (free_list.empty())
{
components.push_back(component);
VAR& component_found = components.back();
component_found.active = false;
return component_found;
}
else
{
VAL index = free_list.front();
free_list.pop();
std::insert_or_assign(component_map, address, index);
VAR& component_found = components.at(index);
component_found = component;
component_found.active = true; // ensure active after assignment
return component_found;
}
}
T& add_component(const ax::address& address) override
{
return ax::system_t<T>::add_component(address, T());
}
bool remove_component(const ax::address& address) override
{
VAL index_iter = component_map.find(address);
if (index_iter != component_map.end())
{
VAL index = index_iter->second;
free_list.push(index);
VAR& component = components.at(index);
component.active = false;
component_map.erase(address);
return true;
}
return false;
}
T* try_get_component(const ax::address& address) override
{
VAL index_iter = component_map.find(address);
if (index_iter != component_map.end())
{
VAL index = index_iter->second;
return &components.at(index);
}
return nullptr;
}
void update(int mode) override
{
for (VAR& component : components)
{
update_component(component, mode);
}
}
virtual void update_component(T& component, int mode) = 0;
protected:
ENABLE_CAST(ax::system_t<T>, ax::system);
ax::vector<T> components;
std::unordered_map<ax::address, std::size_t> component_map;
std::queue<std::size_t> free_list;
};
template<typename S, typename A, std::size_t N>
class multi_system_t final : public ax::system_t<ax::multi_component<typename S::component_t, A, N>>
{
public:
CONSTRAINT(multi_system_t);
using component_t = typename S::component_t;
using multi_component_t = typename ax::multi_component<component_t, A, N>;
using system_t_t = ax::system_t<component_t>;
template<typename S2, typename A2, std::size_t N2> using reify = ax::multi_system_t<S2, A2, N2>;
multi_system_t(S& system) : system(system) { }
void update_component(multi_component_t& multi_component, int mode) override
{
CONSTRAIN(S, system_t_t);
for (VAR& component : multi_component.components)
{
system.update_component(component, mode);
}
}
protected:
using multi_system_s_a_n = ax::multi_system_t<S, A, N>;
ENABLE_CAST(multi_system_s_a_n, system_t_t);
S& system;
};
// The world that contains the entity-component-system, event system, and other mixins.
// Uses function members because the type is not meant to be inherited.
class world final : public ax::eventable<ax::world>
{
public:
world(
std::function<void(ax::world& world)> initialize_systems_impl,
std::function<void(ax::world& world)> update_systems_impl,
std::function<void(ax::world& world)> clean_up_systems_impl);
template<typename T>
T* try_add_component(const ax::name& system_name, const ax::address& address, const T& component = T())
{
VAL& entities_iter = systems.find("entities");
if (entities_iter != systems.end())
{
VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);
VAR* entity_opt = entities->try_get_component(address);
if (entity_opt)
{
VAL& system_iter = systems.find(system_name);
if (system_iter != systems.end())
{
VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);
VAR& result = system->add_component(address, component);
std::insert_or_assign(entity_opt->components, system_name, &result);
return &result;
}
}
}
return nullptr;
}
template<typename T>
T* try_get_component(const ax::name& system_name, const ax::address& address)
{
VAL& entities_iter = systems.find("entities");
if (entities_iter != systems.end())
{
VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);
VAR* entity_opt = entities->try_get_component(address);
if (entity_opt)
{
VAL& system_iter = systems.find(system_name);
if (system_iter != systems.end())
{
VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);
return system->try_get_component(address);
}
}
}
return nullptr;
}
ax::transform* try_get_transform(const ax::address& address);
ax::entity_component* try_get_entity(const ax::address& address);
bool entity_exists(const ax::address& address);
ax::component* try_add_component(const ax::name& system_name, const ax::address& address);
bool try_remove_component(const ax::name& system_name, const ax::address& address);
ax::entity create_entity(const ax::address& address);
bool destroy_entity(const ax::address& address);
ax::system_ptr try_add_system(const ax::name& name, ax::system_ptr system);
bool remove_system(const ax::name& name);
void initialize_systems();
void update_systems();
void clean_up_systems();
private:
ax::entity_component* try_add_entity(const ax::address& address);
bool try_remove_entity(const ax::address& address);
std::unordered_map<ax::name, std::shared_ptr<ax::system>> systems;
std::function<void(ax::world& world)> initialize_systems_impl;
std::function<void(ax::world& world)> update_systems_impl;
std::function<void(ax::world& world)> clean_up_systems_impl;
};
// A handle to an entity in an entity-component-system.
class entity final : public ax::addressable
{
public:
entity(const ax::entity& other) = default;
entity(ax::entity&& other) = default;
ax::entity& operator=(const ax::entity& other) = default;
ax::entity& operator=(ax::entity&& other) = default;
entity(const ax::address& address, ax::world& world) : ax::addressable(address), world(world) { }
template<typename T>
const T* try_get_component(const ax::name& name) const { return world.try_get_component<T>(name, get_address()); }
template<typename T>
T* try_get_component(const ax::name& name) { return world.try_get_component<T>(name, get_address()); }
template<typename T>
const T& get_component(const ax::name& name) const { return *try_get_component<T>(name); }
template<typename T>
T& get_component(const ax::name& name)
{
VAR* component_opt = *try_get_component<T>(name);
if (component_opt) return *component_opt;
throw std::runtime_error("No component "_s + name.to_string() + " found at address " + get_address().to_string());
}
ax::transform& get_transform() const { return *world.try_get_transform(get_address()); }
ax::transform& set_transform(const ax::transform& transform) { return get_transform() = transform; }
float get_x_pos() const { return get_transform().x_pos; }
float set_x_pos(float value) { return get_transform().x_pos = value; }
float get_y_pos() const { return get_transform().y_pos; }
float set_y_pos(float value) { return get_transform().y_pos = value; }
float get_rotation() const { return get_transform().rotation; }
float set_rotation(float value) { return get_transform().rotation = value; }
bool exists() const { return world.entity_exists(get_address()); }
private:
ax::world& world;
};
}
#endif
<|endoftext|> |
<commit_before>//
// ulib - a collection of useful classes
// Copyright (C) 2006,2007,2008,2012,2013,2016,2017 Michael Fink
//
/// \file Timer.hpp Timer class
//
#pragma once
#pragma warning(push)
#pragma warning(disable: 28159) // Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days. Code that does not take that into account can loop indefinitely. GetTickCount64 operates on 64 bit values and does not have that problem
/// \brief Timer class
/// \details Has a precision of about 15 ms. Has identical interface as class
/// HighResolutionTimer. Can be used in TraceOutputStopwatch.
class Timer
{
public:
/// ctor
Timer()
:m_isStarted(false),
m_tickStart(0),
m_totalElapsed(0)
{
}
/// starts timer; timer must be stopped or reset
void Start()
{
ATLASSERT(m_isStarted == false);
m_tickStart = GetTickCount();
m_isStarted = true;
}
/// stops timer; timer must be started
void Stop()
{
ATLASSERT(m_isStarted == true);
DWORD tickEnd = GetTickCount();
m_totalElapsed += (tickEnd - m_tickStart);
m_isStarted = false;
}
/// resets timer; timer must be stopped
void Reset()
{
ATLASSERT(m_isStarted == false); // must be stopped when calling Reset()
m_totalElapsed = 0;
}
/// restarts timer by resetting and starting again
void Restart()
{
// can either be stopped or started when restarting
if (m_isStarted)
Stop();
Reset();
Start();
}
/// returns elapsed time since Start() was called, in seconds
double Elapsed() const
{
if (!m_isStarted)
return 0.0; // no time elapsed, since timer isn't started
DWORD tickNow = GetTickCount();
return 0.001 * (tickNow - m_tickStart);
}
/// returns total elapsed time in seconds
double TotalElapsed() const
{
DWORD tickNow = GetTickCount();
return 0.001 * (m_totalElapsed + (m_isStarted ? (tickNow - m_tickStart) : 0));
}
/// returns if timer is running
bool IsStarted() const { return m_isStarted; }
private:
/// indicates if timer is started
bool m_isStarted;
/// tick count of start
DWORD m_tickStart;
/// number of ticks already elapsed
DWORD m_totalElapsed;
};
#pragma warning(pop)
<commit_msg>ignore warning C26451 when including Timer.hpp<commit_after>//
// ulib - a collection of useful classes
// Copyright (C) 2006,2007,2008,2012,2013,2016,2017 Michael Fink
//
/// \file Timer.hpp Timer class
//
#pragma once
#pragma warning(push)
#pragma warning(disable: 28159) // Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days. Code that does not take that into account can loop indefinitely. GetTickCount64 operates on 64 bit values and does not have that problem
/// \brief Timer class
/// \details Has a precision of about 15 ms. Has identical interface as class
/// HighResolutionTimer. Can be used in TraceOutputStopwatch.
class Timer
{
public:
/// ctor
Timer()
:m_isStarted(false),
m_tickStart(0),
m_totalElapsed(0)
{
}
/// starts timer; timer must be stopped or reset
void Start()
{
ATLASSERT(m_isStarted == false);
m_tickStart = GetTickCount();
m_isStarted = true;
}
/// stops timer; timer must be started
void Stop()
{
ATLASSERT(m_isStarted == true);
DWORD tickEnd = GetTickCount();
m_totalElapsed += (tickEnd - m_tickStart);
m_isStarted = false;
}
/// resets timer; timer must be stopped
void Reset()
{
ATLASSERT(m_isStarted == false); // must be stopped when calling Reset()
m_totalElapsed = 0;
}
/// restarts timer by resetting and starting again
void Restart()
{
// can either be stopped or started when restarting
if (m_isStarted)
Stop();
Reset();
Start();
}
/// returns elapsed time since Start() was called, in seconds
double Elapsed() const
{
if (!m_isStarted)
return 0.0; // no time elapsed, since timer isn't started
DWORD tickNow = GetTickCount();
return 0.001 * (tickNow - m_tickStart);
}
/// returns total elapsed time in seconds
double TotalElapsed() const
{
DWORD tickNow = GetTickCount();
#pragma warning(push)
#pragma warning(disable: 26451)
return 0.001 * (m_totalElapsed + (m_isStarted ? (tickNow - m_tickStart) : 0));
#pragma warning(pop)
}
/// returns if timer is running
bool IsStarted() const { return m_isStarted; }
private:
/// indicates if timer is started
bool m_isStarted;
/// tick count of start
DWORD m_tickStart;
/// number of ticks already elapsed
DWORD m_totalElapsed;
};
#pragma warning(pop)
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 2008-2009 by Rahul Nair and Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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. */
/* */
/************************************************************************/
/*++++++++++++++++++++INCLUDES+and+Definitions++++++++++++++++++++++++*/
#include <vigra/matlab.hxx>
#include <vigra/watersheds.hxx>
#include <vigra/watersheds3d.hxx>
#include <vigra/seededregiongrowing.hxx>
#include <vigra/seededregiongrowing3d.hxx>
using namespace vigra;
using namespace matlab;
//#define RN_DEBUG
#define cP3_(a, b , c) cP3<a, b, c>::value
template <class T>
void vigraMain(matlab::OutputArray outputs, matlab::InputArray inputs){
/***************************************************************************************************
** INIT PART **
****************************************************************************************************/
//Change these as for your needs.
typedef UInt32 outType;
typedef UInt32 seedType;
//Load Input Image
MultiArrayView<3,T> in3D = inputs.getMultiArray<3,T>(0, v_required());
BasicImageView<T> in = makeBasicImageView(in3D.bindOuter(0));
Int32 numOfDim = inputs.getDimOfInput(0, v_required());
//Load seed if provided
enum Methods{UNION = 0, SEED = 1} ;
Methods method = UNION;
MultiArrayView<3,seedType> seed3D = inputs.getMultiArray<3,seedType>("seeds", v_optional());
BasicImageView<seedType> seed = makeBasicImageView(seed3D.bindOuter(0));
if(seed3D.data()!= 0 && !(seed3D.shape() == in3D.shape()))
mexErrMsgTxt("Seed Array and Input Array Dimension/ Number of Value Mismatch");
if(seed3D.data()!= 0 ) method = SEED;
//Get right connectivity options
Int32 v2Dconn[2] = {8, 4};
Int32 v3Dconn[2] = {26, 6};
Int32 connectivity = (method == UNION)
? inputs.getScalarVals2D3D<int>("conn",
numOfDim == 2 ? v_default(8) : v_default(26),
v2Dconn, v2Dconn+2,
v3Dconn, v3Dconn+2,
numOfDim)
: inputs.getScalarVals2D3D<int>("conn",
numOfDim == 2 ? v_default(4) : v_default(6),
v2Dconn+1, v2Dconn+2,
v3Dconn+1, v3Dconn+2,
numOfDim);
//Get Crack options
VIGRA_CREATE_ENUM_AND_STD_MAP2(CrackMap, complete_grow, keep_contours);
int crack = inputs.getEnum("crack", v_default(complete_grow), CrackMap);
SRGType SRGcrack = (crack == complete_grow)? vigra::CompleteGrow : vigra::KeepContours;
double CostThreshold = inputs.getScalar<double>("CostThreshold", v_default(-1.0));
//Allocate space for outputArray.
MultiArrayView<3,outType> out3D = outputs.createMultiArray <3,outType> (0, v_required(), in3D.shape());
BasicImageView<outType> out(out3D.data(), in3D.shape(0), in3D.shape(1));
// contorPair maps 2 integers bijectively onto one dimension. (see Wikipedia Cantor pair Function)
UInt32 max_region_label = 0;
/***************************************************************************************************
** CODE PART **
****************************************************************************************************/
// contorPair maps 2 integers bijectively onto one dimension. (see Wikipedia Cantor pair Function)
switch(cantorPair(method, numOfDim, connectivity)){
//cP is the templated version o f the cantorPair function first value is Dimension of Inputimage, second the connectivity setting
//Code is basically the code on the VIGRA-reference page
case cP3_(UNION, IMAGE, 8):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION IMAGE 8");
#endif
max_region_label = watersheds(srcImageRange(in), destImage(out));
break;
case cP3_(UNION, IMAGE, 4):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION IMAGE 4");
#endif
max_region_label = watersheds(srcImageRange(in), destImage(out), FourNeighborCode());
break;
case cP3_(UNION, VOLUME, 26):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION VOLUME 26");
#endif
max_region_label = watersheds3DTwentySix(srcMultiArrayRange(in3D), destMultiArray(out3D));
break;
case cP3_(UNION, VOLUME, 6):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION VOLUME 6");
#endif
max_region_label = watersheds3DSix(srcMultiArrayRange(in3D), destMultiArray(out3D));
break;
case cP3_(SEED, IMAGE, 4):
{
#ifdef RN_DEBUG
mexWarnMsgTxt("SEED IMAGE 4");
#endif
//find maximimum of seed Image
FindMinMax<seedType> minmax; // init functor
inspectImage(srcImageRange(seed), minmax);
max_region_label = static_cast<UInt32>(minmax.max);
ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<seedType> >
gradstat(max_region_label);
seededRegionGrowing( srcImageRange(in),
srcImage(seed),
destImage(out),
gradstat,SRGcrack );
break;
}
case cP3_(SEED, VOLUME, 6):
{
#ifdef RN_DEBUG
mexWarnMsgTxt("SEED VOLUME 6");
#endif
FindMinMax<seedType> minmax;
inspectMultiArray(srcMultiArrayRange(seed3D), minmax);
max_region_label = static_cast<UInt32>(minmax.max);
ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<seedType> >
gradstat(max_region_label);
seededRegionGrowing3D( srcMultiArrayRange(in3D),
srcMultiArray(seed3D),
destMultiArray(out3D),
gradstat,CostThreshold, SRGcrack);
break;
}
default:
mexErrMsgTxt("Something went horribily wrong - Internal error");
}
outputs.createScalar(1,v_optional(), max_region_label);
}
void vigraMexFunction(vigra::matlab::OutputArray outputs, vigra::matlab::InputArray inputs)
{
//Add classes as you feel
switch(inputs.typeOf(0))
{
ALLOW_FD;
ALLOW_UINT;
ALLOW_INT;
default:
mexErrMsgTxt("Type of input 0 not supported");
}
}
/** MATLAB
function L = vigraWatershed(inputArray)
function L = vigraWatershed(inputArray, options);
L = vigraWatershed(inputArray);
Uses the union find algorithm to compute a label matrix identifying
the watershed regions of the inputArray (which may be 2 or 3 dimensional).
The elements of L are Int32 values greater than 0. Boundaries are
represented by crack edges, i.e. there are no explicit watershed pixels.
options = struct('seeds', seedImage, 'crack' = 'keepContours');
L = vigraWatershed(inputImage, options);
Uses seeded region growing to compute a label matrix identifying
the watershed regions of the inputArray (which may be 2 or 3 dimensional).
The elements of L are Int32 values greater than 0. Boundaries are
represented by explicit watershed pixels, i.e. there is a one-pixel
thick boundary between every pair of regions.
inputArray - a 2D or 3D array of type 'single' or 'double'
options - is a struct with the following possible fields
'seeds': An Array of same size as inputArray. If supplied, seeded region growing
shall be used. If not, the union find algorithm will be used. As of now,
the seed array has to be of same type as the input array - this will be changed in the next update.
'conn': 2D: 4 (default), 8 (only supported by the union find algorithm)
3D: 6 (default), 26 (only supported by the union find algorithm)
While using seeded region growing, only the default values can be used.
'crack': 'completeGrow' (default), 'keepContours' (only supported by seeded region growing and 2D Images)
Choose whether to keep watershed pixels or not. While using union find,
only the default value can be used.
'CostThreshold': -1.0 (default) - any double value.
If, at any point in the algorithm, the cost of the current candidate exceeds the optional
max_cost value (which defaults to -1), region growing is aborted, and all voxels not yet
assigned to a region remain unlabeled.
Usage:
opt = struct('fieldname' ,'value',....);
out = vigraWatershed(in, opt);
*/
<commit_msg>fixed watershed Matlab bindings<commit_after>/************************************************************************/
/* */
/* Copyright 2008-2009 by Rahul Nair and Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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. */
/* */
/************************************************************************/
/*++++++++++++++++++++INCLUDES+and+Definitions++++++++++++++++++++++++*/
#include <vigra/matlab.hxx>
#include <vigra/watersheds.hxx>
#include <vigra/watersheds3d.hxx>
#include <vigra/seededregiongrowing.hxx>
#include <vigra/seededregiongrowing3d.hxx>
using namespace vigra;
using namespace matlab;
//#define RN_DEBUG
#define cP3_(a, b , c) cP3<a, b, c>::value
template <class T>
void vigraMain(matlab::OutputArray outputs, matlab::InputArray inputs){
/***************************************************************************************************
** INIT PART **
****************************************************************************************************/
//Change these as for your needs.
typedef UInt32 outType;
typedef UInt32 seedType;
//Load Input Image
MultiArrayView<3,T> in3D = inputs.getMultiArray<3,T>(0, v_required());
BasicImageView<T> in = makeBasicImageView(in3D.bindOuter(0));
Int32 numOfDim = inputs.getDimOfInput(0, v_required());
//Load seed if provided
enum Methods{UNION = 0, SEED = 1} ;
Methods method = UNION;
MultiArrayView<3,seedType> seed3D = inputs.getMultiArray<3,seedType>("seeds", v_optional());
BasicImageView<seedType> seed = makeBasicImageView(seed3D.bindOuter(0));
if(seed3D.data()!= 0 && !(seed3D.shape() == in3D.shape()))
mexErrMsgTxt("Seed Array and Input Array Dimension/ Number of Value Mismatch");
if(seed3D.data()!= 0 ) method = SEED;
//Get right connectivity options
Int32 v2Dconn[2] = {8, 4};
Int32 v3Dconn[2] = {26, 6};
Int32 connectivity = (method == UNION)
? inputs.getScalarVals2D3D<int>("conn",
numOfDim == 2 ? v_default(8) : v_default(26),
v2Dconn, v2Dconn+2,
v3Dconn, v3Dconn+2,
numOfDim)
: inputs.getScalarVals2D3D<int>("conn",
numOfDim == 2 ? v_default(4) : v_default(6),
v2Dconn+1, v2Dconn+2,
v3Dconn+1, v3Dconn+2,
numOfDim);
//Get Crack options
VIGRA_CREATE_ENUM_AND_STD_MAP2(CrackMap, complete_grow, keep_contours);
int crack = inputs.getEnum("crack", v_default(complete_grow), CrackMap);
SRGType SRGcrack = (crack == complete_grow)? vigra::CompleteGrow : vigra::KeepContours;
double CostThreshold = inputs.getScalar<double>("CostThreshold", v_default(-1.0));
if(CostThreshold >= 0.0)
SRGcrack = (SRGType)(SRGcrack | StopAtThreshold);
//Allocate space for outputArray.
MultiArrayView<3,outType> out3D = outputs.createMultiArray <3,outType> (0, v_required(), in3D.shape());
BasicImageView<outType> out(out3D.data(), in3D.shape(0), in3D.shape(1));
// contorPair maps 2 integers bijectively onto one dimension. (see Wikipedia Cantor pair Function)
UInt32 max_region_label = 0;
/***************************************************************************************************
** CODE PART **
****************************************************************************************************/
// contorPair maps 2 integers bijectively onto one dimension. (see Wikipedia Cantor pair Function)
switch(cantorPair(method, numOfDim, connectivity)){
//cP is the templated version o f the cantorPair function first value is Dimension of Inputimage, second the connectivity setting
//Code is basically the code on the VIGRA-reference page
case cP3_(UNION, IMAGE, 8):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION IMAGE 8");
#endif
max_region_label = watersheds(srcImageRange(in), destImage(out));
break;
case cP3_(UNION, IMAGE, 4):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION IMAGE 4");
#endif
max_region_label = watersheds(srcImageRange(in), destImage(out), FourNeighborCode());
break;
case cP3_(UNION, VOLUME, 26):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION VOLUME 26");
#endif
max_region_label = watersheds3DTwentySix(srcMultiArrayRange(in3D), destMultiArray(out3D));
break;
case cP3_(UNION, VOLUME, 6):
#ifdef RN_DEBUG
mexWarnMsgTxt("UNION VOLUME 6");
#endif
max_region_label = watersheds3DSix(srcMultiArrayRange(in3D), destMultiArray(out3D));
break;
case cP3_(SEED, IMAGE, 4):
{
#ifdef RN_DEBUG
mexWarnMsgTxt("SEED IMAGE 4");
#endif
//find maximimum of seed Image
FindMinMax<seedType> minmax; // init functor
inspectImage(srcImageRange(seed), minmax);
max_region_label = static_cast<UInt32>(minmax.max);
ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<seedType> >
gradstat(max_region_label);
seededRegionGrowing( srcImageRange(in),
srcImage(seed),
destImage(out),
gradstat,SRGcrack, FourNeighborCode(), CostThreshold );
break;
}
case cP3_(SEED, VOLUME, 6):
{
#ifdef RN_DEBUG
mexWarnMsgTxt("SEED VOLUME 6");
#endif
FindMinMax<seedType> minmax;
inspectMultiArray(srcMultiArrayRange(seed3D), minmax);
max_region_label = static_cast<UInt32>(minmax.max);
ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<seedType> >
gradstat(max_region_label);
seededRegionGrowing3D( srcMultiArrayRange(in3D),
srcMultiArray(seed3D),
destMultiArray(out3D),
gradstat, SRGcrack, NeighborCode3DSix(), CostThreshold);
break;
}
default:
mexErrMsgTxt("Something went horribily wrong - Internal error");
}
outputs.createScalar(1,v_optional(), max_region_label);
}
void vigraMexFunction(vigra::matlab::OutputArray outputs, vigra::matlab::InputArray inputs)
{
//Add classes as you feel
switch(inputs.typeOf(0))
{
ALLOW_FD;
ALLOW_UINT;
ALLOW_INT;
default:
mexErrMsgTxt("Type of input 0 not supported");
}
}
/** MATLAB
function L = vigraWatershed(inputArray)
function L = vigraWatershed(inputArray, options);
L = vigraWatershed(inputArray);
Uses the union find algorithm to compute a label matrix identifying
the watershed regions of the inputArray (which may be 2 or 3 dimensional).
The elements of L are Int32 values greater than 0. Boundaries are
represented by crack edges, i.e. there are no explicit watershed pixels.
options = struct('seeds', seedImage, 'crack' = 'keepContours');
L = vigraWatershed(inputImage, options);
Uses seeded region growing to compute a label matrix identifying
the watershed regions of the inputArray (which may be 2 or 3 dimensional).
The elements of L are Int32 values greater than 0. Boundaries are
represented by explicit watershed pixels, i.e. there is a one-pixel
thick boundary between every pair of regions.
inputArray - a 2D or 3D array of type 'single' or 'double'
options - is a struct with the following possible fields
'seeds': An Array of same size as inputArray. If supplied, seeded region growing
shall be used. If not, the union find algorithm will be used. As of now,
the seed array has to be of same type as the input array - this will be changed in the next update.
'conn': 2D: 4 (default), 8 (only supported by the union find algorithm)
3D: 6 (default), 26 (only supported by the union find algorithm)
While using seeded region growing, only the default values can be used.
'crack': 'completeGrow' (default), 'keepContours' (only supported by seeded region growing and 2D Images)
Choose whether to keep watershed pixels or not. While using union find,
only the default value can be used.
'CostThreshold': -1.0 (default) - any double value.
If, at any point in the algorithm, the cost of the current candidate exceeds the optional
max_cost value (which defaults to -1), region growing is aborted, and all voxels not yet
assigned to a region remain unlabeled.
Usage:
opt = struct('fieldname' ,'value',....);
out = vigraWatershed(in, opt);
*/
<|endoftext|> |
<commit_before>#include "FaceDetector.h"
#include <string>
/**
* Open camera stream
* Load pretrained XML file
*/
void FaceDetector::load() {
camera.open(camNumber);
try {
faceCascade.load(cascadeFileName);
}
catch(cv::Exception e){}
if (faceCascade.empty()) {
std::cerr << "ERROR: Couldn't load Face Detector: ";
std::cerr << cascadeFileName << std::endl;
exit(1);
}
}
/**
* Detecting and showing the image
*/
float FaceDetector::detect() {
float xCoord = 0.5f;
std::vector<cv::Rect> faces;
cv::Mat grayFrame;
// Grayscale color conversion:
if (frame.channels() == 3) {
cvtColor(frame, grayFrame, CV_BGR2GRAY);
}
else if (frame.channels() == 4) {
cvtColor(frame, grayFrame, CV_BGRA2GRAY);
}
else {
grayFrame = frame;
}
// Shrinking the camera image to increase speed:
/*const int DETECTION_WIDTH = 320;
cv::Mat smallImg;
float scale = frame.cols / (float)DETECTION_WIDTH;
if (frame.cols > DETECTION_WIDTH) {
int scaledHeight = cvRound(frame.rows / scale);
cv::resize(frame, smallImg, cv::Size(DETECTION_WIDTH, scaledHeight));
}
else {
smallImg = frame;
}*/
// Histogram equalization:
equalizeHist(grayFrame, grayFrame);
// Detecting the face:
faceCascade.detectMultiScale(grayFrame, faces, 1.1f, 4, cv::CASCADE_SCALE_IMAGE, cv::Size(80, 80));
// Iterate over all of the faces
for (size_t i = 0; i < faces.size(); i++) {
// Find center of faces
cv::Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
// Draw ellipse around face
cv::ellipse(frame, center, cv::Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, cv::Scalar(0, 255, 255), 4, 8, 0);
xCoord = (float)center.x / camera.get(CV_CAP_PROP_FRAME_WIDTH);
//cv::imshow(detector.getWindowName(), detector.detectedFrame());
}
cv::imshow(windowName, frame);
cv::waitKey(5);
return xCoord;
}
/**
* Reading the actual camera image
*/
void FaceDetector::read() {
camera.read(frame);
}<commit_msg>flip camera image so that it's more user-friendly<commit_after>#include "FaceDetector.h"
#include <string>
/**
* Open camera stream
* Load pretrained XML file
*/
void FaceDetector::load() {
camera.open(camNumber);
try {
faceCascade.load(cascadeFileName);
}
catch(cv::Exception e){}
if (faceCascade.empty()) {
std::cerr << "ERROR: Couldn't load Face Detector: ";
std::cerr << cascadeFileName << std::endl;
exit(1);
}
}
/**
* Detecting and showing the image
*/
float FaceDetector::detect() {
float xCoord = 0.5f;
std::vector<cv::Rect> faces;
cv::Mat grayFrame;
// Grayscale color conversion:
if (frame.channels() == 3) {
cvtColor(frame, grayFrame, CV_BGR2GRAY);
}
else if (frame.channels() == 4) {
cvtColor(frame, grayFrame, CV_BGRA2GRAY);
}
else {
grayFrame = frame;
}
// Shrinking the camera image to increase speed:
/*const int DETECTION_WIDTH = 320;
cv::Mat smallImg;
float scale = frame.cols / (float)DETECTION_WIDTH;
if (frame.cols > DETECTION_WIDTH) {
int scaledHeight = cvRound(frame.rows / scale);
cv::resize(frame, smallImg, cv::Size(DETECTION_WIDTH, scaledHeight));
}
else {
smallImg = frame;
}*/
// Histogram equalization:
equalizeHist(grayFrame, grayFrame);
// Detecting the face:
faceCascade.detectMultiScale(grayFrame, faces, 1.1f, 4, cv::CASCADE_SCALE_IMAGE, cv::Size(80, 80));
// Iterate over all of the faces
for (size_t i = 0; i < faces.size(); i++) {
// Find center of faces
cv::Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
// Draw ellipse around face
cv::ellipse(frame, center, cv::Size(faces[i].width / 2, faces[i].height / 2), 0, 0, 360, cv::Scalar(0, 255, 255), 4, 8, 0);
xCoord = (float)center.x / camera.get(CV_CAP_PROP_FRAME_WIDTH);
//cv::imshow(detector.getWindowName(), detector.detectedFrame());
}
cv::imshow(windowName, frame);
cv::waitKey(5);
return xCoord;
}
/**
* Reading the actual camera image
*/
void FaceDetector::read() {
cv::Mat temp;
camera.read(temp);
cv::flip(temp, frame, 1);
}<|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 "QXmppVCardIq.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";
}
QXmppVCardIq::QXmppVCardIq(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 QXmppVCardIq::birthday() const
{
return m_birthday;
}
/// Sets the date of birth of the individual associated with the vCard.
///
/// \param birthday
void QXmppVCardIq::setBirthday(const QDate &birthday)
{
m_birthday = birthday;
}
/// Returns the email address.
///
QString QXmppVCardIq::email() const
{
return m_email;
}
/// Sets the email address.
///
/// \param email
void QXmppVCardIq::setEmail(const QString &email)
{
m_email = email;
}
/// Returns the first name.
///
QString QXmppVCardIq::firstName() const
{
return m_firstName;
}
/// Sets the first name.
///
/// \param firstName
void QXmppVCardIq::setFirstName(const QString &firstName)
{
m_firstName = firstName;
}
/// Returns the full name.
///
QString QXmppVCardIq::fullName() const
{
return m_fullName;
}
/// Sets the full name.
///
/// \param fullName
void QXmppVCardIq::setFullName(const QString &fullName)
{
m_fullName = fullName;
}
/// Returns the last name.
///
QString QXmppVCardIq::lastName() const
{
return m_lastName;
}
/// Sets the last name.
///
/// \param lastName
void QXmppVCardIq::setLastName(const QString &lastName)
{
m_lastName = lastName;
}
/// Returns the middle name.
///
QString QXmppVCardIq::middleName() const
{
return m_middleName;
}
/// Sets the middle name.
///
/// \param middleName
void QXmppVCardIq::setMiddleName(const QString &middleName)
{
m_middleName = middleName;
}
/// Returns the nickname.
///
QString QXmppVCardIq::nickName() const
{
return m_nickName;
}
/// Sets the nickname.
///
/// \param nickName
void QXmppVCardIq::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 QXmppVCardIq::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 QXmppVCardIq::setUrl(const QString& url)
{
m_url = url;
}
/// Returns the photo's binary contents.
///
/// If you want to use the photo as a QImage you can use:
///
/// \code
/// QBuffer buffer;
/// buffer.setData(myCard.photo());
/// buffer.open(QIODevice::ReadOnly);
/// QImageReader imageReader(&buffer);
/// QImage myImage = imageReader.read();
/// \endcode
QByteArray QXmppVCardIq::photo() const
{
return m_photo;
}
/// Sets the photo's binary contents.
void QXmppVCardIq::setPhoto(const QByteArray& photo)
{
m_photo = photo;
}
/// Returns the photo's MIME type.
QString QXmppVCardIq::photoType() const
{
return m_photoType;
}
/// Sets the photo's MIME type.
void QXmppVCardIq::setPhotoType(const QString& photoType)
{
m_photoType = photoType;
}
bool QXmppVCardIq::isVCard(const QDomElement &nodeRecv)
{
return nodeRecv.firstChildElement("vCard").namespaceURI() == ns_vcard;
}
void QXmppVCardIq::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 QXmppVCardIq::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 QXmppVCardIq::photoAsImage() const
{
QBuffer buffer;
buffer.setData(m_photo);
buffer.open(QIODevice::ReadOnly);
QImageReader imageReader(&buffer);
return imageReader.read();
}
void QXmppVCardIq::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 QXmppVCardIq::getFullName() const
{
return m_fullName;
}
QString QXmppVCardIq::getNickName() const
{
return m_nickName;
}
const QByteArray& QXmppVCardIq::getPhoto() const
{
return m_photo;
}
#ifndef QXMPP_NO_GUI
QImage QXmppVCardIq::getPhotoAsImage() const
{
return photoAsImage();
}
#endif
<commit_msg>remove internal usage of deprecated function<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 "QXmppVCardIq.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";
}
QXmppVCardIq::QXmppVCardIq(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 QXmppVCardIq::birthday() const
{
return m_birthday;
}
/// Sets the date of birth of the individual associated with the vCard.
///
/// \param birthday
void QXmppVCardIq::setBirthday(const QDate &birthday)
{
m_birthday = birthday;
}
/// Returns the email address.
///
QString QXmppVCardIq::email() const
{
return m_email;
}
/// Sets the email address.
///
/// \param email
void QXmppVCardIq::setEmail(const QString &email)
{
m_email = email;
}
/// Returns the first name.
///
QString QXmppVCardIq::firstName() const
{
return m_firstName;
}
/// Sets the first name.
///
/// \param firstName
void QXmppVCardIq::setFirstName(const QString &firstName)
{
m_firstName = firstName;
}
/// Returns the full name.
///
QString QXmppVCardIq::fullName() const
{
return m_fullName;
}
/// Sets the full name.
///
/// \param fullName
void QXmppVCardIq::setFullName(const QString &fullName)
{
m_fullName = fullName;
}
/// Returns the last name.
///
QString QXmppVCardIq::lastName() const
{
return m_lastName;
}
/// Sets the last name.
///
/// \param lastName
void QXmppVCardIq::setLastName(const QString &lastName)
{
m_lastName = lastName;
}
/// Returns the middle name.
///
QString QXmppVCardIq::middleName() const
{
return m_middleName;
}
/// Sets the middle name.
///
/// \param middleName
void QXmppVCardIq::setMiddleName(const QString &middleName)
{
m_middleName = middleName;
}
/// Returns the nickname.
///
QString QXmppVCardIq::nickName() const
{
return m_nickName;
}
/// Sets the nickname.
///
/// \param nickName
void QXmppVCardIq::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 QXmppVCardIq::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 QXmppVCardIq::setUrl(const QString& url)
{
m_url = url;
}
/// Returns the photo's binary contents.
///
/// If you want to use the photo as a QImage you can use:
///
/// \code
/// QBuffer buffer;
/// buffer.setData(myCard.photo());
/// buffer.open(QIODevice::ReadOnly);
/// QImageReader imageReader(&buffer);
/// QImage myImage = imageReader.read();
/// \endcode
QByteArray QXmppVCardIq::photo() const
{
return m_photo;
}
/// Sets the photo's binary contents.
void QXmppVCardIq::setPhoto(const QByteArray& photo)
{
m_photo = photo;
}
/// Returns the photo's MIME type.
QString QXmppVCardIq::photoType() const
{
return m_photoType;
}
/// Sets the photo's MIME type.
void QXmppVCardIq::setPhotoType(const QString& photoType)
{
m_photoType = photoType;
}
bool QXmppVCardIq::isVCard(const QDomElement &nodeRecv)
{
return nodeRecv.firstChildElement("vCard").namespaceURI() == ns_vcard;
}
void QXmppVCardIq::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 QXmppVCardIq::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 QXmppVCardIq::photoAsImage() const
{
QBuffer buffer;
buffer.setData(m_photo);
buffer.open(QIODevice::ReadOnly);
QImageReader imageReader(&buffer);
return imageReader.read();
}
void QXmppVCardIq::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 QXmppVCardIq::getFullName() const
{
return m_fullName;
}
QString QXmppVCardIq::getNickName() const
{
return m_nickName;
}
const QByteArray& QXmppVCardIq::getPhoto() const
{
return m_photo;
}
#ifndef QXMPP_NO_GUI
QImage QXmppVCardIq::getPhotoAsImage() const
{
QBuffer buffer;
buffer.setData(m_photo);
buffer.open(QIODevice::ReadOnly);
QImageReader imageReader(&buffer);
return imageReader.read();
}
#endif
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>"
// Copyright 2007 Inge Wallin <ingwa@kde.org>"
//
#include "QtMainWindow.h"
#include <QtGui/QAction>
#include <QtGui/QWhatsThis>
#include <QtGui/QApplication>
#include <QtGui/QIcon>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QPrintDialog>
#include <QtGui/QPrinter>
#include <QtGui/QPainter>
#include <QtGui/QClipboard>
#include "lib/katlasaboutdialog.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
m_katlascontrol = new KAtlasControl(this);
setWindowTitle( tr("Marble - Desktop Globe") );
setCentralWidget(m_katlascontrol);
createActions();
createMenus();
createStatusBar();
}
void MainWindow::createActions()
{
openAct = new QAction( QIcon(":/icons/document-open.png"), tr( "&Open File"), this );
openAct->setShortcut( tr( "Ctrl+O" ) );
openAct->setStatusTip( tr( "Open a file for viewing on Marble"));
connect( openAct, SIGNAL( triggered() ),
this, SLOT( openFile() ) );
exportMapAct = new QAction( QIcon(":/icons/document-save-as.png"), tr("&Export Map..."), this);
exportMapAct->setShortcut(tr("Ctrl+S"));
exportMapAct->setStatusTip(tr("Save a screenshot of the map"));
connect(exportMapAct, SIGNAL(triggered()), this, SLOT(exportMapScreenShot()));
printAct = new QAction( QIcon(":/icons/document-print.png"), tr("&Print..."), this);
printAct->setShortcut(tr("Ctrl+P"));
printAct->setStatusTip(tr("Print a screenshot of the map"));
connect(printAct, SIGNAL(triggered()), this, SLOT(printMapScreenShot()));
quitAct = new QAction( QIcon(":/icons/application-exit.png"), tr("&Quit"), this);
quitAct->setShortcut(tr("Ctrl+Q"));
quitAct->setStatusTip(tr("Quit the Application"));
connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
copyMapAct = new QAction( QIcon(":/icons/edit-copy.png"), tr("&Copy Map"), this);
copyMapAct->setShortcut(tr("Ctrl+C"));
copyMapAct->setStatusTip(tr("Copy a screenshot of the map"));
connect(copyMapAct, SIGNAL(triggered()), this, SLOT(copyMap()));
whatsThisAct = new QAction( QIcon(":/icons/help-whatsthis.png"), tr("What's &This"), this);
whatsThisAct->setShortcut(tr("Shift+F1"));
whatsThisAct->setStatusTip(tr("Show a detailed explanation of the action."));
connect(whatsThisAct, SIGNAL(triggered()), this, SLOT(enterWhatsThis()));
aboutMarbleAct = new QAction( QIcon(":/icons/marble.png"), tr("&About Marble Desktop Globe"), this);
aboutMarbleAct->setStatusTip(tr("Show the application's About Box"));
connect(aboutMarbleAct, SIGNAL(triggered()), this, SLOT(aboutMarble()));
aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
fileMenu->addAction(exportMapAct);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(quitAct);
fileMenu = menuBar()->addMenu(tr("&Edit"));
fileMenu->addAction(copyMapAct);
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(whatsThisAct);
helpMenu->addSeparator();
helpMenu->addAction(aboutMarbleAct);
helpMenu->addAction(aboutQtAct);
}
void MainWindow::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
void MainWindow::exportMapScreenShot()
{
QPixmap mapPixmap = m_katlascontrol->mapScreenShot();
QString fileName = QFileDialog::getSaveFileName(this, tr("Export Map"), // krazy:exclude=qclasses
QDir::homePath(),
tr("Images (*.jpg *.png)"));
if ( !fileName.isEmpty() )
{
bool success = mapPixmap.save( fileName );
if ( success == false )
{
QMessageBox::warning(this, tr("Marble"), // krazy:exclude=qclasses
tr( "An error occurred while trying to save the file.\n" ),
QMessageBox::Ok);
}
}
}
void MainWindow::printMapScreenShot()
{
QPixmap mapPixmap = m_katlascontrol->mapScreenShot();
QSize printSize = mapPixmap.size();
QPrinter* printer = new QPrinter();
QPrintDialog printDialog(printer, this);
if (printDialog.exec() == QDialog::Accepted) {
QRect mapPageRect = printer->pageRect();
printSize.scale( ( printer->pageRect() ).size(), Qt::KeepAspectRatio );
QPoint printTopLeft( mapPageRect.x() + mapPageRect.width() /2 - printSize.width() /2 ,
mapPageRect.y() + mapPageRect.height()/2 - printSize.height()/2 );
QRect mapPrintRect( printTopLeft, printSize );
QPainter painter( printer );
painter.drawPixmap( mapPrintRect, mapPixmap, mapPixmap.rect() );
}
}
void MainWindow::copyMap()
{
QPixmap mapPixmap = m_katlascontrol->mapScreenShot();
QClipboard *clipboard = QApplication::clipboard();
clipboard->setPixmap( mapPixmap );
}
void MainWindow::enterWhatsThis()
{
QWhatsThis::enterWhatsThisMode();
}
void MainWindow::aboutMarble()
{
KAtlasAboutDialog dlg(this);
dlg.exec();
}
void MainWindow::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), QString(), tr("GPS Data (*.gpx)"));
m_katlascontrol->marbleWidget()->openGpxFile( fileName );
}
#include "QtMainWindow.moc"
<commit_msg>Ooops, forgot this fix.<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>"
// Copyright 2007 Inge Wallin <ingwa@kde.org>"
//
#include "QtMainWindow.h"
#include <QtGui/QAction>
#include <QtGui/QWhatsThis>
#include <QtGui/QApplication>
#include <QtGui/QIcon>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QPrintDialog>
#include <QtGui/QPrinter>
#include <QtGui/QPainter>
#include <QtGui/QClipboard>
#include "lib/katlasaboutdialog.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
m_katlascontrol = new KAtlasControl(this);
setWindowTitle( tr("Marble - Desktop Globe") );
setCentralWidget(m_katlascontrol);
createActions();
createMenus();
createStatusBar();
}
void MainWindow::createActions()
{
openAct = new QAction( QIcon(":/icons/document-open.png"), tr( "&Open..."), this );
openAct->setShortcut( tr( "Ctrl+O" ) );
openAct->setStatusTip( tr( "Open a file for viewing on Marble"));
connect( openAct, SIGNAL( triggered() ),
this, SLOT( openFile() ) );
exportMapAct = new QAction( QIcon(":/icons/document-save-as.png"), tr("&Export Map..."), this);
exportMapAct->setShortcut(tr("Ctrl+S"));
exportMapAct->setStatusTip(tr("Save a screenshot of the map"));
connect(exportMapAct, SIGNAL(triggered()), this, SLOT(exportMapScreenShot()));
printAct = new QAction( QIcon(":/icons/document-print.png"), tr("&Print..."), this);
printAct->setShortcut(tr("Ctrl+P"));
printAct->setStatusTip(tr("Print a screenshot of the map"));
connect(printAct, SIGNAL(triggered()), this, SLOT(printMapScreenShot()));
quitAct = new QAction( QIcon(":/icons/application-exit.png"), tr("&Quit"), this);
quitAct->setShortcut(tr("Ctrl+Q"));
quitAct->setStatusTip(tr("Quit the Application"));
connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
copyMapAct = new QAction( QIcon(":/icons/edit-copy.png"), tr("&Copy Map"), this);
copyMapAct->setShortcut(tr("Ctrl+C"));
copyMapAct->setStatusTip(tr("Copy a screenshot of the map"));
connect(copyMapAct, SIGNAL(triggered()), this, SLOT(copyMap()));
whatsThisAct = new QAction( QIcon(":/icons/help-whatsthis.png"), tr("What's &This"), this);
whatsThisAct->setShortcut(tr("Shift+F1"));
whatsThisAct->setStatusTip(tr("Show a detailed explanation of the action."));
connect(whatsThisAct, SIGNAL(triggered()), this, SLOT(enterWhatsThis()));
aboutMarbleAct = new QAction( QIcon(":/icons/marble.png"), tr("&About Marble Desktop Globe"), this);
aboutMarbleAct->setStatusTip(tr("Show the application's About Box"));
connect(aboutMarbleAct, SIGNAL(triggered()), this, SLOT(aboutMarble()));
aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
fileMenu->addAction(exportMapAct);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(quitAct);
fileMenu = menuBar()->addMenu(tr("&Edit"));
fileMenu->addAction(copyMapAct);
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(whatsThisAct);
helpMenu->addSeparator();
helpMenu->addAction(aboutMarbleAct);
helpMenu->addAction(aboutQtAct);
}
void MainWindow::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
void MainWindow::exportMapScreenShot()
{
QPixmap mapPixmap = m_katlascontrol->mapScreenShot();
QString fileName = QFileDialog::getSaveFileName(this, tr("Export Map"), // krazy:exclude=qclasses
QDir::homePath(),
tr("Images (*.jpg *.png)"));
if ( !fileName.isEmpty() )
{
bool success = mapPixmap.save( fileName );
if ( success == false )
{
QMessageBox::warning(this, tr("Marble"), // krazy:exclude=qclasses
tr( "An error occurred while trying to save the file.\n" ),
QMessageBox::Ok);
}
}
}
void MainWindow::printMapScreenShot()
{
QPixmap mapPixmap = m_katlascontrol->mapScreenShot();
QSize printSize = mapPixmap.size();
QPrinter* printer = new QPrinter();
QPrintDialog printDialog(printer, this);
if (printDialog.exec() == QDialog::Accepted) {
QRect mapPageRect = printer->pageRect();
printSize.scale( ( printer->pageRect() ).size(), Qt::KeepAspectRatio );
QPoint printTopLeft( mapPageRect.x() + mapPageRect.width() /2 - printSize.width() /2 ,
mapPageRect.y() + mapPageRect.height()/2 - printSize.height()/2 );
QRect mapPrintRect( printTopLeft, printSize );
QPainter painter( printer );
painter.drawPixmap( mapPrintRect, mapPixmap, mapPixmap.rect() );
}
}
void MainWindow::copyMap()
{
QPixmap mapPixmap = m_katlascontrol->mapScreenShot();
QClipboard *clipboard = QApplication::clipboard();
clipboard->setPixmap( mapPixmap );
}
void MainWindow::enterWhatsThis()
{
QWhatsThis::enterWhatsThisMode();
}
void MainWindow::aboutMarble()
{
KAtlasAboutDialog dlg(this);
dlg.exec();
}
void MainWindow::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), QString(), tr("GPS Data (*.gpx)"));
m_katlascontrol->marbleWidget()->openGpxFile( fileName );
}
#include "QtMainWindow.moc"
<|endoftext|> |
<commit_before>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
#include "hadesmem/process.hpp"
#include <array>
#include <utility>
#include <iostream>
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/assert.hpp>
#include <boost/scope_exit.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
namespace hadesmem
{
Process::Process(DWORD id)
: id_(id),
handle_(Open(id))
{
CheckWoW64();
}
Process::Process(Process const& other)
: id_(0),
handle_(nullptr)
{
HANDLE const new_handle = Duplicate(other.handle_);
handle_ = new_handle;
id_ = other.id_;
}
Process& Process::operator=(Process const& other)
{
HANDLE const new_handle = Duplicate(other.handle_);
Cleanup();
handle_ = new_handle;
id_ = other.id_;
return *this;
}
Process::Process(Process&& other) BOOST_NOEXCEPT
: id_(other.id_),
handle_(other.handle_)
{
other.id_ = 0;
other.handle_ = nullptr;
}
Process& Process::operator=(Process&& other) BOOST_NOEXCEPT
{
Cleanup();
id_ = other.id_;
handle_ = other.handle_;
other.id_ = 0;
other.handle_ = nullptr;
return *this;
}
Process::~Process()
{
CleanupUnchecked();
}
DWORD Process::GetId() const BOOST_NOEXCEPT
{
return id_;
}
HANDLE Process::GetHandle() const BOOST_NOEXCEPT
{
return handle_;
}
void Process::Cleanup()
{
if (!handle_)
{
return;
}
BOOST_ASSERT(id_);
if (!::CloseHandle(handle_))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CloseHandle failed.") <<
ErrorCodeWinLast(last_error));
}
id_ = 0;
handle_ = nullptr;
}
void Process::CheckWoW64() const
{
BOOL is_wow64_me = FALSE;
if (!::IsWow64Process(GetCurrentProcess(), &is_wow64_me))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Could not detect WoW64 status of current process.") <<
ErrorCodeWinLast(last_error));
}
BOOL is_wow64 = FALSE;
if (!::IsWow64Process(handle_, &is_wow64))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Could not detect WoW64 status of target process.") <<
ErrorCodeWinLast(last_error));
}
if (is_wow64_me != is_wow64)
{
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Cross-architecture process manipulation is currently "
"unsupported."));
}
}
HANDLE Process::Open(DWORD id)
{
BOOST_ASSERT(id != 0);
HANDLE const handle = ::OpenProcess(PROCESS_ALL_ACCESS, TRUE, id);
if (!handle)
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("OpenProcess failed.") <<
ErrorCodeWinLast(last_error));
}
return handle;
}
void Process::CleanupUnchecked() BOOST_NOEXCEPT
{
try
{
Cleanup();
}
catch (std::exception const& e)
{
(void)e;
// WARNING: Handle is leaked if 'Cleanup' fails.
BOOST_ASSERT_MSG(false, boost::diagnostic_information(e).c_str());
id_ = 0;
handle_ = nullptr;
}
}
HANDLE Process::Duplicate(HANDLE handle)
{
BOOST_ASSERT(handle != nullptr);
HANDLE new_handle = nullptr;
if (!::DuplicateHandle(::GetCurrentProcess(), handle,
::GetCurrentProcess(), &new_handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("DuplicateHandle failed.") <<
ErrorCodeWinLast(last_error));
}
return new_handle;
}
bool operator==(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() == rhs.GetId();
}
bool operator!=(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return !(lhs == rhs);
}
bool operator<(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() < rhs.GetId();
}
bool operator<=(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() <= rhs.GetId();
}
bool operator>(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() > rhs.GetId();
}
bool operator>=(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() >= rhs.GetId();
}
std::ostream& operator<<(std::ostream& lhs, Process const& rhs)
{
return (lhs << rhs.GetId());
}
std::wostream& operator<<(std::wostream& lhs, Process const& rhs)
{
return (lhs << rhs.GetId());
}
std::wstring GetPath(Process const& process)
{
std::array<wchar_t, MAX_PATH> path = { { 0 } };
DWORD path_len = static_cast<DWORD>(path.size());
if (!::QueryFullProcessImageName(process.GetHandle(), 0, path.data(),
&path_len))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("QueryFullProcessImageName failed.") <<
ErrorCodeWinLast(last_error));
}
return path.data();
}
bool IsWoW64(Process const& process)
{
BOOL is_wow64 = FALSE;
if (!::IsWow64Process(process.GetHandle(), &is_wow64))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("IsWow64Process failed.") <<
ErrorCodeWinLast(last_error));
}
return is_wow64 != FALSE;
}
void GetSeDebugPrivilege()
{
HANDLE process_token = 0;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES |
TOKEN_QUERY, &process_token))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("OpenProcessToken failed.") <<
ErrorCodeWinLast(last_error));
}
BOOST_SCOPE_EXIT_ALL(&)
{
// WARNING: Handle is leaked if CloseHandle fails.
BOOST_VERIFY(::CloseHandle(process_token));
};
LUID luid = { 0, 0 };
if (!::LookupPrivilegeValue(nullptr, SE_DEBUG_NAME, &luid))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("LookupPrivilegeValue failed.") <<
ErrorCodeWinLast(last_error));
}
TOKEN_PRIVILEGES privileges;
::ZeroMemory(&privileges, sizeof(privileges));
privileges.PrivilegeCount = 1;
privileges.Privileges[0].Luid = luid;
privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!::AdjustTokenPrivileges(process_token, FALSE, &privileges,
sizeof(privileges), nullptr, nullptr) ||
::GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("AdjustTokenPrivileges failed.") <<
ErrorCodeWinLast(last_error));
}
}
}
<commit_msg>* Remove some assertions that makes otherwise idiomatic code harder to write.<commit_after>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
#include "hadesmem/process.hpp"
#include <array>
#include <utility>
#include <iostream>
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/assert.hpp>
#include <boost/scope_exit.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
namespace hadesmem
{
Process::Process(DWORD id)
: id_(id),
handle_(Open(id))
{
CheckWoW64();
}
Process::Process(Process const& other)
: id_(0),
handle_(nullptr)
{
HANDLE const new_handle = Duplicate(other.handle_);
handle_ = new_handle;
id_ = other.id_;
}
Process& Process::operator=(Process const& other)
{
HANDLE const new_handle = Duplicate(other.handle_);
Cleanup();
handle_ = new_handle;
id_ = other.id_;
return *this;
}
Process::Process(Process&& other) BOOST_NOEXCEPT
: id_(other.id_),
handle_(other.handle_)
{
other.id_ = 0;
other.handle_ = nullptr;
}
Process& Process::operator=(Process&& other) BOOST_NOEXCEPT
{
Cleanup();
id_ = other.id_;
handle_ = other.handle_;
other.id_ = 0;
other.handle_ = nullptr;
return *this;
}
Process::~Process()
{
CleanupUnchecked();
}
DWORD Process::GetId() const BOOST_NOEXCEPT
{
return id_;
}
HANDLE Process::GetHandle() const BOOST_NOEXCEPT
{
return handle_;
}
void Process::Cleanup()
{
if (!handle_)
{
return;
}
if (!::CloseHandle(handle_))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CloseHandle failed.") <<
ErrorCodeWinLast(last_error));
}
id_ = 0;
handle_ = nullptr;
}
void Process::CheckWoW64() const
{
BOOL is_wow64_me = FALSE;
if (!::IsWow64Process(GetCurrentProcess(), &is_wow64_me))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Could not detect WoW64 status of current process.") <<
ErrorCodeWinLast(last_error));
}
BOOL is_wow64 = FALSE;
if (!::IsWow64Process(handle_, &is_wow64))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Could not detect WoW64 status of target process.") <<
ErrorCodeWinLast(last_error));
}
if (is_wow64_me != is_wow64)
{
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Cross-architecture process manipulation is currently "
"unsupported."));
}
}
HANDLE Process::Open(DWORD id)
{
HANDLE const handle = ::OpenProcess(PROCESS_ALL_ACCESS, TRUE, id);
if (!handle)
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("OpenProcess failed.") <<
ErrorCodeWinLast(last_error));
}
return handle;
}
void Process::CleanupUnchecked() BOOST_NOEXCEPT
{
try
{
Cleanup();
}
catch (std::exception const& e)
{
(void)e;
// WARNING: Handle is leaked if 'Cleanup' fails.
BOOST_ASSERT_MSG(false, boost::diagnostic_information(e).c_str());
id_ = 0;
handle_ = nullptr;
}
}
HANDLE Process::Duplicate(HANDLE handle)
{
BOOST_ASSERT(handle != nullptr);
HANDLE new_handle = nullptr;
if (!::DuplicateHandle(::GetCurrentProcess(), handle,
::GetCurrentProcess(), &new_handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("DuplicateHandle failed.") <<
ErrorCodeWinLast(last_error));
}
return new_handle;
}
bool operator==(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() == rhs.GetId();
}
bool operator!=(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return !(lhs == rhs);
}
bool operator<(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() < rhs.GetId();
}
bool operator<=(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() <= rhs.GetId();
}
bool operator>(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() > rhs.GetId();
}
bool operator>=(Process const& lhs, Process const& rhs) BOOST_NOEXCEPT
{
return lhs.GetId() >= rhs.GetId();
}
std::ostream& operator<<(std::ostream& lhs, Process const& rhs)
{
return (lhs << rhs.GetId());
}
std::wostream& operator<<(std::wostream& lhs, Process const& rhs)
{
return (lhs << rhs.GetId());
}
std::wstring GetPath(Process const& process)
{
std::array<wchar_t, MAX_PATH> path = { { 0 } };
DWORD path_len = static_cast<DWORD>(path.size());
if (!::QueryFullProcessImageName(process.GetHandle(), 0, path.data(),
&path_len))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("QueryFullProcessImageName failed.") <<
ErrorCodeWinLast(last_error));
}
return path.data();
}
bool IsWoW64(Process const& process)
{
BOOL is_wow64 = FALSE;
if (!::IsWow64Process(process.GetHandle(), &is_wow64))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("IsWow64Process failed.") <<
ErrorCodeWinLast(last_error));
}
return is_wow64 != FALSE;
}
void GetSeDebugPrivilege()
{
HANDLE process_token = 0;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES |
TOKEN_QUERY, &process_token))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("OpenProcessToken failed.") <<
ErrorCodeWinLast(last_error));
}
BOOST_SCOPE_EXIT_ALL(&)
{
// WARNING: Handle is leaked if CloseHandle fails.
BOOST_VERIFY(::CloseHandle(process_token));
};
LUID luid = { 0, 0 };
if (!::LookupPrivilegeValue(nullptr, SE_DEBUG_NAME, &luid))
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("LookupPrivilegeValue failed.") <<
ErrorCodeWinLast(last_error));
}
TOKEN_PRIVILEGES privileges;
::ZeroMemory(&privileges, sizeof(privileges));
privileges.PrivilegeCount = 1;
privileges.Privileges[0].Luid = luid;
privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!::AdjustTokenPrivileges(process_token, FALSE, &privileges,
sizeof(privileges), nullptr, nullptr) ||
::GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("AdjustTokenPrivileges failed.") <<
ErrorCodeWinLast(last_error));
}
}
}
<|endoftext|> |
<commit_before>// $Id: mesh_communication.C,v 1.2 2003-09-25 21:46:56 benkirk Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2002-2003 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "libmesh_config.h"
#include "libmesh_common.h"
#include "mesh.h"
#include "mesh_base.h"
#include "boundary_info.h"
#include "mesh_communication.h"
// ------------------------------------------------------------
// MeshCommunication class members
void MeshCommunication::clear ()
{
}
void MeshCommunication::distribute (Mesh& mesh)
{
// Don't need to do anything if there is
// only one processor.
if (libMesh::n_processors() == 1)
return;
this->distribute_mesh (mesh);
this->distribute_bcs (mesh, mesh.boundary_info);
}
void MeshCommunication::distribute_mesh (MeshBase& mesh)
{
// Don't need to do anything if there is
// only one processor.
if (libMesh::n_processors() == 1)
return;
#ifdef HAVE_MPI
// Explicitly clear the mesh on all but processor 0.
if (libMesh::processor_id() != 0)
mesh.clear();
// Get important sizes
unsigned int n_nodes = mesh.n_nodes();
unsigned int n_elem = mesh.n_elem();
unsigned int total_weight = mesh.total_weight();
// Broadcast the number of nodes
MPI_Bcast (&n_nodes, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Send the number of elements
MPI_Bcast (&n_elem, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Send the total_weight
MPI_Bcast (&total_weight, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// First build up the pts vector which contains
// the spatial locations of all the nodes
{
std::vector<Real> pts;
// If we are processor 0, we must populate this vector and
// broadcast it to the other processors.
if (libMesh::processor_id() == 0)
{
pts.reserve (3*n_nodes);
const_node_iterator it (mesh.nodes_begin());
const const_node_iterator it_end (mesh.nodes_end());
for (; it != it_end; ++it)
{
assert (*it != NULL);
const Point& p = **it;
pts.push_back ( p(0) ); // x
pts.push_back ( p(1) ); // y
pts.push_back ( p(2) ); // z
}
}
else
pts.resize (3*n_nodes);
// Sanity check for all processors
assert (pts.size() == (3*n_nodes));
// Broadcast the pts vector
MPI_Bcast (&pts[0], pts.size(), MPI_REAL, 0, MPI_COMM_WORLD);
// Add the nodes we just received if we are not
// processor 0.
if (libMesh::processor_id() != 0)
{
assert (mesh.n_nodes() == 0);
for (unsigned int i=0; i<pts.size(); i += 3)
mesh.add_point (Point(pts[i+0],
pts[i+1],
pts[i+2])
);
}
assert (mesh.n_nodes() == n_nodes);
} // Done distributing the nodes
// Now build up the elements vector which
// contains the element types and connectivity
{
std::vector<unsigned int> conn;
// If we are processor 0, we must populate this vector and
// broadcast it to the other processors.
if (libMesh::processor_id() == 0)
{
conn.reserve (n_elem + total_weight);
const_elem_iterator it (mesh.elements_begin());
const const_elem_iterator it_end (mesh.elements_end());
for (; it != it_end; ++it)
{
const Elem* elem = *it;
assert (elem != NULL);
conn.push_back (static_cast<unsigned int>(elem->type()));
for (unsigned int n=0; n<elem->n_nodes(); n++)
conn.push_back (elem->node(n));
}
}
else
conn.resize (n_elem + total_weight);
// Sanity check for all processors
assert (conn.size() == (n_elem + total_weight));
// Broadcast the element connectivity
MPI_Bcast (&conn[0], conn.size(), MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Build the elements we just received if we are not
// processor 0.
if (libMesh::processor_id() != 0)
{
assert (mesh.n_elem() == 0);
unsigned int cnt = 0;
while (cnt < conn.size())
{
Elem* elem =
mesh.add_elem (Elem::build (static_cast<ElemType>(conn[cnt++])));
for (unsigned int n=0; n<elem->n_nodes(); n++)
{
assert (cnt < conn.size());
elem->set_node(n) = mesh.node_ptr (conn[cnt++]);
}
}
}
assert (mesh.n_elem() == n_elem);
} // Done distributing the elements
// Print the information in the mesh for sanity.
mesh.print_info();
#else
// no MPI but multiple processors? Huh??
error();
#endif
}
void MeshCommunication::distribute_bcs (MeshBase& mesh,
BoundaryInfo& boundary_info)
{
// Don't need to do anything if there is
// only one processor.
if (libMesh::n_processors() == 1)
return;
#ifdef HAVE_MPI
// Explicitly clear the boundary conditions on all
// but processor 0.
if (libMesh::processor_id() != 0)
boundary_info.clear();
// Build up the list of elements with boundary conditions
{
std::vector<unsigned int> el_id;
std::vector<unsigned short int> side_id;
std::vector<short int> bc_id;
if (libMesh::processor_id() == 0)
boundary_info.build_side_list (el_id, side_id, bc_id);
assert (el_id.size() == side_id.size());
assert (el_id.size() == bc_id.size());
unsigned int n_bcs = el_id.size();
// Broadcast the number of bcs to expect from processor 0.
MPI_Bcast (&n_bcs, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Allocate space.
el_id.resize (n_bcs);
side_id.resize (n_bcs);
bc_id.resize (n_bcs);
// Broadcast the element identities
MPI_Bcast (&el_id[0], n_bcs, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Broadcast the side ids for those elements
MPI_Bcast (&side_id[0], n_bcs, MPI_UNSIGNED_SHORT, 0, MPI_COMM_WORLD);
// Broadcast the bc ids for each side
MPI_Bcast (&bc_id[0], n_bcs, MPI_SHORT, 0, MPI_COMM_WORLD);
// Build the boundary_info structure if we aren't processor 0
if (libMesh::processor_id() != 0)
for (unsigned int e=0; e<n_bcs; e++)
{
assert (el_id[e] < mesh.n_elem());
const Elem* elem = mesh.elem(el_id[e]);
assert (elem != NULL);
assert (side_id[e] < elem->n_sides());
boundary_info.add_side (elem, side_id[e], bc_id[e]);
}
}
// Build up the list of nodes with boundary conditions
{
std::vector<unsigned int> node_id;
std::vector<short int> bc_id;
if (libMesh::processor_id() == 0)
boundary_info.build_node_list (node_id, bc_id);
assert (node_id.size() == bc_id.size());
unsigned int n_bcs = node_id.size();
// Broadcast the number of bcs to expect from processor 0.
MPI_Bcast (&n_bcs, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Allocate space.
node_id.resize (n_bcs);
bc_id.resize (n_bcs);
// Broadcast the node ids
MPI_Bcast (&node_id[0], n_bcs, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Broadcast the bc ids for each side
MPI_Bcast (&bc_id[0], n_bcs, MPI_SHORT, 0, MPI_COMM_WORLD);
// Build the boundary_info structure if we aren't processor 0
if (libMesh::processor_id() != 0)
for (unsigned int n=0; n<n_bcs; n++)
{
assert (node_id[n] < mesh.n_nodes());
const Node* node = mesh.node_ptr (node_id[n]);
assert (node != NULL);
boundary_info.add_node (node, bc_id[n]);
}
}
#else
// no MPI but multiple processors? Huh??
error();
#endif
}
<commit_msg>removed an unnecessary print statement left over from the development phase<commit_after>// $Id: mesh_communication.C,v 1.3 2003-11-18 23:04:20 benkirk Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2002-2003 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "libmesh_config.h"
#include "libmesh_common.h"
#include "mesh.h"
#include "mesh_base.h"
#include "boundary_info.h"
#include "mesh_communication.h"
// ------------------------------------------------------------
// MeshCommunication class members
void MeshCommunication::clear ()
{
}
void MeshCommunication::distribute (Mesh& mesh)
{
// Don't need to do anything if there is
// only one processor.
if (libMesh::n_processors() == 1)
return;
this->distribute_mesh (mesh);
this->distribute_bcs (mesh, mesh.boundary_info);
}
void MeshCommunication::distribute_mesh (MeshBase& mesh)
{
// Don't need to do anything if there is
// only one processor.
if (libMesh::n_processors() == 1)
return;
#ifdef HAVE_MPI
// Explicitly clear the mesh on all but processor 0.
if (libMesh::processor_id() != 0)
mesh.clear();
// Get important sizes
unsigned int n_nodes = mesh.n_nodes();
unsigned int n_elem = mesh.n_elem();
unsigned int total_weight = mesh.total_weight();
// Broadcast the number of nodes
MPI_Bcast (&n_nodes, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Send the number of elements
MPI_Bcast (&n_elem, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Send the total_weight
MPI_Bcast (&total_weight, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// First build up the pts vector which contains
// the spatial locations of all the nodes
{
std::vector<Real> pts;
// If we are processor 0, we must populate this vector and
// broadcast it to the other processors.
if (libMesh::processor_id() == 0)
{
pts.reserve (3*n_nodes);
const_node_iterator it (mesh.nodes_begin());
const const_node_iterator it_end (mesh.nodes_end());
for (; it != it_end; ++it)
{
assert (*it != NULL);
const Point& p = **it;
pts.push_back ( p(0) ); // x
pts.push_back ( p(1) ); // y
pts.push_back ( p(2) ); // z
}
}
else
pts.resize (3*n_nodes);
// Sanity check for all processors
assert (pts.size() == (3*n_nodes));
// Broadcast the pts vector
MPI_Bcast (&pts[0], pts.size(), MPI_REAL, 0, MPI_COMM_WORLD);
// Add the nodes we just received if we are not
// processor 0.
if (libMesh::processor_id() != 0)
{
assert (mesh.n_nodes() == 0);
for (unsigned int i=0; i<pts.size(); i += 3)
mesh.add_point (Point(pts[i+0],
pts[i+1],
pts[i+2])
);
}
assert (mesh.n_nodes() == n_nodes);
} // Done distributing the nodes
// Now build up the elements vector which
// contains the element types and connectivity
{
std::vector<unsigned int> conn;
// If we are processor 0, we must populate this vector and
// broadcast it to the other processors.
if (libMesh::processor_id() == 0)
{
conn.reserve (n_elem + total_weight);
const_elem_iterator it (mesh.elements_begin());
const const_elem_iterator it_end (mesh.elements_end());
for (; it != it_end; ++it)
{
const Elem* elem = *it;
assert (elem != NULL);
conn.push_back (static_cast<unsigned int>(elem->type()));
for (unsigned int n=0; n<elem->n_nodes(); n++)
conn.push_back (elem->node(n));
}
}
else
conn.resize (n_elem + total_weight);
// Sanity check for all processors
assert (conn.size() == (n_elem + total_weight));
// Broadcast the element connectivity
MPI_Bcast (&conn[0], conn.size(), MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Build the elements we just received if we are not
// processor 0.
if (libMesh::processor_id() != 0)
{
assert (mesh.n_elem() == 0);
unsigned int cnt = 0;
while (cnt < conn.size())
{
Elem* elem =
mesh.add_elem (Elem::build (static_cast<ElemType>(conn[cnt++])));
for (unsigned int n=0; n<elem->n_nodes(); n++)
{
assert (cnt < conn.size());
elem->set_node(n) = mesh.node_ptr (conn[cnt++]);
}
}
}
assert (mesh.n_elem() == n_elem);
} // Done distributing the elements
// Print the information in the mesh for sanity.
// mesh.print_info();
#else
// no MPI but multiple processors? Huh??
error();
#endif
}
void MeshCommunication::distribute_bcs (MeshBase& mesh,
BoundaryInfo& boundary_info)
{
// Don't need to do anything if there is
// only one processor.
if (libMesh::n_processors() == 1)
return;
#ifdef HAVE_MPI
// Explicitly clear the boundary conditions on all
// but processor 0.
if (libMesh::processor_id() != 0)
boundary_info.clear();
// Build up the list of elements with boundary conditions
{
std::vector<unsigned int> el_id;
std::vector<unsigned short int> side_id;
std::vector<short int> bc_id;
if (libMesh::processor_id() == 0)
boundary_info.build_side_list (el_id, side_id, bc_id);
assert (el_id.size() == side_id.size());
assert (el_id.size() == bc_id.size());
unsigned int n_bcs = el_id.size();
// Broadcast the number of bcs to expect from processor 0.
MPI_Bcast (&n_bcs, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Allocate space.
el_id.resize (n_bcs);
side_id.resize (n_bcs);
bc_id.resize (n_bcs);
// Broadcast the element identities
MPI_Bcast (&el_id[0], n_bcs, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Broadcast the side ids for those elements
MPI_Bcast (&side_id[0], n_bcs, MPI_UNSIGNED_SHORT, 0, MPI_COMM_WORLD);
// Broadcast the bc ids for each side
MPI_Bcast (&bc_id[0], n_bcs, MPI_SHORT, 0, MPI_COMM_WORLD);
// Build the boundary_info structure if we aren't processor 0
if (libMesh::processor_id() != 0)
for (unsigned int e=0; e<n_bcs; e++)
{
assert (el_id[e] < mesh.n_elem());
const Elem* elem = mesh.elem(el_id[e]);
assert (elem != NULL);
assert (side_id[e] < elem->n_sides());
boundary_info.add_side (elem, side_id[e], bc_id[e]);
}
}
// Build up the list of nodes with boundary conditions
{
std::vector<unsigned int> node_id;
std::vector<short int> bc_id;
if (libMesh::processor_id() == 0)
boundary_info.build_node_list (node_id, bc_id);
assert (node_id.size() == bc_id.size());
unsigned int n_bcs = node_id.size();
// Broadcast the number of bcs to expect from processor 0.
MPI_Bcast (&n_bcs, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Allocate space.
node_id.resize (n_bcs);
bc_id.resize (n_bcs);
// Broadcast the node ids
MPI_Bcast (&node_id[0], n_bcs, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// Broadcast the bc ids for each side
MPI_Bcast (&bc_id[0], n_bcs, MPI_SHORT, 0, MPI_COMM_WORLD);
// Build the boundary_info structure if we aren't processor 0
if (libMesh::processor_id() != 0)
for (unsigned int n=0; n<n_bcs; n++)
{
assert (node_id[n] < mesh.n_nodes());
const Node* node = mesh.node_ptr (node_id[n]);
assert (node != NULL);
boundary_info.add_node (node, bc_id[n]);
}
}
#else
// no MPI but multiple processors? Huh??
error();
#endif
}
<|endoftext|> |
<commit_before>#include <limits>
#include <cmath>
#include <cgo/minimax/minimax_agent.hpp>
using namespace cgo::base;
using namespace cgo::minimax;
MiniMaxAgent::MiniMaxAgent(Marker marker) :
Agent(marker), _turnNumber(0)
{}
/* virtual */ MiniMaxAgent::~MiniMaxAgent() {}
Move MiniMaxAgent::makeMove(State& state,
const boost::optional< Predecessor >& predecessor) {
// Make an intelligent first move.
if (this->_turnNumber == 0) {
++this->_turnNumber;
return this->makeFirstMove(state);
}
++this->_turnNumber;
return this->makeMiniMaxMove(state, predecessor);
}
Action MiniMaxAgent::makeFirstMove(const State& state) const {
const int crucialPoint = std::ceil(BOARD_DIMENSION / 3.0f) - 1;
Position p1(crucialPoint, crucialPoint);
if (state.getBoard()[State::getIndex(p1)] == none) {
return Action(this->_marker, p1);
}
Position p2(crucialPoint, (BOARD_DIMENSION - 1) - crucialPoint);
return Action(this->_marker, p2);
}
Move MiniMaxAgent::makeMiniMaxMove(State& state,
const boost::optional< Predecessor >& predecessor) const {
int alpha = std::numeric_limits<int>::min();
int beta = std::numeric_limits<int>::max();
int depth = this->getDepth(state);
auto maxMoveValue = this->mmAbMax(state, predecessor, alpha, beta, depth);
return std::get<0>(maxMoveValue);
}
std::tuple< Move, int > MiniMaxAgent::mmAbMax(State& state,
const boost::optional< Predecessor >& predecessor, int alpha, int beta,
int depth) const {
Move maxMove = Pass();
int maxValue = this->utility(maxMove, state);
if (predecessor) {
auto predecessorValue = predecessor.get();
Move predMove = std::get<0>(predecessorValue);
const Pass* pass = boost::get< Pass >(&predMove);
if ((pass != nullptr) && (maxValue > 0)) {
return std::make_tuple(Pass(), maxValue);
}
}
std::vector< Successor > successors =
state.getSuccessors(this->_marker, predecessor);
if (depth == 0) {
if (successors.size() > 0) {
Move chosenMove = std::get<0>(successors[0]);
int chosenScore = std::numeric_limits<int>::min();
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
int succScore = this->utility(succMove, succState);
if (succScore > chosenScore) {
chosenMove = succMove;
chosenScore = succScore;
}
}
return std::make_tuple(chosenMove, chosenScore);
} else {
return std::make_tuple(maxMove, maxValue);
}
}
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
auto minMoveValue = this->mmAbMin(succState, successor, alpha, beta,
depth - 1);
auto minMove = std::get<0>(minMoveValue);
auto minValue = std::get<1>(minMoveValue);
if (minValue > maxValue) {
maxMove = minMove;
maxValue = minValue;
}
if (maxValue >= beta) {
return std::make_tuple(maxMove, maxValue);
}
if (alpha < maxValue) {
alpha = maxValue;
maxMove = succMove;
}
}
return std::make_tuple(maxMove, maxValue);
}
std::tuple< Move, int > MiniMaxAgent::mmAbMin(State& state,
const boost::optional< Predecessor >& predecessor, int alpha, int beta,
int depth) const {
Move minMove = Pass();
int minValue = this->utility(minMove, state);
if (predecessor) {
auto predecessorValue = predecessor.get();
Move predMove = std::get<0>(predecessorValue);
const Pass* pass = boost::get< Pass >(&predMove);
if ((pass != nullptr) && (minValue < 0)) {
return std::make_tuple(Pass(), minValue);
}
}
std::vector< Successor > successors =
state.getSuccessors(this->_marker, predecessor);
if (depth == 0) {
if (successors.size() > 0) {
Move chosenMove = std::get<0>(successors[0]);
int chosenScore = std::numeric_limits<int>::max();
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
int succScore = this->utility(succMove, succState);
if (succScore < chosenScore) {
chosenMove = succMove;
chosenScore = succScore;
}
}
return std::make_tuple(chosenMove, chosenScore);
} else {
return std::make_tuple(minMove, minValue);
}
}
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
auto maxMoveValue = this->mmAbMax(succState, successor, alpha, beta,
depth - 1);
auto maxMove = std::get<0>(maxMoveValue);
auto maxValue = std::get<1>(maxMoveValue);
if (maxValue < minValue) {
minMove = maxMove;
minValue = maxValue;
}
if (minValue <= beta) {
return std::make_tuple(minMove, minValue);
}
if (beta > minValue) {
beta = minValue;
minMove = succMove;
}
}
return std::make_tuple(minMove, minValue);
}
bool MiniMaxAgent::checkBounds(int x, int y) const{
if (x < 0) {
return false;
}
if (x >= BOARD_DIMENSION) {
return false;
}
if (y < 0) {
return false;
}
if (y >= BOARD_DIMENSION) {
return false;
}
return true;
}
int MiniMaxAgent::pseudoControl(const Board& board) const{
int totalControl = 0;
static const int pieceVal = 5; //value for having a piece on a square
static const int controlVal = 10; //bonus value for having 'control' over a square
static const int weakVal = 10; //value for having weak presence on a square
static const int medVal = 20;
static const int strongVal = 30; //value for having strong presence on a square
static const int vStrongVal = 40; //value for having a very strong presence on a square
std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> wcontrol;
std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> bcontrol;
wcontrol.fill(0);
bcontrol.fill(0);
for (int x = 0; x < BOARD_DIMENSION; ++x) {
for (int y = 0; y < BOARD_DIMENSION; ++y) {
Marker curr = board[State::getIndex(Position(x, y))];
if (curr == white) {
if (checkBounds(x, y)) {
wcontrol[State::getIndex(Position(x, y))]++;
}
if (checkBounds(x, y + 1)) {
wcontrol[State::getIndex(Position(x, y + 1))]++;
}
if (checkBounds(x, y - 1)) {
wcontrol[State::getIndex(Position(x, y - 1))]++;
}
if (checkBounds(x + 1, y)) {
wcontrol[State::getIndex(Position(x + 1, y))]++;
}
if (checkBounds(x - 1, y)) {
wcontrol[State::getIndex(Position(x - 1, y))]++;
}
}
if (curr == black) {
if (checkBounds(x, y)) {
bcontrol[State::getIndex(Position(x, y))]++;
}
if (checkBounds(x, y + 1)) {
bcontrol[State::getIndex(Position(x, y + 1))]++;
}
if (checkBounds(x, y - 1)) {
bcontrol[State::getIndex(Position(x, y - 1))]++;
}
if (checkBounds(x + 1, y)) {
bcontrol[State::getIndex(Position(x + 1, y))]++;
}
if (checkBounds(x - 1, y)) {
bcontrol[State::getIndex(Position(x - 1, y))]++;
}
}
}
}
for (int x = 0; x < BOARD_DIMENSION; ++x) {
for (int y = 0; y < BOARD_DIMENSION; ++y) {
Marker curr = board[State::getIndex(Position(x, y))];
int control = 0;
if (wcontrol[State::getIndex(Position(x, y))] == 1) {
control += weakVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 5) {
control += medVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 2 || wcontrol[State::getIndex(Position(x, y))] == 4) {
control += strongVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 3) {
control += vStrongVal;
}
if (bcontrol[State::getIndex(Position(x, y))] == 1) {
control -= weakVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 5) {
control -= medVal;
}
if (bcontrol[State::getIndex(Position(x, y))] == 2 || bcontrol[State::getIndex(Position(x, y))] == 4) {
control -= strongVal;
}
if (bcontrol[State::getIndex(Position(x, y))] == 3) {
control -= vStrongVal;
}
if (curr == white ){
if (control > 0) {
//control = control * 1.5;
}
control += pieceVal;
}
if (curr == black){
if (control < 0) {
//control = control * 1.5;
}
control -= pieceVal;
}
if (bcontrol[State::getIndex(Position(x, y))] > 0 && wcontrol[State::getIndex(Position(x, y))] > 0) {
control *= 2;
}
if (control > 0) {
control += controlVal;
}
if (control < 0) {
control -= controlVal;
}
totalControl += control;
}
}
return totalControl;
}
std::tuple< int, int > MiniMaxAgent::edgeCosts(const Board& board) const {
int whiteCost = 0;
int blackCost = 0;
for (int ndx = 0; ndx < BOARD_DIMENSION; ++ndx) {
Marker rowMarker1 = board[State::getIndex(Position(ndx, 0))];
Marker rowMarker2 = board[State::getIndex(Position(ndx, BOARD_DIMENSION - 1))];
Marker colMarker1 = board[State::getIndex(Position(0, ndx))];
Marker colMarker2 = board[State::getIndex(Position(BOARD_DIMENSION - 1, ndx))];
if (rowMarker1 == white) {
++whiteCost;
}
if (rowMarker2 == white) {
++whiteCost;
}
if (colMarker1 == white) {
++whiteCost;
}
if (colMarker2 == white) {
++whiteCost;
}
if (rowMarker1 == black) {
++blackCost;
}
if (rowMarker2 == black) {
++blackCost;
}
if (colMarker1 == black) {
++blackCost;
}
if (colMarker2 == black) {
++blackCost;
}
}
return std::make_tuple(whiteCost, blackCost);
}
int MiniMaxAgent::utility(const Move& move, const State& state) const {
static const int scoreWeight = 1000;
static const int edgeWeight = 100;
static const int passWeight = 1;
auto control = MiniMaxAgent::pseudoControl(state.getBoard());
//control = (this->_marker == white) ? control : -control;
auto scores = state.getScores();
int scoreValue = std::get<0>(scores) - std::get<1>(scores);
auto edgeCosts = MiniMaxAgent::edgeCosts(state.getBoard());
int edgeValue = (this->_marker == white) ? -std::get<0>(edgeCosts) :
std::get<1>(edgeCosts);
int passValue = 0;
const Pass* pass = boost::get< Pass >(&move);
if (pass != nullptr) {
passValue = (this->_marker == white) ? 1 : -1;
}
int totalValue = scoreWeight * scoreValue + edgeWeight * edgeValue +
passWeight * passValue + control;
return (this->_marker == white) ? totalValue : -totalValue;
}
int MiniMaxAgent::getDepth(const base::State& state) const {
static const int maxNumCases = 5E5;
// Count open positions.
int numOpenPositions = 0;
for (int row = 0; row < BOARD_DIMENSION; ++row) {
for (int col = 0; col < BOARD_DIMENSION; ++col) {
int index = State::getIndex(Position(row, col));
if (state.getBoard()[index] == none) {
++numOpenPositions;
}
}
}
// Factorial.
int numPossibleCases = 1;
for (int ndx = numOpenPositions; ndx > 0; --ndx) {
numPossibleCases *= ndx;
if (numPossibleCases > maxNumCases) {
return (numOpenPositions - ndx) + 1;
}
}
return numOpenPositions + 1;
}
<commit_msg>Tune more. Is now a moderately reasonable opponent on 9x9.<commit_after>#include <limits>
#include <cmath>
#include <cgo/minimax/minimax_agent.hpp>
using namespace cgo::base;
using namespace cgo::minimax;
MiniMaxAgent::MiniMaxAgent(Marker marker) :
Agent(marker), _turnNumber(0)
{}
/* virtual */ MiniMaxAgent::~MiniMaxAgent() {}
Move MiniMaxAgent::makeMove(State& state,
const boost::optional< Predecessor >& predecessor) {
// Make an intelligent first move.
if (this->_turnNumber == 0) {
++this->_turnNumber;
return this->makeFirstMove(state);
}
++this->_turnNumber;
return this->makeMiniMaxMove(state, predecessor);
}
Action MiniMaxAgent::makeFirstMove(const State& state) const {
const int crucialPoint = std::ceil(BOARD_DIMENSION / 3.0f) - 1;
Position p1(crucialPoint, crucialPoint);
if (state.getBoard()[State::getIndex(p1)] == none) {
return Action(this->_marker, p1);
}
Position p2(crucialPoint, (BOARD_DIMENSION - 1) - crucialPoint);
return Action(this->_marker, p2);
}
Move MiniMaxAgent::makeMiniMaxMove(State& state,
const boost::optional< Predecessor >& predecessor) const {
int alpha = std::numeric_limits<int>::min();
int beta = std::numeric_limits<int>::max();
int depth = this->getDepth(state);
auto maxMoveValue = this->mmAbMax(state, predecessor, alpha, beta, depth);
return std::get<0>(maxMoveValue);
}
std::tuple< Move, int > MiniMaxAgent::mmAbMax(State& state,
const boost::optional< Predecessor >& predecessor, int alpha, int beta,
int depth) const {
Move maxMove = Pass();
int maxValue = this->utility(maxMove, state);
if (predecessor) {
auto predecessorValue = predecessor.get();
Move predMove = std::get<0>(predecessorValue);
const Pass* pass = boost::get< Pass >(&predMove);
if ((pass != nullptr) && (maxValue > 0)) {
return std::make_tuple(Pass(), maxValue);
}
}
std::vector< Successor > successors =
state.getSuccessors(this->_marker, predecessor);
if (depth == 0) {
if (successors.size() > 0) {
Move chosenMove = std::get<0>(successors[0]);
int chosenScore = std::numeric_limits<int>::min();
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
int succScore = this->utility(succMove, succState);
if (succScore > chosenScore) {
chosenMove = succMove;
chosenScore = succScore;
}
}
return std::make_tuple(chosenMove, chosenScore);
} else {
return std::make_tuple(maxMove, maxValue);
}
}
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
auto minMoveValue = this->mmAbMin(succState, successor, alpha, beta,
depth - 1);
auto minMove = std::get<0>(minMoveValue);
auto minValue = std::get<1>(minMoveValue);
if (minValue > maxValue) {
maxMove = minMove;
maxValue = minValue;
}
if (maxValue >= beta) {
return std::make_tuple(maxMove, maxValue);
}
if (alpha < maxValue) {
alpha = maxValue;
maxMove = succMove;
}
}
return std::make_tuple(maxMove, maxValue);
}
std::tuple< Move, int > MiniMaxAgent::mmAbMin(State& state,
const boost::optional< Predecessor >& predecessor, int alpha, int beta,
int depth) const {
Move minMove = Pass();
int minValue = this->utility(minMove, state);
if (predecessor) {
auto predecessorValue = predecessor.get();
Move predMove = std::get<0>(predecessorValue);
const Pass* pass = boost::get< Pass >(&predMove);
if ((pass != nullptr) && (minValue < 0)) {
return std::make_tuple(Pass(), minValue);
}
}
std::vector< Successor > successors =
state.getSuccessors(this->_marker, predecessor);
if (depth == 0) {
if (successors.size() > 0) {
Move chosenMove = std::get<0>(successors[0]);
int chosenScore = std::numeric_limits<int>::max();
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
int succScore = this->utility(succMove, succState);
if (succScore < chosenScore) {
chosenMove = succMove;
chosenScore = succScore;
}
}
return std::make_tuple(chosenMove, chosenScore);
} else {
return std::make_tuple(minMove, minValue);
}
}
for (auto successor : successors) {
auto succMove = std::get<0>(successor);
auto succState = std::get<1>(successor);
auto maxMoveValue = this->mmAbMax(succState, successor, alpha, beta,
depth - 1);
auto maxMove = std::get<0>(maxMoveValue);
auto maxValue = std::get<1>(maxMoveValue);
if (maxValue < minValue) {
minMove = maxMove;
minValue = maxValue;
}
if (minValue <= beta) {
return std::make_tuple(minMove, minValue);
}
if (beta > minValue) {
beta = minValue;
minMove = succMove;
}
}
return std::make_tuple(minMove, minValue);
}
bool MiniMaxAgent::checkBounds(int x, int y) const{
if (x < 0) {
return false;
}
if (x >= BOARD_DIMENSION) {
return false;
}
if (y < 0) {
return false;
}
if (y >= BOARD_DIMENSION) {
return false;
}
return true;
}
int MiniMaxAgent::pseudoControl(const Board& board) const{
int totalControl = 0;
static const int pieceVal = 5; //value for having a piece on a square
static const int controlVal = 10; //bonus value for having 'control' over a square
static const int weakVal = 10; //value for having weak presence on a square
static const int medVal = 20;
static const int strongVal = 30; //value for having strong presence on a square
static const int vStrongVal = 40; //value for having a very strong presence on a square
std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> wcontrol;
std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> bcontrol;
wcontrol.fill(0);
bcontrol.fill(0);
for (int x = 0; x < BOARD_DIMENSION; ++x) {
for (int y = 0; y < BOARD_DIMENSION; ++y) {
Marker curr = board[State::getIndex(Position(x, y))];
if (curr == white) {
if (checkBounds(x, y)) {
wcontrol[State::getIndex(Position(x, y))]++;
}
if (checkBounds(x, y + 1)) {
wcontrol[State::getIndex(Position(x, y + 1))]++;
}
if (checkBounds(x, y - 1)) {
wcontrol[State::getIndex(Position(x, y - 1))]++;
}
if (checkBounds(x + 1, y)) {
wcontrol[State::getIndex(Position(x + 1, y))]++;
}
if (checkBounds(x - 1, y)) {
wcontrol[State::getIndex(Position(x - 1, y))]++;
}
}
if (curr == black) {
if (checkBounds(x, y)) {
bcontrol[State::getIndex(Position(x, y))]++;
}
if (checkBounds(x, y + 1)) {
bcontrol[State::getIndex(Position(x, y + 1))]++;
}
if (checkBounds(x, y - 1)) {
bcontrol[State::getIndex(Position(x, y - 1))]++;
}
if (checkBounds(x + 1, y)) {
bcontrol[State::getIndex(Position(x + 1, y))]++;
}
if (checkBounds(x - 1, y)) {
bcontrol[State::getIndex(Position(x - 1, y))]++;
}
}
}
}
for (int x = 0; x < BOARD_DIMENSION; ++x) {
for (int y = 0; y < BOARD_DIMENSION; ++y) {
Marker curr = board[State::getIndex(Position(x, y))];
int control = 0;
if (wcontrol[State::getIndex(Position(x, y))] == 1) {
control += weakVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 5) {
control += medVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 2 || wcontrol[State::getIndex(Position(x, y))] == 4) {
control += strongVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 3) {
control += vStrongVal;
}
if (bcontrol[State::getIndex(Position(x, y))] == 1) {
control -= weakVal;
}
if (wcontrol[State::getIndex(Position(x, y))] == 5) {
control -= medVal;
}
if (bcontrol[State::getIndex(Position(x, y))] == 2 || bcontrol[State::getIndex(Position(x, y))] == 4) {
control -= strongVal;
}
if (bcontrol[State::getIndex(Position(x, y))] == 3) {
control -= vStrongVal;
}
if (curr == white ){
if (control > 0) {
control = control * 1.2;
}
control += pieceVal;
}
if (curr == black){
if (control < 0) {
control = control * 1.2;
}
control -= pieceVal;
}
if (bcontrol[State::getIndex(Position(x, y))] > 0 && wcontrol[State::getIndex(Position(x, y))] > 0) {
control *= 1.5;
}
if (control > 0) {
control += controlVal;
}
if (control < 0) {
control -= controlVal;
}
totalControl += control;
}
}
return totalControl;
}
std::tuple< int, int > MiniMaxAgent::edgeCosts(const Board& board) const {
int whiteCost = 0;
int blackCost = 0;
for (int ndx = 0; ndx < BOARD_DIMENSION; ++ndx) {
Marker rowMarker1 = board[State::getIndex(Position(ndx, 0))];
Marker rowMarker2 = board[State::getIndex(Position(ndx, BOARD_DIMENSION - 1))];
Marker colMarker1 = board[State::getIndex(Position(0, ndx))];
Marker colMarker2 = board[State::getIndex(Position(BOARD_DIMENSION - 1, ndx))];
if (rowMarker1 == white) {
++whiteCost;
}
if (rowMarker2 == white) {
++whiteCost;
}
if (colMarker1 == white) {
++whiteCost;
}
if (colMarker2 == white) {
++whiteCost;
}
if (rowMarker1 == black) {
++blackCost;
}
if (rowMarker2 == black) {
++blackCost;
}
if (colMarker1 == black) {
++blackCost;
}
if (colMarker2 == black) {
++blackCost;
}
}
return std::make_tuple(whiteCost, blackCost);
}
int MiniMaxAgent::utility(const Move& move, const State& state) const {
static const int scoreWeight = 1000;
static const int edgeWeight = 100;
static const int passWeight = 1;
auto control = MiniMaxAgent::pseudoControl(state.getBoard());
//control = (this->_marker == white) ? control : -control;
auto scores = state.getScores();
int scoreValue = std::get<0>(scores) - std::get<1>(scores);
auto edgeCosts = MiniMaxAgent::edgeCosts(state.getBoard());
int edgeValue = (this->_marker == white) ? -std::get<0>(edgeCosts) :
std::get<1>(edgeCosts);
int passValue = 0;
const Pass* pass = boost::get< Pass >(&move);
if (pass != nullptr) {
passValue = (this->_marker == white) ? 1 : -1;
}
int totalValue = scoreWeight * scoreValue + edgeWeight * edgeValue +
passWeight * passValue + control;
return (this->_marker == white) ? totalValue : -totalValue;
}
int MiniMaxAgent::getDepth(const base::State& state) const {
static const int maxNumCases = 5E5;
// Count open positions.
int numOpenPositions = 0;
for (int row = 0; row < BOARD_DIMENSION; ++row) {
for (int col = 0; col < BOARD_DIMENSION; ++col) {
int index = State::getIndex(Position(row, col));
if (state.getBoard()[index] == none) {
++numOpenPositions;
}
}
}
// Factorial.
int numPossibleCases = 1;
for (int ndx = numOpenPositions; ndx > 0; --ndx) {
numPossibleCases *= ndx;
if (numPossibleCases > maxNumCases) {
return (numOpenPositions - ndx) + 1;
}
}
return numOpenPositions + 1;
}
<|endoftext|> |
<commit_before>/**
* @file load.hpp
* @author Ryan Curtin
*
* Load an Armadillo matrix from file. This is necessary because Armadillo does
* not transpose matrices on input, and it allows us to give better error
* output.
*/
#ifndef __MLPACK_CORE_DATA_LOAD_HPP
#define __MLPACK_CORE_DATA_LOAD_HPP
#include <mlpack/core/util/log.hpp>
#include <mlpack/core/arma_extend/arma_extend.hpp> // Includes Armadillo.
#include <string>
#include "format.hpp"
namespace mlpack {
namespace data /** Functions to load and save matrices and models. */ {
/**
* Loads a matrix from file, guessing the filetype from the extension. This
* will transpose the matrix at load time. If the filetype cannot be
* determined, an error will be given.
*
* The supported types of files are the same as found in Armadillo:
*
* - CSV (csv_ascii), denoted by .csv, or optionally .txt
* - ASCII (raw_ascii), denoted by .txt
* - Armadillo ASCII (arma_ascii), also denoted by .txt
* - PGM (pgm_binary), denoted by .pgm
* - PPM (ppm_binary), denoted by .ppm
* - Raw binary (raw_binary), denoted by .bin
* - Armadillo binary (arma_binary), denoted by .bin
* - HDF5, denoted by .hdf, .hdf5, .h5, or .he5
*
* If the file extension is not one of those types, an error will be given.
* This is preferable to Armadillo's default behavior of loading an unknown
* filetype as raw_binary, which can have very confusing effects.
*
* If the parameter 'fatal' is set to true, a std::runtime_error exception will
* be thrown if the matrix does not load successfully. The parameter
* 'transpose' controls whether or not the matrix is transposed after loading.
* In most cases, because data is generally stored in a row-major format and
* mlpack requires column-major matrices, this should be left at its default
* value of 'true'.
*
* @param filename Name of file to load.
* @param matrix Matrix to load contents of file into.
* @param fatal If an error should be reported as fatal (default false).
* @param transpose If true, transpose the matrix after loading.
* @return Boolean value indicating success or failure of load.
*/
template<typename eT>
bool Load(const std::string& filename,
arma::Mat<eT>& matrix,
const bool fatal = false,
bool transpose = true);
/**
* Load a model from a file, guessing the filetype from the extension, or,
* optionally, loading the specified format. If automatic extension detection
* is used and the filetype cannot be determined, an error will be given.
*
* The supported types of files are the same as what is supported by the
* boost::serialization library:
*
* - text, denoted by .txt
* - xml, denoted by .xml
* - binary, denoted by .bin
*
* The format parameter can take any of the values in the 'format' enum:
* 'format::autodetect', 'format::text', 'format::xml', and 'format::binary'.
* The autodetect functionality operates on the file extension (so, "file.txt"
* would be autodetected as text).
*
* The name parameter should be specified to indicate the name of the structure
* to be loaded. This should be the same as the name that was used to save the
* structure (otherwise, the loading procedure will fail).
*
* If the parameter 'fatal' is set to true, then an exception will be thrown in
* the event of load failure. Otherwise, the method will return false and the
* relevant error information will be printed to Log::Warn.
*/
template<typename T>
bool Load(const std::string& filename,
const std::string& name,
T& t,
const bool fatal = false,
format f = format::autodetect);
} // namespace data
} // namespace mlpack
// Include implementation.
#include "load_impl.hpp"
#endif
<commit_msg>Update documentation.<commit_after>/**
* @file load.hpp
* @author Ryan Curtin
*
* Load an Armadillo matrix from file. This is necessary because Armadillo does
* not transpose matrices on input, and it allows us to give better error
* output.
*/
#ifndef __MLPACK_CORE_DATA_LOAD_HPP
#define __MLPACK_CORE_DATA_LOAD_HPP
#include <mlpack/core/util/log.hpp>
#include <mlpack/core/arma_extend/arma_extend.hpp> // Includes Armadillo.
#include <string>
#include "format.hpp"
namespace mlpack {
namespace data /** Functions to load and save matrices and models. */ {
/**
* Loads a matrix from file, guessing the filetype from the extension. This
* will transpose the matrix at load time. If the filetype cannot be
* determined, an error will be given.
*
* The supported types of files are the same as found in Armadillo:
*
* - CSV (csv_ascii), denoted by .csv, or optionally .txt
* - TSV (raw_ascii), denoted by .tsv, .csv, or .txt
* - ASCII (raw_ascii), denoted by .txt
* - Armadillo ASCII (arma_ascii), also denoted by .txt
* - PGM (pgm_binary), denoted by .pgm
* - PPM (ppm_binary), denoted by .ppm
* - Raw binary (raw_binary), denoted by .bin
* - Armadillo binary (arma_binary), denoted by .bin
* - HDF5, denoted by .hdf, .hdf5, .h5, or .he5
*
* If the file extension is not one of those types, an error will be given.
* This is preferable to Armadillo's default behavior of loading an unknown
* filetype as raw_binary, which can have very confusing effects.
*
* If the parameter 'fatal' is set to true, a std::runtime_error exception will
* be thrown if the matrix does not load successfully. The parameter
* 'transpose' controls whether or not the matrix is transposed after loading.
* In most cases, because data is generally stored in a row-major format and
* mlpack requires column-major matrices, this should be left at its default
* value of 'true'.
*
* @param filename Name of file to load.
* @param matrix Matrix to load contents of file into.
* @param fatal If an error should be reported as fatal (default false).
* @param transpose If true, transpose the matrix after loading.
* @return Boolean value indicating success or failure of load.
*/
template<typename eT>
bool Load(const std::string& filename,
arma::Mat<eT>& matrix,
const bool fatal = false,
bool transpose = true);
/**
* Load a model from a file, guessing the filetype from the extension, or,
* optionally, loading the specified format. If automatic extension detection
* is used and the filetype cannot be determined, an error will be given.
*
* The supported types of files are the same as what is supported by the
* boost::serialization library:
*
* - text, denoted by .txt
* - xml, denoted by .xml
* - binary, denoted by .bin
*
* The format parameter can take any of the values in the 'format' enum:
* 'format::autodetect', 'format::text', 'format::xml', and 'format::binary'.
* The autodetect functionality operates on the file extension (so, "file.txt"
* would be autodetected as text).
*
* The name parameter should be specified to indicate the name of the structure
* to be loaded. This should be the same as the name that was used to save the
* structure (otherwise, the loading procedure will fail).
*
* If the parameter 'fatal' is set to true, then an exception will be thrown in
* the event of load failure. Otherwise, the method will return false and the
* relevant error information will be printed to Log::Warn.
*/
template<typename T>
bool Load(const std::string& filename,
const std::string& name,
T& t,
const bool fatal = false,
format f = format::autodetect);
} // namespace data
} // namespace mlpack
// Include implementation.
#include "load_impl.hpp"
#endif
<|endoftext|> |
<commit_before>/**
* @file nmf_test.cpp
* @author Mohan Rajendran
*
* Test file for NMF class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/amf/amf.hpp>
#include <mlpack/methods/amf/init_rules/random_acol_init.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_div.hpp>
#include <mlpack/methods/amf/update_rules/nmf_als.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_dist.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
BOOST_AUTO_TEST_SUITE(NMFTest);
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::amf;
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Default case.
*/
BOOST_AUTO_TEST_CASE(NMFDefaultTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 1.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random Acol initialization distance minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFAcolDistTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
const size_t r = 12;
SimpleResidueTermination srt(1e-7, 10000);
AMF<SimpleResidueTermination,RandomAcolInitialization<> >
nmf(srt);
nmf.Apply(v, r, w, h);
mat wh = w * h;
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random initialization divergence minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFRandomDivTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<SimpleResidueTermination,
RandomInitialization,
NMFMultiplicativeDivergenceUpdate> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 1.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix. This uses the random initialization and alternating least
* squares update rule.
*/
BOOST_AUTO_TEST_CASE(NMFALSTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
SimpleResidueTermination srt(1e-12, 50000);
AMF<SimpleResidueTermination, RandomAcolInitialization<>, NMFALSUpdate>
nmf(srt);
nmf.Apply(v, r, w, h);
const mat wh = w * h;
// Make sure reconstruction error is not too high. 8% tolerance. It seems
// like ALS doesn't converge to results that are as good. It also seems to be
// particularly sensitive to initial conditions.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.08);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. Random Acol initialization,
* distance minimization update.
*/
BOOST_AUTO_TEST_CASE(SparseNMFAcolDistTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(20, 20, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 20; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 15;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomAcolInitialization<> > nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed); // Set random seed so results are the same.
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h;
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. This uses the random
* initialization and alternating least squares update rule.
*/
BOOST_AUTO_TEST_CASE(SparseNMFALSTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(10, 10, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 10; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 5;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomInitialization, NMFALSUpdate> nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed);
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h; // In general vp won't be sparse.
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Modify tolerances for NMF tests.<commit_after>/**
* @file nmf_test.cpp
* @author Mohan Rajendran
*
* Test file for NMF class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/amf/amf.hpp>
#include <mlpack/methods/amf/init_rules/random_acol_init.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_div.hpp>
#include <mlpack/methods/amf/update_rules/nmf_als.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_dist.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
BOOST_AUTO_TEST_SUITE(NMFTest);
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::amf;
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Default case.
*/
BOOST_AUTO_TEST_CASE(NMFDefaultTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 5.0% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.05);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random Acol initialization distance minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFAcolDistTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
const size_t r = 12;
SimpleResidueTermination srt(1e-7, 10000);
AMF<SimpleResidueTermination,RandomAcolInitialization<> >
nmf(srt);
nmf.Apply(v, r, w, h);
mat wh = w * h;
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random initialization divergence minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFRandomDivTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
// Custom tighter tolerance.
SimpleResidueTermination srt(1e-8, 10000);
AMF<SimpleResidueTermination,
RandomInitialization,
NMFMultiplicativeDivergenceUpdate> nmf(srt);
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 1.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix. This uses the random initialization and alternating least
* squares update rule.
*/
BOOST_AUTO_TEST_CASE(NMFALSTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
SimpleResidueTermination srt(1e-12, 50000);
AMF<SimpleResidueTermination, RandomAcolInitialization<>, NMFALSUpdate>
nmf(srt);
nmf.Apply(v, r, w, h);
const mat wh = w * h;
// Make sure reconstruction error is not too high. 8% tolerance. It seems
// like ALS doesn't converge to results that are as good. It also seems to be
// particularly sensitive to initial conditions.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.08);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. Random Acol initialization,
* distance minimization update.
*/
BOOST_AUTO_TEST_CASE(SparseNMFAcolDistTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(20, 20, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 20; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 15;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomAcolInitialization<> > nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed); // Set random seed so results are the same.
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h;
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. This uses the random
* initialization and alternating least squares update rule.
*/
BOOST_AUTO_TEST_CASE(SparseNMFALSTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(10, 10, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 10; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 5;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomInitialization, NMFALSUpdate> nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed);
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h; // In general vp won't be sparse.
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>#include "labels.h"
#include "tangram.h"
#include "platform.h"
#include "gl/shaderProgram.h"
#include "gl/primitives.h"
#include "view/view.h"
#include "style/style.h"
#include "tile/tile.h"
#include "tile/tileCache.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/rotate_vector.hpp"
#include "glm/gtx/norm.hpp"
namespace Tangram {
Labels::Labels()
: m_needUpdate(false),
m_lastZoom(0.0f)
{}
Labels::~Labels() {}
int Labels::LODDiscardFunc(float _maxZoom, float _zoom) {
return (int) MIN(floor(((log(-_zoom + (_maxZoom + 2)) / log(_maxZoom + 2) * (_maxZoom )) * 0.5)), MAX_LOD);
}
bool Labels::updateLabels(const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
float _dt, float _dz, const View& _view)
{
bool animate = false;
glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());
// int lodDiscard = LODDiscardFunc(View::s_maxZoom, _view.getZoom());
for (const auto& tile : _tiles) {
// discard based on level of detail
// if ((zoom - tile->getID().z) > lodDiscard) {
// continue;
// }
bool proxyTile = tile->isProxy();
glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();
for (const auto& style : _styles) {
const auto& mesh = tile->getMesh(*style);
if (!mesh) { continue; }
const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());
if (!labelMesh) { continue; }
for (auto& label : labelMesh->getLabels()) {
animate |= label->update(mvp, screenSize, _dt, _dz);
label->setProxy(proxyTile);
if (label->canOcclude()) {
m_aabbs.push_back(label->aabb());
m_aabbs.back().m_userData = (void*)label.get();
}
m_labels.push_back(label.get());
}
}
}
return animate;
}
std::set<std::pair<Label*, Label*>> Labels::narrowPhase(const CollisionPairs& _pairs) const {
std::set<std::pair<Label*, Label*>> occlusions;
for (auto pair : _pairs) {
const auto& aabb1 = m_aabbs[pair.first];
const auto& aabb2 = m_aabbs[pair.second];
auto l1 = static_cast<Label*>(aabb1.m_userData);
auto l2 = static_cast<Label*>(aabb2.m_userData);
if (intersect(l1->obb(), l2->obb())) {
occlusions.insert({l1, l2});
}
}
return occlusions;
}
void Labels::applyPriorities(const std::set<std::pair<Label*, Label*>> _occlusions) const {
for (auto& pair : _occlusions) {
if (!pair.first->occludedLastFrame() || !pair.second->occludedLastFrame()) {
// check first is the label belongs to a proxy tile
if (pair.first->isProxy() && !pair.second->isProxy()) {
pair.first->occlude(Label::OcclusionType::collision);
} else if (!pair.first->isProxy() && pair.second->isProxy()) {
pair.second->occlude(Label::OcclusionType::collision);
} else {
// lower numeric priority means higher priority
if (pair.first->options().priority < pair.second->options().priority) {
pair.second->occlude(Label::OcclusionType::collision);
} else {
pair.first->occlude(Label::OcclusionType::collision);
}
}
}
}
}
void Labels::skipTransitions(const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
std::unique_ptr<TileCache>& _cache, float _currentZoom) const
{
for (const auto& t0 : _tiles) {
TileID tileID = t0->getID();
std::vector<std::shared_ptr<Tile>> tiles;
if (m_lastZoom < _currentZoom) {
// zooming in, add the one cached parent tile
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getParent()));
} else {
// zooming out, add the 4 cached children tiles
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(0)));
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(1)));
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(2)));
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(3)));
}
for (const auto& t1 : tiles) {
if (!t1) { continue; }
for (const auto& style : _styles) {
const auto& m0 = t0->getMesh(*style);
if (!m0) { continue; }
const LabelMesh* mesh0 = dynamic_cast<const LabelMesh*>(m0.get());
if (!mesh0) { continue; }
const auto& m1 = t1->getMesh(*style);
if (!m1) { continue; }
const LabelMesh* mesh1 = static_cast<const LabelMesh*>(m1.get());
for (auto& l0 : mesh0->getLabels()) {
if (!l0->canOcclude()) { continue; }
for (auto& l1 : mesh1->getLabels()) {
if (!l1 || !l1->canOcclude() || l0->hash() != l1->hash()) {
continue;
}
float d2 = glm::distance2(l0->transform().state.screenPos,
l1->transform().state.screenPos);
// The new label lies within the circle defined by the bbox of l0
if (sqrt(d2) < std::max(l0->dimension().x, l0->dimension().y)) {
l0->skipTransitions();
}
}
}
}
}
}
}
void Labels::checkRepeatGroups(std::vector<TextLabel*>& _visibleSet) const {
struct GroupElement {
glm::vec2 position;
float threshold;
const std::string* group;
bool operator==(const GroupElement& _ge) {
return _ge.position == position
&& _ge.threshold == threshold
&& *_ge.group == *group;
};
};
std::map<size_t, std::vector<GroupElement>> repeatGroups;
for (TextLabel* textLabel : _visibleSet) {
size_t hash = std::hash<std::string>()(textLabel->options().repeatGroup);
GroupElement element;
element.position = textLabel->center();
element.threshold = textLabel->options().repeatDistance;
element.group = &textLabel->options().repeatGroup;
auto it = repeatGroups.find(hash);
if (it == repeatGroups.end()) {
repeatGroups[hash].push_back(element);
continue;
}
std::vector<GroupElement>& group = it->second;
if (std::find(group.begin(), group.end(), element) != group.end()) {
// TBD: when is this case possible?
// -> When two tiles contain the same label?
continue;
}
bool add = true;
float threshold2 = pow(element.threshold, 2);
for (const GroupElement& ge : group) {
float d2 = distance2(ge.position, element.position);
if (d2 < threshold2) {
textLabel->occlude(Label::OcclusionType::repeat_group);
add = false;
break;
}
}
if (add) {
// No other label of this group within repeatDistance
group.push_back(element);
}
}
}
void Labels::update(const View& _view, float _dt,
const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
std::unique_ptr<TileCache>& _cache)
{
// Could clear this at end of function unless debug draw is active
m_labels.clear();
m_aabbs.clear();
float currentZoom = _view.getZoom();
float dz = currentZoom - std::floor(currentZoom);
/// Collect and update labels from visible tiles
m_needUpdate = updateLabels(_styles, _tiles, _dt, dz, _view);
/// Manage occlusions
// Update collision context size
m_isect2d.resize({_view.getWidth() / 256, _view.getHeight() / 256},
{_view.getWidth(), _view.getHeight()});
// Broad phase collision detection
m_isect2d.intersect(m_aabbs);
// Narrow Phase
auto occlusions = narrowPhase(m_isect2d.pairs);
applyPriorities(occlusions);
/// Mark labels to skip transitions
if ((int) m_lastZoom != (int) _view.getZoom()) {
skipTransitions(_styles, _tiles, _cache, currentZoom);
}
/// Update label meshes
std::vector<TextLabel*> repeatGroupSet;
for (auto label : m_labels) {
label->occlusionSolved();
label->pushTransform();
if (label->canOcclude()) {
if (!label->visibleState() && label->occlusionType() == Label::OcclusionType::collision) {
continue;
}
TextLabel* textLabel = dynamic_cast<TextLabel*>(label);
if (!textLabel) { continue; }
repeatGroupSet.push_back(textLabel);
}
}
// Ensure the labels are always treated in the same order in the visible set
std::sort(repeatGroupSet.begin(), repeatGroupSet.end(), [](TextLabel* _a, TextLabel* _b) {
return glm::length2(_a->transform().modelPosition1) < glm::length2(_b->transform().modelPosition1);
});
/// Apply repeat groups
checkRepeatGroups(repeatGroupSet);
// Request for render if labels are in fading in/out states
if (m_needUpdate) {
requestRender();
}
m_lastZoom = currentZoom;
}
const std::vector<TouchItem>& Labels::getFeaturesAtPoint(const View& _view, float _dt,
const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
float _x, float _y, bool _visibleOnly) {
// FIXME dpi dependent threshold
const float thumbSize = 50;
m_touchItems.clear();
glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());
glm::vec2 touchPoint(_x, _y);
OBB obb(_x - thumbSize/2, _y - thumbSize/2, 0, thumbSize, thumbSize);
float z = _view.getZoom();
float dz = z - std::floor(z);
for (const auto& tile : _tiles) {
glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();
for (const auto& style : _styles) {
const auto& mesh = tile->getMesh(*style);
if (!mesh) { continue; }
const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());
if (!labelMesh) { continue; }
for (auto& label : labelMesh->getLabels()) {
auto& options = label->options();
if (!options.interactive) { continue; }
if (!_visibleOnly) {
label->updateScreenTransform(mvp, screenSize, false);
label->updateBBoxes(dz);
}
if (isect2d::intersect(label->obb(), obb)) {
float distance = glm::length2(label->transform().state.screenPos - touchPoint);
m_touchItems.push_back({options.properties, std::sqrt(distance)});
}
}
}
}
std::sort(m_touchItems.begin(), m_touchItems.end(),
[](auto& a, auto& b){ return a.distance < b.distance; });
return m_touchItems;
}
void Labels::drawDebug(const View& _view) {
if (!Tangram::getDebugFlag(Tangram::DebugFlags::labels)) {
return;
}
for (auto label : m_labels) {
if (label->canOcclude()) {
glm::vec2 offset = label->options().offset;
glm::vec2 sp = label->transform().state.screenPos;
float angle = label->transform().state.rotation;
offset = glm::rotate(offset, angle);
// draw bounding box
Label::State state = label->state();
switch (state) {
case Label::State::sleep:
Primitives::setColor(0x00ff00);
break;
case Label::State::visible:
Primitives::setColor(0x000000);
break;
case Label::State::wait_occ:
Primitives::setColor(0x0000ff);
break;
case Label::State::fading_in:
case Label::State::fading_out:
Primitives::setColor(0xffff00);
break;
default:
Primitives::setColor(0xff0000);
}
Primitives::drawPoly(&(label->obb().getQuad())[0], 4);
// draw offset
Primitives::setColor(0x000000);
Primitives::drawLine(sp, sp - offset);
// draw projected anchor point
Primitives::setColor(0x0000ff);
Primitives::drawRect(sp - glm::vec2(1.f), sp + glm::vec2(1.f));
if (!label->options().repeatGroup.empty() && label->state() == Label::State::visible) {
size_t seed = 0;
hash_combine(seed, label->options().repeatGroup);
float repeatDistance = label->options().repeatDistance;
Primitives::setColor(seed);
Primitives::drawLine(label->center(),
glm::vec2(repeatDistance, 0.f) + label->center());
float off = M_PI / 6.f;
for (float pad = 0.f; pad < M_PI * 2.f; pad += off) {
glm::vec2 p0 = glm::vec2(cos(pad), sin(pad)) * repeatDistance
+ label->center();
glm::vec2 p1 = glm::vec2(cos(pad + off), sin(pad + off)) * repeatDistance
+ label->center();
Primitives::drawLine(p0, p1);
}
}
}
}
glm::vec2 split(_view.getWidth() / 256, _view.getHeight() / 256);
glm::vec2 res(_view.getWidth(), _view.getHeight());
const short xpad = short(ceilf(res.x / split.x));
const short ypad = short(ceilf(res.y / split.y));
Primitives::setColor(0x7ef586);
short x = 0, y = 0;
for (int j = 0; j < split.y; ++j) {
for (int i = 0; i < split.x; ++i) {
AABB cell(x, y, x + xpad, y + ypad);
Primitives::drawRect({x, y}, {x + xpad, y + ypad});
x += xpad;
if (x >= res.x) {
x = 0;
y += ypad;
}
}
}
}
}
<commit_msg>skip labels with repeatDistance 0<commit_after>#include "labels.h"
#include "tangram.h"
#include "platform.h"
#include "gl/shaderProgram.h"
#include "gl/primitives.h"
#include "view/view.h"
#include "style/style.h"
#include "tile/tile.h"
#include "tile/tileCache.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/rotate_vector.hpp"
#include "glm/gtx/norm.hpp"
namespace Tangram {
Labels::Labels()
: m_needUpdate(false),
m_lastZoom(0.0f)
{}
Labels::~Labels() {}
int Labels::LODDiscardFunc(float _maxZoom, float _zoom) {
return (int) MIN(floor(((log(-_zoom + (_maxZoom + 2)) / log(_maxZoom + 2) * (_maxZoom )) * 0.5)), MAX_LOD);
}
bool Labels::updateLabels(const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
float _dt, float _dz, const View& _view)
{
bool animate = false;
glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());
// int lodDiscard = LODDiscardFunc(View::s_maxZoom, _view.getZoom());
for (const auto& tile : _tiles) {
// discard based on level of detail
// if ((zoom - tile->getID().z) > lodDiscard) {
// continue;
// }
bool proxyTile = tile->isProxy();
glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();
for (const auto& style : _styles) {
const auto& mesh = tile->getMesh(*style);
if (!mesh) { continue; }
const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());
if (!labelMesh) { continue; }
for (auto& label : labelMesh->getLabels()) {
animate |= label->update(mvp, screenSize, _dt, _dz);
label->setProxy(proxyTile);
if (label->canOcclude()) {
m_aabbs.push_back(label->aabb());
m_aabbs.back().m_userData = (void*)label.get();
}
m_labels.push_back(label.get());
}
}
}
return animate;
}
std::set<std::pair<Label*, Label*>> Labels::narrowPhase(const CollisionPairs& _pairs) const {
std::set<std::pair<Label*, Label*>> occlusions;
for (auto pair : _pairs) {
const auto& aabb1 = m_aabbs[pair.first];
const auto& aabb2 = m_aabbs[pair.second];
auto l1 = static_cast<Label*>(aabb1.m_userData);
auto l2 = static_cast<Label*>(aabb2.m_userData);
if (intersect(l1->obb(), l2->obb())) {
occlusions.insert({l1, l2});
}
}
return occlusions;
}
void Labels::applyPriorities(const std::set<std::pair<Label*, Label*>> _occlusions) const {
for (auto& pair : _occlusions) {
if (!pair.first->occludedLastFrame() || !pair.second->occludedLastFrame()) {
// check first is the label belongs to a proxy tile
if (pair.first->isProxy() && !pair.second->isProxy()) {
pair.first->occlude(Label::OcclusionType::collision);
} else if (!pair.first->isProxy() && pair.second->isProxy()) {
pair.second->occlude(Label::OcclusionType::collision);
} else {
// lower numeric priority means higher priority
if (pair.first->options().priority < pair.second->options().priority) {
pair.second->occlude(Label::OcclusionType::collision);
} else {
pair.first->occlude(Label::OcclusionType::collision);
}
}
}
}
}
void Labels::skipTransitions(const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
std::unique_ptr<TileCache>& _cache, float _currentZoom) const
{
for (const auto& t0 : _tiles) {
TileID tileID = t0->getID();
std::vector<std::shared_ptr<Tile>> tiles;
if (m_lastZoom < _currentZoom) {
// zooming in, add the one cached parent tile
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getParent()));
} else {
// zooming out, add the 4 cached children tiles
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(0)));
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(1)));
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(2)));
tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(3)));
}
for (const auto& t1 : tiles) {
if (!t1) { continue; }
for (const auto& style : _styles) {
const auto& m0 = t0->getMesh(*style);
if (!m0) { continue; }
const LabelMesh* mesh0 = dynamic_cast<const LabelMesh*>(m0.get());
if (!mesh0) { continue; }
const auto& m1 = t1->getMesh(*style);
if (!m1) { continue; }
const LabelMesh* mesh1 = static_cast<const LabelMesh*>(m1.get());
for (auto& l0 : mesh0->getLabels()) {
if (!l0->canOcclude()) { continue; }
for (auto& l1 : mesh1->getLabels()) {
if (!l1 || !l1->canOcclude() || l0->hash() != l1->hash()) {
continue;
}
float d2 = glm::distance2(l0->transform().state.screenPos,
l1->transform().state.screenPos);
// The new label lies within the circle defined by the bbox of l0
if (sqrt(d2) < std::max(l0->dimension().x, l0->dimension().y)) {
l0->skipTransitions();
}
}
}
}
}
}
}
void Labels::checkRepeatGroups(std::vector<TextLabel*>& _visibleSet) const {
struct GroupElement {
glm::vec2 position;
float threshold;
const std::string* group;
bool operator==(const GroupElement& _ge) {
return _ge.position == position
&& _ge.threshold == threshold
&& *_ge.group == *group;
};
};
std::map<size_t, std::vector<GroupElement>> repeatGroups;
for (TextLabel* textLabel : _visibleSet) {
auto& options = textLabel->options();
if (options.repeatDistance == 0.f) { continue; }
size_t hash = std::hash<std::string>()(options.repeatGroup);
GroupElement element {
textLabel->center(),
options.repeatDistance,
&options.repeatGroup
};
auto it = repeatGroups.find(hash);
if (it == repeatGroups.end()) {
repeatGroups[hash].push_back(element);
continue;
}
std::vector<GroupElement>& group = it->second;
if (std::find(group.begin(), group.end(), element) != group.end()) {
// TBD: when is this case possible?
// -> When two tiles contain the same label?
continue;
}
bool add = true;
float threshold2 = pow(element.threshold, 2);
for (const GroupElement& ge : group) {
float d2 = distance2(ge.position, element.position);
if (d2 < threshold2) {
textLabel->occlude(Label::OcclusionType::repeat_group);
add = false;
break;
}
}
if (add) {
// No other label of this group within repeatDistance
group.push_back(element);
}
}
}
void Labels::update(const View& _view, float _dt,
const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
std::unique_ptr<TileCache>& _cache)
{
// Could clear this at end of function unless debug draw is active
m_labels.clear();
m_aabbs.clear();
float currentZoom = _view.getZoom();
float dz = currentZoom - std::floor(currentZoom);
/// Collect and update labels from visible tiles
m_needUpdate = updateLabels(_styles, _tiles, _dt, dz, _view);
/// Manage occlusions
// Update collision context size
m_isect2d.resize({_view.getWidth() / 256, _view.getHeight() / 256},
{_view.getWidth(), _view.getHeight()});
// Broad phase collision detection
m_isect2d.intersect(m_aabbs);
// Narrow Phase
auto occlusions = narrowPhase(m_isect2d.pairs);
applyPriorities(occlusions);
/// Mark labels to skip transitions
if ((int) m_lastZoom != (int) _view.getZoom()) {
skipTransitions(_styles, _tiles, _cache, currentZoom);
}
/// Update label meshes
std::vector<TextLabel*> repeatGroupSet;
for (auto label : m_labels) {
label->occlusionSolved();
label->pushTransform();
if (label->canOcclude()) {
if (!label->visibleState() && label->occlusionType() == Label::OcclusionType::collision) {
continue;
}
TextLabel* textLabel = dynamic_cast<TextLabel*>(label);
if (!textLabel) { continue; }
repeatGroupSet.push_back(textLabel);
}
}
// Ensure the labels are always treated in the same order in the visible set
std::sort(repeatGroupSet.begin(), repeatGroupSet.end(), [](TextLabel* _a, TextLabel* _b) {
return glm::length2(_a->transform().modelPosition1) < glm::length2(_b->transform().modelPosition1);
});
/// Apply repeat groups
checkRepeatGroups(repeatGroupSet);
// Request for render if labels are in fading in/out states
if (m_needUpdate) {
requestRender();
}
m_lastZoom = currentZoom;
}
const std::vector<TouchItem>& Labels::getFeaturesAtPoint(const View& _view, float _dt,
const std::vector<std::unique_ptr<Style>>& _styles,
const std::vector<std::shared_ptr<Tile>>& _tiles,
float _x, float _y, bool _visibleOnly) {
// FIXME dpi dependent threshold
const float thumbSize = 50;
m_touchItems.clear();
glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());
glm::vec2 touchPoint(_x, _y);
OBB obb(_x - thumbSize/2, _y - thumbSize/2, 0, thumbSize, thumbSize);
float z = _view.getZoom();
float dz = z - std::floor(z);
for (const auto& tile : _tiles) {
glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();
for (const auto& style : _styles) {
const auto& mesh = tile->getMesh(*style);
if (!mesh) { continue; }
const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());
if (!labelMesh) { continue; }
for (auto& label : labelMesh->getLabels()) {
auto& options = label->options();
if (!options.interactive) { continue; }
if (!_visibleOnly) {
label->updateScreenTransform(mvp, screenSize, false);
label->updateBBoxes(dz);
}
if (isect2d::intersect(label->obb(), obb)) {
float distance = glm::length2(label->transform().state.screenPos - touchPoint);
m_touchItems.push_back({options.properties, std::sqrt(distance)});
}
}
}
}
std::sort(m_touchItems.begin(), m_touchItems.end(),
[](auto& a, auto& b){ return a.distance < b.distance; });
return m_touchItems;
}
void Labels::drawDebug(const View& _view) {
if (!Tangram::getDebugFlag(Tangram::DebugFlags::labels)) {
return;
}
for (auto label : m_labels) {
if (label->canOcclude()) {
glm::vec2 offset = label->options().offset;
glm::vec2 sp = label->transform().state.screenPos;
float angle = label->transform().state.rotation;
offset = glm::rotate(offset, angle);
// draw bounding box
Label::State state = label->state();
switch (state) {
case Label::State::sleep:
Primitives::setColor(0x00ff00);
break;
case Label::State::visible:
Primitives::setColor(0x000000);
break;
case Label::State::wait_occ:
Primitives::setColor(0x0000ff);
break;
case Label::State::fading_in:
case Label::State::fading_out:
Primitives::setColor(0xffff00);
break;
default:
Primitives::setColor(0xff0000);
}
Primitives::drawPoly(&(label->obb().getQuad())[0], 4);
// draw offset
Primitives::setColor(0x000000);
Primitives::drawLine(sp, sp - offset);
// draw projected anchor point
Primitives::setColor(0x0000ff);
Primitives::drawRect(sp - glm::vec2(1.f), sp + glm::vec2(1.f));
if (!label->options().repeatGroup.empty() && label->state() == Label::State::visible) {
size_t seed = 0;
hash_combine(seed, label->options().repeatGroup);
float repeatDistance = label->options().repeatDistance;
Primitives::setColor(seed);
Primitives::drawLine(label->center(),
glm::vec2(repeatDistance, 0.f) + label->center());
float off = M_PI / 6.f;
for (float pad = 0.f; pad < M_PI * 2.f; pad += off) {
glm::vec2 p0 = glm::vec2(cos(pad), sin(pad)) * repeatDistance
+ label->center();
glm::vec2 p1 = glm::vec2(cos(pad + off), sin(pad + off)) * repeatDistance
+ label->center();
Primitives::drawLine(p0, p1);
}
}
}
}
glm::vec2 split(_view.getWidth() / 256, _view.getHeight() / 256);
glm::vec2 res(_view.getWidth(), _view.getHeight());
const short xpad = short(ceilf(res.x / split.x));
const short ypad = short(ceilf(res.y / split.y));
Primitives::setColor(0x7ef586);
short x = 0, y = 0;
for (int j = 0; j < split.y; ++j) {
for (int i = 0; i < split.x; ++i) {
AABB cell(x, y, x + xpad, y + ypad);
Primitives::drawRect({x, y}, {x + xpad, y + ypad});
x += xpad;
if (x >= res.x) {
x = 0;
y += ypad;
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/flush_job.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <algorithm>
#include <vector>
#include "db/builder.h"
#include "db/db_iter.h"
#include "db/dbformat.h"
#include "db/event_helpers.h"
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/memtable_list.h"
#include "db/merge_context.h"
#include "db/version_set.h"
#include "port/likely.h"
#include "port/port.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/statistics.h"
#include "rocksdb/status.h"
#include "rocksdb/table.h"
#include "table/block.h"
#include "table/block_based_table_factory.h"
#include "table/merger.h"
#include "table/table_builder.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/event_logger.h"
#include "util/file_util.h"
#include "util/iostats_context_imp.h"
#include "util/log_buffer.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/perf_context_imp.h"
#include "util/stop_watch.h"
#include "util/sync_point.h"
#include "util/thread_status_util.h"
namespace rocksdb {
FlushJob::FlushJob(const std::string& dbname, ColumnFamilyData* cfd,
const ImmutableDBOptions& db_options,
const MutableCFOptions& mutable_cf_options,
const EnvOptions& env_options, VersionSet* versions,
InstrumentedMutex* db_mutex,
std::atomic<bool>* shutting_down,
std::vector<SequenceNumber> existing_snapshots,
SequenceNumber earliest_write_conflict_snapshot,
JobContext* job_context, LogBuffer* log_buffer,
Directory* db_directory, Directory* output_file_directory,
CompressionType output_compression, Statistics* stats,
EventLogger* event_logger, bool measure_io_stats)
: dbname_(dbname),
cfd_(cfd),
db_options_(db_options),
mutable_cf_options_(mutable_cf_options),
env_options_(env_options),
versions_(versions),
db_mutex_(db_mutex),
shutting_down_(shutting_down),
existing_snapshots_(std::move(existing_snapshots)),
earliest_write_conflict_snapshot_(earliest_write_conflict_snapshot),
job_context_(job_context),
log_buffer_(log_buffer),
db_directory_(db_directory),
output_file_directory_(output_file_directory),
output_compression_(output_compression),
stats_(stats),
event_logger_(event_logger),
measure_io_stats_(measure_io_stats),
pick_memtable_called(false) {
// Update the thread status to indicate flush.
ReportStartedFlush();
TEST_SYNC_POINT("FlushJob::FlushJob()");
}
FlushJob::~FlushJob() {
ThreadStatusUtil::ResetThreadStatus();
}
void FlushJob::ReportStartedFlush() {
ThreadStatusUtil::SetColumnFamily(cfd_, cfd_->ioptions()->env,
db_options_.enable_thread_tracking);
ThreadStatusUtil::SetThreadOperation(ThreadStatus::OP_FLUSH);
ThreadStatusUtil::SetThreadOperationProperty(
ThreadStatus::COMPACTION_JOB_ID,
job_context_->job_id);
IOSTATS_RESET(bytes_written);
}
void FlushJob::ReportFlushInputSize(const autovector<MemTable*>& mems) {
uint64_t input_size = 0;
for (auto* mem : mems) {
input_size += mem->ApproximateMemoryUsage();
}
ThreadStatusUtil::IncreaseThreadOperationProperty(
ThreadStatus::FLUSH_BYTES_MEMTABLES,
input_size);
}
void FlushJob::RecordFlushIOStats() {
RecordTick(stats_, FLUSH_WRITE_BYTES, IOSTATS(bytes_written));
ThreadStatusUtil::IncreaseThreadOperationProperty(
ThreadStatus::FLUSH_BYTES_WRITTEN, IOSTATS(bytes_written));
IOSTATS_RESET(bytes_written);
}
void FlushJob::PickMemTable() {
db_mutex_->AssertHeld();
assert(!pick_memtable_called);
pick_memtable_called = true;
// Save the contents of the earliest memtable as a new Table
cfd_->imm()->PickMemtablesToFlush(&mems_);
if (mems_.empty()) {
return;
}
ReportFlushInputSize(mems_);
// entries mems are (implicitly) sorted in ascending order by their created
// time. We will use the first memtable's `edit` to keep the meta info for
// this flush.
MemTable* m = mems_[0];
edit_ = m->GetEdits();
edit_->SetPrevLogNumber(0);
// SetLogNumber(log_num) indicates logs with number smaller than log_num
// will no longer be picked up for recovery.
edit_->SetLogNumber(mems_.back()->GetNextLogNumber());
edit_->SetColumnFamily(cfd_->GetID());
// path 0 for level 0 file.
meta_.fd = FileDescriptor(versions_->NewFileNumber(), 0, 0);
base_ = cfd_->current();
base_->Ref(); // it is likely that we do not need this reference
}
Status FlushJob::Run(FileMetaData* file_meta) {
db_mutex_->AssertHeld();
assert(pick_memtable_called);
AutoThreadOperationStageUpdater stage_run(
ThreadStatus::STAGE_FLUSH_RUN);
if (mems_.empty()) {
LogToBuffer(log_buffer_, "[%s] Nothing in memtable to flush",
cfd_->GetName().c_str());
return Status::OK();
}
// I/O measurement variables
PerfLevel prev_perf_level = PerfLevel::kEnableTime;
uint64_t prev_write_nanos = 0;
uint64_t prev_fsync_nanos = 0;
uint64_t prev_range_sync_nanos = 0;
uint64_t prev_prepare_write_nanos = 0;
if (measure_io_stats_) {
prev_perf_level = GetPerfLevel();
SetPerfLevel(PerfLevel::kEnableTime);
prev_write_nanos = IOSTATS(write_nanos);
prev_fsync_nanos = IOSTATS(fsync_nanos);
prev_range_sync_nanos = IOSTATS(range_sync_nanos);
prev_prepare_write_nanos = IOSTATS(prepare_write_nanos);
}
// This will release and re-acquire the mutex.
Status s = WriteLevel0Table();
if (s.ok() &&
(shutting_down_->load(std::memory_order_acquire) || cfd_->IsDropped())) {
s = Status::ShutdownInProgress(
"Database shutdown or Column family drop during flush");
}
if (!s.ok()) {
cfd_->imm()->RollbackMemtableFlush(mems_, meta_.fd.GetNumber());
} else {
TEST_SYNC_POINT("FlushJob::InstallResults");
// Replace immutable memtable with the generated Table
s = cfd_->imm()->InstallMemtableFlushResults(
cfd_, mutable_cf_options_, mems_, versions_, db_mutex_,
meta_.fd.GetNumber(), &job_context_->memtables_to_free, db_directory_,
log_buffer_);
}
if (s.ok() && file_meta != nullptr) {
*file_meta = meta_;
}
RecordFlushIOStats();
auto stream = event_logger_->LogToBuffer(log_buffer_);
stream << "job" << job_context_->job_id << "event"
<< "flush_finished";
stream << "lsm_state";
stream.StartArray();
auto vstorage = cfd_->current()->storage_info();
for (int level = 0; level < vstorage->num_levels(); ++level) {
stream << vstorage->NumLevelFiles(level);
}
stream.EndArray();
stream << "immutable_memtables" << cfd_->imm()->NumNotFlushed();
if (measure_io_stats_) {
if (prev_perf_level != PerfLevel::kEnableTime) {
SetPerfLevel(prev_perf_level);
}
stream << "file_write_nanos" << (IOSTATS(write_nanos) - prev_write_nanos);
stream << "file_range_sync_nanos"
<< (IOSTATS(range_sync_nanos) - prev_range_sync_nanos);
stream << "file_fsync_nanos" << (IOSTATS(fsync_nanos) - prev_fsync_nanos);
stream << "file_prepare_write_nanos"
<< (IOSTATS(prepare_write_nanos) - prev_prepare_write_nanos);
}
return s;
}
Status FlushJob::WriteLevel0Table() {
AutoThreadOperationStageUpdater stage_updater(
ThreadStatus::STAGE_FLUSH_WRITE_L0);
db_mutex_->AssertHeld();
const uint64_t start_micros = db_options_.env->NowMicros();
Status s;
{
db_mutex_->Unlock();
if (log_buffer_) {
log_buffer_->FlushBufferToLog();
}
// memtables and range_del_iters store internal iterators over each data
// memtable and its associated range deletion memtable, respectively, at
// corresponding indexes.
std::vector<InternalIterator*> memtables;
std::vector<InternalIterator*> range_del_iters;
ReadOptions ro;
ro.total_order_seek = true;
Arena arena;
uint64_t total_num_entries = 0, total_num_deletes = 0;
size_t total_memory_usage = 0;
for (MemTable* m : mems_) {
Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
"[%s] [JOB %d] Flushing memtable with next log file: %" PRIu64 "\n",
cfd_->GetName().c_str(), job_context_->job_id, m->GetNextLogNumber());
memtables.push_back(m->NewIterator(ro, &arena));
auto* range_del_iter = m->NewRangeTombstoneIterator(ro);
if (range_del_iter != nullptr) {
range_del_iters.push_back(range_del_iter);
}
total_num_entries += m->num_entries();
total_num_deletes += m->num_deletes();
total_memory_usage += m->ApproximateMemoryUsage();
}
event_logger_->Log() << "job" << job_context_->job_id << "event"
<< "flush_started"
<< "num_memtables" << mems_.size() << "num_entries"
<< total_num_entries << "num_deletes"
<< total_num_deletes << "memory_usage"
<< total_memory_usage;
{
ScopedArenaIterator iter(
NewMergingIterator(&cfd_->internal_comparator(), &memtables[0],
static_cast<int>(memtables.size()), &arena));
std::unique_ptr<InternalIterator> range_del_iter(NewMergingIterator(
&cfd_->internal_comparator(), &range_del_iters[0],
static_cast<int>(range_del_iters.size())));
Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
"[%s] [JOB %d] Level-0 flush table #%" PRIu64 ": started",
cfd_->GetName().c_str(), job_context_->job_id, meta_.fd.GetNumber());
TEST_SYNC_POINT_CALLBACK("FlushJob::WriteLevel0Table:output_compression",
&output_compression_);
s = BuildTable(
dbname_, db_options_.env, *cfd_->ioptions(), mutable_cf_options_,
env_options_, cfd_->table_cache(), iter.get(),
std::move(range_del_iter), &meta_, cfd_->internal_comparator(),
cfd_->int_tbl_prop_collector_factories(), cfd_->GetID(),
cfd_->GetName(), existing_snapshots_,
earliest_write_conflict_snapshot_, output_compression_,
cfd_->ioptions()->compression_opts,
mutable_cf_options_.paranoid_file_checks, cfd_->internal_stats(),
TableFileCreationReason::kFlush, event_logger_, job_context_->job_id,
Env::IO_HIGH, &table_properties_, 0 /* level */);
LogFlush(db_options_.info_log);
}
Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
"[%s] [JOB %d] Level-0 flush table #%" PRIu64 ": %" PRIu64
" bytes %s"
"%s",
cfd_->GetName().c_str(), job_context_->job_id, meta_.fd.GetNumber(),
meta_.fd.GetFileSize(), s.ToString().c_str(),
meta_.marked_for_compaction ? " (needs compaction)" : "");
if (!db_options_.disable_data_sync && output_file_directory_ != nullptr) {
output_file_directory_->Fsync();
}
TEST_SYNC_POINT("FlushJob::WriteLevel0Table");
db_mutex_->Lock();
}
base_->Unref();
// Note that if file_size is zero, the file has been deleted and
// should not be added to the manifest.
if (s.ok() && meta_.fd.GetFileSize() > 0) {
// if we have more than 1 background thread, then we cannot
// insert files directly into higher levels because some other
// threads could be concurrently producing compacted files for
// that key range.
// Add file to L0
edit_->AddFile(0 /* level */, meta_.fd.GetNumber(), meta_.fd.GetPathId(),
meta_.fd.GetFileSize(), meta_.smallest, meta_.largest,
meta_.smallest_seqno, meta_.largest_seqno,
meta_.marked_for_compaction);
}
// Note that here we treat flush as level 0 compaction in internal stats
InternalStats::CompactionStats stats(1);
stats.micros = db_options_.env->NowMicros() - start_micros;
stats.bytes_written = meta_.fd.GetFileSize();
cfd_->internal_stats()->AddCompactionStats(0 /* level */, stats);
cfd_->internal_stats()->AddCFStats(InternalStats::BYTES_FLUSHED,
meta_.fd.GetFileSize());
RecordFlushIOStats();
return s;
}
} // namespace rocksdb
<commit_msg>Fixed a crash in debug build in flush_job.cc<commit_after>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/flush_job.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <algorithm>
#include <vector>
#include "db/builder.h"
#include "db/db_iter.h"
#include "db/dbformat.h"
#include "db/event_helpers.h"
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/memtable_list.h"
#include "db/merge_context.h"
#include "db/version_set.h"
#include "port/likely.h"
#include "port/port.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/statistics.h"
#include "rocksdb/status.h"
#include "rocksdb/table.h"
#include "table/block.h"
#include "table/block_based_table_factory.h"
#include "table/merger.h"
#include "table/table_builder.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/event_logger.h"
#include "util/file_util.h"
#include "util/iostats_context_imp.h"
#include "util/log_buffer.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/perf_context_imp.h"
#include "util/stop_watch.h"
#include "util/sync_point.h"
#include "util/thread_status_util.h"
namespace rocksdb {
FlushJob::FlushJob(const std::string& dbname, ColumnFamilyData* cfd,
const ImmutableDBOptions& db_options,
const MutableCFOptions& mutable_cf_options,
const EnvOptions& env_options, VersionSet* versions,
InstrumentedMutex* db_mutex,
std::atomic<bool>* shutting_down,
std::vector<SequenceNumber> existing_snapshots,
SequenceNumber earliest_write_conflict_snapshot,
JobContext* job_context, LogBuffer* log_buffer,
Directory* db_directory, Directory* output_file_directory,
CompressionType output_compression, Statistics* stats,
EventLogger* event_logger, bool measure_io_stats)
: dbname_(dbname),
cfd_(cfd),
db_options_(db_options),
mutable_cf_options_(mutable_cf_options),
env_options_(env_options),
versions_(versions),
db_mutex_(db_mutex),
shutting_down_(shutting_down),
existing_snapshots_(std::move(existing_snapshots)),
earliest_write_conflict_snapshot_(earliest_write_conflict_snapshot),
job_context_(job_context),
log_buffer_(log_buffer),
db_directory_(db_directory),
output_file_directory_(output_file_directory),
output_compression_(output_compression),
stats_(stats),
event_logger_(event_logger),
measure_io_stats_(measure_io_stats),
pick_memtable_called(false) {
// Update the thread status to indicate flush.
ReportStartedFlush();
TEST_SYNC_POINT("FlushJob::FlushJob()");
}
FlushJob::~FlushJob() {
ThreadStatusUtil::ResetThreadStatus();
}
void FlushJob::ReportStartedFlush() {
ThreadStatusUtil::SetColumnFamily(cfd_, cfd_->ioptions()->env,
db_options_.enable_thread_tracking);
ThreadStatusUtil::SetThreadOperation(ThreadStatus::OP_FLUSH);
ThreadStatusUtil::SetThreadOperationProperty(
ThreadStatus::COMPACTION_JOB_ID,
job_context_->job_id);
IOSTATS_RESET(bytes_written);
}
void FlushJob::ReportFlushInputSize(const autovector<MemTable*>& mems) {
uint64_t input_size = 0;
for (auto* mem : mems) {
input_size += mem->ApproximateMemoryUsage();
}
ThreadStatusUtil::IncreaseThreadOperationProperty(
ThreadStatus::FLUSH_BYTES_MEMTABLES,
input_size);
}
void FlushJob::RecordFlushIOStats() {
RecordTick(stats_, FLUSH_WRITE_BYTES, IOSTATS(bytes_written));
ThreadStatusUtil::IncreaseThreadOperationProperty(
ThreadStatus::FLUSH_BYTES_WRITTEN, IOSTATS(bytes_written));
IOSTATS_RESET(bytes_written);
}
void FlushJob::PickMemTable() {
db_mutex_->AssertHeld();
assert(!pick_memtable_called);
pick_memtable_called = true;
// Save the contents of the earliest memtable as a new Table
cfd_->imm()->PickMemtablesToFlush(&mems_);
if (mems_.empty()) {
return;
}
ReportFlushInputSize(mems_);
// entries mems are (implicitly) sorted in ascending order by their created
// time. We will use the first memtable's `edit` to keep the meta info for
// this flush.
MemTable* m = mems_[0];
edit_ = m->GetEdits();
edit_->SetPrevLogNumber(0);
// SetLogNumber(log_num) indicates logs with number smaller than log_num
// will no longer be picked up for recovery.
edit_->SetLogNumber(mems_.back()->GetNextLogNumber());
edit_->SetColumnFamily(cfd_->GetID());
// path 0 for level 0 file.
meta_.fd = FileDescriptor(versions_->NewFileNumber(), 0, 0);
base_ = cfd_->current();
base_->Ref(); // it is likely that we do not need this reference
}
Status FlushJob::Run(FileMetaData* file_meta) {
db_mutex_->AssertHeld();
assert(pick_memtable_called);
AutoThreadOperationStageUpdater stage_run(
ThreadStatus::STAGE_FLUSH_RUN);
if (mems_.empty()) {
LogToBuffer(log_buffer_, "[%s] Nothing in memtable to flush",
cfd_->GetName().c_str());
return Status::OK();
}
// I/O measurement variables
PerfLevel prev_perf_level = PerfLevel::kEnableTime;
uint64_t prev_write_nanos = 0;
uint64_t prev_fsync_nanos = 0;
uint64_t prev_range_sync_nanos = 0;
uint64_t prev_prepare_write_nanos = 0;
if (measure_io_stats_) {
prev_perf_level = GetPerfLevel();
SetPerfLevel(PerfLevel::kEnableTime);
prev_write_nanos = IOSTATS(write_nanos);
prev_fsync_nanos = IOSTATS(fsync_nanos);
prev_range_sync_nanos = IOSTATS(range_sync_nanos);
prev_prepare_write_nanos = IOSTATS(prepare_write_nanos);
}
// This will release and re-acquire the mutex.
Status s = WriteLevel0Table();
if (s.ok() &&
(shutting_down_->load(std::memory_order_acquire) || cfd_->IsDropped())) {
s = Status::ShutdownInProgress(
"Database shutdown or Column family drop during flush");
}
if (!s.ok()) {
cfd_->imm()->RollbackMemtableFlush(mems_, meta_.fd.GetNumber());
} else {
TEST_SYNC_POINT("FlushJob::InstallResults");
// Replace immutable memtable with the generated Table
s = cfd_->imm()->InstallMemtableFlushResults(
cfd_, mutable_cf_options_, mems_, versions_, db_mutex_,
meta_.fd.GetNumber(), &job_context_->memtables_to_free, db_directory_,
log_buffer_);
}
if (s.ok() && file_meta != nullptr) {
*file_meta = meta_;
}
RecordFlushIOStats();
auto stream = event_logger_->LogToBuffer(log_buffer_);
stream << "job" << job_context_->job_id << "event"
<< "flush_finished";
stream << "lsm_state";
stream.StartArray();
auto vstorage = cfd_->current()->storage_info();
for (int level = 0; level < vstorage->num_levels(); ++level) {
stream << vstorage->NumLevelFiles(level);
}
stream.EndArray();
stream << "immutable_memtables" << cfd_->imm()->NumNotFlushed();
if (measure_io_stats_) {
if (prev_perf_level != PerfLevel::kEnableTime) {
SetPerfLevel(prev_perf_level);
}
stream << "file_write_nanos" << (IOSTATS(write_nanos) - prev_write_nanos);
stream << "file_range_sync_nanos"
<< (IOSTATS(range_sync_nanos) - prev_range_sync_nanos);
stream << "file_fsync_nanos" << (IOSTATS(fsync_nanos) - prev_fsync_nanos);
stream << "file_prepare_write_nanos"
<< (IOSTATS(prepare_write_nanos) - prev_prepare_write_nanos);
}
return s;
}
Status FlushJob::WriteLevel0Table() {
AutoThreadOperationStageUpdater stage_updater(
ThreadStatus::STAGE_FLUSH_WRITE_L0);
db_mutex_->AssertHeld();
const uint64_t start_micros = db_options_.env->NowMicros();
Status s;
{
db_mutex_->Unlock();
if (log_buffer_) {
log_buffer_->FlushBufferToLog();
}
// memtables and range_del_iters store internal iterators over each data
// memtable and its associated range deletion memtable, respectively, at
// corresponding indexes.
std::vector<InternalIterator*> memtables;
std::vector<InternalIterator*> range_del_iters;
ReadOptions ro;
ro.total_order_seek = true;
Arena arena;
uint64_t total_num_entries = 0, total_num_deletes = 0;
size_t total_memory_usage = 0;
for (MemTable* m : mems_) {
Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
"[%s] [JOB %d] Flushing memtable with next log file: %" PRIu64 "\n",
cfd_->GetName().c_str(), job_context_->job_id, m->GetNextLogNumber());
memtables.push_back(m->NewIterator(ro, &arena));
auto* range_del_iter = m->NewRangeTombstoneIterator(ro);
if (range_del_iter != nullptr) {
range_del_iters.push_back(range_del_iter);
}
total_num_entries += m->num_entries();
total_num_deletes += m->num_deletes();
total_memory_usage += m->ApproximateMemoryUsage();
}
event_logger_->Log() << "job" << job_context_->job_id << "event"
<< "flush_started"
<< "num_memtables" << mems_.size() << "num_entries"
<< total_num_entries << "num_deletes"
<< total_num_deletes << "memory_usage"
<< total_memory_usage;
{
ScopedArenaIterator iter(
NewMergingIterator(&cfd_->internal_comparator(), &memtables[0],
static_cast<int>(memtables.size()), &arena));
std::unique_ptr<InternalIterator> range_del_iter(NewMergingIterator(
&cfd_->internal_comparator(),
range_del_iters.empty() ? nullptr : &range_del_iters[0],
static_cast<int>(range_del_iters.size())));
Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
"[%s] [JOB %d] Level-0 flush table #%" PRIu64 ": started",
cfd_->GetName().c_str(), job_context_->job_id, meta_.fd.GetNumber());
TEST_SYNC_POINT_CALLBACK("FlushJob::WriteLevel0Table:output_compression",
&output_compression_);
s = BuildTable(
dbname_, db_options_.env, *cfd_->ioptions(), mutable_cf_options_,
env_options_, cfd_->table_cache(), iter.get(),
std::move(range_del_iter), &meta_, cfd_->internal_comparator(),
cfd_->int_tbl_prop_collector_factories(), cfd_->GetID(),
cfd_->GetName(), existing_snapshots_,
earliest_write_conflict_snapshot_, output_compression_,
cfd_->ioptions()->compression_opts,
mutable_cf_options_.paranoid_file_checks, cfd_->internal_stats(),
TableFileCreationReason::kFlush, event_logger_, job_context_->job_id,
Env::IO_HIGH, &table_properties_, 0 /* level */);
LogFlush(db_options_.info_log);
}
Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
"[%s] [JOB %d] Level-0 flush table #%" PRIu64 ": %" PRIu64
" bytes %s"
"%s",
cfd_->GetName().c_str(), job_context_->job_id, meta_.fd.GetNumber(),
meta_.fd.GetFileSize(), s.ToString().c_str(),
meta_.marked_for_compaction ? " (needs compaction)" : "");
if (!db_options_.disable_data_sync && output_file_directory_ != nullptr) {
output_file_directory_->Fsync();
}
TEST_SYNC_POINT("FlushJob::WriteLevel0Table");
db_mutex_->Lock();
}
base_->Unref();
// Note that if file_size is zero, the file has been deleted and
// should not be added to the manifest.
if (s.ok() && meta_.fd.GetFileSize() > 0) {
// if we have more than 1 background thread, then we cannot
// insert files directly into higher levels because some other
// threads could be concurrently producing compacted files for
// that key range.
// Add file to L0
edit_->AddFile(0 /* level */, meta_.fd.GetNumber(), meta_.fd.GetPathId(),
meta_.fd.GetFileSize(), meta_.smallest, meta_.largest,
meta_.smallest_seqno, meta_.largest_seqno,
meta_.marked_for_compaction);
}
// Note that here we treat flush as level 0 compaction in internal stats
InternalStats::CompactionStats stats(1);
stats.micros = db_options_.env->NowMicros() - start_micros;
stats.bytes_written = meta_.fd.GetFileSize();
cfd_->internal_stats()->AddCompactionStats(0 /* level */, stats);
cfd_->internal_stats()->AddCFStats(InternalStats::BYTES_FLUSHED,
meta_.fd.GetFileSize());
RecordFlushIOStats();
return s;
}
} // namespace rocksdb
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Wisconsin Robotics
* 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 <dinput.h>
#include <windows.h>
#include "joystick.h"
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")
using namespace JoystickLibrary;
const std::array<POV, 8> povList = {
POV::POV_NORTH,
POV::POV_NORTHEAST,
POV::POV_EAST,
POV::POV_SOUTHEAST,
POV::POV_SOUTH,
POV::POV_SOUTHWEST,
POV::POV_WEST,
POV::POV_NORTHWEST,
};
struct
{
int *nextJoystickID;
int *connectedJoysticks;
int *requestedJoysticks;
std::map<int, JoystickData> *jsMap;
} EnumerateContext;
LPDIRECTINPUT8 di;
/**
* Callback to configure the axis values on the joystick.
* @param instance A pointer to the device instance
* @param context A pointer to the joystick instance
* @return DIENUM_CONTINUE on success, DIENUM_STOP otherwise
*/
static BOOL CALLBACK JoystickConfigCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context)
{
DIPROPRANGE propRange;
LPDIRECTINPUTDEVICE8 joystick;
if (!context)
return DIENUM_STOP;
memset(&propRange, 0, sizeof(DIPROPRANGE));
propRange.diph.dwSize = sizeof(DIPROPRANGE);
propRange.diph.dwHeaderSize = sizeof(DIPROPHEADER);
propRange.diph.dwHow = DIPH_BYID;
propRange.diph.dwObj = instance->dwType;
propRange.lMin = -100;
propRange.lMax = +100;
// Set the range for the axis
joystick = (LPDIRECTINPUTDEVICE8) context;
if (FAILED(joystick->SetProperty(DIPROP_RANGE, &propRange.diph)))
return DIENUM_STOP;
return DIENUM_CONTINUE;
}
/**
* A callback function called for each found joystick.
* @param instance A pointer to the device instance.
* @param context (unused)
* @return DIENUM_CONTINUE on success, DIENUM_STOP otherwise
*/
static BOOL CALLBACK EnumerateJoysticks(const DIDEVICEINSTANCE *instance, void *context)
{
LPDIRECTINPUTDEVICE8 joystick;
DIPROPDWORD dipdw;
// context is not used
UNREFERENCED_PARAMETER(context);
if (*EnumerateContext.connectedJoysticks >= *EnumerateContext.requestedJoysticks)
return DIENUM_STOP;
// check if joystick was a formerly removed one
for (auto& pair : *EnumerateContext.jsMap)
{
DIDEVICEINSTANCE info;
if (pair.second.alive)
continue;
LPDIRECTINPUTDEVICE8 inactiveJoystick = (LPDIRECTINPUTDEVICE8) pair.second.os_obj;
info.dwSize = sizeof(DIDEVICEINSTANCE);
if (FAILED(inactiveJoystick->GetDeviceInfo(&info)))
continue;
if (info.guidInstance == instance->guidInstance)
{
pair.second.alive = true;
inactiveJoystick->Acquire();
(*EnumerateContext.connectedJoysticks)++;
return DIENUM_CONTINUE;
}
}
if (FAILED(di->CreateDevice(instance->guidInstance, &joystick, nullptr)))
return DIENUM_CONTINUE;
// check vendor and product ID
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
if (FAILED(joystick->GetProperty(DIPROP_VIDPID, &dipdw.diph)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
if (LOWORD(dipdw.dwData) != JOYSTICK_VENDOR_ID || HIWORD(dipdw.dwData) != JOYSTICK_PRODUCT_ID)
{
joystick->Release();
return DIENUM_CONTINUE;
}
// create and start tracking joystick
// use DIJOYSTATE struct for data acquisition
if (FAILED(joystick->SetDataFormat(&c_dfDIJoystick)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
// axis configuration to -100 -> 100
if (FAILED(joystick->EnumObjects(JoystickConfigCallback, joystick, DIDFT_AXIS)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
// new joystick - add to map & acquire
joystick->Acquire();
(*EnumerateContext.jsMap)[*(EnumerateContext.nextJoystickID)] = { };
(*EnumerateContext.jsMap)[*(EnumerateContext.nextJoystickID)].alive = true;
(*EnumerateContext.jsMap)[*(EnumerateContext.nextJoystickID)].os_obj = joystick;
(*EnumerateContext.nextJoystickID)++;
(*EnumerateContext.connectedJoysticks)++;
return DIENUM_CONTINUE;
}
JoystickService::~JoystickService(void)
{
this->jsPollerStop = true;
this->jsPoller.join();
for (auto pair : this->jsMap)
{
LPDIRECTINPUTDEVICE8 js = (LPDIRECTINPUTDEVICE8) pair.second.os_obj;
if (js)
{
js->Unacquire();
js->Release();
}
}
if (di)
di->Release();
}
bool JoystickService::Initialize(void)
{
HRESULT hr;
if (this->initialized)
return false;
EnumerateContext.connectedJoysticks = &this->connectedJoysticks;
EnumerateContext.nextJoystickID = &this->nextJoystickID;
EnumerateContext.requestedJoysticks = &this->requestedJoysticks;
EnumerateContext.jsMap = &this->jsMap;
// initialize directinput
hr = DirectInput8Create(
GetModuleHandle(nullptr),
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void **) &di,
nullptr
);
if (FAILED(hr))
return false;
this->initialized = true;
return true;
}
bool JoystickService::RemoveJoystick(int joystickID)
{
if (!this->initialized || !this->IsValidJoystickID(joystickID))
return false;
this->rwLock.lock();
LPDIRECTINPUTDEVICE8 joystick = (LPDIRECTINPUTDEVICE8) this->jsMap[joystickID].os_obj;
joystick->Unacquire();
this->jsMap[joystickID].alive = false;
this->connectedJoysticks--;
this->rwLock.unlock();
return true;
}
void JoystickService::PollJoysticks(void)
{
if (!this->initialized)
return;
while (!this->jsPollerStop)
{
HRESULT hr;
DIJOYSTATE js;
LPDIRECTINPUTDEVICE8 joystick;
this->rwLock.lock();
this->LocateJoysticks();
for (auto& pair : this->jsMap)
{
if (!pair.second.alive)
continue;
JoystickData& jsData = pair.second;
joystick = (LPDIRECTINPUTDEVICE8) jsData.os_obj;
hr = joystick->Poll();
if (FAILED(hr))
{
do
{
hr = joystick->Acquire();
}
while (hr == DIERR_INPUTLOST);
// joystick fatal error
if (hr == DIERR_INVALIDPARAM ||
hr == DIERR_NOTINITIALIZED ||
hr == DIERR_OTHERAPPHASPRIO)
{
// release and invalidate joystick - not found!
this->rwLock.unlock();
this->RemoveJoystick(pair.first);
this->rwLock.lock();
continue;
}
}
hr = joystick->GetDeviceState(sizeof(DIJOYSTATE), &js);
if (FAILED(hr))
{
// release and invalidate joystick - not found!
this->rwLock.unlock();
this->RemoveJoystick(pair.first);
this->rwLock.lock();
continue;
}
jsData.x = js.lX;
jsData.y = -js.lY; // y is backwards for some reason
jsData.rz = js.lRz;
// slider goes from -100 to 100, but it makes more sense from 0 -> 100.
// it's also backwards. The bottom part of the slider was 100, and the top -100.
// the formula below corrects this.
jsData.slider = (100 - js.rglSlider[0]) / 2;
// POV values are done in 45 deg segments (0 is up) * 100.
// i.e. straight right = 90 deg = 9000.
// determine POV value by way of lookup table (divide by 4500)
unsigned int povListIndex = js.rgdwPOV[0] / 4500;
jsData.pov = (povListIndex < povList.size()) ? povList[povListIndex] : POV::POV_NONE;
for (int i = 0; i < NUMBER_BUTTONS; i++)
jsData.buttons[i] = !!js.rgbButtons[i];
// joystick read complete
this->jsMap[pair.first] = jsData;
}
this->rwLock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void JoystickService::LocateJoysticks(void)
{
di->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumerateJoysticks, nullptr, DIEDFL_ATTACHEDONLY);
}
<commit_msg>Force Windows to match by path and to check if the device is already enumerated.<commit_after>/*
* Copyright (c) 2016, Wisconsin Robotics
* 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 <dinput.h>
#include <windows.h>
#include "joystick.h"
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")
using namespace JoystickLibrary;
const std::array<POV, 8> povList = {
POV::POV_NORTH,
POV::POV_NORTHEAST,
POV::POV_EAST,
POV::POV_SOUTHEAST,
POV::POV_SOUTH,
POV::POV_SOUTHWEST,
POV::POV_WEST,
POV::POV_NORTHWEST,
};
struct
{
int *nextJoystickID;
int *connectedJoysticks;
int *requestedJoysticks;
std::map<int, JoystickData> *jsMap;
} EnumerateContext;
LPDIRECTINPUT8 di;
/**
* Callback to configure the axis values on the joystick.
* @param instance A pointer to the device instance
* @param context A pointer to the joystick instance
* @return DIENUM_CONTINUE on success, DIENUM_STOP otherwise
*/
static BOOL CALLBACK JoystickConfigCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context)
{
DIPROPRANGE propRange;
LPDIRECTINPUTDEVICE8 joystick;
if (!context)
return DIENUM_STOP;
memset(&propRange, 0, sizeof(DIPROPRANGE));
propRange.diph.dwSize = sizeof(DIPROPRANGE);
propRange.diph.dwHeaderSize = sizeof(DIPROPHEADER);
propRange.diph.dwHow = DIPH_BYID;
propRange.diph.dwObj = instance->dwType;
propRange.lMin = -100;
propRange.lMax = +100;
// Set the range for the axis
joystick = (LPDIRECTINPUTDEVICE8) context;
if (FAILED(joystick->SetProperty(DIPROP_RANGE, &propRange.diph)))
return DIENUM_STOP;
return DIENUM_CONTINUE;
}
/**
* A callback function called for each found joystick.
* @param instance A pointer to the device instance.
* @param context (unused)
* @return DIENUM_CONTINUE on success, DIENUM_STOP otherwise
*/
static BOOL CALLBACK EnumerateJoysticks(const DIDEVICEINSTANCE *instance, void *context)
{
LPDIRECTINPUTDEVICE8 joystick;
DIPROPDWORD dipdw;
// context is not used
UNREFERENCED_PARAMETER(context);
if (*EnumerateContext.connectedJoysticks >= *EnumerateContext.requestedJoysticks)
return DIENUM_STOP;
if (FAILED(di->CreateDevice(instance->guidInstance, &joystick, nullptr)))
return DIENUM_CONTINUE;
DIPROPGUIDANDPATH jsGuidPath;
jsGuidPath.diph.dwSize = sizeof(DIPROPGUIDANDPATH);
jsGuidPath.diph.dwHeaderSize = sizeof(DIPROPHEADER);
jsGuidPath.diph.dwHow = DIPH_DEVICE;
jsGuidPath.diph.dwObj = 0;
if (FAILED(joystick->GetProperty(DIPROP_GUIDANDPATH, &jsGuidPath.diph)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
// check if joystick was a formerly removed one
for (auto& pair : *EnumerateContext.jsMap)
{
DIPROPGUIDANDPATH info;
LPDIRECTINPUTDEVICE8 inactiveJoystick;
inactiveJoystick = (LPDIRECTINPUTDEVICE8) pair.second.os_obj;
info.diph.dwSize = sizeof(DIPROPGUIDANDPATH);
info.diph.dwHeaderSize = sizeof(DIPROPHEADER);
info.diph.dwHow = DIPH_DEVICE;
info.diph.dwObj = 0;
if (FAILED(inactiveJoystick->GetProperty(DIPROP_GUIDANDPATH, &info.diph)))
continue;
// path match
if (info.wszPath && jsGuidPath.wszPath && lstrcmp(info.wszPath, jsGuidPath.wszPath) == 0)
{
// if this path is already active, don't enumerate
if (pair.second.alive)
{
joystick->Release();
return DIENUM_CONTINUE;
}
pair.second.alive = true;
inactiveJoystick->Acquire();
(*EnumerateContext.connectedJoysticks)++;
joystick->Release();
return DIENUM_CONTINUE;
}
}
// check vendor and product ID
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
if (FAILED(joystick->GetProperty(DIPROP_VIDPID, &dipdw.diph)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
if (LOWORD(dipdw.dwData) != JOYSTICK_VENDOR_ID || HIWORD(dipdw.dwData) != JOYSTICK_PRODUCT_ID)
{
joystick->Release();
return DIENUM_CONTINUE;
}
// create and start tracking joystick
// use DIJOYSTATE struct for data acquisition
if (FAILED(joystick->SetDataFormat(&c_dfDIJoystick)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
// axis configuration to -100 -> 100
if (FAILED(joystick->EnumObjects(JoystickConfigCallback, joystick, DIDFT_AXIS)))
{
joystick->Release();
return DIENUM_CONTINUE;
}
// new joystick - add to map & acquire
joystick->Acquire();
(*EnumerateContext.jsMap)[*(EnumerateContext.nextJoystickID)] = { };
(*EnumerateContext.jsMap)[*(EnumerateContext.nextJoystickID)].alive = true;
(*EnumerateContext.jsMap)[*(EnumerateContext.nextJoystickID)].os_obj = joystick;
(*EnumerateContext.nextJoystickID)++;
(*EnumerateContext.connectedJoysticks)++;
return DIENUM_CONTINUE;
}
JoystickService::~JoystickService(void)
{
this->jsPollerStop = true;
this->jsPoller.join();
for (auto& pair : this->jsMap)
{
LPDIRECTINPUTDEVICE8 js = (LPDIRECTINPUTDEVICE8) pair.second.os_obj;
if (js)
{
js->Unacquire();
js->Release();
}
}
if (di)
di->Release();
}
bool JoystickService::Initialize(void)
{
HRESULT hr;
if (this->initialized)
return false;
EnumerateContext.connectedJoysticks = &this->connectedJoysticks;
EnumerateContext.nextJoystickID = &this->nextJoystickID;
EnumerateContext.requestedJoysticks = &this->requestedJoysticks;
EnumerateContext.jsMap = &this->jsMap;
// initialize directinput
hr = DirectInput8Create(
GetModuleHandle(nullptr),
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void **) &di,
nullptr
);
if (FAILED(hr))
return false;
this->initialized = true;
return true;
}
bool JoystickService::RemoveJoystick(int joystickID)
{
if (!this->initialized || !this->IsValidJoystickID(joystickID))
return false;
this->rwLock.lock();
LPDIRECTINPUTDEVICE8 joystick = (LPDIRECTINPUTDEVICE8) this->jsMap[joystickID].os_obj;
joystick->Unacquire();
this->jsMap[joystickID].alive = false;
this->connectedJoysticks--;
this->rwLock.unlock();
return true;
}
void JoystickService::PollJoysticks(void)
{
if (!this->initialized)
return;
while (!this->jsPollerStop)
{
HRESULT hr;
DIJOYSTATE js;
LPDIRECTINPUTDEVICE8 joystick;
this->rwLock.lock();
this->LocateJoysticks();
for (auto& pair : this->jsMap)
{
if (!pair.second.alive)
continue;
JoystickData& jsData = pair.second;
joystick = (LPDIRECTINPUTDEVICE8) jsData.os_obj;
hr = joystick->Poll();
if (FAILED(hr))
{
do
{
hr = joystick->Acquire();
}
while (hr == DIERR_INPUTLOST);
// joystick fatal error
if (hr == DIERR_INVALIDPARAM ||
hr == DIERR_NOTINITIALIZED ||
hr == DIERR_OTHERAPPHASPRIO)
{
// release and invalidate joystick - not found!
this->rwLock.unlock();
this->RemoveJoystick(pair.first);
this->rwLock.lock();
continue;
}
}
hr = joystick->GetDeviceState(sizeof(DIJOYSTATE), &js);
if (FAILED(hr))
{
// release and invalidate joystick - not found!
this->rwLock.unlock();
this->RemoveJoystick(pair.first);
this->rwLock.lock();
continue;
}
jsData.x = js.lX;
jsData.y = -js.lY; // y is backwards for some reason
jsData.rz = js.lRz;
// slider goes from -100 to 100, but it makes more sense from 0 -> 100.
// it's also backwards. The bottom part of the slider was 100, and the top -100.
// the formula below corrects this.
jsData.slider = (100 - js.rglSlider[0]) / 2;
// POV values are done in 45 deg segments (0 is up) * 100.
// i.e. straight right = 90 deg = 9000.
// determine POV value by way of lookup table (divide by 4500)
unsigned int povListIndex = js.rgdwPOV[0] / 4500;
jsData.pov = (povListIndex < povList.size()) ? povList[povListIndex] : POV::POV_NONE;
for (int i = 0; i < NUMBER_BUTTONS; i++)
jsData.buttons[i] = !!js.rgbButtons[i];
// joystick read complete
this->jsMap[pair.first] = jsData;
}
this->rwLock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void JoystickService::LocateJoysticks(void)
{
di->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumerateJoysticks, nullptr, DIEDFL_ATTACHEDONLY);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.