text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
* Copyright (c) 2016 Jason Waataja
*
* 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 "options.h"
#include <err.h>
#include <getopt.h>
#include <iostream>
#include "util.h"
namespace dfm {
/*
* I couyld use default values since this requires C++ 11 and it's easier and
* easier to read, but it only really offers a benefit it there are multiple
* constructors.
*/
DfmOptions::DfmOptions()
: installModulesFlag(false),
uninstallModulesFlag(false),
updateModulesFlag(false),
allFlag(false),
verboseFlag(false),
interactiveFlag(false),
generateConfigFileFlag(false),
dumpConfigFileFlag(false),
hasSourceDirectory(false)
{
}
bool
DfmOptions::loadFromArguments(int argc, char* argv[])
{
int optionIndex = 0;
/*
* ClangFormat does a weird thing here, but I don't want to add a
* suppression and I'll just leave it.
*/
struct option longOptions[] = { { "install", no_argument, NULL, 'i' },
{ "uninstall", no_argument, NULL, 'u' },
{ "all", no_argument, NULL, 'a' },
{ "interactive", no_argument, NULL, 'I' },
{ "check", no_argument, NULL, 'c' },
{ "verbose", no_argument, NULL, 'v' },
{ "generate-config-file", no_argument, NULL, 'g' },
{ "dump-config-file", no_argument, NULL, 'G' },
{ "directory", required_argument, NULL, 'd' }, { 0, 0, 0, 0 } };
int getoptValue = getopt_long_only(
argc, argv, GETOPT_SHORT_OPTIONS, longOptions, &optionIndex);
while (getoptValue != -1) {
switch (getoptValue) {
case 0:
/*
* A flag was set, so do nothing. In the getopt example on the
* glibc documentation, they do an additional check to see if it
* sets a flag and something else if it's not, but in the
* documentation they give I don't see any other reason it could
* take 0. I'm kind of confused about it.
*/
break;
case 'i':
installModulesFlag = true;
break;
case 'u':
uninstallModulesFlag = true;
break;
case 'a':
allFlag = true;
break;
case 'I':
interactiveFlag = true;
break;
case 'c':
updateModulesFlag = true;
break;
case 'g':
generateConfigFileFlag = true;
break;
case 'G':
dumpConfigFileFlag = true;
break;
case 'd':
hasSourceDirectory = true;
sourceDirectory = shellExpandPath(optarg);
break;
case 'v':
verboseFlag = true;
break;
case '?':
usage();
return false;
case ':':
/*
* I'm not sure if this case is possible if optstring doesn't start
* with a colon, but I'm including it just to be safe.
*/
usage();
return false;
}
getoptValue = getopt_long_only(
argc, argv, GETOPT_SHORT_OPTIONS, longOptions, &optionIndex);
}
for (int i = optind; i < argc; i++)
remainingArguments.push_back(std::string(argv[i]));
return true;
}
bool
DfmOptions::verifyArguments() const
{
if (!verifyFlagsConsistency())
return false;
if (!verifyDirectoryExists())
return false;
return true;
}
bool
DfmOptions::verifyFlagsConsistency() const
{
int operationsCount = 0;
if (installModulesFlag)
operationsCount++;
if (uninstallModulesFlag)
operationsCount++;
if (updateModulesFlag)
operationsCount++;
if (generateConfigFileFlag)
operationsCount++;
if (dumpConfigFileFlag)
operationsCount++;
if (operationsCount == 0) {
warnx("Must specify an operation.");
return false;
}
if (operationsCount > 1) {
warnx("May only specify one operation.");
return false;
}
if (generateConfigFileFlag || dumpConfigFileFlag) {
if (remainingArguments.size() > 0) {
warnx("No arguments expected when creating config file.");
return false;
}
return true;
}
/*
* Fails if the all flag is passed and there are remaining arguments or the
* all flag isn't passed and there are also no additional argumens. I used
* the == operator here as an xnor operator. If both are true or both are
* false, then fail.
*/
if (allFlag == (remainingArguments.size() > 0)) {
warnx(
"Must specify either the --all flag or at least one remaining argument, but not both.");
return false;
}
return true;
}
bool
DfmOptions::verifyDirectoryExists() const
{
if (hasSourceDirectory) {
if (!fileExists(sourceDirectory)) {
warnx("Directory doesn't exist: %s.", sourceDirectory.c_str());
return false;
}
if (!isDirectory(sourceDirectory)) {
warnx("Given file isn't a directory: %s", sourceDirectory.c_str());
return false;
}
}
return true;
}
void
DfmOptions::usage()
{
std::cout
<< "usage: dfm [-Iv] [-c|-g|-G|-i|-u] [-d directory] [-a|[MODULES]]"
<< std::endl;
}
} /* namespace dfm */
<commit_msg>Added some extra usage calls<commit_after>/*
* Copyright (c) 2016 Jason Waataja
*
* 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 "options.h"
#include <err.h>
#include <getopt.h>
#include <iostream>
#include "util.h"
namespace dfm {
/*
* I couyld use default values since this requires C++ 11 and it's easier and
* easier to read, but it only really offers a benefit it there are multiple
* constructors.
*/
DfmOptions::DfmOptions()
: installModulesFlag(false),
uninstallModulesFlag(false),
updateModulesFlag(false),
allFlag(false),
verboseFlag(false),
interactiveFlag(false),
generateConfigFileFlag(false),
dumpConfigFileFlag(false),
hasSourceDirectory(false)
{
}
bool
DfmOptions::loadFromArguments(int argc, char* argv[])
{
int optionIndex = 0;
/*
* ClangFormat does a weird thing here, but I don't want to add a
* suppression and I'll just leave it.
*/
struct option longOptions[] = { { "install", no_argument, NULL, 'i' },
{ "uninstall", no_argument, NULL, 'u' },
{ "all", no_argument, NULL, 'a' },
{ "interactive", no_argument, NULL, 'I' },
{ "check", no_argument, NULL, 'c' },
{ "verbose", no_argument, NULL, 'v' },
{ "generate-config-file", no_argument, NULL, 'g' },
{ "dump-config-file", no_argument, NULL, 'G' },
{ "directory", required_argument, NULL, 'd' }, { 0, 0, 0, 0 } };
int getoptValue = getopt_long_only(
argc, argv, GETOPT_SHORT_OPTIONS, longOptions, &optionIndex);
while (getoptValue != -1) {
switch (getoptValue) {
case 0:
/*
* A flag was set, so do nothing. In the getopt example on the
* glibc documentation, they do an additional check to see if it
* sets a flag and something else if it's not, but in the
* documentation they give I don't see any other reason it could
* take 0. I'm kind of confused about it.
*/
break;
case 'i':
installModulesFlag = true;
break;
case 'u':
uninstallModulesFlag = true;
break;
case 'a':
allFlag = true;
break;
case 'I':
interactiveFlag = true;
break;
case 'c':
updateModulesFlag = true;
break;
case 'g':
generateConfigFileFlag = true;
break;
case 'G':
dumpConfigFileFlag = true;
break;
case 'd':
hasSourceDirectory = true;
sourceDirectory = shellExpandPath(optarg);
break;
case 'v':
verboseFlag = true;
break;
case '?':
usage();
return false;
case ':':
/*
* I'm not sure if this case is possible if optstring doesn't start
* with a colon, but I'm including it just to be safe.
*/
usage();
return false;
}
getoptValue = getopt_long_only(
argc, argv, GETOPT_SHORT_OPTIONS, longOptions, &optionIndex);
}
for (int i = optind; i < argc; i++)
remainingArguments.push_back(std::string(argv[i]));
return true;
}
bool
DfmOptions::verifyArguments() const
{
if (!verifyFlagsConsistency())
return false;
if (!verifyDirectoryExists())
return false;
return true;
}
bool
DfmOptions::verifyFlagsConsistency() const
{
int operationsCount = 0;
if (installModulesFlag)
operationsCount++;
if (uninstallModulesFlag)
operationsCount++;
if (updateModulesFlag)
operationsCount++;
if (generateConfigFileFlag)
operationsCount++;
if (dumpConfigFileFlag)
operationsCount++;
if (operationsCount == 0) {
warnx("Must specify an operation.");
usage();
return false;
}
if (operationsCount > 1) {
warnx("May only specify one operation.");
usage();
return false;
}
if (generateConfigFileFlag || dumpConfigFileFlag) {
if (remainingArguments.size() > 0) {
warnx("No arguments expected when creating config file.");
usage();
return false;
}
return true;
}
/*
* Fails if the all flag is passed and there are remaining arguments or the
* all flag isn't passed and there are also no additional argumens. I used
* the == operator here as an xnor operator. If both are true or both are
* false, then fail.
*/
if (allFlag == (remainingArguments.size() > 0)) {
warnx(
"Must specify either the --all flag or at least one remaining argument, but not both.");
usage();
return false;
}
return true;
}
bool
DfmOptions::verifyDirectoryExists() const
{
if (hasSourceDirectory) {
if (!fileExists(sourceDirectory)) {
warnx("Directory doesn't exist: %s.", sourceDirectory.c_str());
return false;
}
if (!isDirectory(sourceDirectory)) {
warnx("Given file isn't a directory: %s", sourceDirectory.c_str());
return false;
}
}
return true;
}
void
DfmOptions::usage()
{
std::cout
<< "usage: dfm [-Iv] [-c|-g|-G|-i|-u] [-d directory] [-a|[MODULES]]"
<< std::endl;
}
} /* namespace dfm */
<|endoftext|>
|
<commit_before>#include "GLFWController.hpp"
#include "ModelView.hpp"
#include "AffinePoint.hpp"
#include "AffineVector.hpp"
#include "ModelViewWithShader.hpp"
#include "Block.hpp"
#include "DependencyContainer.hpp"
#include "otuchaConfig.h"
#include <memory>
#include <iostream>
using namespace otucha;
void set3DViewingInformation(double xyz[6])
{
ModelView::setMCRegionOfInterest(xyz);
s1::AffinePoint eye(1.0, 1.0, 1.0);
s1::AffinePoint center(0, 0, 0);
s1::AffineVector up(0, 1, 0);
ModelView::setEyeCenterUp(eye, center, up);
double zpp = -1.0;
double zmin = -99.0;
double zmax = -0.01;
ModelView::setProjectionType(PERSPECTIVE);
ModelView::setZProjectionPlane(zpp);
ModelView::setEyeCoordinatesZMinZMax(zmin, zmax);
}
int main(int argc, char* argv[])
{
fprintf(stdout, "%s Version %d.%d\n", argv[0], otucha_VERSION_MAJOR, otucha_VERSION_MINOR);
GLFWController c("otucha", Controller::DEPTH);
c.reportVersions(std::cout);
std::string appPath(argv[0]);
unsigned found = appPath.find_last_of("/\\");
std::string appDir = appPath.substr(0, found + 1);
ModelViewWithShader::setShaderSources(appDir + "simple.vsh", appDir + "simple.fsh");
c.addModel(new Block(-0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f));
glClearColor(0.9f, 0.9f, 0.9f, 1.0f);
double xyz[6];
c.getOverallMCBoundingBox(xyz);
set3DViewingInformation(xyz);
// test console code to be removed later
DependencyContainer::getSingleton()->getConsole()->registerCommand("test", [](warbler::t_consoleArgs_ptr args) {
std::cout << "Console online" << std::endl;
}, std::make_shared<warbler::t_consoleArgTypes>());
DependencyContainer::getSingleton()->getConsole()->executeCommand("test");
// end test console code
c.run();
return 0;
}
<commit_msg>Initializing appdir and pulling font face to trigger load<commit_after>#include "GLFWController.hpp"
#include "ModelView.hpp"
#include "AffinePoint.hpp"
#include "AffineVector.hpp"
#include "ModelViewWithShader.hpp"
#include "Block.hpp"
#include "DependencyContainer.hpp"
#include "otuchaConfig.h"
#include <memory>
#include <iostream>
using namespace otucha;
void set3DViewingInformation(double xyz[6])
{
ModelView::setMCRegionOfInterest(xyz);
s1::AffinePoint eye(1.0, 1.0, 1.0);
s1::AffinePoint center(0, 0, 0);
s1::AffineVector up(0, 1, 0);
ModelView::setEyeCenterUp(eye, center, up);
double zpp = -1.0;
double zmin = -99.0;
double zmax = -0.01;
ModelView::setProjectionType(PERSPECTIVE);
ModelView::setZProjectionPlane(zpp);
ModelView::setEyeCoordinatesZMinZMax(zmin, zmax);
}
int main(int argc, char* argv[])
{
fprintf(stdout, "%s Version %d.%d\n", argv[0], otucha_VERSION_MAJOR, otucha_VERSION_MINOR);
GLFWController c("otucha", Controller::DEPTH);
c.reportVersions(std::cout);
std::string appPath(argv[0]);
unsigned found = appPath.find_last_of("/\\");
std::string appDir = appPath.substr(0, found + 1);
DependencyContainer::getSingleton()->setAppDir(appDir);
ModelViewWithShader::setShaderSources(appDir + "simple.vsh", appDir + "simple.fsh");
c.addModel(new Block(-0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f));
glClearColor(0.9f, 0.9f, 0.9f, 1.0f);
double xyz[6];
c.getOverallMCBoundingBox(xyz);
set3DViewingInformation(xyz);
// test console code to be removed later
DependencyContainer::getSingleton()->getConsole()->registerCommand("test", [](warbler::t_consoleArgs_ptr args) {
std::cout << "Console online" << std::endl;
}, std::make_shared<warbler::t_consoleArgTypes>());
DependencyContainer::getSingleton()->getConsole()->executeCommand("test");
// end test console code
auto fontFace = DependencyContainer::getSingleton()->getFontFace();
c.run();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "seastar/core/file.hh"
#include "disk-error-handler.hh"
class checked_file_impl : public file_impl {
public:
checked_file_impl(const io_error_handler& error_handler, file f)
: _error_handler(error_handler), _file(f) {
_memory_dma_alignment = f.memory_dma_alignment();
_disk_read_dma_alignment = f.disk_read_dma_alignment();
_disk_write_dma_alignment = f.disk_write_dma_alignment();
}
virtual future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->write_dma(pos, buffer, len, pc);
});
}
virtual future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->write_dma(pos, iov, pc);
});
}
virtual future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->read_dma(pos, buffer, len, pc);
});
}
virtual future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->read_dma(pos, iov, pc);
});
}
virtual future<> flush(void) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->flush();
});
}
virtual future<struct stat> stat(void) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->stat();
});
}
virtual future<> truncate(uint64_t length) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->truncate(length);
});
}
virtual future<> discard(uint64_t offset, uint64_t length) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->discard(offset, length);
});
}
virtual future<> allocate(uint64_t position, uint64_t length) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->allocate(position, length);
});
}
virtual future<uint64_t> size(void) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->size();
});
}
virtual future<> close() override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->close();
});
}
virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)> next) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->list_directory(next);
});
}
private:
const io_error_handler& _error_handler;
file _file;
};
inline file make_checked_file(const io_error_handler& error_handler, file& f)
{
return file(::make_shared<checked_file_impl>(error_handler, f));
}
future<file>
inline open_checked_file_dma(const io_error_handler& error_handler,
sstring name, open_flags flags,
file_open_options options)
{
return do_io_check(error_handler, [&] {
return open_file_dma(name, flags, options).then([&] (file f) {
return make_ready_future<file>(make_checked_file(error_handler, f));
});
});
}
future<file>
inline open_checked_file_dma(const io_error_handler& error_handler,
sstring name, open_flags flags)
{
return do_io_check(error_handler, [&] {
return open_file_dma(name, flags).then([&] (file f) {
return make_ready_future<file>(make_checked_file(error_handler, f));
});
});
}
future<file>
inline open_checked_directory(const io_error_handler& error_handler,
sstring name)
{
return do_io_check(error_handler, [&] {
return engine().open_directory(name).then([&] (file f) {
return make_ready_future<file>(make_checked_file(error_handler, f));
});
});
}
<commit_msg>checked_file_impl: add support to dup<commit_after>/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "seastar/core/file.hh"
#include "disk-error-handler.hh"
class checked_file_impl : public file_impl {
public:
checked_file_impl(const io_error_handler& error_handler, file f)
: _error_handler(error_handler), _file(f) {
_memory_dma_alignment = f.memory_dma_alignment();
_disk_read_dma_alignment = f.disk_read_dma_alignment();
_disk_write_dma_alignment = f.disk_write_dma_alignment();
}
virtual future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->write_dma(pos, buffer, len, pc);
});
}
virtual future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->write_dma(pos, iov, pc);
});
}
virtual future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->read_dma(pos, buffer, len, pc);
});
}
virtual future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->read_dma(pos, iov, pc);
});
}
virtual future<> flush(void) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->flush();
});
}
virtual future<struct stat> stat(void) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->stat();
});
}
virtual future<> truncate(uint64_t length) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->truncate(length);
});
}
virtual future<> discard(uint64_t offset, uint64_t length) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->discard(offset, length);
});
}
virtual future<> allocate(uint64_t position, uint64_t length) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->allocate(position, length);
});
}
virtual future<uint64_t> size(void) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->size();
});
}
virtual future<> close() override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->close();
});
}
// returns a handle for plain file, so make_checked_file() should be called
// on file returned by handle.
virtual std::unique_ptr<seastar::file_handle_impl> dup() override {
return get_file_impl(_file)->dup();
}
virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)> next) override {
return do_io_check(_error_handler, [&] {
return get_file_impl(_file)->list_directory(next);
});
}
private:
const io_error_handler& _error_handler;
file _file;
};
inline file make_checked_file(const io_error_handler& error_handler, file& f)
{
return file(::make_shared<checked_file_impl>(error_handler, f));
}
future<file>
inline open_checked_file_dma(const io_error_handler& error_handler,
sstring name, open_flags flags,
file_open_options options)
{
return do_io_check(error_handler, [&] {
return open_file_dma(name, flags, options).then([&] (file f) {
return make_ready_future<file>(make_checked_file(error_handler, f));
});
});
}
future<file>
inline open_checked_file_dma(const io_error_handler& error_handler,
sstring name, open_flags flags)
{
return do_io_check(error_handler, [&] {
return open_file_dma(name, flags).then([&] (file f) {
return make_ready_future<file>(make_checked_file(error_handler, f));
});
});
}
future<file>
inline open_checked_directory(const io_error_handler& error_handler,
sstring name)
{
return do_io_check(error_handler, [&] {
return engine().open_directory(name).then([&] (file f) {
return make_ready_future<file>(make_checked_file(error_handler, f));
});
});
}
<|endoftext|>
|
<commit_before>#include "output.h"
#include "buffer_pool.h"
#include "compress.h"
#include "cso.h"
namespace maxcso {
// TODO: Tune, less may be better.
static const size_t QUEUE_SIZE = 32;
Output::Output(uv_loop_t *loop, const Task &task)
: loop_(loop), flags_(task.flags), state_(STATE_INIT), fmt_(CSO_FMT_CSO1), srcSize_(-1), index_(nullptr) {
for (size_t i = 0; i < QUEUE_SIZE; ++i) {
freeSectors_.push_back(new Sector(flags_, task.orig_max_cost, task.lz4_max_cost));
}
}
Output::~Output() {
for (Sector *sector : freeSectors_) {
delete sector;
}
for (auto pair : pendingSectors_) {
delete pair.second;
}
for (auto pair : partialSectors_) {
delete pair.second;
}
freeSectors_.clear();
pendingSectors_.clear();
partialSectors_.clear();
delete [] index_;
index_ = nullptr;
}
void Output::SetFile(uv_file file, int64_t srcSize, uint32_t blockSize, CSOFormat fmt) {
file_ = file;
srcSize_ = srcSize;
srcPos_ = 0;
fmt_ = fmt;
blockSize_ = blockSize;
for (blockShift_ = 0; blockSize > 1; blockSize >>= 1) {
++blockShift_;
}
const uint32_t sectors = static_cast<uint32_t>((srcSize + blockSize_ - 1) >> blockShift_);
// Start after the header and index, which we'll fill in later.
index_ = new uint32_t[sectors + 1];
// Start after the end of the index data and header.
dstPos_ = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);
// TODO: We might be able to optimize shift better by running through the data.
// That would require either a second pass or keeping the entire result in RAM.
// For now, just take worst case (all blocks stored uncompressed.)
int64_t worstSize = dstPos_ + srcSize;
indexShift_ = 0;
for (int i = 62; i >= 31; --i) {
int64_t max = 1LL << i;
if (worstSize >= max) {
// This means we need i + 1 bits to store the position.
// We have to shift enough off to fit into 31.
indexShift_ = i + 1 - 31;
break;
}
}
// If the shift is above 11, the padding could make it need more space.
// But that would be > 4 TB anyway, so let's not worry about it.
indexAlign_ = 1 << indexShift_;
Align(dstPos_);
state_ |= STATE_HAS_FILE;
for (Sector *sector : freeSectors_) {
sector->Setup(loop_, blockSize_, indexAlign_);
}
}
int32_t Output::Align(int64_t &pos) {
uint32_t off = static_cast<uint32_t>(pos % indexAlign_);
if (off != 0) {
pos += indexAlign_ - off;
return indexAlign_ - off;
}
return 0;
}
void Output::Enqueue(int64_t pos, uint8_t *buffer) {
// We might not compress all blocks.
const bool tryCompress = ShouldCompress(pos, buffer);
const uint32_t block = static_cast<uint32_t>(pos >> blockShift_);
Sector *sector;
if (blockSize_ != SECTOR_SIZE) {
// Guaranteed to be zero-initialized on insert.
sector = partialSectors_[block];
if (sector == nullptr) {
sector = freeSectors_.back();
freeSectors_.pop_back();
partialSectors_[block] = sector;
}
} else {
sector = freeSectors_.back();
freeSectors_.pop_back();
}
if (!tryCompress) {
sector->DisableCompress();
}
sector->Process(pos, buffer, [this, sector, block](bool status, const char *reason) {
if (blockSize_ != SECTOR_SIZE) {
partialSectors_.erase(block);
}
HandleReadySector(sector);
});
// Only check for the last block of a larger block size.
if (blockSize_ != SECTOR_SIZE && pos + SECTOR_SIZE >= srcSize_) {
// Our src may not be aligned to the blockSize_, so this sector might never wake up.
// So let's send in some padding if needed.
const int64_t paddedSize = SrcSizeAligned() & ~static_cast<int64_t>(blockSize_ - 1);
for (int64_t padPos = srcSize_; padPos < paddedSize; padPos += SECTOR_SIZE) {
// Sector takes ownership, so we need a new one each time.
uint8_t *padBuffer = pool.Alloc();
memset(padBuffer, 0, SECTOR_SIZE);
sector->Process(padPos, padBuffer, [this, sector, block](bool status, const char *reason) {
partialSectors_.erase(block);
HandleReadySector(sector);
});
}
}
}
void Output::HandleReadySector(Sector *sector) {
if (sector != nullptr) {
if (srcPos_ != sector->Pos()) {
// We're not there yet in the file stream. Queue this, get to it later.
pendingSectors_[sector->Pos()] = sector;
return;
}
} else {
// If no sector was provided, we're looking at the first in the queue.
if (pendingSectors_.empty()) {
return;
}
sector = pendingSectors_.begin()->second;
if (srcPos_ != sector->Pos()) {
return;
}
// Remove it from the queue, and then run with it.
pendingSectors_.erase(pendingSectors_.begin());
}
// Check for any sectors that immediately follow the one we're writing.
// We'll just write them all together.
std::vector<Sector *> sectors;
sectors.push_back(sector);
// TODO: Try other numbers.
static const size_t MAX_BUFS = 8;
int64_t nextPos = srcPos_ + blockSize_;
auto it = pendingSectors_.find(nextPos);
while (it != pendingSectors_.end()) {
sectors.push_back(it->second);
pendingSectors_.erase(it);
nextPos += blockSize_;
it = pendingSectors_.find(nextPos);
// Don't do more than 4 at a time.
if (sectors.size() >= MAX_BUFS) {
break;
}
}
int64_t dstPos = dstPos_;
uv_buf_t bufs[MAX_BUFS * 2];
unsigned int nbufs = 0;
static char padding[2048] = {0};
for (size_t i = 0; i < sectors.size(); ++i) {
unsigned int bestSize = sectors[i]->BestSize();
bufs[nbufs++] = uv_buf_init(reinterpret_cast<char *>(sectors[i]->BestBuffer()), bestSize);
// Update the index.
const int32_t s = static_cast<int32_t>(sectors[i]->Pos() >> blockShift_);
index_[s] = static_cast<int32_t>(dstPos >> indexShift_);
// CSO2 doesn't use a flag for uncompressed, only the size of the block.
if (!sectors[i]->Compressed() && fmt_ != CSO_FMT_CSO2) {
index_[s] |= CSO_INDEX_UNCOMPRESSED;
}
switch (fmt_) {
case CSO_FMT_CSO1:
if (sectors[i]->Format() == SECTOR_FMT_LZ4) {
finish_(false, "LZ4 format not supported within CSO v1 file");
return;
}
break;
case CSO_FMT_ZSO:
if (sectors[i]->Format() == SECTOR_FMT_DEFLATE) {
finish_(false, "Deflate format not supported within ZSO file");
return;
}
break;
case CSO_FMT_CSO2:
if (sectors[i]->Format() == SECTOR_FMT_LZ4) {
index_[s] |= CSO2_INDEX_LZ4;
}
break;
}
dstPos += bestSize;
int32_t padSize = Align(dstPos);
if (padSize != 0) {
// We need uv to write the padding out as well.
bufs[nbufs++] = uv_buf_init(padding, padSize);
}
}
// If we're working on the last sectors, then the index is ready to write.
if (nextPos >= srcSize_) {
// Update the final index entry.
const int32_t s = static_cast<int32_t>(SrcSizeAligned() >> blockShift_);
index_[s] = static_cast<int32_t>(dstPos >> indexShift_);
state_ |= STATE_INDEX_READY;
Flush();
}
const int64_t totalWrite = dstPos - dstPos_;
uv_.fs_write(loop_, sector->WriteReq(), file_, bufs, nbufs, dstPos_, [this, sectors, nextPos, totalWrite](uv_fs_t *req) {
for (Sector *sector : sectors) {
sector->Release();
freeSectors_.push_back(sector);
}
if (req->result != totalWrite) {
finish_(false, "Data could not be written to output file");
uv_fs_req_cleanup(req);
return;
}
uv_fs_req_cleanup(req);
srcPos_ = nextPos;
dstPos_ += totalWrite;
progress_(srcPos_, srcSize_, dstPos_);
if (nextPos >= srcSize_) {
state_ |= STATE_DATA_WRITTEN;
CheckFinish();
} else {
// Check if there's more data to write out.
HandleReadySector(nullptr);
}
});
}
bool Output::ShouldCompress(int64_t pos, uint8_t *buffer) {
if (flags_ & TASKFLAG_FORCE_ALL) {
return true;
}
if (pos == 16 * SECTOR_SIZE) {
// This is the volume descriptor.
// TODO: Could read it in and map all the directory structures.
// Would just need to keep a list, assuming they are sequential, we'd get most of them.
// TODO: This doesn't really seem to help anyone. Rethink.
//return false;
}
// TODO
return true;
}
bool Output::QueueFull() {
return freeSectors_.empty();
}
void Output::OnProgress(OutputCallback callback) {
progress_ = callback;
}
void Output::OnFinish(OutputFinishCallback callback) {
finish_ = callback;
}
void Output::Flush() {
if (!(state_ & STATE_INDEX_READY)) {
finish_(false, "Flush called before index finalized");
return;
}
CSOHeader *header = new CSOHeader;
if (fmt_ == CSO_FMT_ZSO) {
memcpy(header->magic, ZSO_MAGIC, sizeof(header->magic));
} else {
memcpy(header->magic, CSO_MAGIC, sizeof(header->magic));
}
header->header_size = sizeof(CSOHeader);
header->uncompressed_size = srcSize_;
header->sector_size = blockSize_;
header->version = fmt_ == CSO_FMT_CSO2 ? 2 : 1;
header->index_shift = indexShift_;
header->unused[0] = 0;
header->unused[1] = 0;
const uint32_t sectors = static_cast<uint32_t>(SrcSizeAligned() >> blockShift_);
uv_buf_t bufs[2];
bufs[0] = uv_buf_init(reinterpret_cast<char *>(header), sizeof(CSOHeader));
bufs[1] = uv_buf_init(reinterpret_cast<char *>(index_), (sectors + 1) * sizeof(uint32_t));
const size_t totalBytes = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);
uv_.fs_write(loop_, &flush_, file_, bufs, 2, 0, [this, header, totalBytes](uv_fs_t *req) {
if (req->result != totalBytes) {
finish_(false, "Unable to write header data");
} else {
state_ |= STATE_INDEX_WRITTEN;
CheckFinish();
}
uv_fs_req_cleanup(req);
delete header;
});
}
void Output::CheckFinish() {
if ((state_ & STATE_INDEX_WRITTEN) && (state_ & STATE_DATA_WRITTEN)) {
finish_(true, nullptr);
}
}
inline int64_t Output::SrcSizeAligned() {
return srcSize_ + blockSize_ - 1;
}
};
<commit_msg>Make sure to report compression errors.<commit_after>#include "output.h"
#include "buffer_pool.h"
#include "compress.h"
#include "cso.h"
namespace maxcso {
// TODO: Tune, less may be better.
static const size_t QUEUE_SIZE = 32;
Output::Output(uv_loop_t *loop, const Task &task)
: loop_(loop), flags_(task.flags), state_(STATE_INIT), fmt_(CSO_FMT_CSO1), srcSize_(-1), index_(nullptr) {
for (size_t i = 0; i < QUEUE_SIZE; ++i) {
freeSectors_.push_back(new Sector(flags_, task.orig_max_cost, task.lz4_max_cost));
}
}
Output::~Output() {
for (Sector *sector : freeSectors_) {
delete sector;
}
for (auto pair : pendingSectors_) {
delete pair.second;
}
for (auto pair : partialSectors_) {
delete pair.second;
}
freeSectors_.clear();
pendingSectors_.clear();
partialSectors_.clear();
delete [] index_;
index_ = nullptr;
}
void Output::SetFile(uv_file file, int64_t srcSize, uint32_t blockSize, CSOFormat fmt) {
file_ = file;
srcSize_ = srcSize;
srcPos_ = 0;
fmt_ = fmt;
blockSize_ = blockSize;
for (blockShift_ = 0; blockSize > 1; blockSize >>= 1) {
++blockShift_;
}
const uint32_t sectors = static_cast<uint32_t>((srcSize + blockSize_ - 1) >> blockShift_);
// Start after the header and index, which we'll fill in later.
index_ = new uint32_t[sectors + 1];
// Start after the end of the index data and header.
dstPos_ = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);
// TODO: We might be able to optimize shift better by running through the data.
// That would require either a second pass or keeping the entire result in RAM.
// For now, just take worst case (all blocks stored uncompressed.)
int64_t worstSize = dstPos_ + srcSize;
indexShift_ = 0;
for (int i = 62; i >= 31; --i) {
int64_t max = 1LL << i;
if (worstSize >= max) {
// This means we need i + 1 bits to store the position.
// We have to shift enough off to fit into 31.
indexShift_ = i + 1 - 31;
break;
}
}
// If the shift is above 11, the padding could make it need more space.
// But that would be > 4 TB anyway, so let's not worry about it.
indexAlign_ = 1 << indexShift_;
Align(dstPos_);
state_ |= STATE_HAS_FILE;
for (Sector *sector : freeSectors_) {
sector->Setup(loop_, blockSize_, indexAlign_);
}
}
int32_t Output::Align(int64_t &pos) {
uint32_t off = static_cast<uint32_t>(pos % indexAlign_);
if (off != 0) {
pos += indexAlign_ - off;
return indexAlign_ - off;
}
return 0;
}
void Output::Enqueue(int64_t pos, uint8_t *buffer) {
// We might not compress all blocks.
const bool tryCompress = ShouldCompress(pos, buffer);
const uint32_t block = static_cast<uint32_t>(pos >> blockShift_);
Sector *sector;
if (blockSize_ != SECTOR_SIZE) {
// Guaranteed to be zero-initialized on insert.
sector = partialSectors_[block];
if (sector == nullptr) {
sector = freeSectors_.back();
freeSectors_.pop_back();
partialSectors_[block] = sector;
}
} else {
sector = freeSectors_.back();
freeSectors_.pop_back();
}
if (!tryCompress) {
sector->DisableCompress();
}
sector->Process(pos, buffer, [this, sector, block](bool status, const char *reason) {
if (!status) {
finish_(false, reason);
return;
}
if (blockSize_ != SECTOR_SIZE) {
// Not in progress anymore.
partialSectors_.erase(block);
}
HandleReadySector(sector);
});
// Only check for the last block of a larger block size.
if (blockSize_ != SECTOR_SIZE && pos + SECTOR_SIZE >= srcSize_) {
// Our src may not be aligned to the blockSize_, so this sector might never wake up.
// So let's send in some padding if needed.
const int64_t paddedSize = SrcSizeAligned() & ~static_cast<int64_t>(blockSize_ - 1);
for (int64_t padPos = srcSize_; padPos < paddedSize; padPos += SECTOR_SIZE) {
// Sector takes ownership, so we need a new one each time.
uint8_t *padBuffer = pool.Alloc();
memset(padBuffer, 0, SECTOR_SIZE);
sector->Process(padPos, padBuffer, [this, sector, block](bool status, const char *reason) {
if (!status) {
finish_(false, reason);
return;
}
partialSectors_.erase(block);
HandleReadySector(sector);
});
}
}
}
void Output::HandleReadySector(Sector *sector) {
if (sector != nullptr) {
if (srcPos_ != sector->Pos()) {
// We're not there yet in the file stream. Queue this, get to it later.
pendingSectors_[sector->Pos()] = sector;
return;
}
} else {
// If no sector was provided, we're looking at the first in the queue.
if (pendingSectors_.empty()) {
return;
}
sector = pendingSectors_.begin()->second;
if (srcPos_ != sector->Pos()) {
return;
}
// Remove it from the queue, and then run with it.
pendingSectors_.erase(pendingSectors_.begin());
}
// Check for any sectors that immediately follow the one we're writing.
// We'll just write them all together.
std::vector<Sector *> sectors;
sectors.push_back(sector);
// TODO: Try other numbers.
static const size_t MAX_BUFS = 8;
int64_t nextPos = srcPos_ + blockSize_;
auto it = pendingSectors_.find(nextPos);
while (it != pendingSectors_.end()) {
sectors.push_back(it->second);
pendingSectors_.erase(it);
nextPos += blockSize_;
it = pendingSectors_.find(nextPos);
// Don't do more than 4 at a time.
if (sectors.size() >= MAX_BUFS) {
break;
}
}
int64_t dstPos = dstPos_;
uv_buf_t bufs[MAX_BUFS * 2];
unsigned int nbufs = 0;
static char padding[2048] = {0};
for (size_t i = 0; i < sectors.size(); ++i) {
unsigned int bestSize = sectors[i]->BestSize();
bufs[nbufs++] = uv_buf_init(reinterpret_cast<char *>(sectors[i]->BestBuffer()), bestSize);
// Update the index.
const int32_t s = static_cast<int32_t>(sectors[i]->Pos() >> blockShift_);
index_[s] = static_cast<int32_t>(dstPos >> indexShift_);
// CSO2 doesn't use a flag for uncompressed, only the size of the block.
if (!sectors[i]->Compressed() && fmt_ != CSO_FMT_CSO2) {
index_[s] |= CSO_INDEX_UNCOMPRESSED;
}
switch (fmt_) {
case CSO_FMT_CSO1:
if (sectors[i]->Format() == SECTOR_FMT_LZ4) {
finish_(false, "LZ4 format not supported within CSO v1 file");
return;
}
break;
case CSO_FMT_ZSO:
if (sectors[i]->Format() == SECTOR_FMT_DEFLATE) {
finish_(false, "Deflate format not supported within ZSO file");
return;
}
break;
case CSO_FMT_CSO2:
if (sectors[i]->Format() == SECTOR_FMT_LZ4) {
index_[s] |= CSO2_INDEX_LZ4;
}
break;
}
dstPos += bestSize;
int32_t padSize = Align(dstPos);
if (padSize != 0) {
// We need uv to write the padding out as well.
bufs[nbufs++] = uv_buf_init(padding, padSize);
}
}
// If we're working on the last sectors, then the index is ready to write.
if (nextPos >= srcSize_) {
// Update the final index entry.
const int32_t s = static_cast<int32_t>(SrcSizeAligned() >> blockShift_);
index_[s] = static_cast<int32_t>(dstPos >> indexShift_);
state_ |= STATE_INDEX_READY;
Flush();
}
const int64_t totalWrite = dstPos - dstPos_;
uv_.fs_write(loop_, sector->WriteReq(), file_, bufs, nbufs, dstPos_, [this, sectors, nextPos, totalWrite](uv_fs_t *req) {
for (Sector *sector : sectors) {
sector->Release();
freeSectors_.push_back(sector);
}
if (req->result != totalWrite) {
finish_(false, "Data could not be written to output file");
uv_fs_req_cleanup(req);
return;
}
uv_fs_req_cleanup(req);
srcPos_ = nextPos;
dstPos_ += totalWrite;
progress_(srcPos_, srcSize_, dstPos_);
if (nextPos >= srcSize_) {
state_ |= STATE_DATA_WRITTEN;
CheckFinish();
} else {
// Check if there's more data to write out.
HandleReadySector(nullptr);
}
});
}
bool Output::ShouldCompress(int64_t pos, uint8_t *buffer) {
if (flags_ & TASKFLAG_FORCE_ALL) {
return true;
}
if (pos == 16 * SECTOR_SIZE) {
// This is the volume descriptor.
// TODO: Could read it in and map all the directory structures.
// Would just need to keep a list, assuming they are sequential, we'd get most of them.
// TODO: This doesn't really seem to help anyone. Rethink.
//return false;
}
// TODO
return true;
}
bool Output::QueueFull() {
return freeSectors_.empty();
}
void Output::OnProgress(OutputCallback callback) {
progress_ = callback;
}
void Output::OnFinish(OutputFinishCallback callback) {
finish_ = callback;
}
void Output::Flush() {
if (!(state_ & STATE_INDEX_READY)) {
finish_(false, "Flush called before index finalized");
return;
}
CSOHeader *header = new CSOHeader;
if (fmt_ == CSO_FMT_ZSO) {
memcpy(header->magic, ZSO_MAGIC, sizeof(header->magic));
} else {
memcpy(header->magic, CSO_MAGIC, sizeof(header->magic));
}
header->header_size = sizeof(CSOHeader);
header->uncompressed_size = srcSize_;
header->sector_size = blockSize_;
header->version = fmt_ == CSO_FMT_CSO2 ? 2 : 1;
header->index_shift = indexShift_;
header->unused[0] = 0;
header->unused[1] = 0;
const uint32_t sectors = static_cast<uint32_t>(SrcSizeAligned() >> blockShift_);
uv_buf_t bufs[2];
bufs[0] = uv_buf_init(reinterpret_cast<char *>(header), sizeof(CSOHeader));
bufs[1] = uv_buf_init(reinterpret_cast<char *>(index_), (sectors + 1) * sizeof(uint32_t));
const size_t totalBytes = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t);
uv_.fs_write(loop_, &flush_, file_, bufs, 2, 0, [this, header, totalBytes](uv_fs_t *req) {
if (req->result != totalBytes) {
finish_(false, "Unable to write header data");
} else {
state_ |= STATE_INDEX_WRITTEN;
CheckFinish();
}
uv_fs_req_cleanup(req);
delete header;
});
}
void Output::CheckFinish() {
if ((state_ & STATE_INDEX_WRITTEN) && (state_ & STATE_DATA_WRITTEN)) {
finish_(true, nullptr);
}
}
inline int64_t Output::SrcSizeAligned() {
return srcSize_ + blockSize_ - 1;
}
};
<|endoftext|>
|
<commit_before>#include "parser.h"
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include <sstream>
namespace YAML
{
Parser::Parser(std::istream& in): m_pScanner(0)
{
Load(in);
}
Parser::~Parser()
{
delete m_pScanner;
}
Parser::operator bool() const
{
return m_pScanner->PeekNextToken() != 0;
}
void Parser::Load(std::istream& in)
{
delete m_pScanner;
m_pScanner = new Scanner(in);
m_state.Reset();
}
// GetNextDocument
// . Reads the next document in the queue (of tokens).
// . Throws (ParserException|ParserException)s on errors.
void Parser::GetNextDocument(Node& document)
{
// clear node
document.Clear();
// first read directives
ParseDirectives();
// we better have some tokens in the queue
if(!m_pScanner->PeekNextToken())
return;
// first eat doc start (optional)
if(m_pScanner->PeekNextToken()->type == TT_DOC_START)
m_pScanner->EatNextToken();
// now parse our root node
document.Parse(m_pScanner, m_state);
// and finally eat any doc ends we see
while(m_pScanner->PeekNextToken() && m_pScanner->PeekNextToken()->type == TT_DOC_END)
m_pScanner->EatNextToken();
}
// ParseDirectives
// . Reads any directives that are next in the queue.
void Parser::ParseDirectives()
{
bool readDirective = false;
while(1) {
Token *pToken = m_pScanner->PeekNextToken();
if(!pToken || pToken->type != TT_DIRECTIVE)
break;
// we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them
if(!readDirective)
m_state.Reset();
readDirective = true;
HandleDirective(pToken);
m_pScanner->PopNextToken();
}
}
void Parser::HandleDirective(Token *pToken)
{
if(pToken->value == "YAML")
HandleYamlDirective(pToken);
else if(pToken->value == "TAG")
HandleTagDirective(pToken);
}
// HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(Token *pToken)
{
if(pToken->params.size() != 1)
throw ParserException(pToken->line, pToken->column, ErrorMsg::YAML_DIRECTIVE_ARGS);
std::stringstream str(pToken->params[0]);
str >> m_state.version.major;
str.get();
str >> m_state.version.minor;
if(!str || str.peek() != EOF)
throw ParserException(pToken->line, pToken->column, ErrorMsg::YAML_VERSION + pToken->params[0]);
if(m_state.version.major > 1)
throw ParserException(pToken->line, pToken->column, ErrorMsg::YAML_MAJOR_VERSION);
// TODO: warning on major == 1, minor > 2?
}
// HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file.
void Parser::HandleTagDirective(Token *pToken)
{
if(pToken->params.size() != 2)
throw ParserException(pToken->line, pToken->column, ErrorMsg::TAG_DIRECTIVE_ARGS);
std::string handle = pToken->params[0], prefix = pToken->params[1];
m_state.tags[handle] = prefix;
}
void Parser::PrintTokens(std::ostream& out)
{
while(1) {
Token *pToken = m_pScanner->GetNextToken();
if(!pToken)
break;
out << *pToken << std::endl;
}
}
}
<commit_msg><commit_after>#include "parser.h"
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include <sstream>
namespace YAML
{
Parser::Parser(std::istream& in): m_pScanner(0)
{
Load(in);
}
Parser::~Parser()
{
delete m_pScanner;
}
Parser::operator bool() const
{
return m_pScanner->PeekNextToken() != 0;
}
void Parser::Load(std::istream& in)
{
delete m_pScanner;
m_pScanner = new Scanner(in);
m_state.Reset();
}
// GetNextDocument
// . Reads the next document in the queue (of tokens).
// . Throws a ParserException on error.
void Parser::GetNextDocument(Node& document)
{
// clear node
document.Clear();
// first read directives
ParseDirectives();
// we better have some tokens in the queue
if(!m_pScanner->PeekNextToken())
return;
// first eat doc start (optional)
if(m_pScanner->PeekNextToken()->type == TT_DOC_START)
m_pScanner->EatNextToken();
// now parse our root node
document.Parse(m_pScanner, m_state);
// and finally eat any doc ends we see
while(m_pScanner->PeekNextToken() && m_pScanner->PeekNextToken()->type == TT_DOC_END)
m_pScanner->EatNextToken();
}
// ParseDirectives
// . Reads any directives that are next in the queue.
void Parser::ParseDirectives()
{
bool readDirective = false;
while(1) {
Token *pToken = m_pScanner->PeekNextToken();
if(!pToken || pToken->type != TT_DIRECTIVE)
break;
// we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them
if(!readDirective)
m_state.Reset();
readDirective = true;
HandleDirective(pToken);
m_pScanner->PopNextToken();
}
}
void Parser::HandleDirective(Token *pToken)
{
if(pToken->value == "YAML")
HandleYamlDirective(pToken);
else if(pToken->value == "TAG")
HandleTagDirective(pToken);
}
// HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(Token *pToken)
{
if(pToken->params.size() != 1)
throw ParserException(pToken->line, pToken->column, ErrorMsg::YAML_DIRECTIVE_ARGS);
std::stringstream str(pToken->params[0]);
str >> m_state.version.major;
str.get();
str >> m_state.version.minor;
if(!str || str.peek() != EOF)
throw ParserException(pToken->line, pToken->column, ErrorMsg::YAML_VERSION + pToken->params[0]);
if(m_state.version.major > 1)
throw ParserException(pToken->line, pToken->column, ErrorMsg::YAML_MAJOR_VERSION);
// TODO: warning on major == 1, minor > 2?
}
// HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file.
void Parser::HandleTagDirective(Token *pToken)
{
if(pToken->params.size() != 2)
throw ParserException(pToken->line, pToken->column, ErrorMsg::TAG_DIRECTIVE_ARGS);
std::string handle = pToken->params[0], prefix = pToken->params[1];
m_state.tags[handle] = prefix;
}
void Parser::PrintTokens(std::ostream& out)
{
while(1) {
Token *pToken = m_pScanner->GetNextToken();
if(!pToken)
break;
out << *pToken << std::endl;
}
}
}
<|endoftext|>
|
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bstbuseditor.hh"
#include "bstparam.hh"
#include "bstitemseqdialog.hh" // FIXME
#include "bstsnifferscope.hh" // FIXME
#include "bse/internal.hh"
/* --- prototypes --- */
static void bus_editor_action_exec (gpointer data,
size_t action);
static gboolean bus_editor_action_check (gpointer data,
size_t action,
guint64 action_stamp);
/* --- bus actions --- */
enum {
ACTION_ADD_BUS,
ACTION_DELETE_BUS,
ACTION_EDIT_BUS
};
static const GxkStockAction bus_editor_actions[] = {
{ N_("Add"), NULL, NULL, ACTION_ADD_BUS, BST_STOCK_PART },
{ N_("Delete"), NULL, NULL, ACTION_DELETE_BUS, BST_STOCK_TRASHCAN },
{ N_("Editor"), NULL, NULL, ACTION_EDIT_BUS, BST_STOCK_PART_EDITOR },
};
/* --- functions --- */
G_DEFINE_TYPE (BstBusEditor, bst_bus_editor, GTK_TYPE_ALIGNMENT);
static void
bst_bus_editor_init (BstBusEditor *self)
{
new (&self->source) Bse::SourceS();
new (&self->lmonitor) Bse::SignalMonitorS();
new (&self->rmonitor) Bse::SignalMonitorS();
self->mon_handler = 0;
/* complete GUI */
gxk_radget_complete (GTK_WIDGET (self), "beast", "bus-editor", NULL);
/* create tool actions */
gxk_widget_publish_actions (self, "bus-editor-actions",
G_N_ELEMENTS (bus_editor_actions), bus_editor_actions,
NULL, bus_editor_action_check, bus_editor_action_exec);
}
static void
bst_bus_editor_destroy (GtkObject *object)
{
BstBusEditor *self = BST_BUS_EDITOR (object);
bst_bus_editor_set_bus (self, 0);
GTK_OBJECT_CLASS (bst_bus_editor_parent_class)->destroy (object);
}
static void
bst_bus_editor_finalize (GObject *object)
{
BstBusEditor *self = BST_BUS_EDITOR (object);
bst_bus_editor_set_bus (self, 0);
G_OBJECT_CLASS (bst_bus_editor_parent_class)->finalize (object);
using namespace Bse;
Bst::remove_handler (&self->mon_handler);
self->source.~SourceS();
self->lmonitor.~SignalMonitorS();
self->rmonitor.~SignalMonitorS();
}
GtkWidget*
bst_bus_editor_new (SfiProxy bus)
{
assert_return (BSE_IS_BUS (bus), NULL);
GtkWidget *widget = (GtkWidget*) g_object_new (BST_TYPE_BUS_EDITOR, NULL);
BstBusEditor *self = BST_BUS_EDITOR (widget);
bst_bus_editor_set_bus (self, bus);
return widget;
}
static void
bus_editor_release_item (SfiProxy item,
BstBusEditor *self)
{
assert_return (self->item == item);
bst_bus_editor_set_bus (self, 0);
}
static GxkParam *
get_property_param (BstBusEditor *self,
const gchar *property)
{
Bse::BusH bus = Bse::BusH::__cast__ (bse_server.from_proxy (self->item));
const Bse::StringSeq kvlist = bus.find_prop (property);
GParamSpec *cxxpspec = Bse::pspec_from_key_value_list (property, kvlist);
if (cxxpspec)
return bst_param_new_property (cxxpspec, bus);
return nullptr;
}
static GtkWidget*
bus_build_param (BstBusEditor *self,
const gchar *property,
const gchar *area,
const gchar *editor,
const gchar *label)
{
GxkParam *gxk_param = get_property_param (self, property); /* aida property? */
if (!gxk_param)
{
/* proxy property */
auto pspec = bse_proxy_get_pspec (self->item, property);
gxk_param = bst_param_new_proxy (pspec, self->item);
}
self->params = sfi_ring_prepend (self->params, gxk_param);
GtkWidget *ewidget = gxk_param_create_editor ((GxkParam*) self->params->data, editor);
gxk_radget_add (self, area, ewidget);
if (label)
g_object_set (gxk_parent_find_descendant (ewidget, GTK_TYPE_LABEL), "label", label, NULL);
return ewidget;
}
static gboolean
grab_focus_and_false (GtkWidget *widget)
{
gtk_widget_grab_focus (widget);
return FALSE;
}
void
bst_bus_editor_set_bus (BstBusEditor *self,
SfiProxy item)
{
if (item)
assert_return (BSE_IS_BUS (item));
if (self->item)
{
Bst::remove_handler (&self->mon_handler);
self->lmonitor = NULL;
self->rmonitor = NULL;
Bse::SourceH source = Bse::SourceH::__cast__ (bse_server.from_proxy (self->item));
bse_proxy_disconnect (self->item,
"any-signal", bus_editor_release_item, self,
NULL);
self->source = NULL;
while (self->params)
gxk_param_destroy ((GxkParam*) sfi_ring_pop_head (&self->params));
}
self->item = item;
if (self->item)
{
self->source = Bse::SourceH::__cast__ (bse_server.from_proxy (self->item));
GParamSpec *pspec;
SfiRing *ring;
bse_proxy_connect (self->item,
"signal::release", bus_editor_release_item, self,
NULL);
/* create and hook up volume params & scopes */
GxkParam *lvolume = get_property_param (self, "left_volume");
GtkWidget *lspinner = gxk_param_create_editor (lvolume, "spinner");
pspec = bse_proxy_get_pspec (self->item, "right-volume");
GxkParam *rvolume = bst_param_new_proxy (pspec, self->item);
GtkWidget *rspinner = gxk_param_create_editor (rvolume, "spinner");
BstDBMeter *dbmeter = (BstDBMeter*) gxk_radget_find (self, "db-meter");
if (dbmeter)
{
GtkRange *range = bst_db_meter_get_scale (dbmeter, 0);
bst_db_scale_hook_up_param (range, lvolume);
g_signal_connect_object (range, "button-press-event", G_CALLBACK (grab_focus_and_false), lspinner, G_CONNECT_SWAPPED);
range = bst_db_meter_get_scale (dbmeter, 1);
bst_db_scale_hook_up_param (range, rvolume);
g_signal_connect_object (range, "button-press-event", G_CALLBACK (grab_focus_and_false), rspinner, G_CONNECT_SWAPPED);
self->lbeam = bst_db_meter_get_beam (dbmeter, 0);
if (self->lbeam)
bst_db_beam_set_value (self->lbeam, -G_MAXDOUBLE);
self->rbeam = bst_db_meter_get_beam (dbmeter, 1);
if (self->rbeam)
bst_db_beam_set_value (self->rbeam, -G_MAXDOUBLE);
}
gxk_radget_add (self, "spinner-box", lspinner);
gxk_radget_add (self, "spinner-box", rspinner);
self->params = sfi_ring_prepend (self->params, lvolume);
self->params = sfi_ring_prepend (self->params, rvolume);
/* create remaining params */
bus_build_param (self, "uname", "name-box", NULL, NULL);
bus_build_param (self, "inputs", "inputs-box", NULL, NULL);
bus_build_param (self, "mute", "toggle-box", "toggle+label", "M");
bus_build_param (self, "sync", "toggle-box", "toggle+label", "Y");
bus_build_param (self, "solo", "toggle-box", "toggle+label", "S");
bus_build_param (self, "outputs", "outputs-box", NULL, NULL);
/* update params */
for (ring = self->params; ring; ring = sfi_ring_walk (ring, self->params))
gxk_param_update ((GxkParam*) ring->data);
/* setup scope */
Bse::ProbeFeatures features;
features.probe_energy = true;
self->lmonitor = self->source.create_signal_monitor (0);
self->rmonitor = self->source.create_signal_monitor (1);
self->lmonitor.set_probe_features (features);
self->rmonitor.set_probe_features (features);
Bst::MonitorFieldU lfields = Bst::monitor_fields_from_shm (self->lmonitor.get_shm_id(), self->lmonitor.get_shm_offset());
Bst::MonitorFieldU rfields = Bst::monitor_fields_from_shm (self->rmonitor.get_shm_id(), self->rmonitor.get_shm_offset());
auto framecb = [self, lfields, rfields] () {
bst_db_beam_set_value (self->lbeam, lfields.f32 (Bse::MonitorField::F32_DB_SPL));
bst_db_beam_set_value (self->rbeam, rfields.f32 (Bse::MonitorField::F32_DB_SPL));
if (0)
printerr ("BstBusEditor: (%x.%x/%x %x.%x/%x) ldb=%f rdb=%f\n",
self->lmonitor.get_shm_id(), self->lmonitor.get_shm_offset(),
lfields.f64 (Bse::MonitorField::F64_GENERATION),
self->rmonitor.get_shm_id(), self->rmonitor.get_shm_offset(),
rfields.f64 (Bse::MonitorField::F64_GENERATION),
lfields.f32 (Bse::MonitorField::F32_DB_SPL),
rfields.f32 (Bse::MonitorField::F32_DB_SPL));
};
self->mon_handler = Bst::add_frame_handler (framecb);
}
}
static void
bus_editor_action_exec (gpointer data,
size_t action)
{
BstBusEditor *self = BST_BUS_EDITOR (data);
switch (action)
{
case ACTION_ADD_BUS:
break;
case ACTION_DELETE_BUS:
break;
case ACTION_EDIT_BUS:
break;
}
gxk_widget_update_actions_downwards (self);
}
static gboolean
bus_editor_action_check (gpointer data,
size_t action,
guint64 action_stamp)
{
// BstBusEditor *self = BST_BUS_EDITOR (data);
switch (action)
{
case ACTION_ADD_BUS:
case ACTION_DELETE_BUS:
case ACTION_EDIT_BUS:
return TRUE;
default:
return FALSE;
}
}
static void
bst_bus_editor_class_init (BstBusEditorClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GtkObjectClass *object_class = GTK_OBJECT_CLASS (klass);
gobject_class->finalize = bst_bus_editor_finalize;
object_class->destroy = bst_bus_editor_destroy;
}
<commit_msg>BEAST-GTK: bstbuseditor: use right_volume C++ property<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bstbuseditor.hh"
#include "bstparam.hh"
#include "bstitemseqdialog.hh" // FIXME
#include "bstsnifferscope.hh" // FIXME
#include "bse/internal.hh"
/* --- prototypes --- */
static void bus_editor_action_exec (gpointer data,
size_t action);
static gboolean bus_editor_action_check (gpointer data,
size_t action,
guint64 action_stamp);
/* --- bus actions --- */
enum {
ACTION_ADD_BUS,
ACTION_DELETE_BUS,
ACTION_EDIT_BUS
};
static const GxkStockAction bus_editor_actions[] = {
{ N_("Add"), NULL, NULL, ACTION_ADD_BUS, BST_STOCK_PART },
{ N_("Delete"), NULL, NULL, ACTION_DELETE_BUS, BST_STOCK_TRASHCAN },
{ N_("Editor"), NULL, NULL, ACTION_EDIT_BUS, BST_STOCK_PART_EDITOR },
};
/* --- functions --- */
G_DEFINE_TYPE (BstBusEditor, bst_bus_editor, GTK_TYPE_ALIGNMENT);
static void
bst_bus_editor_init (BstBusEditor *self)
{
new (&self->source) Bse::SourceS();
new (&self->lmonitor) Bse::SignalMonitorS();
new (&self->rmonitor) Bse::SignalMonitorS();
self->mon_handler = 0;
/* complete GUI */
gxk_radget_complete (GTK_WIDGET (self), "beast", "bus-editor", NULL);
/* create tool actions */
gxk_widget_publish_actions (self, "bus-editor-actions",
G_N_ELEMENTS (bus_editor_actions), bus_editor_actions,
NULL, bus_editor_action_check, bus_editor_action_exec);
}
static void
bst_bus_editor_destroy (GtkObject *object)
{
BstBusEditor *self = BST_BUS_EDITOR (object);
bst_bus_editor_set_bus (self, 0);
GTK_OBJECT_CLASS (bst_bus_editor_parent_class)->destroy (object);
}
static void
bst_bus_editor_finalize (GObject *object)
{
BstBusEditor *self = BST_BUS_EDITOR (object);
bst_bus_editor_set_bus (self, 0);
G_OBJECT_CLASS (bst_bus_editor_parent_class)->finalize (object);
using namespace Bse;
Bst::remove_handler (&self->mon_handler);
self->source.~SourceS();
self->lmonitor.~SignalMonitorS();
self->rmonitor.~SignalMonitorS();
}
GtkWidget*
bst_bus_editor_new (SfiProxy bus)
{
assert_return (BSE_IS_BUS (bus), NULL);
GtkWidget *widget = (GtkWidget*) g_object_new (BST_TYPE_BUS_EDITOR, NULL);
BstBusEditor *self = BST_BUS_EDITOR (widget);
bst_bus_editor_set_bus (self, bus);
return widget;
}
static void
bus_editor_release_item (SfiProxy item,
BstBusEditor *self)
{
assert_return (self->item == item);
bst_bus_editor_set_bus (self, 0);
}
static GxkParam *
get_property_param (BstBusEditor *self,
const gchar *property)
{
Bse::BusH bus = Bse::BusH::__cast__ (bse_server.from_proxy (self->item));
const Bse::StringSeq kvlist = bus.find_prop (property);
GParamSpec *cxxpspec = Bse::pspec_from_key_value_list (property, kvlist);
if (cxxpspec)
return bst_param_new_property (cxxpspec, bus);
return nullptr;
}
static GtkWidget*
bus_build_param (BstBusEditor *self,
const gchar *property,
const gchar *area,
const gchar *editor,
const gchar *label)
{
GxkParam *gxk_param = get_property_param (self, property); /* aida property? */
if (!gxk_param)
{
/* proxy property */
auto pspec = bse_proxy_get_pspec (self->item, property);
gxk_param = bst_param_new_proxy (pspec, self->item);
}
self->params = sfi_ring_prepend (self->params, gxk_param);
GtkWidget *ewidget = gxk_param_create_editor ((GxkParam*) self->params->data, editor);
gxk_radget_add (self, area, ewidget);
if (label)
g_object_set (gxk_parent_find_descendant (ewidget, GTK_TYPE_LABEL), "label", label, NULL);
return ewidget;
}
static gboolean
grab_focus_and_false (GtkWidget *widget)
{
gtk_widget_grab_focus (widget);
return FALSE;
}
void
bst_bus_editor_set_bus (BstBusEditor *self,
SfiProxy item)
{
if (item)
assert_return (BSE_IS_BUS (item));
if (self->item)
{
Bst::remove_handler (&self->mon_handler);
self->lmonitor = NULL;
self->rmonitor = NULL;
Bse::SourceH source = Bse::SourceH::__cast__ (bse_server.from_proxy (self->item));
bse_proxy_disconnect (self->item,
"any-signal", bus_editor_release_item, self,
NULL);
self->source = NULL;
while (self->params)
gxk_param_destroy ((GxkParam*) sfi_ring_pop_head (&self->params));
}
self->item = item;
if (self->item)
{
self->source = Bse::SourceH::__cast__ (bse_server.from_proxy (self->item));
SfiRing *ring;
bse_proxy_connect (self->item,
"signal::release", bus_editor_release_item, self,
NULL);
/* create and hook up volume params & scopes */
GxkParam *lvolume = get_property_param (self, "left_volume");
GtkWidget *lspinner = gxk_param_create_editor (lvolume, "spinner");
GxkParam *rvolume = get_property_param (self, "right_volume");
GtkWidget *rspinner = gxk_param_create_editor (rvolume, "spinner");
BstDBMeter *dbmeter = (BstDBMeter*) gxk_radget_find (self, "db-meter");
if (dbmeter)
{
GtkRange *range = bst_db_meter_get_scale (dbmeter, 0);
bst_db_scale_hook_up_param (range, lvolume);
g_signal_connect_object (range, "button-press-event", G_CALLBACK (grab_focus_and_false), lspinner, G_CONNECT_SWAPPED);
range = bst_db_meter_get_scale (dbmeter, 1);
bst_db_scale_hook_up_param (range, rvolume);
g_signal_connect_object (range, "button-press-event", G_CALLBACK (grab_focus_and_false), rspinner, G_CONNECT_SWAPPED);
self->lbeam = bst_db_meter_get_beam (dbmeter, 0);
if (self->lbeam)
bst_db_beam_set_value (self->lbeam, -G_MAXDOUBLE);
self->rbeam = bst_db_meter_get_beam (dbmeter, 1);
if (self->rbeam)
bst_db_beam_set_value (self->rbeam, -G_MAXDOUBLE);
}
gxk_radget_add (self, "spinner-box", lspinner);
gxk_radget_add (self, "spinner-box", rspinner);
self->params = sfi_ring_prepend (self->params, lvolume);
self->params = sfi_ring_prepend (self->params, rvolume);
/* create remaining params */
bus_build_param (self, "uname", "name-box", NULL, NULL);
bus_build_param (self, "inputs", "inputs-box", NULL, NULL);
bus_build_param (self, "mute", "toggle-box", "toggle+label", "M");
bus_build_param (self, "sync", "toggle-box", "toggle+label", "Y");
bus_build_param (self, "solo", "toggle-box", "toggle+label", "S");
bus_build_param (self, "outputs", "outputs-box", NULL, NULL);
/* update params */
for (ring = self->params; ring; ring = sfi_ring_walk (ring, self->params))
gxk_param_update ((GxkParam*) ring->data);
/* setup scope */
Bse::ProbeFeatures features;
features.probe_energy = true;
self->lmonitor = self->source.create_signal_monitor (0);
self->rmonitor = self->source.create_signal_monitor (1);
self->lmonitor.set_probe_features (features);
self->rmonitor.set_probe_features (features);
Bst::MonitorFieldU lfields = Bst::monitor_fields_from_shm (self->lmonitor.get_shm_id(), self->lmonitor.get_shm_offset());
Bst::MonitorFieldU rfields = Bst::monitor_fields_from_shm (self->rmonitor.get_shm_id(), self->rmonitor.get_shm_offset());
auto framecb = [self, lfields, rfields] () {
bst_db_beam_set_value (self->lbeam, lfields.f32 (Bse::MonitorField::F32_DB_SPL));
bst_db_beam_set_value (self->rbeam, rfields.f32 (Bse::MonitorField::F32_DB_SPL));
if (0)
printerr ("BstBusEditor: (%x.%x/%x %x.%x/%x) ldb=%f rdb=%f\n",
self->lmonitor.get_shm_id(), self->lmonitor.get_shm_offset(),
lfields.f64 (Bse::MonitorField::F64_GENERATION),
self->rmonitor.get_shm_id(), self->rmonitor.get_shm_offset(),
rfields.f64 (Bse::MonitorField::F64_GENERATION),
lfields.f32 (Bse::MonitorField::F32_DB_SPL),
rfields.f32 (Bse::MonitorField::F32_DB_SPL));
};
self->mon_handler = Bst::add_frame_handler (framecb);
}
}
static void
bus_editor_action_exec (gpointer data,
size_t action)
{
BstBusEditor *self = BST_BUS_EDITOR (data);
switch (action)
{
case ACTION_ADD_BUS:
break;
case ACTION_DELETE_BUS:
break;
case ACTION_EDIT_BUS:
break;
}
gxk_widget_update_actions_downwards (self);
}
static gboolean
bus_editor_action_check (gpointer data,
size_t action,
guint64 action_stamp)
{
// BstBusEditor *self = BST_BUS_EDITOR (data);
switch (action)
{
case ACTION_ADD_BUS:
case ACTION_DELETE_BUS:
case ACTION_EDIT_BUS:
return TRUE;
default:
return FALSE;
}
}
static void
bst_bus_editor_class_init (BstBusEditorClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GtkObjectClass *object_class = GTK_OBJECT_CLASS (klass);
gobject_class->finalize = bst_bus_editor_finalize;
object_class->destroy = bst_bus_editor_destroy;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "IncrementalExecutor.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace cling {
Transaction::Transaction(Sema& S) : m_Sema(S) {
Initialize(S);
}
Transaction::Transaction(const CompilationOptions& Opts, Sema& S)
: m_Sema(S) {
Initialize(S);
m_Opts = Opts; // intentional copy.
}
void Transaction::Initialize(Sema& S) {
m_NestedTransactions.reset(0);
m_Parent = 0;
m_State = kCollecting;
m_IssuedDiags = kNone;
m_Opts = CompilationOptions();
m_Module = 0;
m_ExeUnload = {(void*)(size_t)-1};
m_WrapperFD = 0;
m_Next = 0;
//m_Sema = S;
m_BufferFID = FileID(); // sets it to invalid.
m_Exe = 0;
}
Transaction::~Transaction() {
if (hasNestedTransactions())
for (size_t i = 0; i < m_NestedTransactions->size(); ++i) {
assert(((*m_NestedTransactions)[i]->getState() == kCommitted
|| (*m_NestedTransactions)[i]->getState() == kRolledBack)
&& "All nested transactions must be committed!");
delete (*m_NestedTransactions)[i];
}
}
NamedDecl* Transaction::containsNamedDecl(llvm::StringRef name) const {
for (auto I = decls_begin(), E = decls_end(); I < E; ++I) {
for (auto DI : I->m_DGR) {
if (NamedDecl* ND = dyn_cast<NamedDecl>(DI)) {
if (name.equals(ND->getNameAsString()))
return ND;
}
else if (LinkageSpecDecl* LSD = dyn_cast<LinkageSpecDecl>(DI)) {
for (Decl* DI : LSD->decls()) {
if (NamedDecl* ND = dyn_cast<NamedDecl>(DI)) {
if (name.equals(ND->getNameAsString()))
return ND;
}
}
}
}
}
return 0;
}
void Transaction::addNestedTransaction(Transaction* nested) {
// Create lazily the list
if (!m_NestedTransactions)
m_NestedTransactions.reset(new NestedTransactions());
nested->setParent(this);
// Leave a marker in the parent transaction, where the nested transaction
// started.
DelayCallInfo marker(clang::DeclGroupRef(), Transaction::kCCINone);
m_DeclQueue.push_back(marker);
m_NestedTransactions->push_back(nested);
}
void Transaction::removeNestedTransaction(Transaction* nested) {
assert(hasNestedTransactions() && "Does not contain nested transactions");
int nestedPos = -1;
for (size_t i = 0; i < m_NestedTransactions->size(); ++i)
if ((*m_NestedTransactions)[i] == nested) {
nestedPos = i;
break;
}
assert(nestedPos > -1 && "Not found!?");
m_NestedTransactions->erase(m_NestedTransactions->begin() + nestedPos);
// We need to remove the marker too.
int markerPos = -1;
for (iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull() && I->m_Call == kCCINone) {
++markerPos;
if (nestedPos == markerPos) {
erase(I); // Safe because of the break stmt.
break;
}
}
}
if (!m_NestedTransactions->size())
m_NestedTransactions.reset(0);
}
void Transaction::append(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert(getState() == kCollecting
&& "Cannot append declarations in current state.");
forceAppend(DCI);
}
void Transaction::forceAppend(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert((getState() == kCollecting || getState() == kCompleted)
&& "Must not be");
bool checkForWrapper = !m_WrapperFD;
#ifndef NDEBUG
// Check for duplicates
for (size_t i = 0, e = m_DeclQueue.size(); i < e; ++i) {
DelayCallInfo &oldDCI (m_DeclQueue[i]);
// FIXME: This is possible bug in clang, which will instantiate one and
// the same CXXStaticMemberVar several times. This happens when there are
// two dependent expressions and the first uses another declaration from
// the redeclaration chain. This will force Sema in to instantiate the
// definition (usually the most recent decl in the chain) and then the
// second expression might referece the definition (which was already)
// instantiated, but Sema seems not to keep track of these kinds of
// instantiations, even though the points of instantiation are the same!
//
// This should be investigated further when we merge with newest clang.
// This is triggered by running the roottest: ./root/io/newstl
if (oldDCI.m_Call == kCCIHandleCXXStaticMemberVarInstantiation)
continue;
// It is possible to have duplicate calls to HandleVTable with the same
// declaration, because each time Sema believes a vtable is used it emits
// that callback.
// For reference (clang::CodeGen::CodeGenModule::EmitVTable).
if (oldDCI.m_Call != kCCIHandleVTable
&& oldDCI.m_Call != kCCIHandleCXXImplicitFunctionInstantiation)
assert(oldDCI != DCI && "Duplicates?!");
}
// We want to assert there is only one wrapper per transaction.
checkForWrapper = true;
#endif
// register the wrapper if any.
if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())){
if (checkForWrapper && utils::Analyze::IsWrapper(FD)) {
assert(!m_WrapperFD && "Two wrappers in one transaction?");
m_WrapperFD = FD;
}
}
}
if (comesFromASTReader(DCI.m_DGR))
m_DeserializedDeclQueue.push_back(DCI);
else
m_DeclQueue.push_back(DCI);
}
void Transaction::append(clang::DeclGroupRef DGR) {
append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl));
}
void Transaction::append(Decl* D) {
append(DeclGroupRef(D));
}
void Transaction::forceAppend(Decl* D) {
forceAppend(DelayCallInfo(DeclGroupRef(D), kCCIHandleTopLevelDecl));
}
void Transaction::append(MacroDirectiveInfo MDE) {
assert(MDE.m_II && "Appending null IdentifierInfo?!");
assert(MDE.m_MD && "Appending null MacroDirective?!");
assert(getState() == kCollecting
&& "Cannot append declarations in current state.");
#ifndef NDEBUG
// Check for duplicates
for (size_t i = 0, e = m_MacroDirectiveInfoQueue.size(); i < e; ++i) {
MacroDirectiveInfo &oldMacroDirectiveInfo (m_MacroDirectiveInfoQueue[i]);
assert(oldMacroDirectiveInfo != MDE && "Duplicates?!");
}
#endif
m_MacroDirectiveInfoQueue.push_back(MDE);
}
unsigned Transaction::getUniqueID() const {
return m_BufferFID.getHashValue();
}
void Transaction::erase(iterator pos) {
assert(!empty() && "Erasing from an empty transaction.");
if (!pos->m_DGR.isNull() && m_WrapperFD == *pos->m_DGR.begin())
m_WrapperFD = 0;
m_DeclQueue.erase(pos);
}
void Transaction::DelayCallInfo::dump() const {
PrintingPolicy Policy((LangOptions()));
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::DelayCallInfo::print(llvm::raw_ostream& Out,
const PrintingPolicy& Policy,
unsigned Indent,
bool PrintInstantiation,
llvm::StringRef prependInfo /*=""*/) const {
static const char* const stateNames[Transaction::kCCINumStates] = {
"kCCINone",
"kCCIHandleTopLevelDecl",
"kCCIHandleInterestingDecl",
"kCCIHandleTagDeclDefinition",
"kCCIHandleVTable",
"kCCIHandleCXXImplicitFunctionInstantiation",
"kCCIHandleCXXStaticMemberVarInstantiation",
"kCCICompleteTentativeDefinition",
};
assert((sizeof(stateNames) /sizeof(void*)) == Transaction::kCCINumStates
&& "Missing states?");
if (!prependInfo.empty()) {
Out.changeColor(llvm::raw_ostream::RED);
Out << prependInfo;
Out.resetColor();
Out << ", ";
}
Out.changeColor(llvm::raw_ostream::BLUE);
Out << stateNames[m_Call];
Out.changeColor(llvm::raw_ostream::GREEN);
Out << " <- ";
Out.resetColor();
for (DeclGroupRef::const_iterator I = m_DGR.begin(), E = m_DGR.end();
I != E; ++I) {
if (*I)
(*I)->print(Out, Policy, Indent, PrintInstantiation);
else
Out << "<<NULL DECL>>";
Out << '\n';
}
}
void Transaction::MacroDirectiveInfo::dump(const clang::Preprocessor& PP) const {
print(llvm::errs(), PP);
}
void Transaction::MacroDirectiveInfo::print(llvm::raw_ostream& Out,
const clang::Preprocessor& PP) const {
PP.printMacro(this->m_II, this->m_MD, Out);
}
void Transaction::dump() const {
const ASTContext& C = m_Sema.getASTContext();
PrintingPolicy Policy = C.getPrintingPolicy();
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::dumpPretty() const {
const ASTContext& C = m_Sema.getASTContext();
PrintingPolicy Policy(C.getLangOpts());
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy,
unsigned Indent, bool PrintInstantiation) const {
int nestedT = 0;
for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull()) {
assert(hasNestedTransactions() && "DGR is null even if no nesting?");
// print the nested decl
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" Nested Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
(*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent,
PrintInstantiation);
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" End Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
}
I->print(Out, Policy, Indent, PrintInstantiation);
}
// Print the deserialized decls if any.
for (const_iterator I = deserialized_decls_begin(),
E = deserialized_decls_end(); I != E; ++I) {
assert(!I->m_DGR.isNull() && "Must not contain null DGR.");
I->print(Out, Policy, Indent, PrintInstantiation, "Deserialized");
}
for (Transaction::const_reverse_macros_iterator MI = rmacros_begin(),
ME = rmacros_end(); MI != ME; ++MI) {
MI->print(Out, m_Sema.getPreprocessor());
}
}
void Transaction::printStructure(size_t nindent) const {
static const char* const stateNames[kNumStates] = {
"Collecting",
"kCompleted",
"RolledBack",
"RolledBackWithErrors",
"Committed"
};
assert((sizeof(stateNames) / sizeof(void*)) == kNumStates
&& "Missing a state to print.");
std::string indent(nindent, ' ');
llvm::errs() << indent << "Transaction @" << this << ": \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
(*I)->printStructure(nindent + 3);
}
llvm::errs() << indent << " state: " << stateNames[getState()]
<< " decl groups, ";
if (hasNestedTransactions())
llvm::errs() << m_NestedTransactions->size();
else
llvm::errs() << "0";
llvm::errs() << " nested transactions\n"
<< indent << " wrapper: " << m_WrapperFD
<< ", parent: " << m_Parent
<< ", next: " << m_Next << "\n";
}
void Transaction::printStructureBrief(size_t nindent /*=0*/) const {
std::string indent(nindent, ' ');
llvm::errs() << indent << "<cling::Transaction* " << this
<< " isEmpty=" << empty();
llvm::errs() << " isCommitted=" << (getState() == kCommitted);
llvm::errs() <<"> \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
llvm::errs() << indent << "`";
(*I)->printStructureBrief(nindent + 3);
}
}
bool Transaction::comesFromASTReader(DeclGroupRef DGR) const {
assert(!DGR.isNull() && "DeclGroupRef is Null!");
if (getCompilationOpts().CodeGenerationForModule)
return true;
// Take the first/only decl in the group.
Decl* D = *DGR.begin();
return D->isFromASTFile();
}
} // end namespace cling
<commit_msg>Peek inside extern "C" declarations only after name hasn't been matched. Change initial for loop use != comparison rather than <<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "IncrementalExecutor.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace cling {
Transaction::Transaction(Sema& S) : m_Sema(S) {
Initialize(S);
}
Transaction::Transaction(const CompilationOptions& Opts, Sema& S)
: m_Sema(S) {
Initialize(S);
m_Opts = Opts; // intentional copy.
}
void Transaction::Initialize(Sema& S) {
m_NestedTransactions.reset(0);
m_Parent = 0;
m_State = kCollecting;
m_IssuedDiags = kNone;
m_Opts = CompilationOptions();
m_Module = 0;
m_ExeUnload = {(void*)(size_t)-1};
m_WrapperFD = 0;
m_Next = 0;
//m_Sema = S;
m_BufferFID = FileID(); // sets it to invalid.
m_Exe = 0;
}
Transaction::~Transaction() {
if (hasNestedTransactions())
for (size_t i = 0; i < m_NestedTransactions->size(); ++i) {
assert(((*m_NestedTransactions)[i]->getState() == kCommitted
|| (*m_NestedTransactions)[i]->getState() == kRolledBack)
&& "All nested transactions must be committed!");
delete (*m_NestedTransactions)[i];
}
}
NamedDecl* Transaction::containsNamedDecl(llvm::StringRef name) const {
for (auto I = decls_begin(), E = decls_end(); I != E; ++I) {
for (auto DI : I->m_DGR) {
if (NamedDecl* ND = dyn_cast<NamedDecl>(DI)) {
if (name.equals(ND->getNameAsString()))
return ND;
}
}
}
// Not found yet, peek inside extern "C" declarations
for (auto I = decls_begin(), E = decls_end(); I != E; ++I) {
for (auto DI : I->m_DGR) {
if (LinkageSpecDecl* LSD = dyn_cast<LinkageSpecDecl>(DI)) {
for (Decl* DI : LSD->decls()) {
if (NamedDecl* ND = dyn_cast<NamedDecl>(DI)) {
if (name.equals(ND->getNameAsString()))
return ND;
}
}
}
}
}
return nullptr;
}
void Transaction::addNestedTransaction(Transaction* nested) {
// Create lazily the list
if (!m_NestedTransactions)
m_NestedTransactions.reset(new NestedTransactions());
nested->setParent(this);
// Leave a marker in the parent transaction, where the nested transaction
// started.
DelayCallInfo marker(clang::DeclGroupRef(), Transaction::kCCINone);
m_DeclQueue.push_back(marker);
m_NestedTransactions->push_back(nested);
}
void Transaction::removeNestedTransaction(Transaction* nested) {
assert(hasNestedTransactions() && "Does not contain nested transactions");
int nestedPos = -1;
for (size_t i = 0; i < m_NestedTransactions->size(); ++i)
if ((*m_NestedTransactions)[i] == nested) {
nestedPos = i;
break;
}
assert(nestedPos > -1 && "Not found!?");
m_NestedTransactions->erase(m_NestedTransactions->begin() + nestedPos);
// We need to remove the marker too.
int markerPos = -1;
for (iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull() && I->m_Call == kCCINone) {
++markerPos;
if (nestedPos == markerPos) {
erase(I); // Safe because of the break stmt.
break;
}
}
}
if (!m_NestedTransactions->size())
m_NestedTransactions.reset(0);
}
void Transaction::append(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert(getState() == kCollecting
&& "Cannot append declarations in current state.");
forceAppend(DCI);
}
void Transaction::forceAppend(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert((getState() == kCollecting || getState() == kCompleted)
&& "Must not be");
bool checkForWrapper = !m_WrapperFD;
#ifndef NDEBUG
// Check for duplicates
for (size_t i = 0, e = m_DeclQueue.size(); i < e; ++i) {
DelayCallInfo &oldDCI (m_DeclQueue[i]);
// FIXME: This is possible bug in clang, which will instantiate one and
// the same CXXStaticMemberVar several times. This happens when there are
// two dependent expressions and the first uses another declaration from
// the redeclaration chain. This will force Sema in to instantiate the
// definition (usually the most recent decl in the chain) and then the
// second expression might referece the definition (which was already)
// instantiated, but Sema seems not to keep track of these kinds of
// instantiations, even though the points of instantiation are the same!
//
// This should be investigated further when we merge with newest clang.
// This is triggered by running the roottest: ./root/io/newstl
if (oldDCI.m_Call == kCCIHandleCXXStaticMemberVarInstantiation)
continue;
// It is possible to have duplicate calls to HandleVTable with the same
// declaration, because each time Sema believes a vtable is used it emits
// that callback.
// For reference (clang::CodeGen::CodeGenModule::EmitVTable).
if (oldDCI.m_Call != kCCIHandleVTable
&& oldDCI.m_Call != kCCIHandleCXXImplicitFunctionInstantiation)
assert(oldDCI != DCI && "Duplicates?!");
}
// We want to assert there is only one wrapper per transaction.
checkForWrapper = true;
#endif
// register the wrapper if any.
if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())){
if (checkForWrapper && utils::Analyze::IsWrapper(FD)) {
assert(!m_WrapperFD && "Two wrappers in one transaction?");
m_WrapperFD = FD;
}
}
}
if (comesFromASTReader(DCI.m_DGR))
m_DeserializedDeclQueue.push_back(DCI);
else
m_DeclQueue.push_back(DCI);
}
void Transaction::append(clang::DeclGroupRef DGR) {
append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl));
}
void Transaction::append(Decl* D) {
append(DeclGroupRef(D));
}
void Transaction::forceAppend(Decl* D) {
forceAppend(DelayCallInfo(DeclGroupRef(D), kCCIHandleTopLevelDecl));
}
void Transaction::append(MacroDirectiveInfo MDE) {
assert(MDE.m_II && "Appending null IdentifierInfo?!");
assert(MDE.m_MD && "Appending null MacroDirective?!");
assert(getState() == kCollecting
&& "Cannot append declarations in current state.");
#ifndef NDEBUG
// Check for duplicates
for (size_t i = 0, e = m_MacroDirectiveInfoQueue.size(); i < e; ++i) {
MacroDirectiveInfo &oldMacroDirectiveInfo (m_MacroDirectiveInfoQueue[i]);
assert(oldMacroDirectiveInfo != MDE && "Duplicates?!");
}
#endif
m_MacroDirectiveInfoQueue.push_back(MDE);
}
unsigned Transaction::getUniqueID() const {
return m_BufferFID.getHashValue();
}
void Transaction::erase(iterator pos) {
assert(!empty() && "Erasing from an empty transaction.");
if (!pos->m_DGR.isNull() && m_WrapperFD == *pos->m_DGR.begin())
m_WrapperFD = 0;
m_DeclQueue.erase(pos);
}
void Transaction::DelayCallInfo::dump() const {
PrintingPolicy Policy((LangOptions()));
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::DelayCallInfo::print(llvm::raw_ostream& Out,
const PrintingPolicy& Policy,
unsigned Indent,
bool PrintInstantiation,
llvm::StringRef prependInfo /*=""*/) const {
static const char* const stateNames[Transaction::kCCINumStates] = {
"kCCINone",
"kCCIHandleTopLevelDecl",
"kCCIHandleInterestingDecl",
"kCCIHandleTagDeclDefinition",
"kCCIHandleVTable",
"kCCIHandleCXXImplicitFunctionInstantiation",
"kCCIHandleCXXStaticMemberVarInstantiation",
"kCCICompleteTentativeDefinition",
};
assert((sizeof(stateNames) /sizeof(void*)) == Transaction::kCCINumStates
&& "Missing states?");
if (!prependInfo.empty()) {
Out.changeColor(llvm::raw_ostream::RED);
Out << prependInfo;
Out.resetColor();
Out << ", ";
}
Out.changeColor(llvm::raw_ostream::BLUE);
Out << stateNames[m_Call];
Out.changeColor(llvm::raw_ostream::GREEN);
Out << " <- ";
Out.resetColor();
for (DeclGroupRef::const_iterator I = m_DGR.begin(), E = m_DGR.end();
I != E; ++I) {
if (*I)
(*I)->print(Out, Policy, Indent, PrintInstantiation);
else
Out << "<<NULL DECL>>";
Out << '\n';
}
}
void Transaction::MacroDirectiveInfo::dump(const clang::Preprocessor& PP) const {
print(llvm::errs(), PP);
}
void Transaction::MacroDirectiveInfo::print(llvm::raw_ostream& Out,
const clang::Preprocessor& PP) const {
PP.printMacro(this->m_II, this->m_MD, Out);
}
void Transaction::dump() const {
const ASTContext& C = m_Sema.getASTContext();
PrintingPolicy Policy = C.getPrintingPolicy();
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::dumpPretty() const {
const ASTContext& C = m_Sema.getASTContext();
PrintingPolicy Policy(C.getLangOpts());
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy,
unsigned Indent, bool PrintInstantiation) const {
int nestedT = 0;
for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull()) {
assert(hasNestedTransactions() && "DGR is null even if no nesting?");
// print the nested decl
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" Nested Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
(*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent,
PrintInstantiation);
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" End Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
}
I->print(Out, Policy, Indent, PrintInstantiation);
}
// Print the deserialized decls if any.
for (const_iterator I = deserialized_decls_begin(),
E = deserialized_decls_end(); I != E; ++I) {
assert(!I->m_DGR.isNull() && "Must not contain null DGR.");
I->print(Out, Policy, Indent, PrintInstantiation, "Deserialized");
}
for (Transaction::const_reverse_macros_iterator MI = rmacros_begin(),
ME = rmacros_end(); MI != ME; ++MI) {
MI->print(Out, m_Sema.getPreprocessor());
}
}
void Transaction::printStructure(size_t nindent) const {
static const char* const stateNames[kNumStates] = {
"Collecting",
"kCompleted",
"RolledBack",
"RolledBackWithErrors",
"Committed"
};
assert((sizeof(stateNames) / sizeof(void*)) == kNumStates
&& "Missing a state to print.");
std::string indent(nindent, ' ');
llvm::errs() << indent << "Transaction @" << this << ": \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
(*I)->printStructure(nindent + 3);
}
llvm::errs() << indent << " state: " << stateNames[getState()]
<< " decl groups, ";
if (hasNestedTransactions())
llvm::errs() << m_NestedTransactions->size();
else
llvm::errs() << "0";
llvm::errs() << " nested transactions\n"
<< indent << " wrapper: " << m_WrapperFD
<< ", parent: " << m_Parent
<< ", next: " << m_Next << "\n";
}
void Transaction::printStructureBrief(size_t nindent /*=0*/) const {
std::string indent(nindent, ' ');
llvm::errs() << indent << "<cling::Transaction* " << this
<< " isEmpty=" << empty();
llvm::errs() << " isCommitted=" << (getState() == kCommitted);
llvm::errs() <<"> \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
llvm::errs() << indent << "`";
(*I)->printStructureBrief(nindent + 3);
}
}
bool Transaction::comesFromASTReader(DeclGroupRef DGR) const {
assert(!DGR.isNull() && "DeclGroupRef is Null!");
if (getCompilationOpts().CodeGenerationForModule)
return true;
// Take the first/only decl in the group.
Decl* D = *DGR.begin();
return D->isFromASTFile();
}
} // end namespace cling
<|endoftext|>
|
<commit_before>#define GLEW_STATIC
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
//#include <GL/glext.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <fstream>
#include <float.h>
// GLM
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Mesh.hpp"
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
/*
How to use this code:
Call init_timer before starting rendering, i.e., before calling
glutMainLoop. Then, make sure your display function is organized
roughly as the example below.
*/
// Bunny
Mesh bunny("bunny.obj");
// Lighting
static GLfloat lightPos[] = {0.0f, 0.0f, 0.0f, 0.0f};
static GLfloat ambient[] = {0.2f, 0.2f, 0.2f, 1.0f};
static GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
static GLfloat black[] = {0.0f, 0.0f, 0.0f, 1.0f};
static glm::vec3 lightDir = glm::normalize(glm::vec3(-1.0f));
// Timing
float gTotalTimeElapsed = 0;
int gTotalFrames = 0;
GLuint gTimer;
void initGL()
{
// Setup depth buffer, shading, and culling
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDepthFunc(GL_LESS);
glShadeModel(GL_SMOOTH);
//glCullFace(GL_BACK);
// Setup lightings
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// Load view matrices onto initial projection stack.
glViewport(0.0f, 0.0f, 512.0f, 512.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 1000.0f);
// set matrix mode back to model
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Set eye
gluLookAt(0.0f, 0.0f, 0.0f, // eye position
0.0f, 0.0f, -1.0f, // Target
0.0f, 1.0f, 0.0f); // Up vector
}
void init_timer()
{
printf("Initializing Timer\n");
glGenQueries(1, &gTimer);
}
void start_timing()
{
glBeginQuery(GL_TIME_ELAPSED, gTimer);
}
float stop_timing()
{
glEndQuery(GL_TIME_ELAPSED);
GLint available = GL_FALSE;
while (available == GL_FALSE)
glGetQueryObjectiv(gTimer, GL_QUERY_RESULT_AVAILABLE, &available);
GLint result;
glGetQueryObjectiv(gTimer, GL_QUERY_RESULT, &result);
float timeElapsed = result / (1000.0f * 1000.0f * 1000.0f);
return timeElapsed;
}
void Resize(int w, int h) {
// Prevent a divide by zero, when window is too short
if(h == 0) h = 1;
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 1000.0f);
// set matrix mode back to model
glMatrixMode(GL_MODELVIEW);
}
void MouseFunc(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
printf("Mouse left pressed: x: %d, y: %d\n", x, y);
}
}
void KeyboardFunc(unsigned char key, int x, int y)
{
if (key == 116)
{
bunny.ToggleRenderMethod();
}
else if(key == 119) // W
{
lightPos[1] += 1.0f;
printf("W pressed %f\n", lightPos[1]);
}
else if(key == 115)
{
lightPos[1] -= 1.0f;
printf("Light pos y changed: %f\n", lightPos[1]);
}
else if(key == 97)
{
lightPos[0] -= 1.0f;
printf("Light pos x: %f\n", lightPos[0]);
}
else if(key == 100) // d
{
lightPos[0] += 1.0f;
printf("Light pos x: %f\n", lightPos[0]);
}
else if( key == 101) // e
{
lightPos[2] += 1.0f;
printf("Light pos z: %f\n", lightPos[2]);
}
else if(key == 112) // q
{
lightPos[2] -= 1.0f;
printf("Light pos z: %f\n", lightPos[2]);
}
}
void SetLighting()
{
// GL default: Initial ambient is 0.2 0.2 0.2 1.0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
// Add directed light here
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glLightfv(GL_LIGHT0, GL_AMBIENT, black ); // Default ambient is 0
glLightfv(GL_LIGHT0, GL_DIFFUSE, white); // Default diffuse is 1
glLightfv(GL_LIGHT0, GL_SPECULAR, black); // Default for light0 is 1 so set to 0
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, glm::value_ptr(lightDir));
}
/**
* Your display function should look roughly like the following.
*/
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
start_timing();
SetLighting();
CALL_MEMBER_FN(bunny, bunny.render)();
float timeElapsed = stop_timing();
gTotalFrames++;
gTotalTimeElapsed += timeElapsed;
float fps = gTotalFrames / gTotalTimeElapsed;
char string[1024] = {0};
sprintf(string, "OpenGL Bunny: %0.2f FPS", fps);
glutSetWindowTitle(string);
glutPostRedisplay();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
// Glut initialization
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(512, 512);
glutCreateWindow("GL");
// Glew initialization
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (err != GLEW_OK)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
exit(EXIT_FAILURE);
}
printf("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
initGL();
init_timer();
bunny.SetupMesh();
glutReshapeFunc(Resize);
glutDisplayFunc(display);
glutKeyboardFunc(KeyboardFunc);
glutMouseFunc(MouseFunc);
glutMainLoop();
exit(EXIT_SUCCESS);
}
<commit_msg>had to glEnable(GL_NORMALIZE), fixed lighting, still need to optimize buffer rendering<commit_after>#define GLEW_STATIC
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
//#include <GL/glext.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <fstream>
#include <float.h>
// GLM
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Mesh.hpp"
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
/*
How to use this code:
Call init_timer before starting rendering, i.e., before calling
glutMainLoop. Then, make sure your display function is organized
roughly as the example below.
*/
// Bunny
Mesh bunny("bunny.obj");
// Lighting
static GLfloat lightPos[] = {0.0f, 0.0f, 0.0f, 0.0f};
static GLfloat ambient[] = {0.2f, 0.2f, 0.2f, 1.0f};
static GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
static GLfloat black[] = {0.0f, 0.0f, 0.0f, 1.0f};
static glm::vec3 lightDir = glm::vec3(-1.0f);//glm::normalize(glm::vec3(-1.0f));
// Timing
float gTotalTimeElapsed = 0;
int gTotalFrames = 0;
GLuint gTimer;
void initGL()
{
// Setup depth buffer, shading, and culling
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDepthFunc(GL_LESS);
glShadeModel(GL_SMOOTH);
glEnable(GL_NORMALIZE);
//glCullFace(GL_BACK);
// Setup lightings
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// Load view matrices onto initial projection stack.
glViewport(0.0f, 0.0f, 512.0f, 512.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 1000.0f);
// set matrix mode back to model
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Set eye
gluLookAt(0.0f, 0.0f, 0.0f, // eye position
0.0f, 0.0f, -1.0f, // Target
0.0f, 1.0f, 0.0f); // Up vector
}
void init_timer()
{
printf("Initializing Timer\n");
glGenQueries(1, &gTimer);
}
void start_timing()
{
glBeginQuery(GL_TIME_ELAPSED, gTimer);
}
float stop_timing()
{
glEndQuery(GL_TIME_ELAPSED);
GLint available = GL_FALSE;
while (available == GL_FALSE)
glGetQueryObjectiv(gTimer, GL_QUERY_RESULT_AVAILABLE, &available);
GLint result;
glGetQueryObjectiv(gTimer, GL_QUERY_RESULT, &result);
float timeElapsed = result / (1000.0f * 1000.0f * 1000.0f);
return timeElapsed;
}
void Resize(int w, int h) {
// Prevent a divide by zero, when window is too short
if(h == 0) h = 1;
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 1000.0f);
// set matrix mode back to model
glMatrixMode(GL_MODELVIEW);
}
void MouseFunc(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
printf("Mouse left pressed: x: %d, y: %d\n", x, y);
}
}
void KeyboardFunc(unsigned char key, int x, int y)
{
if (key == 116)
{
bunny.ToggleRenderMethod();
}
else if(key == 119) // W
{
lightPos[1] += 1.0f;
printf("W pressed %f\n", lightPos[1]);
}
else if(key == 115)
{
lightPos[1] -= 1.0f;
printf("Light pos y changed: %f\n", lightPos[1]);
}
else if(key == 97)
{
lightPos[0] -= 1.0f;
printf("Light pos x: %f\n", lightPos[0]);
}
else if(key == 100) // d
{
lightPos[0] += 1.0f;
printf("Light pos x: %f\n", lightPos[0]);
}
else if( key == 101) // e
{
lightPos[2] += 1.0f;
printf("Light pos z: %f\n", lightPos[2]);
}
else if(key == 113) // q
{
lightPos[2] -= 1.0f;
printf("Light pos z: %f\n", lightPos[2]);
}
}
void SetLighting()
{
// GL default: Initial ambient is 0.2 0.2 0.2 1.0
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
// Add directed light here
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glLightfv(GL_LIGHT0, GL_AMBIENT, black ); // Default ambient is 0
glLightfv(GL_LIGHT0, GL_DIFFUSE, white); // Default diffuse is 1
glLightfv(GL_LIGHT0, GL_SPECULAR, black); // Default for light0 is 1 so set to 0
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, glm::value_ptr(lightDir));
}
/**
* Your display function should look roughly like the following.
*/
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
start_timing();
SetLighting();
CALL_MEMBER_FN(bunny, bunny.render)();
float timeElapsed = stop_timing();
gTotalFrames++;
gTotalTimeElapsed += timeElapsed;
float fps = gTotalFrames / gTotalTimeElapsed;
char string[1024] = {0};
sprintf(string, "OpenGL Bunny: %0.2f FPS", fps);
glutSetWindowTitle(string);
glutPostRedisplay();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
// Glut initialization
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(512, 512);
glutCreateWindow("GL");
// Glew initialization
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (err != GLEW_OK)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
exit(EXIT_FAILURE);
}
printf("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
initGL();
init_timer();
bunny.SetupMesh();
glutReshapeFunc(Resize);
glutDisplayFunc(display);
glutKeyboardFunc(KeyboardFunc);
glutMouseFunc(MouseFunc);
glutMainLoop();
exit(EXIT_SUCCESS);
}
<|endoftext|>
|
<commit_before>// Copyright (C) Oscar Takeshita 2017
// This code is a translation of the 2-layer neural network Python code in
// http://cs231n.github.io/neural-networks-case-study/
// Andrej Karpathy
// to C++ with some modifications.
//
// The machine learning course webpage and the code are quite instructive and I
// decided to write this translation for my own experiments
// and for those wanting to play with a C++ version.
#include<algorithm>
#include<cassert>
#include<vector>
#include<fstream>
#include<sstream>
#include<iostream>
typedef double field; // field of real numbers
// RNG generator
static std::mt19937 generator;
static std::normal_distribution<field> dist;
class rand_field {
public:
field randn() {
return dist(generator);
}
};
#include "mtx.h"
#include "pnndata.h"
class network {
private:
int D; // input data dimension
int K; // number of classes
int h; // number of neurons in hidden layer
int N;
int U; // batch size
rand_field *rd; // normal gaussian random variable
t_data *tdt; // data class
field step_size; // gradient descent step size
field reg; // regularization strength
field loss;
field data_loss;
field reg_loss;
void build() {
fprintf(stderr, "Network parameters: Batch size = %d, Dimension D = %d Classes K = %d Hidden nodes h = %d\n", U, D, K, h);
W1.init(D, h);
b1.init(h, 1);
W2.init(h, K);
b2.init(K, 1);
dW1.init(D, h);
db1.init(h, 1);
dW2.init(h, K);
db2.init(K, 1);
Hidden.init(U, h);
dHidden.init(U, h);
Scores.init(U, K);
Probs.init(U, K);
step_size = static_cast<field>(1.);
reg = static_cast<field>(1e-3);
loss = static_cast<field>(0.);
data_loss = static_cast<field>(0.);
reg_loss = static_cast<field>(0.);
}
public:
mtx W1, b1;
mtx W2, b2;
mtx dW1, db1;
mtx dW2, db2;
// hidden layer output
mtx Hidden;
mtx dHidden;
mtx Scores;
mtx Probs;
void set_loss(field l) { loss = l; };
void set_data_loss(field l) { data_loss = l; };
void set_reg_loss(field l) { reg_loss = l; };
field get_loss() { return loss ; };
field get_data_loss() { return data_loss ; };
field get_reg_loss() { return reg_loss ; };
// gradient descent step sizes
// normally between 1. and smaller values
void set_step_size(field step_size) {
this->step_size = step_size;
}
// regularization parameter
void set_reg(field reg) {
this->reg = reg;
}
void network_state(int i) {
fprintf(stderr, "**** network state dump ****\n\n");
fprintf(stderr, "%d W2:\n",i); W2.print(10);
fprintf(stderr, "%d b2:\n",i); b2.print(10);
fprintf(stderr, "%d scores:\n",i); Scores.print(8);
fprintf(stderr, "%d probs:\n",i); Probs.print(8);
fprintf(stderr, "%d loss(%.10f) = data loss(%.10f) + reg loss(%.10f):\n",i, get_loss(), get_data_loss(), get_reg_loss());
fprintf(stderr, "%d hidden:\n",i); Hidden.print(20);
fprintf(stderr, "%d dW2:\n",i); dW2.print(8);
fprintf(stderr, "%d db2:\n",i); db2.print(8);
fprintf(stderr, "%d dhidden:\n",i); dHidden.print(20);
fprintf(stderr, "%d dW1:\n",i); dW1.print(20);
fprintf(stderr, "%d db:\n",i); db1.print(20);
fprintf(stderr, "%d W1:\n",i); W1.print(8);
fprintf(stderr, "%d b:\n",i); b1.print(8);
fprintf(stderr, "**** dump completed ****\n\n");
}
// function to be called to set the initial state of the network
void initialize_net(field W1std, field b1const, field W2std, field b2const) {
W1.rnd(W1std, *rd); // weight is normal distributed with std deviation W1std
b1.ld(b1const); // bias initialized with constant b1const
W2.rnd(W2std, *rd); // weight is normal distributed with std deviation W2std
b2.ld(b2const); // bias initialized with constant b2const
}
// forward pass routines
void evaluate_class_scores(mtx input) {
Hidden.mult(input, false, W1, false, static_cast<void*>(&b1)); // Hidden = X * W1 + b1
Hidden.ReLU(); // Non-linearity
Scores.mult(Hidden, false, W2, false, static_cast<void*>(&b2)); // Scores = Hidden * W2 + b2
}
void compute_class_probabilities() {
mtx Expscores(Scores);
Expscores.exp();
auto expscores = Expscores.vec();
std::vector<field> sum(U);
for(int i = 0; i<U; i++)
sum[i] = std::accumulate(expscores.begin() + i*K, expscores.begin() + (i+1)*K, static_cast<field>(0.));
for(int i = 0; i<U; i++)
std::transform(expscores.begin() + i*K, expscores.begin() + (i+1)*K,
Probs.vecp()->begin() + i*K, [i, sum](field &p) { return p/sum[i];} );
}
// Note that none of these computations affect the optimization
// algorithm (loss is not used either directly or to control parameters)
// It is only used for monitoring at the moment
void compute_loss() {
double dloss = 0.;
for(int i = 0; i<U; i++)
dloss -= std::log(Probs.get(i, tdt->Y.get(i)));
set_data_loss(static_cast<field>(dloss)/(U));
set_reg_loss(static_cast<field>(0.5 * reg) * (W1.L2() + W2.L2()));
set_loss(get_data_loss() + get_reg_loss());
}
void compute_gradient_on_scores() {
for (int i = 0; i<U ; i++)
Probs.add(i, tdt->Y.get(i), -1.);
Probs.div_all(U);
}
void compute_dW2db2() { //
dW2.mult(Hidden, true, Probs, false); // dW2 = t(Hidden) * dScores
db2.marg(Probs);
}
void compute_dhidden() {
dHidden.mult(Probs, false, W2, true); // dHidden = dScores * t(W2)
}
void compute_dReLU() {
dHidden.dReLU(Hidden);
}
void compute_dWdb() {
dW1.mult(tdt->X, true, dHidden, false);
db1.marg(dHidden, true);
}
// backprop gradient into W2 and b2
void back_propagate() {
compute_dW2db2();
compute_dhidden();
compute_dReLU();
compute_dWdb();
}
// add regularization gradient constribution
void add_regularization() {
dW1.linear_add( W1, reg); // dW1 += reg * W1
dW2.linear_add( W2, reg); // dW2 += reg * W2
}
// descend the cost topology by applying adding a negative scaled value of the gradient
void descend() {
W1.linear_add(dW1, -step_size); // W1 += -stepsize * dW1
b1.linear_add(db1, -step_size); // b1 += -stepsize * db1
W2.linear_add(dW2, -step_size); // W2 += -stepsize * dW2
b2.linear_add(db2, -step_size); // b2 += -stepsize * db2
}
// THE GRADIENT DESCENT. It optimizes the cost function.
void gradient_descent(unsigned int iterations) {
for(unsigned int i = 0; i<iterations; i++) {
evaluate_class_scores(tdt->X);
compute_class_probabilities();
compute_loss();
compute_gradient_on_scores();
back_propagate();
add_regularization();
descend();
if(i%1000 == 0) {
fprintf(stdout, "iteration %6d: loss %f data_loss %f reg_loss %f ", i, get_loss(), get_data_loss(), get_reg_loss());
accuracy();
//network_state(i); // uncomment for full dump of network state
}
}
}
// network constructor
// It builds network topology using
// model parameters
network(int h, t_data &tdt, rand_field &rd) {
this->h = h;
this->tdt = &tdt;
this->U = tdt.get_U();
this->K = tdt.get_K();
this->D = tdt.get_D();
this->rd = &rd;
build();
}
// reports training accuracy
void accuracy() {
int hit = 0;
for(int i = 0; i< U; i++) {
field best_score = -10000;
int best_index = -1;
for(int j = 0; j<K; j++) {
if(Scores.get(i,j)>best_score) {
best_score = Scores.get(i,j);
best_index = j;
}
}
assert(best_index != -1);
if(best_index == tdt->Y.get(i))
hit++;
}
std::fprintf(stdout, "training accuracy %.2f%%\n", static_cast<field>(hit)*100/(U));
}
// predicts on model. The input_file is contains
// the data to be classified in csv format.
// The output is written in csv format as well
void predict(std::string input_file, std::string output_file) {
mtx A;
A.init(1,D); // row vector for data
std::string line;
std::ifstream in (input_file.c_str());
std::ofstream out (output_file.c_str());
if(!out.is_open()) {
std::cerr << "problem opening " << output_file << std::endl;
return;
}
else {
out << "Label";
for (int i = 0; i<D; i++)
out << "," << "d" << i;
out << std::endl;
}
if(in.is_open()) {
getline(in, line); // discard header
std::string entry;
while(getline(in, line)) {
std::istringstream ss(line);
for (int i = 0; i<D; i++) {
std::getline(ss, entry, ',');
A.set(0, i, static_cast<field>(std::stod(entry)));
}
evaluate_class_scores(A);
float best_score = Scores.get(0, 0);
int best_label = 0;
for(int j = 1; j<K ;j++) {
if(Scores.get(0, j) > best_score) {
best_label = j;
best_score = Scores.get(0, j);
}
}
out << best_label;
for (int i = 0; i<D; i++)
out << "," << A.get(0,i);
out << std::endl;
}
in.close();
out.close();
}
else {
std::cerr << "problem opening " << input_file << std::endl;
exit(-1);
}
}
};
int main(int argc, char *argv[]) {
// normal distributed RV
if(argc == 2)
generator.seed(atoi(argv[1]));
else
generator.seed(1);
rand_field rd;
// Data model spiral : U points inside a 2 x 2 square
// Points belong to K different classes and the configuration is such that
// there are no linear boundaries that separates each class. In other words,
// they can't be grouped by drawing a few straight lines. See figure...
int N = 100; // number of points per class
int K = 3; // number of classes
spiral tdt(N, K, rd);
//tdt.print_train(); // prints the train data in libsvm format
// Setup a 2-layer neural network
// plus the number of hidden nodes
int h = 100; // hidden nodes
network nn(h, tdt, rd);
// Initial conditions for the network
field W1, b1, W2, b2;
W1 = 0.01;
b1 = 0.00;
W2 = 0.01;
b2 = 0.00;
nn.initialize_net(W1, b1, W2, b2);
// Optimization parameters
int iter = 10000; // number of iterations
nn.set_reg(1e-3); // regularization
nn.set_step_size(1.); // gradient descent step size.
// Starts training/optimization
nn.gradient_descent(iter);
// Reports training accuracy
nn.accuracy();
// Read test cordinates and write predictions
//nn.predict("../extras/test.csv","../extras/prediction.csv");
return 0;
}
<commit_msg>Removed obsolete variable N from src/piconn.cpp.<commit_after>// Copyright (C) Oscar Takeshita 2017
// This code is a translation of the 2-layer neural network Python code in
// http://cs231n.github.io/neural-networks-case-study/
// Andrej Karpathy
// to C++ with some modifications.
//
// The machine learning course webpage and the code are quite instructive and I
// decided to write this translation for my own experiments
// and for those wanting to play with a C++ version.
#include<algorithm>
#include<cassert>
#include<vector>
#include<fstream>
#include<sstream>
#include<iostream>
typedef double field; // field of real numbers
// RNG generator
static std::mt19937 generator;
static std::normal_distribution<field> dist;
class rand_field {
public:
field randn() {
return dist(generator);
}
};
#include "mtx.h"
#include "pnndata.h"
class network {
private:
int D; // input data dimension
int K; // number of classes
int h; // number of neurons in hidden layer
int U; // batch size
rand_field *rd; // normal gaussian random variable
t_data *tdt; // data class
field step_size; // gradient descent step size
field reg; // regularization strength
field loss;
field data_loss;
field reg_loss;
void build() {
fprintf(stderr, "Network parameters: Batch size = %d, Dimension D = %d Classes K = %d Hidden nodes h = %d\n", U, D, K, h);
W1.init(D, h);
b1.init(h, 1);
W2.init(h, K);
b2.init(K, 1);
dW1.init(D, h);
db1.init(h, 1);
dW2.init(h, K);
db2.init(K, 1);
Hidden.init(U, h);
dHidden.init(U, h);
Scores.init(U, K);
Probs.init(U, K);
step_size = static_cast<field>(1.);
reg = static_cast<field>(1e-3);
loss = static_cast<field>(0.);
data_loss = static_cast<field>(0.);
reg_loss = static_cast<field>(0.);
}
public:
mtx W1, b1;
mtx W2, b2;
mtx dW1, db1;
mtx dW2, db2;
// hidden layer output
mtx Hidden;
mtx dHidden;
mtx Scores;
mtx Probs;
void set_loss(field l) { loss = l; };
void set_data_loss(field l) { data_loss = l; };
void set_reg_loss(field l) { reg_loss = l; };
field get_loss() { return loss ; };
field get_data_loss() { return data_loss ; };
field get_reg_loss() { return reg_loss ; };
// gradient descent step sizes
// normally between 1. and smaller values
void set_step_size(field step_size) {
this->step_size = step_size;
}
// regularization parameter
void set_reg(field reg) {
this->reg = reg;
}
void network_state(int i) {
fprintf(stderr, "**** network state dump ****\n\n");
fprintf(stderr, "%d W2:\n",i); W2.print(10);
fprintf(stderr, "%d b2:\n",i); b2.print(10);
fprintf(stderr, "%d scores:\n",i); Scores.print(8);
fprintf(stderr, "%d probs:\n",i); Probs.print(8);
fprintf(stderr, "%d loss(%.10f) = data loss(%.10f) + reg loss(%.10f):\n",i, get_loss(), get_data_loss(), get_reg_loss());
fprintf(stderr, "%d hidden:\n",i); Hidden.print(20);
fprintf(stderr, "%d dW2:\n",i); dW2.print(8);
fprintf(stderr, "%d db2:\n",i); db2.print(8);
fprintf(stderr, "%d dhidden:\n",i); dHidden.print(20);
fprintf(stderr, "%d dW1:\n",i); dW1.print(20);
fprintf(stderr, "%d db:\n",i); db1.print(20);
fprintf(stderr, "%d W1:\n",i); W1.print(8);
fprintf(stderr, "%d b:\n",i); b1.print(8);
fprintf(stderr, "**** dump completed ****\n\n");
}
// function to be called to set the initial state of the network
void initialize_net(field W1std, field b1const, field W2std, field b2const) {
W1.rnd(W1std, *rd); // weight is normal distributed with std deviation W1std
b1.ld(b1const); // bias initialized with constant b1const
W2.rnd(W2std, *rd); // weight is normal distributed with std deviation W2std
b2.ld(b2const); // bias initialized with constant b2const
}
// forward pass routines
void evaluate_class_scores(mtx input) {
Hidden.mult(input, false, W1, false, static_cast<void*>(&b1)); // Hidden = X * W1 + b1
Hidden.ReLU(); // Non-linearity
Scores.mult(Hidden, false, W2, false, static_cast<void*>(&b2)); // Scores = Hidden * W2 + b2
}
void compute_class_probabilities() {
mtx Expscores(Scores);
Expscores.exp();
auto expscores = Expscores.vec();
std::vector<field> sum(U);
for(int i = 0; i<U; i++)
sum[i] = std::accumulate(expscores.begin() + i*K, expscores.begin() + (i+1)*K, static_cast<field>(0.));
for(int i = 0; i<U; i++)
std::transform(expscores.begin() + i*K, expscores.begin() + (i+1)*K,
Probs.vecp()->begin() + i*K, [i, sum](field &p) { return p/sum[i];} );
}
// Note that none of these computations affect the optimization
// algorithm (loss is not used either directly or to control parameters)
// It is only used for monitoring at the moment
void compute_loss() {
double dloss = 0.;
for(int i = 0; i<U; i++)
dloss -= std::log(Probs.get(i, tdt->Y.get(i)));
set_data_loss(static_cast<field>(dloss)/(U));
set_reg_loss(static_cast<field>(0.5 * reg) * (W1.L2() + W2.L2()));
set_loss(get_data_loss() + get_reg_loss());
}
void compute_gradient_on_scores() {
for (int i = 0; i<U ; i++)
Probs.add(i, tdt->Y.get(i), -1.);
Probs.div_all(U);
}
void compute_dW2db2() { //
dW2.mult(Hidden, true, Probs, false); // dW2 = t(Hidden) * dScores
db2.marg(Probs);
}
void compute_dhidden() {
dHidden.mult(Probs, false, W2, true); // dHidden = dScores * t(W2)
}
void compute_dReLU() {
dHidden.dReLU(Hidden);
}
void compute_dWdb() {
dW1.mult(tdt->X, true, dHidden, false);
db1.marg(dHidden, true);
}
// backprop gradient into W2 and b2
void back_propagate() {
compute_dW2db2();
compute_dhidden();
compute_dReLU();
compute_dWdb();
}
// add regularization gradient constribution
void add_regularization() {
dW1.linear_add( W1, reg); // dW1 += reg * W1
dW2.linear_add( W2, reg); // dW2 += reg * W2
}
// descend the cost topology by applying adding a negative scaled value of the gradient
void descend() {
W1.linear_add(dW1, -step_size); // W1 += -stepsize * dW1
b1.linear_add(db1, -step_size); // b1 += -stepsize * db1
W2.linear_add(dW2, -step_size); // W2 += -stepsize * dW2
b2.linear_add(db2, -step_size); // b2 += -stepsize * db2
}
// THE GRADIENT DESCENT. It optimizes the cost function.
void gradient_descent(unsigned int iterations) {
for(unsigned int i = 0; i<iterations; i++) {
evaluate_class_scores(tdt->X);
compute_class_probabilities();
compute_loss();
compute_gradient_on_scores();
back_propagate();
add_regularization();
descend();
if(i%1000 == 0) {
fprintf(stdout, "iteration %6d: loss %f data_loss %f reg_loss %f ", i, get_loss(), get_data_loss(), get_reg_loss());
accuracy();
//network_state(i); // uncomment for full dump of network state
}
}
}
// network constructor
// It builds network topology using
// model parameters
network(int h, t_data &tdt, rand_field &rd) {
this->h = h;
this->tdt = &tdt;
this->U = tdt.get_U();
this->K = tdt.get_K();
this->D = tdt.get_D();
this->rd = &rd;
build();
}
// reports training accuracy
void accuracy() {
int hit = 0;
for(int i = 0; i< U; i++) {
field best_score = -10000;
int best_index = -1;
for(int j = 0; j<K; j++) {
if(Scores.get(i,j)>best_score) {
best_score = Scores.get(i,j);
best_index = j;
}
}
assert(best_index != -1);
if(best_index == tdt->Y.get(i))
hit++;
}
std::fprintf(stdout, "training accuracy %.2f%%\n", static_cast<field>(hit)*100/(U));
}
// predicts on model. The input_file is contains
// the data to be classified in csv format.
// The output is written in csv format as well
void predict(std::string input_file, std::string output_file) {
mtx A;
A.init(1,D); // row vector for data
std::string line;
std::ifstream in (input_file.c_str());
std::ofstream out (output_file.c_str());
if(!out.is_open()) {
std::cerr << "problem opening " << output_file << std::endl;
return;
}
else {
out << "Label";
for (int i = 0; i<D; i++)
out << "," << "d" << i;
out << std::endl;
}
if(in.is_open()) {
getline(in, line); // discard header
std::string entry;
while(getline(in, line)) {
std::istringstream ss(line);
for (int i = 0; i<D; i++) {
std::getline(ss, entry, ',');
A.set(0, i, static_cast<field>(std::stod(entry)));
}
evaluate_class_scores(A);
float best_score = Scores.get(0, 0);
int best_label = 0;
for(int j = 1; j<K ;j++) {
if(Scores.get(0, j) > best_score) {
best_label = j;
best_score = Scores.get(0, j);
}
}
out << best_label;
for (int i = 0; i<D; i++)
out << "," << A.get(0,i);
out << std::endl;
}
in.close();
out.close();
}
else {
std::cerr << "problem opening " << input_file << std::endl;
exit(-1);
}
}
};
int main(int argc, char *argv[]) {
// normal distributed RV
if(argc == 2)
generator.seed(atoi(argv[1]));
else
generator.seed(1);
rand_field rd;
// Data model spiral : U points inside a 2 x 2 square
// Points belong to K different classes and the configuration is such that
// there are no linear boundaries that separates each class. In other words,
// they can't be grouped by drawing a few straight lines. See figure...
int N = 100; // number of points per class
int K = 3; // number of classes
spiral tdt(N, K, rd);
//tdt.print_train(); // prints the train data in libsvm format
// Setup a 2-layer neural network
// plus the number of hidden nodes
int h = 100; // hidden nodes
network nn(h, tdt, rd);
// Initial conditions for the network
field W1, b1, W2, b2;
W1 = 0.01;
b1 = 0.00;
W2 = 0.01;
b2 = 0.00;
nn.initialize_net(W1, b1, W2, b2);
// Optimization parameters
int iter = 10000; // number of iterations
nn.set_reg(1e-3); // regularization
nn.set_step_size(1.); // gradient descent step size.
// Starts training/optimization
nn.gradient_descent(iter);
// Reports training accuracy
nn.accuracy();
// Read test cordinates and write predictions
//nn.predict("../extras/test.csv","../extras/prediction.csv");
return 0;
}
<|endoftext|>
|
<commit_before>// SA:MP Profiler plugin
//
// Copyright (c) 2011 Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#ifdef _WIN32
#include <Windows.h>
#endif
#include "amx_name.h"
#include "config_reader.h"
#include "debug_info.h"
#include "html_printer.h"
#include "jump_x86.h"
#include "plugin.h"
#include "profiler.h"
#include "text_printer.h"
#include "version.h"
#include "xml_printer.h"
#include "amx/amx.h"
typedef void (*logprintf_t)(const char *format, ...);
// AMX API functons array
extern void *pAMXFunctions;
// For logging
static logprintf_t logprintf;
// Symbolic info, used for getting function names
static std::map<AMX*, samp_profiler::DebugInfo> debug_infos;
// Contains currently loaded AMX scripts
static std::list<AMX*> loaded_scripts;
// Hooks
static samp_profiler::JumpX86 ExecHook;
static samp_profiler::JumpX86 CallbackHook;
static int AMXAPI Exec(AMX *amx, cell *retval, int index) {
ExecHook.Remove();
CallbackHook.Install(); // P-code may call natives
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx);
if (prof != 0) {
error = prof->Exec(retval, index);
} else {
error = amx_Exec(amx, retval, index);
}
CallbackHook.Remove();
ExecHook.Install();
return error;
}
static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
CallbackHook.Remove();
ExecHook.Install(); // Natives may call amx_Exec()
// The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes
// with SYSREQ.D for better performance.
amx->sysreq_d = 0;
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx);
if (prof != 0) {
error = prof->Callback(index, result, params);
} else {
error = amx_Callback(amx, index, result, params);
}
ExecHook.Remove();
CallbackHook.Install();
return error;
}
// Replaces back slashes with forward slashes
static std::string ToNormalPath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
static bool IsGameMode(const std::string &amxName) {
return ToNormalPath(amxName).find("gamemodes/") != std::string::npos;
}
static bool IsFilterScript(const std::string &amxName) {
return ToNormalPath(amxName).find("filterscripts/") != std::string::npos;
}
static bool GetPublicVariable(AMX *amx, const char *name, cell &value) {
cell amx_addr;
if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) {
cell *phys_addr;
amx_GetAddr(amx, amx_addr, &phys_addr);
value = *phys_addr;
return true;
}
return false;
}
// Returns true if the .amx should be profiled
static bool WantsProfiler(const std::string &amxName) {
std::string goodAmxName = ToNormalPath(amxName);
samp_profiler::ConfigReader server_cfg("server.cfg");
if (IsGameMode(amxName)) {
// This is a gamemode
if (server_cfg.GetOption("profile_gamemode", false)) {
return true;
}
} else if (IsFilterScript(amxName)) {
std::string fsList = server_cfg.GetOption("profile_filterscripts", std::string(""));
std::stringstream fsStream(fsList);
do {
std::string fsName;
fsStream >> fsName;
if (goodAmxName == "filterscripts/" + fsName + ".amx"
|| goodAmxName == "filterscripts/" + fsName) {
return true;
}
} while (!fsStream.eof());
}
return false;
}
#ifdef _WIN32
PLUGIN_EXPORT void PLUGIN_CALL Unload();
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx);
// Manually call Unload and AmxUnload on Ctrl+Break
// and server window close event.
static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
switch (dwCtrlType) {
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
for (std::list<AMX*>::const_iterator iterator = ::loaded_scripts.begin();
iterator != ::loaded_scripts.end(); ++iterator) {
AmxUnload(*iterator);
}
Unload();
}
return FALSE;
}
#endif
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
// x86 is Little Endian...
static void *AMXAPI my_amx_Align(void *v) { return v; }
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
// The server does not export amx_Align* for some reason.
// They are used in amxdbg.c and amxaux.c, so they must be callable.
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align; // amx_Align16
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align; // amx_Align32
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align; // amx_Align64
ExecHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)::Exec);
CallbackHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)::Callback);
#ifdef _WIN32
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
#endif
logprintf(" Profiler plugin "VERSION_STRING" is OK.");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
logprintf("Profiler got unloaded.");
return;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
std::string filename = samp_profiler::GetAmxName(amx);
if (filename.empty()) {
logprintf("Profiler: Failed to detect .amx name, prifiling will not be done");
return AMX_ERR_NONE;
}
if (!samp_profiler::Profiler::IsScriptProfilable(amx)) {
logprintf("Profiler: Can't profile script %s (are you using -d0?)", filename.c_str());
return AMX_ERR_NONE;
}
cell profiler_enabled = false;
if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled)
&& !profiler_enabled) {
return AMX_ERR_NONE;
}
if (profiler_enabled || WantsProfiler(filename)) {
if (samp_profiler::DebugInfo::HasDebugInfo(amx)) {
samp_profiler::DebugInfo debugInfo;
debugInfo.Load(filename);
if (debugInfo.IsLoaded()) {
logprintf("Profiler: Loaded debug info from %s", filename.c_str());
::debug_infos[amx] = debugInfo;
samp_profiler::Profiler::Attach(amx, debugInfo);
logprintf("Profiler: Attached profiler instance to %s", filename.c_str());
return AMX_ERR_NONE;
} else {
logprintf("Profiler: Error loading debug info from %s", filename.c_str());
}
}
samp_profiler::Profiler::Attach(amx);
logprintf("Profiler: Attached profiler instance to %s (no debug symbols)", filename.c_str());
}
::loaded_scripts.push_back(amx);
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
// Get an instance of Profiler attached to the unloading AMX
samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx);
// Detach profiler
if (prof != 0) {
std::string amx_path = samp_profiler::GetAmxName(amx); // must be in cache
std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));
// Output stats depending on currently set output_format
samp_profiler::ConfigReader server_cfg("server.cfg");
std::string format =
server_cfg.GetOption("profile_format", std::string("html"));
std::string filename;
samp_profiler::AbstractPrinter *printer = 0;
if (format == "html") {
filename = amx_name + "-profile.html";
printer = new samp_profiler::HtmlPrinter;
} else if (format == "text") {
filename = amx_name + "-profile.txt";
printer = new samp_profiler::TextPrinter;
} else if (format == "xml") {
filename = amx_name + "-profile.xml";
printer = new samp_profiler::XmlPrinter;
} else {
logprintf("Profiler: Unknown output format '%s'", format.c_str());
}
std::ofstream ostream(filename.c_str());
prof->PrintStats(ostream, printer);
delete printer;
samp_profiler::Profiler::Detach(amx);
}
// Free debug info
std::map<AMX*, samp_profiler::DebugInfo>::iterator it = ::debug_infos.find(amx);
if (it != ::debug_infos.end()) {
it->second.Free();
::debug_infos.erase(it);
}
::loaded_scripts.remove(amx);
return AMX_ERR_NONE;
}
<commit_msg>Fix crash on server exit if invalid output format specified<commit_after>// SA:MP Profiler plugin
//
// Copyright (c) 2011 Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#ifdef _WIN32
#include <Windows.h>
#endif
#include "amx_name.h"
#include "config_reader.h"
#include "debug_info.h"
#include "html_printer.h"
#include "jump_x86.h"
#include "plugin.h"
#include "profiler.h"
#include "text_printer.h"
#include "version.h"
#include "xml_printer.h"
#include "amx/amx.h"
typedef void (*logprintf_t)(const char *format, ...);
// AMX API functons array
extern void *pAMXFunctions;
// For logging
static logprintf_t logprintf;
// Symbolic info, used for getting function names
static std::map<AMX*, samp_profiler::DebugInfo> debug_infos;
// Contains currently loaded AMX scripts
static std::list<AMX*> loaded_scripts;
// Hooks
static samp_profiler::JumpX86 ExecHook;
static samp_profiler::JumpX86 CallbackHook;
static int AMXAPI Exec(AMX *amx, cell *retval, int index) {
ExecHook.Remove();
CallbackHook.Install(); // P-code may call natives
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx);
if (prof != 0) {
error = prof->Exec(retval, index);
} else {
error = amx_Exec(amx, retval, index);
}
CallbackHook.Remove();
ExecHook.Install();
return error;
}
static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
CallbackHook.Remove();
ExecHook.Install(); // Natives may call amx_Exec()
// The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes
// with SYSREQ.D for better performance.
amx->sysreq_d = 0;
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx);
if (prof != 0) {
error = prof->Callback(index, result, params);
} else {
error = amx_Callback(amx, index, result, params);
}
ExecHook.Remove();
CallbackHook.Install();
return error;
}
// Replaces back slashes with forward slashes
static std::string ToNormalPath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
static bool IsGameMode(const std::string &amxName) {
return ToNormalPath(amxName).find("gamemodes/") != std::string::npos;
}
static bool IsFilterScript(const std::string &amxName) {
return ToNormalPath(amxName).find("filterscripts/") != std::string::npos;
}
static bool GetPublicVariable(AMX *amx, const char *name, cell &value) {
cell amx_addr;
if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) {
cell *phys_addr;
amx_GetAddr(amx, amx_addr, &phys_addr);
value = *phys_addr;
return true;
}
return false;
}
// Returns true if the .amx should be profiled
static bool WantsProfiler(const std::string &amxName) {
std::string goodAmxName = ToNormalPath(amxName);
samp_profiler::ConfigReader server_cfg("server.cfg");
if (IsGameMode(amxName)) {
// This is a gamemode
if (server_cfg.GetOption("profile_gamemode", false)) {
return true;
}
} else if (IsFilterScript(amxName)) {
std::string fsList = server_cfg.GetOption("profile_filterscripts", std::string(""));
std::stringstream fsStream(fsList);
do {
std::string fsName;
fsStream >> fsName;
if (goodAmxName == "filterscripts/" + fsName + ".amx"
|| goodAmxName == "filterscripts/" + fsName) {
return true;
}
} while (!fsStream.eof());
}
return false;
}
#ifdef _WIN32
PLUGIN_EXPORT void PLUGIN_CALL Unload();
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx);
// Manually call Unload and AmxUnload on Ctrl+Break
// and server window close event.
static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
switch (dwCtrlType) {
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
for (std::list<AMX*>::const_iterator iterator = ::loaded_scripts.begin();
iterator != ::loaded_scripts.end(); ++iterator) {
AmxUnload(*iterator);
}
Unload();
}
return FALSE;
}
#endif
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
// x86 is Little Endian...
static void *AMXAPI my_amx_Align(void *v) { return v; }
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
// The server does not export amx_Align* for some reason.
// They are used in amxdbg.c and amxaux.c, so they must be callable.
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align; // amx_Align16
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align; // amx_Align32
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align; // amx_Align64
ExecHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)::Exec);
CallbackHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)::Callback);
#ifdef _WIN32
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
#endif
logprintf(" Profiler plugin "VERSION_STRING" is OK.");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
logprintf("Profiler got unloaded.");
return;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
std::string filename = samp_profiler::GetAmxName(amx);
if (filename.empty()) {
logprintf("Profiler: Failed to detect .amx name, prifiling will not be done");
return AMX_ERR_NONE;
}
if (!samp_profiler::Profiler::IsScriptProfilable(amx)) {
logprintf("Profiler: Can't profile script %s (are you using -d0?)", filename.c_str());
return AMX_ERR_NONE;
}
cell profiler_enabled = false;
if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled)
&& !profiler_enabled) {
return AMX_ERR_NONE;
}
if (profiler_enabled || WantsProfiler(filename)) {
if (samp_profiler::DebugInfo::HasDebugInfo(amx)) {
samp_profiler::DebugInfo debugInfo;
debugInfo.Load(filename);
if (debugInfo.IsLoaded()) {
logprintf("Profiler: Loaded debug info from %s", filename.c_str());
::debug_infos[amx] = debugInfo;
samp_profiler::Profiler::Attach(amx, debugInfo);
logprintf("Profiler: Attached profiler instance to %s", filename.c_str());
return AMX_ERR_NONE;
} else {
logprintf("Profiler: Error loading debug info from %s", filename.c_str());
}
}
samp_profiler::Profiler::Attach(amx);
logprintf("Profiler: Attached profiler instance to %s (no debug symbols)", filename.c_str());
}
::loaded_scripts.push_back(amx);
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
// Get an instance of Profiler attached to the unloading AMX
samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx);
// Detach profiler
if (prof != 0) {
std::string amx_path = samp_profiler::GetAmxName(amx); // must be in cache
std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));
// Output stats depending on currently set output_format
samp_profiler::ConfigReader server_cfg("server.cfg");
std::string format =
server_cfg.GetOption("profile_format", std::string("html"));
std::string filename = amx_name + "-profile";
samp_profiler::AbstractPrinter *printer = 0;
if (format == "html") {
filename += ".html";
printer = new samp_profiler::HtmlPrinter;
} else if (format == "text") {
filename += ".txt";
printer = new samp_profiler::TextPrinter;
} else if (format == "xml") {
filename += ".xml";
printer = new samp_profiler::XmlPrinter;
} else {
logprintf("Profiler: Unknown output format '%s'", format.c_str());
}
if (printer != 0) {
std::ofstream ostream(filename.c_str());
prof->PrintStats(ostream, printer);
delete printer;
}
samp_profiler::Profiler::Detach(amx);
}
// Free debug info
std::map<AMX*, samp_profiler::DebugInfo>::iterator it = ::debug_infos.find(amx);
if (it != ::debug_infos.end()) {
it->second.Free();
::debug_infos.erase(it);
}
::loaded_scripts.remove(amx);
return AMX_ERR_NONE;
}
<|endoftext|>
|
<commit_before>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include "pm.h"
HWND handle;
DWORD threadId;
HANDLE threadHandle;
HANDLE notifyEvent;
char notify_msg[1024];
bool isRunning = false;
DWORD WINAPI ListenerThread( LPVOID lpParam );
void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);
void NotifyAsync(uv_work_t* req)
{
WaitForSingleObject(notifyEvent, INFINITE);
}
void NotifyFinished(uv_work_t* req)
{
if (isRunning)
{
Notify(notify_msg);
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
}
static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if(message == WM_POWERBROADCAST)
{
// printf("%d\n", wParam);
if (wParam == PBT_APMRESUMESUSPEND)
{
// printf("wake\n");
strcpy(notify_msg, "wake");
SetEvent(notifyEvent);
}
if (wParam == PBT_APMRESUMEAUTOMATIC)
{
// printf("waking\n");
// strcpy(notify_msg, "waking");
// SetEvent(notifyEvent);
}
if (wParam == PBT_APMSUSPEND)
{
// printf("sleeping\n");
strcpy(notify_msg, "sleep");
SetEvent(notifyEvent);
}
if (wParam == PBT_APMPOWERSTATUSCHANGE)
{
// printf("PBT_APMPOWERSTATUSCHANGE\n");
// SetEvent(notifyEvent);
}
//Do something
return TRUE;
}
else
return DefWindowProc(hWnd, message, wParam, lParam);
}
DWORD WINAPI ListenerThread( LPVOID lpParam )
{
const char *className = "ListnerThread";
WNDCLASS wc = {0};
// Set up and register window class
wc.lpfnWndProc = (WNDPROC)WindowProc;
wc.lpszClassName = className;
RegisterClass(&wc);
HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);
BOOL bRet;
MSG msg;
while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
void Start()
{
isRunning = true;
threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
ListenerThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&threadId);
uv_work_t* req = new uv_work_t();
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
void Stop()
{
isRunning = false;
SetEvent(notifyEvent);
// ExitThread(threadHandle);
}
void InitPM()
{
notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
Start();
}<commit_msg>unique listener thread name<commit_after>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include "pm.h"
HWND handle;
DWORD threadId;
HANDLE threadHandle;
HANDLE notifyEvent;
char notify_msg[1024];
bool isRunning = false;
DWORD WINAPI ListenerThread( LPVOID lpParam );
void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);
void NotifyAsync(uv_work_t* req)
{
WaitForSingleObject(notifyEvent, INFINITE);
}
void NotifyFinished(uv_work_t* req)
{
if (isRunning)
{
Notify(notify_msg);
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
}
static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if(message == WM_POWERBROADCAST)
{
// printf("%d\n", wParam);
if (wParam == PBT_APMRESUMESUSPEND)
{
// printf("wake\n");
strcpy(notify_msg, "wake");
SetEvent(notifyEvent);
}
if (wParam == PBT_APMRESUMEAUTOMATIC)
{
// printf("waking\n");
// strcpy(notify_msg, "waking");
// SetEvent(notifyEvent);
}
if (wParam == PBT_APMSUSPEND)
{
// printf("sleeping\n");
strcpy(notify_msg, "sleep");
SetEvent(notifyEvent);
}
if (wParam == PBT_APMPOWERSTATUSCHANGE)
{
// printf("PBT_APMPOWERSTATUSCHANGE\n");
// SetEvent(notifyEvent);
}
//Do something
return TRUE;
}
else
return DefWindowProc(hWnd, message, wParam, lParam);
}
DWORD WINAPI ListenerThread( LPVOID lpParam )
{
const char *className = "ListnerThreadPmNotify";
WNDCLASS wc = {0};
// Set up and register window class
wc.lpfnWndProc = (WNDPROC)WindowProc;
wc.lpszClassName = className;
RegisterClass(&wc);
HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);
BOOL bRet;
MSG msg;
while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
void Start()
{
isRunning = true;
threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
ListenerThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&threadId);
uv_work_t* req = new uv_work_t();
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
void Stop()
{
isRunning = false;
SetEvent(notifyEvent);
// ExitThread(threadHandle);
}
void InitPM()
{
notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
Start();
}<|endoftext|>
|
<commit_before>// @(#)alimdc:$Name$:$Id$
// Author: Fons Rademakers 26/11/99
/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// AliRawDB //
// //
//////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <TSystem.h>
#include <TKey.h>
#include "AliESD.h"
#include "AliRawEvent.h"
#include "AliRawEventHeaderBase.h"
#include "AliStats.h"
#include "AliRawDB.h"
ClassImp(AliRawDB)
const char *AliRawDB::fgkAliRootTag = "$Name$";
//______________________________________________________________________________
AliRawDB::AliRawDB(AliRawEvent *event,
AliESD *esd,
Int_t compress,
const char* fileName) :
fRawDB(NULL),
fTree(NULL),
fEvent(event),
fESDTree(NULL),
fESD(esd),
fCompress(compress),
fMaxSize(-1),
fFS1(""),
fFS2(""),
fDeleteFiles(kFALSE),
fStop(kFALSE)
{
// Create a new raw DB
if (fileName) {
if (!Create(fileName))
MakeZombie();
}
}
//______________________________________________________________________________
Bool_t AliRawDB::FSHasSpace(const char *fs) const
{
// Check for at least fMaxSize bytes of free space on the file system.
// If the space is not available return kFALSE, kTRUE otherwise.
Long_t id, bsize, blocks, bfree;
if (gSystem->GetFsInfo(fs, &id, &bsize, &blocks, &bfree) == 1) {
Error("FSHasSpace", "could not stat file system %s", fs);
return kFALSE;
}
// Leave 5 percent of diskspace free
Double_t avail = Double_t(bfree) * 0.95;
if (avail*bsize > fMaxSize)
return kTRUE;
Warning("FSHasSpace", "no space on file system %s", fs);
return kFALSE;
}
//______________________________________________________________________________
const char *AliRawDB::GetFileName() const
{
// Return filename based on hostname and date and time. This will make
// each file unique. Also makes sure (via FSHasSpace()) that there is
// enough space on the file system to store the file. Returns 0 in
// case of error or interrupt signal.
static TString fname;
static Bool_t fstoggle = kFALSE;
TString fs = fstoggle ? fFS2 : fFS1;
TDatime dt;
TString hostname = gSystem->HostName();
Int_t pos;
if ((pos = hostname.Index(".")) != kNPOS)
hostname.Remove(pos);
if (!FSHasSpace(fs)) {
while (1) {
fstoggle = !fstoggle;
fs = fstoggle ? fFS2 : fFS1;
if (FSHasSpace(fs)) break;
Info("GetFileName", "sleeping 30 seconds before retrying...");
gSystem->Sleep(30000); // sleep for 30 seconds
if (fStop) return 0;
}
}
fname = fs + "/" + hostname + "_";
fname += dt.GetDate();
fname += "_";
fname += dt.GetTime();
fname += ".root";
fstoggle = !fstoggle;
return fname;
}
//______________________________________________________________________________
void AliRawDB::SetFS(const char* fs1, const char* fs2)
{
// set the file system location
fFS1 = fs1;
if (fs1 && !fFS1.Contains(":")) {
gSystem->ResetErrno();
gSystem->MakeDirectory(fs1);
if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
SysError("SetFS", "mkdir %s", fs1);
}
}
fFS2 = fs2;
if (fs2) {
gSystem->ResetErrno();
gSystem->MakeDirectory(fs2);
if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
SysError("SetFS", "mkdir %s", fs2);
}
}
}
//______________________________________________________________________________
Bool_t AliRawDB::Create(const char* fileName)
{
// Create a new raw DB.
const Int_t kMaxRetry = 1;
const Int_t kMaxSleep = 1; // seconds
const Int_t kMaxSleepLong = 10; // seconds
Int_t retry = 0;
again:
if (fStop) return kFALSE;
const char *fname = fileName;
if (!fname) fname = GetFileName();
if (!fname) {
Error("Create", "error getting raw DB file name");
return kFALSE;
}
retry++;
fRawDB = TFile::Open(fname, GetOpenOption(),
Form("ALICE raw-data file (%s)", GetAliRootTag()), fCompress,
GetNetopt());
if (!fRawDB) {
if (retry < kMaxRetry) {
Warning("Create", "failure to open file, sleeping %d %s before retrying...",
kMaxSleep, kMaxSleep==1 ? "second" : "seconds");
gSystem->Sleep(kMaxSleep*1000);
goto again;
}
Error("Create", "failure to open file %s after %d tries", fname, kMaxRetry);
return kFALSE;
}
if (retry > 1)
Warning("Create", "succeeded to open file after %d retries", retry);
if (fRawDB->IsZombie()) {
if (fRawDB->GetErrno() == ENOSPC ||
fRawDB->GetErrno() == 1018 || // SECOMERR
fRawDB->GetErrno() == 1027) { // SESYSERR
fRawDB->ResetErrno();
delete fRawDB;
Warning("Create", "file is a zombie (no space), sleeping %d %s before retrying...",
kMaxSleepLong, kMaxSleepLong==1 ? "second" : "seconds");
gSystem->Sleep(kMaxSleepLong*1000); // sleep 10 seconds before retrying
goto again;
}
Error("Create", "file %s is zombie", fname);
fRawDB->ResetErrno();
delete fRawDB;
fRawDB = 0;
if (retry < kMaxRetry) {
Warning("Create", "file is a zombie, sleeping %d %s before retrying...",
kMaxSleep, kMaxSleep==1 ? "second" : "seconds");
gSystem->Sleep(kMaxSleep*1000);
goto again;
}
Error("Create", "failure to open file %s after %d tries", fname, kMaxRetry);
return kFALSE;
}
// Create raw data TTree
MakeTree();
return kTRUE;
}
//______________________________________________________________________________
void AliRawDB::MakeTree()
{
// Create ROOT Tree object container.
fTree = new TTree("RAW", Form("ALICE raw-data tree (%s)", GetAliRootTag()));
fTree->SetAutoSave(2000000000); // autosave when 2 Gbyte written
Int_t bufsize = 256000;
// splitting 29.6 MB/s, no splitting 35.3 MB/s on P4 2GHz 15k SCSI
//Int_t split = 1;
Int_t split = 0;
fTree->Branch("rawevent", "AliRawEvent", &fEvent, bufsize, split);
// Create tree which will contain the HLT ESD information
if (fESD) {
fESDTree = new TTree("esdTree", Form("ALICE HLT ESD tree (%s)", GetAliRootTag()));
fESDTree->SetAutoSave(2000000000); // autosave when 2 Gbyte written
split = 0;
fESDTree->Branch("ESD", "AliESD", &fESD, bufsize, split);
}
}
//______________________________________________________________________________
Int_t AliRawDB::Close()
{
// Close raw DB.
if (!fRawDB) return 0;
if (!fRawDB->IsOpen()) return 0;
fRawDB->cd();
// Write the tree.
Bool_t error = kFALSE;
if (fTree->Write() == 0)
error = kTRUE;
if (fESDTree)
if (fESDTree->Write() == 0)
error = kTRUE;
// Close DB, this also deletes the fTree
fRawDB->Close();
Int_t filesize = fRawDB->GetEND();
if (fDeleteFiles) {
gSystem->Unlink(fRawDB->GetName());
delete fRawDB;
fRawDB = 0;
if(!error)
return filesize;
else
return -1;
}
delete fRawDB;
fRawDB = 0;
if(!error)
return filesize;
else
return -1;
}
//______________________________________________________________________________
Int_t AliRawDB::Fill()
{
// Fill the trees and return the number of written bytes
Double_t bytes = fRawDB->GetBytesWritten();
Bool_t error = kFALSE;
if (fTree->Fill() == -1)
error = kTRUE;
if (fESDTree)
if (fESDTree->Fill() == -1)
error = kTRUE;
if(!error)
return Int_t(fRawDB->GetBytesWritten() - bytes);
else
return -1;
}
//______________________________________________________________________________
Int_t AliRawDB::GetTotalSize()
{
// Return the total size of the trees
Int_t total = 0;
{
Int_t skey = 0;
TDirectory *dir = fTree->GetDirectory();
if (dir) {
TKey *key = dir->GetKey(fTree->GetName());
if (key) skey = key->GetKeylen();
}
total += skey;
if (fTree->GetZipBytes() > 0) total += fTree->GetTotBytes();
TBuffer b(TBuffer::kWrite,10000);
TTree::Class()->WriteBuffer(b,fTree);
total += b.Length();
}
if(fESDTree)
{
Int_t skey = 0;
TDirectory *dir = fESDTree->GetDirectory();
if (dir) {
TKey *key = dir->GetKey(fESDTree->GetName());
if (key) skey = key->GetKeylen();
}
total += skey;
if (fESDTree->GetZipBytes() > 0) total += fESDTree->GetTotBytes();
TBuffer b(TBuffer::kWrite,10000);
TTree::Class()->WriteBuffer(b,fESDTree);
total += b.Length();
}
return total;
}
//______________________________________________________________________________
void AliRawDB::WriteStats(AliStats* stats)
{
// Write stats to raw DB, local run DB and global MySQL DB.
AliRawEventHeaderBase &header = *GetEvent()->GetHeader();
// Write stats into RawDB
TDirectory *ds = gDirectory;
GetDB()->cd();
stats->SetEvents(GetEvents());
stats->SetLastId(header.GetP("Id")[0]);
stats->SetFileSize(GetBytesWritten());
stats->SetCompressionFactor(GetCompressionFactor());
stats->SetEndTime();
stats->Write("stats");
ds->cd();
}
//______________________________________________________________________________
Bool_t AliRawDB::NextFile(const char* fileName)
{
// Close te current file and open a new one.
// Returns kFALSE in case opening failed.
Close();
if (!Create(fileName)) return kFALSE;
return kTRUE;
}
//______________________________________________________________________________
Float_t AliRawDB::GetCompressionFactor() const
{
// Return compression factor.
if (fTree->GetZipBytes() == 0.)
return 1.0;
else
return fTree->GetTotBytes()/fTree->GetZipBytes();
}
//______________________________________________________________________________
const char *AliRawDB::GetAliRootTag()
{
// Return the aliroot tag (version)
// used to generate the raw data file.
// Stored in the raw-data file title.
TString version = fgkAliRootTag;
version.Remove(TString::kBoth,'$');
version.ReplaceAll("Name","AliRoot version");
return version.Data();
}
<commit_msg>Adding a text file with the raw-data file guid. TO be used by online during the registration into the AliEn FC<commit_after>// @(#)alimdc:$Name$:$Id$
// Author: Fons Rademakers 26/11/99
/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// AliRawDB //
// //
//////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <Riostream.h>
#include <TSystem.h>
#include <TKey.h>
#include "AliESD.h"
#include "AliRawEvent.h"
#include "AliRawEventHeaderBase.h"
#include "AliStats.h"
#include "AliRawDB.h"
ClassImp(AliRawDB)
const char *AliRawDB::fgkAliRootTag = "$Name$";
//______________________________________________________________________________
AliRawDB::AliRawDB(AliRawEvent *event,
AliESD *esd,
Int_t compress,
const char* fileName) :
fRawDB(NULL),
fTree(NULL),
fEvent(event),
fESDTree(NULL),
fESD(esd),
fCompress(compress),
fMaxSize(-1),
fFS1(""),
fFS2(""),
fDeleteFiles(kFALSE),
fStop(kFALSE)
{
// Create a new raw DB
if (fileName) {
if (!Create(fileName))
MakeZombie();
}
}
//______________________________________________________________________________
Bool_t AliRawDB::FSHasSpace(const char *fs) const
{
// Check for at least fMaxSize bytes of free space on the file system.
// If the space is not available return kFALSE, kTRUE otherwise.
Long_t id, bsize, blocks, bfree;
if (gSystem->GetFsInfo(fs, &id, &bsize, &blocks, &bfree) == 1) {
Error("FSHasSpace", "could not stat file system %s", fs);
return kFALSE;
}
// Leave 5 percent of diskspace free
Double_t avail = Double_t(bfree) * 0.95;
if (avail*bsize > fMaxSize)
return kTRUE;
Warning("FSHasSpace", "no space on file system %s", fs);
return kFALSE;
}
//______________________________________________________________________________
const char *AliRawDB::GetFileName() const
{
// Return filename based on hostname and date and time. This will make
// each file unique. Also makes sure (via FSHasSpace()) that there is
// enough space on the file system to store the file. Returns 0 in
// case of error or interrupt signal.
static TString fname;
static Bool_t fstoggle = kFALSE;
TString fs = fstoggle ? fFS2 : fFS1;
TDatime dt;
TString hostname = gSystem->HostName();
Int_t pos;
if ((pos = hostname.Index(".")) != kNPOS)
hostname.Remove(pos);
if (!FSHasSpace(fs)) {
while (1) {
fstoggle = !fstoggle;
fs = fstoggle ? fFS2 : fFS1;
if (FSHasSpace(fs)) break;
Info("GetFileName", "sleeping 30 seconds before retrying...");
gSystem->Sleep(30000); // sleep for 30 seconds
if (fStop) return 0;
}
}
fname = fs + "/" + hostname + "_";
fname += dt.GetDate();
fname += "_";
fname += dt.GetTime();
fname += ".root";
fstoggle = !fstoggle;
return fname;
}
//______________________________________________________________________________
void AliRawDB::SetFS(const char* fs1, const char* fs2)
{
// set the file system location
fFS1 = fs1;
if (fs1 && !fFS1.Contains(":")) {
gSystem->ResetErrno();
gSystem->MakeDirectory(fs1);
if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
SysError("SetFS", "mkdir %s", fs1);
}
}
fFS2 = fs2;
if (fs2) {
gSystem->ResetErrno();
gSystem->MakeDirectory(fs2);
if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
SysError("SetFS", "mkdir %s", fs2);
}
}
}
//______________________________________________________________________________
Bool_t AliRawDB::Create(const char* fileName)
{
// Create a new raw DB.
const Int_t kMaxRetry = 1;
const Int_t kMaxSleep = 1; // seconds
const Int_t kMaxSleepLong = 10; // seconds
Int_t retry = 0;
again:
if (fStop) return kFALSE;
const char *fname = fileName;
if (!fname) fname = GetFileName();
if (!fname) {
Error("Create", "error getting raw DB file name");
return kFALSE;
}
retry++;
fRawDB = TFile::Open(fname, GetOpenOption(),
Form("ALICE raw-data file (%s)", GetAliRootTag()), fCompress,
GetNetopt());
if (!fRawDB) {
if (retry < kMaxRetry) {
Warning("Create", "failure to open file, sleeping %d %s before retrying...",
kMaxSleep, kMaxSleep==1 ? "second" : "seconds");
gSystem->Sleep(kMaxSleep*1000);
goto again;
}
Error("Create", "failure to open file %s after %d tries", fname, kMaxRetry);
return kFALSE;
}
if (retry > 1)
Warning("Create", "succeeded to open file after %d retries", retry);
if (fRawDB->IsZombie()) {
if (fRawDB->GetErrno() == ENOSPC ||
fRawDB->GetErrno() == 1018 || // SECOMERR
fRawDB->GetErrno() == 1027) { // SESYSERR
fRawDB->ResetErrno();
delete fRawDB;
Warning("Create", "file is a zombie (no space), sleeping %d %s before retrying...",
kMaxSleepLong, kMaxSleepLong==1 ? "second" : "seconds");
gSystem->Sleep(kMaxSleepLong*1000); // sleep 10 seconds before retrying
goto again;
}
Error("Create", "file %s is zombie", fname);
fRawDB->ResetErrno();
delete fRawDB;
fRawDB = 0;
if (retry < kMaxRetry) {
Warning("Create", "file is a zombie, sleeping %d %s before retrying...",
kMaxSleep, kMaxSleep==1 ? "second" : "seconds");
gSystem->Sleep(kMaxSleep*1000);
goto again;
}
Error("Create", "failure to open file %s after %d tries", fname, kMaxRetry);
return kFALSE;
}
// Create raw data TTree
MakeTree();
return kTRUE;
}
//______________________________________________________________________________
void AliRawDB::MakeTree()
{
// Create ROOT Tree object container.
fTree = new TTree("RAW", Form("ALICE raw-data tree (%s)", GetAliRootTag()));
fTree->SetAutoSave(2000000000); // autosave when 2 Gbyte written
Int_t bufsize = 256000;
// splitting 29.6 MB/s, no splitting 35.3 MB/s on P4 2GHz 15k SCSI
//Int_t split = 1;
Int_t split = 0;
fTree->Branch("rawevent", "AliRawEvent", &fEvent, bufsize, split);
// Create tree which will contain the HLT ESD information
if (fESD) {
fESDTree = new TTree("esdTree", Form("ALICE HLT ESD tree (%s)", GetAliRootTag()));
fESDTree->SetAutoSave(2000000000); // autosave when 2 Gbyte written
split = 0;
fESDTree->Branch("ESD", "AliESD", &fESD, bufsize, split);
}
}
//______________________________________________________________________________
Int_t AliRawDB::Close()
{
// Close raw DB.
if (!fRawDB) return 0;
if (!fRawDB->IsOpen()) return 0;
fRawDB->cd();
// Write the tree.
Bool_t error = kFALSE;
if (fTree->Write() == 0)
error = kTRUE;
if (fESDTree)
if (fESDTree->Write() == 0)
error = kTRUE;
// Close DB, this also deletes the fTree
fRawDB->Close();
Int_t filesize = fRawDB->GetEND();
if (fDeleteFiles) {
gSystem->Unlink(fRawDB->GetName());
delete fRawDB;
fRawDB = 0;
if(!error)
return filesize;
else
return -1;
}
// Write a text file with file GUID
TString guidFileName = fRawDB->GetName();
guidFileName += ".guid";
ofstream fguid(guidFileName.Data());
TString guid = fRawDB->GetUUID().AsString();
fguid << fRawDB->GetName() << " \t" << guid.Data();
fguid.close();
delete fRawDB;
fRawDB = 0;
if(!error)
return filesize;
else
return -1;
}
//______________________________________________________________________________
Int_t AliRawDB::Fill()
{
// Fill the trees and return the number of written bytes
Double_t bytes = fRawDB->GetBytesWritten();
Bool_t error = kFALSE;
if (fTree->Fill() == -1)
error = kTRUE;
if (fESDTree)
if (fESDTree->Fill() == -1)
error = kTRUE;
if(!error)
return Int_t(fRawDB->GetBytesWritten() - bytes);
else
return -1;
}
//______________________________________________________________________________
Int_t AliRawDB::GetTotalSize()
{
// Return the total size of the trees
Int_t total = 0;
{
Int_t skey = 0;
TDirectory *dir = fTree->GetDirectory();
if (dir) {
TKey *key = dir->GetKey(fTree->GetName());
if (key) skey = key->GetKeylen();
}
total += skey;
if (fTree->GetZipBytes() > 0) total += fTree->GetTotBytes();
TBuffer b(TBuffer::kWrite,10000);
TTree::Class()->WriteBuffer(b,fTree);
total += b.Length();
}
if(fESDTree)
{
Int_t skey = 0;
TDirectory *dir = fESDTree->GetDirectory();
if (dir) {
TKey *key = dir->GetKey(fESDTree->GetName());
if (key) skey = key->GetKeylen();
}
total += skey;
if (fESDTree->GetZipBytes() > 0) total += fESDTree->GetTotBytes();
TBuffer b(TBuffer::kWrite,10000);
TTree::Class()->WriteBuffer(b,fESDTree);
total += b.Length();
}
return total;
}
//______________________________________________________________________________
void AliRawDB::WriteStats(AliStats* stats)
{
// Write stats to raw DB, local run DB and global MySQL DB.
AliRawEventHeaderBase &header = *GetEvent()->GetHeader();
// Write stats into RawDB
TDirectory *ds = gDirectory;
GetDB()->cd();
stats->SetEvents(GetEvents());
stats->SetLastId(header.GetP("Id")[0]);
stats->SetFileSize(GetBytesWritten());
stats->SetCompressionFactor(GetCompressionFactor());
stats->SetEndTime();
stats->Write("stats");
ds->cd();
}
//______________________________________________________________________________
Bool_t AliRawDB::NextFile(const char* fileName)
{
// Close te current file and open a new one.
// Returns kFALSE in case opening failed.
Close();
if (!Create(fileName)) return kFALSE;
return kTRUE;
}
//______________________________________________________________________________
Float_t AliRawDB::GetCompressionFactor() const
{
// Return compression factor.
if (fTree->GetZipBytes() == 0.)
return 1.0;
else
return fTree->GetTotBytes()/fTree->GetZipBytes();
}
//______________________________________________________________________________
const char *AliRawDB::GetAliRootTag()
{
// Return the aliroot tag (version)
// used to generate the raw data file.
// Stored in the raw-data file title.
TString version = fgkAliRootTag;
version.Remove(TString::kBoth,'$');
version.ReplaceAll("Name","AliRoot version");
return version.Data();
}
<|endoftext|>
|
<commit_before>/*
The MIT License
Copyright (c) 2009 Institut of Mechanics and Fluid Dynamics,
TU Bergakademie Freiberg.
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.
*/
/**
\file REKConverter.cpp
\author Andre Liebscher
Institut of Mechanics and Fluid Dynamics
TU Bergakademie Freiberg
\date March 2009
*/
#include <fstream>
#include <sstream>
#include <cstring>
#include "REKConverter.h"
#include "Controller/Controller.h"
#include "boost/cstdint.hpp"
using namespace std;
REKConverter::REKConverter()
{
m_vConverterDesc = "Fraunhofer EZRT Volume";
m_vSupportedExt.push_back("REK");
}
bool
REKConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&,
bool, UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINTVECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
MESSAGE("Attempting to convert REK dataset %s", strSourceFilename.c_str());
// Read header an check for "magic" values of the REK file
ifstream fileData(strSourceFilename.c_str(), ifstream::in | ifstream::binary);
char buffer[2048];
if(fileData.is_open()) {
fileData.read( buffer, sizeof(buffer) );
char ff[] = { 255, 255, 255, 255 };
if( memcmp(&buffer[116], &ff, 4) != 0 ) {
WARNING("The file %s is not a REK file", strSourceFilename.c_str());
fileData.close();
return false;
}
} else {
WARNING("Could not open REK file %s", strSourceFilename.c_str());
return false;
}
fileData.close();
// standard values which are always true (I guess)
strTitle = "Fraunhofer EZRT";
eType = UVFTables::ES_UNDEFINED;
vVolumeAspect = FLOATVECTOR3(1,1,1);
bSigned = false;
bIsFloat = false;
iComponentCount = 1;
strIntermediateFile = strSourceFilename;
bDeleteIntermediateFile = false;
// read file format from header - first try to guess endieness from offset 4-5 (bits per pixel)
// Anyway, I do not think that anyone would ever encounter such a file stored in big endian encoding.
bConvertEndianess = Parse<boost::uint16_t, 2>( &buffer[4] ) > 32;
vVolumeSize[0] = Parse<boost::uint16_t, 2>( &buffer[0], bConvertEndianess );
vVolumeSize[1] = Parse<boost::uint16_t, 2>( &buffer[2], bConvertEndianess );
vVolumeSize[2] = Parse<boost::uint16_t, 2>( &buffer[6], bConvertEndianess );
iComponentSize = Parse<boost::uint16_t, 2>( &buffer[4], bConvertEndianess );
iHeaderSkip = Parse<boost::uint16_t, 2>( &buffer[8], bConvertEndianess );
return true;
}
// unimplemented!
bool
REKConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64, UINT64,
UINT64, bool,
bool,
UINTVECTOR3,
FLOATVECTOR3,
bool)
{
return false;
}
<commit_msg>Fix warning on win32.<commit_after>/*
The MIT License
Copyright (c) 2009 Institut of Mechanics and Fluid Dynamics,
TU Bergakademie Freiberg.
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.
*/
/**
\file REKConverter.cpp
\author Andre Liebscher
Institut of Mechanics and Fluid Dynamics
TU Bergakademie Freiberg
\date March 2009
*/
#include <fstream>
#include <sstream>
#include <cstring>
#include "REKConverter.h"
#include "Controller/Controller.h"
#include "boost/cstdint.hpp"
using namespace std;
REKConverter::REKConverter()
{
m_vConverterDesc = "Fraunhofer EZRT Volume";
m_vSupportedExt.push_back("REK");
}
bool
REKConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&,
bool, UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINTVECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
MESSAGE("Attempting to convert REK dataset %s", strSourceFilename.c_str());
// Read header an check for "magic" values of the REK file
ifstream fileData(strSourceFilename.c_str(), ifstream::in | ifstream::binary);
char buffer[2048];
if(fileData.is_open()) {
fileData.read( buffer, sizeof(buffer) );
unsigned char ff[] = { 255, 255, 255, 255 };
if( memcmp(&buffer[116], &ff, 4) != 0 ) {
WARNING("The file %s is not a REK file", strSourceFilename.c_str());
fileData.close();
return false;
}
} else {
WARNING("Could not open REK file %s", strSourceFilename.c_str());
return false;
}
fileData.close();
// standard values which are always true (I guess)
strTitle = "Fraunhofer EZRT";
eType = UVFTables::ES_UNDEFINED;
vVolumeAspect = FLOATVECTOR3(1,1,1);
bSigned = false;
bIsFloat = false;
iComponentCount = 1;
strIntermediateFile = strSourceFilename;
bDeleteIntermediateFile = false;
// read file format from header - first try to guess endieness from offset 4-5 (bits per pixel)
// Anyway, I do not think that anyone would ever encounter such a file stored in big endian encoding.
bConvertEndianess = Parse<boost::uint16_t, 2>( &buffer[4] ) > 32;
vVolumeSize[0] = Parse<boost::uint16_t, 2>( &buffer[0], bConvertEndianess );
vVolumeSize[1] = Parse<boost::uint16_t, 2>( &buffer[2], bConvertEndianess );
vVolumeSize[2] = Parse<boost::uint16_t, 2>( &buffer[6], bConvertEndianess );
iComponentSize = Parse<boost::uint16_t, 2>( &buffer[4], bConvertEndianess );
iHeaderSkip = Parse<boost::uint16_t, 2>( &buffer[8], bConvertEndianess );
return true;
}
// unimplemented!
bool
REKConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64, UINT64,
UINT64, bool,
bool,
UINTVECTOR3,
FLOATVECTOR3,
bool)
{
return false;
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#define PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#include "pcl/filters/normal_space.h"
#include <vector>
#include <list>
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (PointCloud &output)
{
// If sample size is 0 or if the sample size is greater then input cloud size
// then return entire copy of cloud
if (sample_ >= input_->size ())
{
output = *input_;
return;
}
// Resize output cloud to sample size
output.points.resize (sample_);
output.width = sample_;
output.height = 1;
// allocate memory for the histogram of normals.. Normals will then be sampled from each bin..
unsigned int n_bins = binsx_ * binsy_ * binsz_;
// list<int> holds the indices of points in that bin.. Using list to avoid repeated resizing of vectors.. Helps when the point cloud is
// large..
std::vector< std::list <int> > normals_hg;
normals_hg.reserve (n_bins);
for (unsigned int i = 0; i < n_bins; i++)
normals_hg.push_back (std::list<int> ());
for (unsigned int i = 0; i < input_normals_->points.size (); i++)
{
unsigned int bin_number = findBin (input_normals_->points[i].normal, n_bins);
normals_hg[bin_number].push_back (i);
}
// Setting up random access for the list created above.. Maintaining the iterators to individual elements of the list in a vector.. Using
// vector now as the size of the list is known..
std::vector< std::vector <std::list<int>::iterator> > random_access (normals_hg.size ());
for (unsigned int i = 0; i < normals_hg.size (); i++)
{
random_access.push_back (std::vector< std::list<int>::iterator> ());
random_access[i].resize (normals_hg[i].size ());
unsigned int j=0;
for (std::list<int>::iterator itr = normals_hg[i].begin (); itr != normals_hg[i].end (); itr++, j++)
{
random_access[i][j] = itr;
}
}
unsigned int* start_index = new unsigned int[normals_hg.size ()];
start_index[0] = 0;
unsigned int prev_index = start_index[0];
for (unsigned int i = 1; i < normals_hg.size (); i++)
{
start_index[i] = prev_index + normals_hg[i-1].size ();
prev_index = start_index[i];
}
// maintaining flags to check if a point is sampled
boost::dynamic_bitset<> is_sampled_flag (input_normals_->points.size ());
// maintaining flags to check if all points in the bin are sampled
boost::dynamic_bitset<> bin_empty_flag (normals_hg.size ());
unsigned int i = 0;
while (i < sample_)
{
// iterating through every bin and picking one point at random, until the required number of points are sampled..
for (unsigned int j = 0; j < normals_hg.size (); j++)
{
unsigned int M = normals_hg[j].size ();
if (M == 0 || bin_empty_flag.test (j))// bin_empty_flag(i) is set if all points in that bin are sampled..
{
continue;
}
unsigned int pos = 0;
unsigned int random_index = 0;
//picking up a sample at random from jth bin
do
{
random_index = std::rand () % M;
pos = start_index[j] + random_index;
} while (is_sampled_flag.test (pos));
is_sampled_flag.flip (start_index[j] + random_index);
// checking if all points in bin j are sampled..
if (isEntireBinSampled (is_sampled_flag, start_index[j], normals_hg[j].size ()))
{
bin_empty_flag.flip (j);
}
unsigned int index = *(random_access[j][random_index]);
output.points[i] = input_->points[index];
i++;
if (i == sample_)
{
break;
}
}
}
delete start_index;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> bool
pcl::NormalSpaceSampling<PointT, NormalT>::isEntireBinSampled (boost::dynamic_bitset<> &array, unsigned int start_index, unsigned int length)
{
bool status = true;
for (unsigned int i = start_index; i < start_index + length; i++)
{
status = status & array.test (i);
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> unsigned int
pcl::NormalSpaceSampling<PointT, NormalT>::findBin (float *normal, unsigned int nbins)
{
unsigned int bin_number = 0;
// holds the bin numbers for direction cosines in x,y,z directions
unsigned int t[3] = {0,0,0};
// dcos is the direction cosine.
float dcos = 0.0;
float bin_size = 0.0;
// max_cos and min_cos are the maximum and minimum values of cos(theta) respectively
float max_cos = 1.0;
float min_cos = -1.0;
dcos = cos(normal[0]);
bin_size = (max_cos - min_cos) / binsx_;
// finding bin number for direction cosine in x direction
unsigned int k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[0] = k;
dcos = cos(normal[1]);
bin_size = (max_cos - min_cos) / binsy_;
// finding bin number for direction cosine in y direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[1] = k;
dcos = cos(normal[2]);
bin_size = (max_cos - min_cos) / binsz_;
// finding bin number for direction cosine in z direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[2] = k;
bin_number = t[0] * (binsy_*binsz_) + t[1] * binsz_ + t[2];
return bin_number;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT>
void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (std::vector<int> &indices)
{
// If sample size is 0 or if the sample size is greater then input cloud size
// then return all indices
if (sample_ >= input_->width * input_->height)
{
indices = *indices_;
return;
}
// Resize output indices to sample size
indices.resize (sample_);
// allocate memory for the histogram of normals.. Normals will then be sampled from each bin..
unsigned int n_bins = binsx_ * binsy_ * binsz_;
// list<int> holds the indices of points in that bin.. Using list to avoid repeated resizing of vectors.. Helps when the point cloud is
// large..
std::vector< std::list <int> > normals_hg;
normals_hg.reserve (n_bins);
for (unsigned int i = 0; i < n_bins; i++)
normals_hg.push_back (std::list<int> ());
for (unsigned int i=0; i < input_normals_->points.size (); i++)
{
unsigned int bin_number = findBin (input_normals_->points[i].normal, n_bins);
normals_hg[bin_number].push_back (i);
}
// Setting up random access for the list created above.. Maintaining the iterators to individual elements of the list in a vector.. Using
// vector now as the size of the list is known..
std::vector< std::vector <std::list<int>::iterator> > random_access (normals_hg.size ());
for (unsigned int i = 0; i < normals_hg.size (); i++)
{
random_access.push_back (std::vector<std::list<int>::iterator> ());
random_access[i].resize (normals_hg[i].size ());
unsigned int j = 0;
for (std::list<int>::iterator itr = normals_hg[i].begin (); itr != normals_hg[i].end (); itr++, j++)
{
random_access[i][j] = itr;
}
}
unsigned int* start_index = new unsigned int[normals_hg.size ()];
start_index[0] = 0;
unsigned int prev_index = start_index[0];
for (unsigned int i = 1; i < normals_hg.size (); i++)
{
start_index[i] = prev_index + normals_hg[i-1].size ();
prev_index = start_index[i];
}
// maintaining flags to check if a point is sampled
boost::dynamic_bitset<> is_sampled_flag (input_normals_->points.size ());
// maintaining flags to check if all points in the bin are sampled
boost::dynamic_bitset<> bin_empty_flag (normals_hg.size ());
unsigned int i=0;
while (i < sample_)
{
// iterating through every bin and picking one point at random, until the required number of points are sampled..
for (unsigned int j = 0; j < normals_hg.size (); j++)
{
unsigned int M = normals_hg[j].size();
if (M==0 || bin_empty_flag.test (j)) // bin_empty_flag(i) is set if all points in that bin are sampled..
{
continue;
}
unsigned int pos = 0;
unsigned int random_index = 0;
//picking up a sample at random from jth bin
do
{
random_index = std::rand () % M;
pos = start_index[j] + random_index;
} while (is_sampled_flag.test (pos));
is_sampled_flag.flip (start_index[j] + random_index);
// checking if all points in bin j are sampled..
if (isEntireBinSampled (is_sampled_flag, start_index[j], normals_hg[j].size ()))
{
bin_empty_flag.flip (j);
}
unsigned int index = *(random_access[j][random_index]);
indices[i] = index;
i++;
if (i == sample_)
{
break;
}
}
}
delete start_index;
}
#define PCL_INSTANTIATE_NormalSpaceSampling(T,NT) template class PCL_EXPORTS pcl::NormalSpaceSampling<T,NT>;
#endif // PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
<commit_msg>fixed a memory leak<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#define PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
#include "pcl/filters/normal_space.h"
#include <vector>
#include <list>
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (PointCloud &output)
{
// If sample size is 0 or if the sample size is greater then input cloud size
// then return entire copy of cloud
if (sample_ >= input_->size ())
{
output = *input_;
return;
}
// Resize output cloud to sample size
output.points.resize (sample_);
output.width = sample_;
output.height = 1;
// allocate memory for the histogram of normals.. Normals will then be sampled from each bin..
unsigned int n_bins = binsx_ * binsy_ * binsz_;
// list<int> holds the indices of points in that bin.. Using list to avoid repeated resizing of vectors.. Helps when the point cloud is
// large..
std::vector< std::list <int> > normals_hg;
normals_hg.reserve (n_bins);
for (unsigned int i = 0; i < n_bins; i++)
normals_hg.push_back (std::list<int> ());
for (unsigned int i = 0; i < input_normals_->points.size (); i++)
{
unsigned int bin_number = findBin (input_normals_->points[i].normal, n_bins);
normals_hg[bin_number].push_back (i);
}
// Setting up random access for the list created above.. Maintaining the iterators to individual elements of the list in a vector.. Using
// vector now as the size of the list is known..
std::vector< std::vector <std::list<int>::iterator> > random_access (normals_hg.size ());
for (unsigned int i = 0; i < normals_hg.size (); i++)
{
random_access.push_back (std::vector< std::list<int>::iterator> ());
random_access[i].resize (normals_hg[i].size ());
unsigned int j=0;
for (std::list<int>::iterator itr = normals_hg[i].begin (); itr != normals_hg[i].end (); itr++, j++)
{
random_access[i][j] = itr;
}
}
unsigned int* start_index = new unsigned int[normals_hg.size ()];
start_index[0] = 0;
unsigned int prev_index = start_index[0];
for (unsigned int i = 1; i < normals_hg.size (); i++)
{
start_index[i] = prev_index + normals_hg[i-1].size ();
prev_index = start_index[i];
}
// maintaining flags to check if a point is sampled
boost::dynamic_bitset<> is_sampled_flag (input_normals_->points.size ());
// maintaining flags to check if all points in the bin are sampled
boost::dynamic_bitset<> bin_empty_flag (normals_hg.size ());
unsigned int i = 0;
while (i < sample_)
{
// iterating through every bin and picking one point at random, until the required number of points are sampled..
for (unsigned int j = 0; j < normals_hg.size (); j++)
{
unsigned int M = normals_hg[j].size ();
if (M == 0 || bin_empty_flag.test (j))// bin_empty_flag(i) is set if all points in that bin are sampled..
{
continue;
}
unsigned int pos = 0;
unsigned int random_index = 0;
//picking up a sample at random from jth bin
do
{
random_index = std::rand () % M;
pos = start_index[j] + random_index;
} while (is_sampled_flag.test (pos));
is_sampled_flag.flip (start_index[j] + random_index);
// checking if all points in bin j are sampled..
if (isEntireBinSampled (is_sampled_flag, start_index[j], normals_hg[j].size ()))
{
bin_empty_flag.flip (j);
}
unsigned int index = *(random_access[j][random_index]);
output.points[i] = input_->points[index];
i++;
if (i == sample_)
{
break;
}
}
}
delete[] start_index;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> bool
pcl::NormalSpaceSampling<PointT, NormalT>::isEntireBinSampled (boost::dynamic_bitset<> &array, unsigned int start_index, unsigned int length)
{
bool status = true;
for (unsigned int i = start_index; i < start_index + length; i++)
{
status = status & array.test (i);
}
return status;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT> unsigned int
pcl::NormalSpaceSampling<PointT, NormalT>::findBin (float *normal, unsigned int nbins)
{
unsigned int bin_number = 0;
// holds the bin numbers for direction cosines in x,y,z directions
unsigned int t[3] = {0,0,0};
// dcos is the direction cosine.
float dcos = 0.0;
float bin_size = 0.0;
// max_cos and min_cos are the maximum and minimum values of cos(theta) respectively
float max_cos = 1.0;
float min_cos = -1.0;
dcos = cos(normal[0]);
bin_size = (max_cos - min_cos) / binsx_;
// finding bin number for direction cosine in x direction
unsigned int k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[0] = k;
dcos = cos(normal[1]);
bin_size = (max_cos - min_cos) / binsy_;
// finding bin number for direction cosine in y direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[1] = k;
dcos = cos(normal[2]);
bin_size = (max_cos - min_cos) / binsz_;
// finding bin number for direction cosine in z direction
k = 0;
for (float i = min_cos; (i + bin_size) < (max_cos - bin_size); i += bin_size , k++)
{
if (dcos >= i && dcos <= (i+bin_size))
{
break;
}
}
t[2] = k;
bin_number = t[0] * (binsy_*binsz_) + t[1] * binsz_ + t[2];
return bin_number;
}
///////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename NormalT>
void
pcl::NormalSpaceSampling<PointT, NormalT>::applyFilter (std::vector<int> &indices)
{
// If sample size is 0 or if the sample size is greater then input cloud size
// then return all indices
if (sample_ >= input_->width * input_->height)
{
indices = *indices_;
return;
}
// Resize output indices to sample size
indices.resize (sample_);
// allocate memory for the histogram of normals.. Normals will then be sampled from each bin..
unsigned int n_bins = binsx_ * binsy_ * binsz_;
// list<int> holds the indices of points in that bin.. Using list to avoid repeated resizing of vectors.. Helps when the point cloud is
// large..
std::vector< std::list <int> > normals_hg;
normals_hg.reserve (n_bins);
for (unsigned int i = 0; i < n_bins; i++)
normals_hg.push_back (std::list<int> ());
for (unsigned int i=0; i < input_normals_->points.size (); i++)
{
unsigned int bin_number = findBin (input_normals_->points[i].normal, n_bins);
normals_hg[bin_number].push_back (i);
}
// Setting up random access for the list created above.. Maintaining the iterators to individual elements of the list in a vector.. Using
// vector now as the size of the list is known..
std::vector< std::vector <std::list<int>::iterator> > random_access (normals_hg.size ());
for (unsigned int i = 0; i < normals_hg.size (); i++)
{
random_access.push_back (std::vector<std::list<int>::iterator> ());
random_access[i].resize (normals_hg[i].size ());
unsigned int j = 0;
for (std::list<int>::iterator itr = normals_hg[i].begin (); itr != normals_hg[i].end (); itr++, j++)
{
random_access[i][j] = itr;
}
}
unsigned int* start_index = new unsigned int[normals_hg.size ()];
start_index[0] = 0;
unsigned int prev_index = start_index[0];
for (unsigned int i = 1; i < normals_hg.size (); i++)
{
start_index[i] = prev_index + normals_hg[i-1].size ();
prev_index = start_index[i];
}
// maintaining flags to check if a point is sampled
boost::dynamic_bitset<> is_sampled_flag (input_normals_->points.size ());
// maintaining flags to check if all points in the bin are sampled
boost::dynamic_bitset<> bin_empty_flag (normals_hg.size ());
unsigned int i=0;
while (i < sample_)
{
// iterating through every bin and picking one point at random, until the required number of points are sampled..
for (unsigned int j = 0; j < normals_hg.size (); j++)
{
unsigned int M = normals_hg[j].size();
if (M==0 || bin_empty_flag.test (j)) // bin_empty_flag(i) is set if all points in that bin are sampled..
{
continue;
}
unsigned int pos = 0;
unsigned int random_index = 0;
//picking up a sample at random from jth bin
do
{
random_index = std::rand () % M;
pos = start_index[j] + random_index;
} while (is_sampled_flag.test (pos));
is_sampled_flag.flip (start_index[j] + random_index);
// checking if all points in bin j are sampled..
if (isEntireBinSampled (is_sampled_flag, start_index[j], normals_hg[j].size ()))
{
bin_empty_flag.flip (j);
}
unsigned int index = *(random_access[j][random_index]);
indices[i] = index;
i++;
if (i == sample_)
{
break;
}
}
}
delete[] start_index;
}
#define PCL_INSTANTIATE_NormalSpaceSampling(T,NT) template class PCL_EXPORTS pcl::NormalSpaceSampling<T,NT>;
#endif // PCL_FILTERS_IMPL_NORMAL_SPACE_SAMPLE_H_
<|endoftext|>
|
<commit_before>#include <Arduino.h>
#include <Wire.h>
#include <EEPROM.h>
#include <CmdMessenger.h>
#include <Adafruit_PWMServoDriver.h>
#define SWITCH_TELE1 2
#define SWITCH_TELE2 3
#define SWITCH_TELE3 4
#define OE_PIN 5
uint8_t positions[16] = {0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255};
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
CmdMessenger cmdMessenger = CmdMessenger(Serial, ',', ';');
enum{
kAcknowledge, // 0
kError, // 1
kSetServo, // 2
kStoreServo, // 3
kButtonPressed, // 4
kServoPosition // 5
};
void storePositions(){
for(uint8_t i = 0; i < sizeof(positions); i++){
EEPROM.write(i, positions[i]);
}
}
void loadPositions(){
for(uint8_t i = 0; i < sizeof(positions); i++){
positions[i] = EEPROM.read(i);
}
}
void OnUnknownCommand(){
cmdMessenger.sendCmd(kError,"Command without attached callback");
}
void OnSetServo(){
}
void OnStoreServo(){
}
void OnButtonPressed(){
}
void OnServoPosition(){
}
void attachCommandCallbacks(){
cmdMessenger.attach(OnUnknownCommand);
cmdMessenger.attach(OnSetServo);
cmdMessenger.attach(OnStoreServo);
cmdMessenger.attach(OnButtonPressed);
cmdMessenger.attach(OnServoPosition);
}
void setup() {
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(SWITCH_TELE1, INPUT_PULLUP);
loadPositions();
Serial.begin(9600);
cmdMessenger.printLfCr(true);
attachCommandCallbacks();
cmdMessenger.sendCmd(kAcknowledge, "Arduino ready!");
}
void loop() {
cmdMessenger.feedinSerialData();
if(!digitalRead(SWITCH_TELE1)){
}
if(!digitalRead(SWITCH_TELE2)){
}
if(!digitalRead(SWITCH_TELE3)){
}
}
<commit_msg>Storing and reading positions in eeprom<commit_after>#include <Arduino.h>
#include <Wire.h>
#include <EEPROM.h>
#include <CmdMessenger.h>
#include <Adafruit_PWMServoDriver.h>
#define NUM_SERVOS 8
#define SWITCH_TELE1 2
#define SWITCH_TELE2 3
#define SWITCH_TELE3 4
#define OE_PIN 5
uint16_t positionsMin[NUM_SERVOS] = {};
uint16_t positionsMax[NUM_SERVOS] = {};
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
CmdMessenger cmdMessenger = CmdMessenger(Serial, ',', ';');
enum{
kAcknowledge, // 0
kError, // 1
kSetServo, // 2
kStoreServo, // 3
kButtonPressed, // 4
kServoPosition // 5
};
void storePositions(){
uint8_t ee = 0;
uint8_t* p = (uint8_t*)(void*)&positionsMin;
for (uint8_t i = 0; i < sizeof(positionsMin); i++){
EEPROM.write(ee++, *p++);
}
ee = 100;
p = (uint8_t*)(void*)&positionsMax;
for (uint8_t i = 0; i < sizeof(positionsMax); i++){
EEPROM.write(ee++, *p++);
}
}
void loadPositions(){
uint8_t ee = 0;
uint8_t* p = (uint8_t*)(void*)&positionsMin;
for (uint8_t i = 0; i < sizeof(positionsMin); i++){
*p++ = EEPROM.read(ee++);
}
ee = 100;
p = (uint8_t*)(void*)&positionsMax;
for (uint8_t i = 0; i < sizeof(positionsMax); i++){
*p++ = EEPROM.read(ee++);
}
}
void OnUnknownCommand(){
cmdMessenger.sendCmd(kError,"Command without attached callback");
}
void OnSetServo(){
}
void OnStoreServo(){
}
void OnButtonPressed(){
}
void OnServoPosition(){
}
void attachCommandCallbacks(){
cmdMessenger.attach(OnUnknownCommand);
cmdMessenger.attach(OnSetServo);
cmdMessenger.attach(OnStoreServo);
cmdMessenger.attach(OnButtonPressed);
cmdMessenger.attach(OnServoPosition);
}
void setup() {
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(OE_PIN , OUTPUT);
digitalWrite(OE_PIN, LOW); // Enable
Serial.begin(9600);
cmdMessenger.printLfCr(true);
attachCommandCallbacks();
cmdMessenger.sendCmd(kAcknowledge, "Arduino ready!");
loadPositions();
}
void loop() {
cmdMessenger.feedinSerialData();
if(!digitalRead(SWITCH_TELE1)){
}
if(!digitalRead(SWITCH_TELE2)){
}
if(!digitalRead(SWITCH_TELE3)){
}
}
<|endoftext|>
|
<commit_before>#ifndef COORDINATOR_HPP
#define COORDINATOR_HPP
#include <QObject>
#include <vector>
#include <memory>
#include <common/module.hpp>
#include <common/datastructures/MotorCommand.hpp>
typedef std::vector< std::shared_ptr<Module> > module_list_t;
class Coordinator : public QObject {
Q_OBJECT
public:
virtual const module_list_t& getModules() = 0;
virtual std::shared_ptr<Module> getModuleWithName(std::string name) = 0;
virtual ~Coordinator() { }
signals:
void newMotorCommand(MotorCommand cmd);
void finished();
public slots:
virtual void changeLidar(std::shared_ptr<Module>) { }
virtual void changeGPS(std::shared_ptr<Module>) { }
};
#endif // COORDINATOR_HPP
<commit_msg>Adds run, pause, stop slots to Coordinator.<commit_after>#ifndef COORDINATOR_HPP
#define COORDINATOR_HPP
#include <QObject>
#include <vector>
#include <memory>
#include <common/module.hpp>
#include <common/datastructures/MotorCommand.hpp>
typedef std::vector< std::shared_ptr<Module> > module_list_t;
class Coordinator : public QObject {
Q_OBJECT
public:
virtual const module_list_t& getModules() = 0;
virtual std::shared_ptr<Module> getModuleWithName(std::string name) = 0;
virtual ~Coordinator() { }
signals:
void newMotorCommand(MotorCommand cmd);
void finished();
public slots:
virtual void changeLidar(std::shared_ptr<Module>) { }
virtual void changeGPS(std::shared_ptr<Module>) { }
virtual void run() { }
virtual void pause() { }
virtual void stop() { }
};
#endif // COORDINATOR_HPP
<|endoftext|>
|
<commit_before><commit_msg>Perception: code style refinement of rt_common<commit_after><|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* result.cxx
*
* DESCRIPTION
* implementation of the pqxx::result class and support classes.
* pqxx::result represents the set of result tuples from a database query
*
* Copyright (c) 2001-2007, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-internal.hxx"
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/except"
#include "pqxx/result"
using namespace PGSTD;
const string pqxx::result::s_empty_string;
pqxx::internal::result_data::result_data() : data(0), protocol(0), query() {}
pqxx::internal::result_data::result_data(pqxx::internal::pq::PGresult *d,
int p,
const string &q) :
data(d),
protocol(p),
query(q)
{}
pqxx::internal::result_data::~result_data() { PQclear(data); }
void pqxx::internal::freemem_result_data(result_data *d) throw () { delete d; }
pqxx::result::result(pqxx::internal::pq::PGresult *rhs,
int protocol,
const string &Query) :
super(new internal::result_data(rhs, protocol, Query)),
m_data(rhs)
{}
bool pqxx::result::operator==(const result &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
for (size_type i=0; i<s; ++i)
if ((*this)[i] != rhs[i]) return false;
return true;
}
bool pqxx::result::tuple::operator==(const tuple &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
// TODO: Depends on how null is handled!
for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false;
return true;
}
void pqxx::result::tuple::swap(tuple &rhs) throw ()
{
const result *const h(m_Home);
const result::size_type i(m_Index);
m_Home = rhs.m_Home;
m_Index = rhs.m_Index;
rhs.m_Home = h;
rhs.m_Index = i;
}
bool pqxx::result::field::operator==(const field &rhs) const
{
if (is_null() != rhs.is_null()) return false;
// TODO: Verify null handling decision
const size_type s = size();
if (s != rhs.size()) return false;
const char *const l(c_str()), *const r(rhs.c_str());
for (size_type i = 0; i < s; ++i) if (l[i] != r[i]) return false;
return true;
}
pqxx::result::size_type pqxx::result::size() const throw ()
{
return m_data ? PQntuples(m_data) : 0;
}
bool pqxx::result::empty() const throw ()
{
return !m_data || !PQntuples(m_data);
}
void pqxx::result::swap(result &rhs) throw ()
{
super::swap(rhs);
m_data = (c_ptr() ? c_ptr()->data : 0);
rhs.m_data = (rhs.c_ptr() ? rhs.c_ptr()->data : 0);
}
const pqxx::result::tuple pqxx::result::at(pqxx::result::size_type i) const
throw (out_of_range)
{
if (i >= size())
throw out_of_range("Tuple number out of range");
return operator[](i);
}
void pqxx::result::ThrowSQLError(const PGSTD::string &Err,
const PGSTD::string &Query) const
{
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
// Try to establish more precise error type, and throw corresponding exception
const char *const code = PQresultErrorField(m_data, PG_DIAG_SQLSTATE);
if (code) switch (code[0])
{
case '0':
switch (code[1])
{
case '8':
throw broken_connection(Err);
case 'A':
throw feature_not_supported(Err, Query);
}
break;
case '2':
switch (code[1])
{
case '2':
throw data_exception(Err, Query);
case '3':
throw integrity_constraint_violation(Err, Query);
case '4':
throw invalid_cursor_state(Err, Query);
case '6':
throw invalid_sql_statement_name(Err, Query);
}
break;
case '3':
switch (code[1])
{
case '4':
throw invalid_cursor_name(Err, Query);
}
break;
case '4':
switch (code[1])
{
case '2':
if (strcmp(code,"42501")==0) throw insufficient_privilege(Err, Query);
if (strcmp(code,"42601")==0) throw syntax_error(Err, Query);
if (strcmp(code,"42703")==0) throw undefined_column(Err, Query);
if (strcmp(code,"42883")==0) throw undefined_function(Err, Query);
if (strcmp(code,"42P01")==0) throw undefined_table(Err, Query);
}
break;
case '5':
switch (code[1])
{
case '3':
if (strcmp(code,"53100")==0) throw disk_full(Err, Query);
if (strcmp(code,"53200")==0) throw out_of_memory(Err, Query);
if (strcmp(code,"53300")==0) throw too_many_connections(Err);
throw insufficient_resources(Err, Query);
}
break;
}
#endif
throw sql_error(Err, Query);
}
void pqxx::result::CheckStatus() const
{
const string Err = StatusError();
if (!Err.empty()) ThrowSQLError(Err, query());
}
string pqxx::result::StatusError() const
{
if (!m_data)
throw runtime_error("No result set given");
string Err;
switch (PQresultStatus(m_data))
{
case PGRES_EMPTY_QUERY: // The string sent to the backend was empty.
case PGRES_COMMAND_OK: // Successful completion of a command returning no data
case PGRES_TUPLES_OK: // The query successfully executed
break;
case PGRES_COPY_OUT: // Copy Out (from server) data transfer started
case PGRES_COPY_IN: // Copy In (to server) data transfer started
break;
case PGRES_BAD_RESPONSE: // The server's response was not understood
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
Err = PQresultErrorMessage(m_data);
break;
default:
throw internal_error("pqxx::result: Unrecognized response code " +
to_string(int(PQresultStatus(m_data))));
}
return Err;
}
const char *pqxx::result::CmdStatus() const throw ()
{
return PQcmdStatus(m_data);
}
const string &pqxx::result::query() const throw ()
{
return c_ptr() ? c_ptr()->query : s_empty_string;
}
pqxx::oid pqxx::result::inserted_oid() const
{
if (!m_data)
throw logic_error("Attempt to read oid of inserted row without an INSERT "
"result");
return PQoidValue(m_data);
}
pqxx::result::size_type pqxx::result::affected_rows() const
{
const char *const RowsStr = PQcmdTuples(m_data);
return RowsStr[0] ? atoi(RowsStr) : 0;
}
const char *pqxx::result::GetValue(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetvalue(m_data, Row, Col);
}
bool pqxx::result::GetIsNull(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetisnull(m_data, Row, Col) != 0;
}
pqxx::result::field::size_type
pqxx::result::GetLength(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetlength(m_data, Row, Col);
}
pqxx::oid pqxx::result::column_type(tuple::size_type ColNum) const
{
const oid T = PQftype(m_data, ColNum);
if (T == oid_none)
throw PGSTD::invalid_argument(
"Attempt to retrieve type of nonexistant column " +
to_string(ColNum) + " of query result");
return T;
}
#ifdef PQXX_HAVE_PQFTABLE
pqxx::oid pqxx::result::column_table(tuple::size_type ColNum) const
{
const oid T = PQftable(m_data, ColNum);
/* If we get oid_none, it may be because the column is computed, or because we
* got an invalid row number.
*/
if (T == oid_none && ColNum >= columns())
throw PGSTD::invalid_argument("Attempt to retrieve table ID for column " +
to_string(ColNum) + " out of " + to_string(columns()));
return T;
}
#endif
#ifdef PQXX_HAVE_PQFTABLECOL
pqxx::result::tuple::size_type
pqxx::result::table_column(tuple::size_type ColNum) const
{
const tuple::size_type n = PQftablecol(m_data, ColNum);
if (n) return n-1;
// Failed. Now find out why, so we can throw a sensible exception.
// Possible reasons:
// 1. Column out of range
// 2. Not using protocol 3.0 or better
// 3. Column not taken directly from a table
if (ColNum > columns())
throw out_of_range("Invalid column index in table_column(): " +
to_string(ColNum));
if (!c_ptr() || c_ptr()->protocol < 3)
throw feature_not_supported("Backend version does not support querying of "
"column's original number",
"[TABLE_COLUMN]");
throw logic_error("Can't query origin of column " + to_string(ColNum) + ": "
"not derived from table column");
}
#endif
int pqxx::result::errorposition() const throw ()
{
int pos = -1;
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
if (m_data)
{
const char *p = PQresultErrorField(m_data, PG_DIAG_STATEMENT_POSITION);
if (p) from_string(p, pos);
}
#endif // PQXX_HAVE_PQRESULTERRORFIELD
return pos;
}
// tuple
pqxx::result::field pqxx::result::tuple::operator[](const char f[]) const
{
return field(*this, m_Home->column_number(f));
}
pqxx::result::field pqxx::result::tuple::at(const char f[]) const
{
const int fnum = m_Home->column_number(f);
// TODO: Should this be an out_of_range?
if (fnum == -1)
throw invalid_argument(string("Unknown field '") + f + "'");
return field(*this, fnum);
}
pqxx::result::field
pqxx::result::tuple::at(pqxx::result::tuple::size_type i) const throw (out_of_range)
{
if (i >= size())
throw out_of_range("Invalid field number");
return operator[](i);
}
const char *
pqxx::result::column_name(pqxx::result::tuple::size_type Number) const
{
const char *const N = PQfname(m_data, Number);
if (!N)
throw out_of_range("Invalid column number: " + to_string(Number));
return N;
}
pqxx::result::tuple::size_type pqxx::result::columns() const throw ()
{
return m_data ? PQnfields(m_data) : 0;
}
pqxx::result::tuple::size_type
pqxx::result::column_number(const char ColName[]) const
{
const int N = PQfnumber(m_data, ColName);
// TODO: Should this be an out_of_range?
if (N == -1)
throw invalid_argument("Unknown column name: '" + string(ColName) + "'");
return tuple::size_type(N);
}
// const_iterator
pqxx::result::const_iterator
pqxx::result::const_iterator::operator++(int)
{
const_iterator old(*this);
m_Index++;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_iterator::operator--(int)
{
const_iterator old(*this);
m_Index--;
return old;
}
// const_fielditerator
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator++(int)
{
const_fielditerator old(*this);
m_col++;
return old;
}
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator--(int)
{
const_fielditerator old(*this);
m_col--;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_reverse_iterator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator++(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator--();
return tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator--(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator++();
return tmp;
}
pqxx::result::const_fielditerator
pqxx::result::const_reverse_fielditerator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator++(int)
{
const_reverse_fielditerator tmp(*this);
operator++();
return tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator--(int)
{
const_reverse_fielditerator tmp(*this);
operator--();
return tmp;
}
<commit_msg>Hopefully silence some Doxygen warnings<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* result.cxx
*
* DESCRIPTION
* implementation of the pqxx::result class and support classes.
* pqxx::result represents the set of result tuples from a database query
*
* Copyright (c) 2001-2007, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-internal.hxx"
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/except"
#include "pqxx/result"
using namespace PGSTD;
const string pqxx::result::s_empty_string;
pqxx::internal::result_data::result_data() : data(0), protocol(0), query() {}
pqxx::internal::result_data::result_data(pqxx::internal::pq::PGresult *d,
int p,
const PGSTD::string &q) :
data(d),
protocol(p),
query(q)
{}
pqxx::internal::result_data::~result_data() { PQclear(data); }
void pqxx::internal::freemem_result_data(result_data *d) throw () { delete d; }
pqxx::result::result(pqxx::internal::pq::PGresult *rhs,
int protocol,
const PGSTD::string &Query) :
super(new internal::result_data(rhs, protocol, Query)),
m_data(rhs)
{}
bool pqxx::result::operator==(const result &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
for (size_type i=0; i<s; ++i)
if ((*this)[i] != rhs[i]) return false;
return true;
}
bool pqxx::result::tuple::operator==(const tuple &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
// TODO: Depends on how null is handled!
for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false;
return true;
}
void pqxx::result::tuple::swap(tuple &rhs) throw ()
{
const result *const h(m_Home);
const result::size_type i(m_Index);
m_Home = rhs.m_Home;
m_Index = rhs.m_Index;
rhs.m_Home = h;
rhs.m_Index = i;
}
bool pqxx::result::field::operator==(const field &rhs) const
{
if (is_null() != rhs.is_null()) return false;
// TODO: Verify null handling decision
const size_type s = size();
if (s != rhs.size()) return false;
const char *const l(c_str()), *const r(rhs.c_str());
for (size_type i = 0; i < s; ++i) if (l[i] != r[i]) return false;
return true;
}
pqxx::result::size_type pqxx::result::size() const throw ()
{
return m_data ? PQntuples(m_data) : 0;
}
bool pqxx::result::empty() const throw ()
{
return !m_data || !PQntuples(m_data);
}
void pqxx::result::swap(result &rhs) throw ()
{
super::swap(rhs);
m_data = (c_ptr() ? c_ptr()->data : 0);
rhs.m_data = (rhs.c_ptr() ? rhs.c_ptr()->data : 0);
}
const pqxx::result::tuple pqxx::result::at(pqxx::result::size_type i) const
throw (out_of_range)
{
if (i >= size())
throw out_of_range("Tuple number out of range");
return operator[](i);
}
void pqxx::result::ThrowSQLError(const PGSTD::string &Err,
const PGSTD::string &Query) const
{
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
// Try to establish more precise error type, and throw corresponding exception
const char *const code = PQresultErrorField(m_data, PG_DIAG_SQLSTATE);
if (code) switch (code[0])
{
case '0':
switch (code[1])
{
case '8':
throw broken_connection(Err);
case 'A':
throw feature_not_supported(Err, Query);
}
break;
case '2':
switch (code[1])
{
case '2':
throw data_exception(Err, Query);
case '3':
throw integrity_constraint_violation(Err, Query);
case '4':
throw invalid_cursor_state(Err, Query);
case '6':
throw invalid_sql_statement_name(Err, Query);
}
break;
case '3':
switch (code[1])
{
case '4':
throw invalid_cursor_name(Err, Query);
}
break;
case '4':
switch (code[1])
{
case '2':
if (strcmp(code,"42501")==0) throw insufficient_privilege(Err, Query);
if (strcmp(code,"42601")==0) throw syntax_error(Err, Query);
if (strcmp(code,"42703")==0) throw undefined_column(Err, Query);
if (strcmp(code,"42883")==0) throw undefined_function(Err, Query);
if (strcmp(code,"42P01")==0) throw undefined_table(Err, Query);
}
break;
case '5':
switch (code[1])
{
case '3':
if (strcmp(code,"53100")==0) throw disk_full(Err, Query);
if (strcmp(code,"53200")==0) throw out_of_memory(Err, Query);
if (strcmp(code,"53300")==0) throw too_many_connections(Err);
throw insufficient_resources(Err, Query);
}
break;
}
#endif
throw sql_error(Err, Query);
}
void pqxx::result::CheckStatus() const
{
const string Err = StatusError();
if (!Err.empty()) ThrowSQLError(Err, query());
}
string pqxx::result::StatusError() const
{
if (!m_data)
throw runtime_error("No result set given");
string Err;
switch (PQresultStatus(m_data))
{
case PGRES_EMPTY_QUERY: // The string sent to the backend was empty.
case PGRES_COMMAND_OK: // Successful completion of a command returning no data
case PGRES_TUPLES_OK: // The query successfully executed
break;
case PGRES_COPY_OUT: // Copy Out (from server) data transfer started
case PGRES_COPY_IN: // Copy In (to server) data transfer started
break;
case PGRES_BAD_RESPONSE: // The server's response was not understood
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
Err = PQresultErrorMessage(m_data);
break;
default:
throw internal_error("pqxx::result: Unrecognized response code " +
to_string(int(PQresultStatus(m_data))));
}
return Err;
}
const char *pqxx::result::CmdStatus() const throw ()
{
return PQcmdStatus(m_data);
}
const string &pqxx::result::query() const throw ()
{
return c_ptr() ? c_ptr()->query : s_empty_string;
}
pqxx::oid pqxx::result::inserted_oid() const
{
if (!m_data)
throw logic_error("Attempt to read oid of inserted row without an INSERT "
"result");
return PQoidValue(m_data);
}
pqxx::result::size_type pqxx::result::affected_rows() const
{
const char *const RowsStr = PQcmdTuples(m_data);
return RowsStr[0] ? atoi(RowsStr) : 0;
}
const char *pqxx::result::GetValue(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetvalue(m_data, Row, Col);
}
bool pqxx::result::GetIsNull(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetisnull(m_data, Row, Col) != 0;
}
pqxx::result::field::size_type
pqxx::result::GetLength(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetlength(m_data, Row, Col);
}
pqxx::oid pqxx::result::column_type(tuple::size_type ColNum) const
{
const oid T = PQftype(m_data, ColNum);
if (T == oid_none)
throw PGSTD::invalid_argument(
"Attempt to retrieve type of nonexistant column " +
to_string(ColNum) + " of query result");
return T;
}
#ifdef PQXX_HAVE_PQFTABLE
pqxx::oid pqxx::result::column_table(tuple::size_type ColNum) const
{
const oid T = PQftable(m_data, ColNum);
/* If we get oid_none, it may be because the column is computed, or because we
* got an invalid row number.
*/
if (T == oid_none && ColNum >= columns())
throw PGSTD::invalid_argument("Attempt to retrieve table ID for column " +
to_string(ColNum) + " out of " + to_string(columns()));
return T;
}
#endif
#ifdef PQXX_HAVE_PQFTABLECOL
pqxx::result::tuple::size_type
pqxx::result::table_column(tuple::size_type ColNum) const
{
const tuple::size_type n = PQftablecol(m_data, ColNum);
if (n) return n-1;
// Failed. Now find out why, so we can throw a sensible exception.
// Possible reasons:
// 1. Column out of range
// 2. Not using protocol 3.0 or better
// 3. Column not taken directly from a table
if (ColNum > columns())
throw out_of_range("Invalid column index in table_column(): " +
to_string(ColNum));
if (!c_ptr() || c_ptr()->protocol < 3)
throw feature_not_supported("Backend version does not support querying of "
"column's original number",
"[TABLE_COLUMN]");
throw logic_error("Can't query origin of column " + to_string(ColNum) + ": "
"not derived from table column");
}
#endif
int pqxx::result::errorposition() const throw ()
{
int pos = -1;
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
if (m_data)
{
const char *p = PQresultErrorField(m_data, PG_DIAG_STATEMENT_POSITION);
if (p) from_string(p, pos);
}
#endif // PQXX_HAVE_PQRESULTERRORFIELD
return pos;
}
// tuple
pqxx::result::field pqxx::result::tuple::operator[](const char f[]) const
{
return field(*this, m_Home->column_number(f));
}
pqxx::result::field pqxx::result::tuple::at(const char f[]) const
{
const int fnum = m_Home->column_number(f);
// TODO: Should this be an out_of_range?
if (fnum == -1)
throw invalid_argument(string("Unknown field '") + f + "'");
return field(*this, fnum);
}
pqxx::result::field
pqxx::result::tuple::at(pqxx::result::tuple::size_type i) const throw (out_of_range)
{
if (i >= size())
throw out_of_range("Invalid field number");
return operator[](i);
}
const char *
pqxx::result::column_name(pqxx::result::tuple::size_type Number) const
{
const char *const N = PQfname(m_data, Number);
if (!N)
throw out_of_range("Invalid column number: " + to_string(Number));
return N;
}
pqxx::result::tuple::size_type pqxx::result::columns() const throw ()
{
return m_data ? PQnfields(m_data) : 0;
}
pqxx::result::tuple::size_type
pqxx::result::column_number(const char ColName[]) const
{
const int N = PQfnumber(m_data, ColName);
// TODO: Should this be an out_of_range?
if (N == -1)
throw invalid_argument("Unknown column name: '" + string(ColName) + "'");
return tuple::size_type(N);
}
// const_iterator
pqxx::result::const_iterator
pqxx::result::const_iterator::operator++(int)
{
const_iterator old(*this);
m_Index++;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_iterator::operator--(int)
{
const_iterator old(*this);
m_Index--;
return old;
}
// const_fielditerator
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator++(int)
{
const_fielditerator old(*this);
m_col++;
return old;
}
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator--(int)
{
const_fielditerator old(*this);
m_col--;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_reverse_iterator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator++(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator--();
return tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator--(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator++();
return tmp;
}
pqxx::result::const_fielditerator
pqxx::result::const_reverse_fielditerator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator++(int)
{
const_reverse_fielditerator tmp(*this);
operator++();
return tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator--(int)
{
const_reverse_fielditerator tmp(*this);
operator--();
return tmp;
}
<|endoftext|>
|
<commit_before>// AWSUtilTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../AWSUtil/Auth.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include "../AWSUtil/hmac/hmac_sha2.h"
void GetS3Object(const std::string &sBucketName, const std::string &sRegionName, const std::string &awsAccessKey, const std::string &awsSecretKey)
{
printf("*******************************************************\n");
printf("* Executing sample 'GetObjectUsingHostedAddressing' *\n");
printf("*******************************************************\n");
// the region-specific endpoint to the target object expressed in path style
std::string sEndpointUrl = "https://" + sBucketName + ".s3.amazonaws.com/ExampleObject.txt";
// for a simple GET, we have no body so supply the precomputed 'empty' hash
std::map<std::string, std::string> Headers;
Headers["x-amz-content-sha256"] = AWS::Auth::AWS4SignerBase::EmptyBodySHA256();
std::map<std::string, std::string> QueryParameters;
AWS::Auth::AWS4SignerForAuthorizationHeader Signer(sEndpointUrl, "GET", "s3", sRegionName);
std::string authorization = Signer.ComputeSignature(Headers,
QueryParameters,
AWS::Auth::AWS4SignerBase::EmptyBodySHA256(),
awsAccessKey,
awsSecretKey);
// place the computed signature into a formatted 'Authorization' header
// and call S3
Headers["Authorization"] = authorization;
//String response = HttpUtils.invokeHttpRequest(endpointUrl, "GET", headers, null);
printf("--------- Response content ---------\n");
//printf("%s\n", response.c_str());
printf("------------------------------------\n");
}
int main()
{
GetS3Object("bucket", "us-west-2", "chris", "tapley");
return 0;
}
<commit_msg>run get<commit_after>// AWSUtilTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../AWSUtil/Auth.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <curl/curl.h>
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
printf("%s\n", static_cast<char*>(contents));
return nmemb;
}
void GetS3Object(const std::string &sBucketName, const std::string &sFileKey, const std::string &sRegionName, const std::string &awsAccessKey, const std::string &awsSecretKey)
{
printf("*******************************************************\n");
printf("* Executing sample 'GetObjectUsingHostedAddressing' *\n");
printf("*******************************************************\n");
// the region-specific endpoint to the target object expressed in path style
std::string sEndpointUrl = "http://" + sBucketName + ".s3.amazonaws.com/" + sFileKey;
// for a simple GET, we have no body so supply the precomputed 'empty' hash
std::map<std::string, std::string> Headers;
Headers["x-amz-content-sha256"] = AWS::Auth::AWS4SignerBase::EmptyBodySHA256();
Headers["Accept"] = "*/*";
std::map<std::string, std::string> QueryParameters;
AWS::Auth::AWS4SignerForAuthorizationHeader Signer(sEndpointUrl, "GET", "s3", sRegionName);
std::string authorization = Signer.ComputeSignature(Headers,
QueryParameters,
AWS::Auth::AWS4SignerBase::EmptyBodySHA256(),
awsAccessKey,
awsSecretKey);
// place the computed signature into a formatted 'Authorization' header
// and call S3
Headers["Authorization"] = authorization;
CURL *curl_handle;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, sEndpointUrl.c_str());
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
struct curl_slist *headerlist = NULL;
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
std::list<std::string> HeadersList;
for (auto it = Headers.cbegin(); it != Headers.cend(); ++it) {
HeadersList.push_back(it->first + ": " + it->second);
}
for (auto it = HeadersList.cbegin(); it != HeadersList.cend(); ++it) {
headerlist = curl_slist_append(headerlist, it->c_str());
}
res = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headerlist);
printf("--------- Response content ---------\n");
res = curl_easy_perform(curl_handle);
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
printf("------------------------------------\n");
curl_easy_cleanup(curl_handle);
}
int main(int argc, char **argv)
{
if (argc != 6) {
printf("%s key secret region bucket filekey\n", argv[0]);
return 1;
}
std::string sKey = argv[1];
std::string sSecret = argv[2];
std::string sRegion = argv[3];
std::string sBucket = argv[4];
std::string sFileKey = argv[5];
GetS3Object(sBucket, sFileKey, sRegion, sKey, sSecret);
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
template <typename Result, typename... Arguments>
class BaseSlot
{
public:
virtual Result operator()(Arguments...) = 0;
};
template <typename T, typename Result, typename... Arguments>
class Slot: public BaseSlot<Result, Arguments...>
{
public:
typedef Result (T::*Method)(Arguments...);
Slot(T *object, Method method):
object_(object),
method_(method)
{}
virtual Result operator()(Arguments... arguments)
{
return (object_->*method_)(arguments...);
}
private:
T *object_;
Method method_;
};
template <typename Result, typename... Arguments>
class Signal
{
public:
Signal():
slot_(nullptr)
{}
~Signal()
{
delete slot_;
}
Result operator()(Arguments... arguments)
{
if (slot_)
return slot_->operator()(arguments...);
return Result();
}
template <typename T>
void connect(T *object, Result (T::*method)(Arguments...))
{
delete slot_;
slot_ = new Slot<T, Result, Arguments...>(object, method);
};
void disconnect()
{
delete slot_;
slot_ = nullptr;
}
private:
BaseSlot<Result, Arguments...> *slot_;
};
template <typename T, typename Result, typename... Arguments>
void connect(Signal<Result, Arguments...> &signal, T *object, Result (T::*method)(Arguments...))
{
signal.connect(object, method);
}
template <typename Result, typename... Arguments>
void disconnect(Signal<Result, Arguments...> &signal)
{
signal.disconnect();
}
template <typename T>
struct RemovePointer;
template <typename T>
struct RemovePointer<T *>
{
typedef T type;
};
#define SIGNAL(o, s) (o)->s
#define SLOT(o, s) (o), &RemovePointer<decltype(o)>::type::s
<commit_msg>make Mac OS X compiler happy<commit_after>#pragma once
template <typename Result, typename... Arguments>
class BaseSlot
{
public:
virtual ~BaseSlot() {}
virtual Result operator()(Arguments...) = 0;
};
template <typename T, typename Result, typename... Arguments>
class Slot: public BaseSlot<Result, Arguments...>
{
public:
typedef Result (T::*Method)(Arguments...);
Slot(T *object, Method method):
object_(object),
method_(method)
{}
virtual Result operator()(Arguments... arguments)
{
return (object_->*method_)(arguments...);
}
private:
T *object_;
Method method_;
};
template <typename Result, typename... Arguments>
class Signal
{
public:
Signal():
slot_(nullptr)
{}
~Signal()
{
delete slot_;
}
Result operator()(Arguments... arguments)
{
if (slot_)
return slot_->operator()(arguments...);
return Result();
}
template <typename T>
void connect(T *object, Result (T::*method)(Arguments...))
{
delete slot_;
slot_ = new Slot<T, Result, Arguments...>(object, method);
};
void disconnect()
{
delete slot_;
slot_ = nullptr;
}
private:
BaseSlot<Result, Arguments...> *slot_;
};
template <typename T, typename Result, typename... Arguments>
void connect(Signal<Result, Arguments...> &signal, T *object, Result (T::*method)(Arguments...))
{
signal.connect(object, method);
}
template <typename Result, typename... Arguments>
void disconnect(Signal<Result, Arguments...> &signal)
{
signal.disconnect();
}
template <typename T>
struct RemovePointer;
template <typename T>
struct RemovePointer<T *>
{
typedef T type;
};
#define SIGNAL(o, s) (o)->s
#define SLOT(o, s) (o), &RemovePointer<decltype(o)>::type::s
<|endoftext|>
|
<commit_before>#include <memory>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include <utility>
#include "s_rules.hh"
#include "s_closure.hh"
#include "cons_util.hh"
#include "env.hh"
#include "zs_error.hh"
#include "builtin_extra.hh"
#include "printer.hh"
#include "equality.hh"
#include "eval.hh"
using namespace std;
namespace {
// internal types
typedef std::unordered_map<Lisp_ptr, Lisp_ptr, eq_hash_obj, eq_obj> EqHashMap;
typedef std::unordered_set<Lisp_ptr, eq_hash_obj, eq_obj> MatchSet;
typedef std::unordered_set<Lisp_ptr, eq_id_hash_obj, eq_id_obj> ExpandSet;
// error classes
struct try_match_failed{};
struct expand_failed {};
bool is_literal_identifier(const SyntaxRules& sr, Lisp_ptr p){
for(auto l : sr.literals()){
if(eq_internal(l, p)){
return true;
}
}
return false;
}
bool is_ellipsis(Lisp_ptr p){
if(!identifierp(p)) return false;
auto sym = identifier_symbol(p);
return sym->name() == "...";
}
void push_tail_cons_list_nl(Lisp_ptr p, Lisp_ptr value){
if(p.tag() != Ptr_tag::cons)
throw zs_error(printf_string("internal %s: the passed list is a dotted list!\n", __func__));
auto c = p.get<Cons*>();
if(!c)
throw zs_error(printf_string("internal %s: the passed list is an empty list!\n", __func__));
if(nullp(c->cdr())){
c->rplacd(make_cons_list({value}));
}else{
push_tail_cons_list_nl(c->cdr(), value);
}
}
void push_tail_cons_list(Lisp_ptr* p, Lisp_ptr value){
if(nullp(*p)){
*p = make_cons_list({value});
}else{
push_tail_cons_list_nl(*p, value);
}
}
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw zs_error_arg1("syntax-rules", "the pattern is empty list");
return c->car();
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw zs_error_arg1("syntax-rules", "the pattern is empty vector");
return (*v)[0];
}else{
throw zs_error_arg1("syntax-rules", "informal pattern passed!", {p});
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p, MatchSet tab){
if(identifierp(p)){
if(is_literal_identifier(sr, p)){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw zs_error_arg1("syntax-rules", "duplicated pattern variable!", {p});
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
template<typename DefaultGen>
void ensure_binding(EqHashMap& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
const DefaultGen& default_gen_func){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
return; // literal identifier
}
// non-literal identifier
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, default_gen_func()});
}
return;
}else if(pattern.tag() == Ptr_tag::cons){
if(nullp(pattern)){
return;
}
auto p_i = begin(pattern);
for(; p_i; ++p_i){
// checks ellipsis
if(is_ellipsis(*p_i)){
return;
}
ensure_binding(match_obj, sr, ignore_ident, *p_i, default_gen_func);
}
if(!nullp(p_i.base())){
// dotted list case
ensure_binding(match_obj, sr, ignore_ident, p_i.base(), default_gen_func);
}
}else if(pattern.tag() == Ptr_tag::vector){
auto p_v = pattern.get<Vector*>();
for(auto p : *p_v){
ensure_binding(match_obj, sr, ignore_ident, p, default_gen_func);
}
}else{
return;
}
}
template<typename Iter, typename Fun1, typename Fun2>
EqHashMap
try_match_1_seq(const SyntaxRules& sr, Lisp_ptr ignore_ident,
Iter pattern_begin, Iter pattern_end,
Env* form_env,
Iter form_begin, Iter form_end,
Fun1 dotted_checker,
Fun2 dotted_handler){
EqHashMap match_obj;
auto p_i = pattern_begin;
auto f_i = form_begin;
for(; p_i != pattern_end; ++p_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n != pattern_end) && is_ellipsis(*p_n)){
if(eq_internal(*p_i, ignore_ident)){
throw zs_error_arg1("syntax-rules", "'...' is appeared following the first identifier");
}
if(dotted_checker(pattern_end)){
throw zs_error_arg1("syntax-rules", "'...' is appeared in a inproper list pattern");
}
if(dotted_checker(form_end)){
throw zs_error_arg1("syntax-rules", "'...' is used for a inproper list form");
}
// accumulating...
EqHashMap acc_map;
ensure_binding(acc_map, sr, ignore_ident, *p_i,
[](){ return Cons::NIL; });
for(; f_i != form_end; ++f_i){
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
for(auto i : m){
auto place = acc_map.find(i.first);
assert(place->second.tag() == Ptr_tag::cons);
push_tail_cons_list(&place->second, i.second);
}
}
match_obj.insert(begin(acc_map), end(acc_map));
return match_obj;
}
if(f_i == form_end) break; // this check is delayed to here, for checking the ellipsis.
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
match_obj.insert(begin(m), end(m));
assert(f_i != form_end);
++f_i;
}
assert((p_i == pattern_end) || (f_i == form_end));
if(dotted_checker(p_i)){
return dotted_handler(p_i, f_i, match_obj);
}else if((p_i == pattern_end) && (f_i == form_end)){
return match_obj;
}else{
throw try_match_failed();
}
}
EqHashMap
try_match_1(const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
// literal identifier
if(identifierp(form) && identifier_eq(sr.env(), pattern, form_env, form)){
return {};
}else{
throw try_match_failed();
}
}
// non-literal identifier
EqHashMap match_obj;
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, form});
}
return match_obj;
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons){
throw try_match_failed();
}
return try_match_1_seq
(sr, ignore_ident,
begin(pattern), end(pattern),
form_env,
begin(form), end(form),
[](ConsIter i){ return !nullp(i.base()); },
[&](ConsIter p_i, ConsIter f_i, EqHashMap& match_obj) -> EqHashMap{
if(p_i.base().tag() == Ptr_tag::cons){
throw try_match_failed();
}
auto m = try_match_1(sr, ignore_ident, p_i.base(), form_env, f_i.base());
match_obj.insert(begin(m), end(m));
return match_obj;
});
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector){
throw try_match_failed();
}
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
return try_match_1_seq
(sr, ignore_ident,
begin(*p_v), end(*p_v),
form_env,
begin(*f_v), end(*f_v),
[](Vector::iterator){ return false; },
[](Vector::iterator, Vector::iterator, EqHashMap&) -> EqHashMap{
return {};
});
}else{
if(equal_internal(pattern, form)){
return {};
}else{
throw try_match_failed();
}
}
}
EqHashMap remake_matchobj(const EqHashMap& match_obj, int pick_depth){
EqHashMap ret;
for(auto i : match_obj){
if(i.second.tag() == Ptr_tag::vector){
auto v = i.second.get<Vector*>();
if(pick_depth < static_cast<signed>(v->size())){
ret.insert({i.first, (*v)[pick_depth]});
continue;
}
}else if(i.second.tag() == Ptr_tag::cons){
ConsIter ci = begin(i.second);
std::advance(ci, pick_depth);
auto nthcdr = ci.base();
if(!nullp(nthcdr)){
ret.insert({i.first, nthcdr.get<Cons*>()->car()});
continue;
}
}
ret.insert({i.first, {}});
}
return ret;
}
Lisp_ptr expand(ExpandSet&, const EqHashMap&,
const SyntaxRules&, Lisp_ptr);
template<typename Iter, typename Fun>
Iter expand_seq(ExpandSet& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Iter i_begin,
Iter i_end,
Fun push_handler){
auto i = i_begin;
for(; i != i_end; ++i){
auto i_next = next(i);
// check ellipsis
if((i_next != i_end) && is_ellipsis(*i_next)){
int depth = 0;
while(1){
auto emap = remake_matchobj(match_obj, depth);
try{
auto ex = expand(expand_ctx, emap, sr, *i);
push_handler(ex);
++depth;
}catch(const expand_failed& e){
break;
}
}
++i;
}else{
auto ex = expand(expand_ctx, match_obj, sr, *i);
push_handler(ex);
}
}
return i;
}
Lisp_ptr expand(ExpandSet& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Lisp_ptr tmpl){
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
if(m_ret->second){
return m_ret->second;
}else{
throw expand_failed();
}
}
// close to pattern variable
if(tmpl.tag() == Ptr_tag::symbol){
if(is_literal_identifier(sr, tmpl)){
return tmpl;
}
auto new_sc = new SyntacticClosure(sr.env(), nullptr, tmpl);
auto iter = expand_ctx.find(new_sc);
if(iter == expand_ctx.end()){
expand_ctx.insert(new_sc);
return new_sc;
}else{
delete new_sc;
return *iter;
}
}else if(tmpl.tag() == Ptr_tag::syntactic_closure){
return tmpl;
}else{
UNEXP_DEFAULT();
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto last =
expand_seq(expand_ctx, match_obj, sr,
begin(tmpl), end(tmpl),
[&](Lisp_ptr ex){ gl.push(ex); });
auto ex = expand(expand_ctx, match_obj, sr, last.base());
return gl.extract_with_tail(ex);
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
expand_seq(expand_ctx, match_obj, sr,
begin(*t_vec), end(*t_vec),
[&](Lisp_ptr ex){ vec.push_back(ex); });
return new Vector(move(vec));
}else{
return tmpl;
}
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(lits), rules_(rls){
for(auto i : lits){
if(!identifierp(i))
throw builtin_identifier_check_failed("syntax-rules", i);
}
for(auto i : rls){
bind_cons_list_strict
(i,
[&](Lisp_ptr pat, Lisp_ptr tmpl){
(void)tmpl;
check_pattern(*this, pat);
});
}
}
SyntaxRules::~SyntaxRules() = default;
Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{
for(auto i : this->rules()){
auto pat = nth_cons_list<0>(i);
auto tmpl = nth_cons_list<1>(i);
auto ignore_ident = pick_first(pat);
try{
auto match_ret = try_match_1(*this, ignore_ident, pat, form_env, form);
ExpandSet expand_ctx;
return expand(expand_ctx, match_ret, *this, tmpl);
}catch(const try_match_failed& e){
continue;
}catch(const expand_failed& e){
throw zs_error_arg1("syntax-rules", "expand failed!", {form});
}
}
throw zs_error_arg1("syntax-rules", "no matching pattern found!", {form});
}
<commit_msg>added bug comment<commit_after>#include <memory>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include <utility>
#include "s_rules.hh"
#include "s_closure.hh"
#include "cons_util.hh"
#include "env.hh"
#include "zs_error.hh"
#include "builtin_extra.hh"
#include "printer.hh"
#include "equality.hh"
#include "eval.hh"
using namespace std;
namespace {
// internal types
typedef std::unordered_map<Lisp_ptr, Lisp_ptr, eq_hash_obj, eq_obj> EqHashMap;
typedef std::unordered_set<Lisp_ptr, eq_hash_obj, eq_obj> MatchSet;
typedef std::unordered_set<Lisp_ptr, eq_id_hash_obj, eq_id_obj> ExpandSet;
// error classes
struct try_match_failed{};
struct expand_failed {};
bool is_literal_identifier(const SyntaxRules& sr, Lisp_ptr p){
for(auto l : sr.literals()){
if(eq_internal(l, p)){
return true;
}
}
return false;
}
bool is_ellipsis(Lisp_ptr p){
if(!identifierp(p)) return false;
auto sym = identifier_symbol(p);
return sym->name() == "...";
}
void push_tail_cons_list_nl(Lisp_ptr p, Lisp_ptr value){
if(p.tag() != Ptr_tag::cons)
throw zs_error(printf_string("internal %s: the passed list is a dotted list!\n", __func__));
auto c = p.get<Cons*>();
if(!c)
throw zs_error(printf_string("internal %s: the passed list is an empty list!\n", __func__));
if(nullp(c->cdr())){
c->rplacd(make_cons_list({value}));
}else{
push_tail_cons_list_nl(c->cdr(), value);
}
}
void push_tail_cons_list(Lisp_ptr* p, Lisp_ptr value){
if(nullp(*p)){
*p = make_cons_list({value});
}else{
push_tail_cons_list_nl(*p, value);
}
}
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw zs_error_arg1("syntax-rules", "the pattern is empty list");
return c->car();
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw zs_error_arg1("syntax-rules", "the pattern is empty vector");
return (*v)[0];
}else{
throw zs_error_arg1("syntax-rules", "informal pattern passed!", {p});
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p, MatchSet tab){
if(identifierp(p)){
if(is_literal_identifier(sr, p)){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw zs_error_arg1("syntax-rules", "duplicated pattern variable!", {p});
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
template<typename DefaultGen>
void ensure_binding(EqHashMap& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
const DefaultGen& default_gen_func){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
return; // literal identifier
}
// non-literal identifier
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, default_gen_func()});
}
return;
}else if(pattern.tag() == Ptr_tag::cons){
if(nullp(pattern)){
return;
}
auto p_i = begin(pattern);
for(; p_i; ++p_i){
// checks ellipsis
if(is_ellipsis(*p_i)){
return;
}
ensure_binding(match_obj, sr, ignore_ident, *p_i, default_gen_func);
}
if(!nullp(p_i.base())){
// dotted list case
ensure_binding(match_obj, sr, ignore_ident, p_i.base(), default_gen_func);
}
}else if(pattern.tag() == Ptr_tag::vector){
auto p_v = pattern.get<Vector*>();
for(auto p : *p_v){
ensure_binding(match_obj, sr, ignore_ident, p, default_gen_func);
}
}else{
return;
}
}
template<typename Iter, typename Fun1, typename Fun2>
EqHashMap
try_match_1_seq(const SyntaxRules& sr, Lisp_ptr ignore_ident,
Iter pattern_begin, Iter pattern_end,
Env* form_env,
Iter form_begin, Iter form_end,
Fun1 dotted_checker,
Fun2 dotted_handler){
EqHashMap match_obj;
auto p_i = pattern_begin;
auto f_i = form_begin;
for(; p_i != pattern_end; ++p_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n != pattern_end) && is_ellipsis(*p_n)){
if(eq_internal(*p_i, ignore_ident)){
throw zs_error_arg1("syntax-rules", "'...' is appeared following the first identifier");
}
if(dotted_checker(pattern_end)){
throw zs_error_arg1("syntax-rules", "'...' is appeared in a inproper list pattern");
}
if(dotted_checker(form_end)){
throw zs_error_arg1("syntax-rules", "'...' is used for a inproper list form");
}
// accumulating...
// BUG: this code only accepts cons. vector is rejected.
// (commit adcd5e7f56298d1dddc777dd894762cf0d3ec92c)
EqHashMap acc_map;
ensure_binding(acc_map, sr, ignore_ident, *p_i,
[](){ return Cons::NIL; });
for(; f_i != form_end; ++f_i){
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
for(auto i : m){
auto place = acc_map.find(i.first);
assert(place->second.tag() == Ptr_tag::cons);
push_tail_cons_list(&place->second, i.second);
}
}
match_obj.insert(begin(acc_map), end(acc_map));
return match_obj;
}
if(f_i == form_end) break; // this check is delayed to here, for checking the ellipsis.
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
match_obj.insert(begin(m), end(m));
assert(f_i != form_end);
++f_i;
}
assert((p_i == pattern_end) || (f_i == form_end));
if(dotted_checker(p_i)){
return dotted_handler(p_i, f_i, match_obj);
}else if((p_i == pattern_end) && (f_i == form_end)){
return match_obj;
}else{
throw try_match_failed();
}
}
EqHashMap
try_match_1(const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
// literal identifier
if(identifierp(form) && identifier_eq(sr.env(), pattern, form_env, form)){
return {};
}else{
throw try_match_failed();
}
}
// non-literal identifier
EqHashMap match_obj;
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, form});
}
return match_obj;
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons){
throw try_match_failed();
}
return try_match_1_seq
(sr, ignore_ident,
begin(pattern), end(pattern),
form_env,
begin(form), end(form),
[](ConsIter i){ return !nullp(i.base()); },
[&](ConsIter p_i, ConsIter f_i, EqHashMap& match_obj) -> EqHashMap{
if(p_i.base().tag() == Ptr_tag::cons){
throw try_match_failed();
}
auto m = try_match_1(sr, ignore_ident, p_i.base(), form_env, f_i.base());
match_obj.insert(begin(m), end(m));
return match_obj;
});
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector){
throw try_match_failed();
}
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
return try_match_1_seq
(sr, ignore_ident,
begin(*p_v), end(*p_v),
form_env,
begin(*f_v), end(*f_v),
[](Vector::iterator){ return false; },
[](Vector::iterator, Vector::iterator, EqHashMap&) -> EqHashMap{
return {};
});
}else{
if(equal_internal(pattern, form)){
return {};
}else{
throw try_match_failed();
}
}
}
EqHashMap remake_matchobj(const EqHashMap& match_obj, int pick_depth){
EqHashMap ret;
for(auto i : match_obj){
if(i.second.tag() == Ptr_tag::vector){
auto v = i.second.get<Vector*>();
if(pick_depth < static_cast<signed>(v->size())){
ret.insert({i.first, (*v)[pick_depth]});
continue;
}
}else if(i.second.tag() == Ptr_tag::cons){
ConsIter ci = begin(i.second);
std::advance(ci, pick_depth);
auto nthcdr = ci.base();
if(!nullp(nthcdr)){
ret.insert({i.first, nthcdr.get<Cons*>()->car()});
continue;
}
}
ret.insert({i.first, {}});
}
return ret;
}
Lisp_ptr expand(ExpandSet&, const EqHashMap&,
const SyntaxRules&, Lisp_ptr);
template<typename Iter, typename Fun>
Iter expand_seq(ExpandSet& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Iter i_begin,
Iter i_end,
Fun push_handler){
auto i = i_begin;
for(; i != i_end; ++i){
auto i_next = next(i);
// check ellipsis
if((i_next != i_end) && is_ellipsis(*i_next)){
int depth = 0;
while(1){
auto emap = remake_matchobj(match_obj, depth);
try{
auto ex = expand(expand_ctx, emap, sr, *i);
push_handler(ex);
++depth;
}catch(const expand_failed& e){
break;
}
}
++i;
}else{
auto ex = expand(expand_ctx, match_obj, sr, *i);
push_handler(ex);
}
}
return i;
}
Lisp_ptr expand(ExpandSet& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Lisp_ptr tmpl){
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
if(m_ret->second){
return m_ret->second;
}else{
throw expand_failed();
}
}
// close to pattern variable
if(tmpl.tag() == Ptr_tag::symbol){
if(is_literal_identifier(sr, tmpl)){
return tmpl;
}
auto new_sc = new SyntacticClosure(sr.env(), nullptr, tmpl);
auto iter = expand_ctx.find(new_sc);
if(iter == expand_ctx.end()){
expand_ctx.insert(new_sc);
return new_sc;
}else{
delete new_sc;
return *iter;
}
}else if(tmpl.tag() == Ptr_tag::syntactic_closure){
return tmpl;
}else{
UNEXP_DEFAULT();
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto last =
expand_seq(expand_ctx, match_obj, sr,
begin(tmpl), end(tmpl),
[&](Lisp_ptr ex){ gl.push(ex); });
auto ex = expand(expand_ctx, match_obj, sr, last.base());
return gl.extract_with_tail(ex);
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
expand_seq(expand_ctx, match_obj, sr,
begin(*t_vec), end(*t_vec),
[&](Lisp_ptr ex){ vec.push_back(ex); });
return new Vector(move(vec));
}else{
return tmpl;
}
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(lits), rules_(rls){
for(auto i : lits){
if(!identifierp(i))
throw builtin_identifier_check_failed("syntax-rules", i);
}
for(auto i : rls){
bind_cons_list_strict
(i,
[&](Lisp_ptr pat, Lisp_ptr tmpl){
(void)tmpl;
check_pattern(*this, pat);
});
}
}
SyntaxRules::~SyntaxRules() = default;
Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{
for(auto i : this->rules()){
auto pat = nth_cons_list<0>(i);
auto tmpl = nth_cons_list<1>(i);
auto ignore_ident = pick_first(pat);
try{
auto match_ret = try_match_1(*this, ignore_ident, pat, form_env, form);
ExpandSet expand_ctx;
return expand(expand_ctx, match_ret, *this, tmpl);
}catch(const try_match_failed& e){
continue;
}catch(const expand_failed& e){
throw zs_error_arg1("syntax-rules", "expand failed!", {form});
}
}
throw zs_error_arg1("syntax-rules", "no matching pattern found!", {form});
}
<|endoftext|>
|
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
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 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 "metadata/ColorFilterArray.h"
#include "common/Common.h" // for uint32, writeLog, DEBUG_PR...
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include <cstdarg> // for va_arg, va_end, va_list
#include <cstdio> // for NULL
#include <cstring> // for memcpy, memset
#include <map> // for map
#include <string> // for string
using namespace std;
namespace RawSpeed {
ColorFilterArray::ColorFilterArray(const iPoint2D &_size) {
setSize(_size);
}
void ColorFilterArray::setSize(const iPoint2D& _size)
{
size = _size;
if (size.area() > 36) {
// Bayer, FC() supports 2x8 pattern
// X-Trans is 6x6 pattern
// is there anything bigger?
ThrowRDE("ColorFilterArray:setSize if your CFA pattern is really %d pixels "
"in area we may as well give up now",
size.area());
}
if (size.area() <= 0)
return;
cfa.resize(size.area());
fill(cfa.begin(), cfa.end(), CFA_UNKNOWN);
}
CFAColor ColorFilterArray::getColorAt( int x, int y ) const
{
if (cfa.empty())
ThrowRDE("ColorFilterArray:getColorAt: No CFA size set");
// calculate the positive modulo [0 .. size-1]
x = (x % size.x + size.x) % size.x;
y = (y % size.y + size.y) % size.y;
return cfa[x + y * size.x];
}
void ColorFilterArray::setCFA( iPoint2D in_size, ... )
{
if (in_size != size) {
setSize(in_size);
}
va_list arguments;
va_start(arguments, in_size);
for (uint32 i = 0; i < size.area(); i++ ) {
cfa[i] = (CFAColor)va_arg(arguments, int);
}
va_end (arguments);
}
void ColorFilterArray::shiftLeft(int n) {
if (cfa.empty())
ThrowRDE("ColorFilterArray:shiftLeft: No CFA size set (or set to zero)");
writeLog(DEBUG_PRIO_EXTRA, "Shift left:%d\n", n);
n %= size.x;
if (n == 0)
return;
vector<CFAColor> tmp(size.area());
for (int y = 0; y < size.y; ++y) {
for (int x = 0; x < size.x; ++x) {
tmp[x + y * size.x] = getColorAt(x+n, y);
}
}
cfa = tmp;
}
void ColorFilterArray::shiftDown(int n) {
if (cfa.empty())
ThrowRDE("ColorFilterArray:shiftDown: No CFA size set (or set to zero)");
writeLog(DEBUG_PRIO_EXTRA, "Shift down:%d\n", n);
n %= size.y;
if (n == 0)
return;
vector<CFAColor> tmp(size.area());
for (int y = 0; y < size.y; ++y) {
for (int x = 0; x < size.x; ++x) {
tmp[x + y * size.x] = getColorAt(x, y+n);
}
}
cfa = tmp;
}
string ColorFilterArray::asString() const {
string dst;
for (int y = 0; y < size.y; y++) {
for (int x = 0; x < size.x; x++) {
dst += colorToString(getColorAt(x,y));
dst += (x == size.x - 1) ? "\n" : ",";
}
}
return dst;
}
uint32 ColorFilterArray::shiftDcrawFilter(uint32 filter, int x, int y)
{
// filter is a series of 4 bytes that describe a 2x8 matrix. 2 is the width,
// 8 is the height. each byte describes a 2x2 pixel block. so each pixel has
// 2 bits of information. This allows to distinguish 4 different colors.
if (std::abs(x) & 1) {
// A shift in x direction means swapping the first and second half of each
// nibble.
// see http://graphics.stanford.edu/~seander/bithacks.html#SwappingBitsXOR
for (int n = 0; n < 8; ++n) {
int i = n * 4;
int j = i + 2;
uint32 t = ((filter >> i) ^ (filter >> j)) & ((1U << 2) - 1);
filter = filter ^ ((t << i) | (t << j));
}
}
// A shift in y direction means rotating the whole int by 4 bits.
y *= 4;
y = y >= 0 ? y % 32 : 32 - ((-y) % 32);
filter = (filter >> y) | (filter << (32 - y));
return filter;
}
const static map<CFAColor, string> color2String = {
{CFA_RED, "RED"}, {CFA_GREEN, "GREEN"},
{CFA_BLUE, "BLUE"}, {CFA_CYAN, "CYAN"},
{CFA_MAGENTA, "MAGENTA"}, {CFA_YELLOW, "YELLOW"},
{CFA_WHITE, "WHITE"}, {CFA_FUJI_GREEN, "FUJIGREEN"},
{CFA_UNKNOWN, "UNKNOWN"}
};
string ColorFilterArray::colorToString(CFAColor c)
{
try {
return color2String.at(c);
} catch (std::out_of_range&) {
ThrowRDE("ColorFilterArray: Unsupported CFA Color: %u", c);
}
}
void ColorFilterArray::setColorAt(iPoint2D pos, CFAColor c) {
if (pos.x >= size.x || pos.x < 0)
ThrowRDE("ColorFilterArray::SetColor: position out of CFA pattern");
if (pos.y >= size.y || pos.y < 0)
ThrowRDE("ColorFilterArray::SetColor: position out of CFA pattern");
cfa[pos.x+pos.y*size.x] = c;
}
static uint32 toDcrawColor( CFAColor c )
{
switch (c) {
case CFA_FUJI_GREEN:
case CFA_RED: return 0;
case CFA_MAGENTA:
case CFA_GREEN: return 1;
case CFA_CYAN:
case CFA_BLUE: return 2;
case CFA_YELLOW: return 3;
default:
throw out_of_range(ColorFilterArray::colorToString(c));
}
}
uint32 ColorFilterArray::getDcrawFilter() const
{
//dcraw magic
if (size.x == 6 && size.y == 6)
return 9;
if (cfa.empty() || size.x > 2 || size.y > 8 || !isPowerOfTwo(size.y))
return 1;
uint32 ret = 0;
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 8; y++) {
uint32 c = toDcrawColor(getColorAt(x,y));
int g = (x >> 1) * 8;
ret |= c << ((x&1)*2 + y*4 + g);
}
}
for (int y = 0; y < size.y; y++) {
for (int x = 0; x < size.x; x++) {
writeLog(DEBUG_PRIO_EXTRA, "%s,", colorToString((CFAColor)toDcrawColor(getColorAt(x,y))).c_str());
}
writeLog(DEBUG_PRIO_EXTRA, "\n");
}
writeLog(DEBUG_PRIO_EXTRA, "DCRAW filter:%x\n",ret);
return ret;
}
} // namespace RawSpeed
<commit_msg>ColorFilterArray: clang-tidy: widening cast<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
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 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 "metadata/ColorFilterArray.h"
#include "common/Common.h" // for uint32, writeLog, DEBUG_PR...
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include <cstdarg> // for va_arg, va_end, va_list
#include <cstdio> // for NULL
#include <cstring> // for memcpy, memset
#include <map> // for map
#include <string> // for string
using namespace std;
namespace RawSpeed {
ColorFilterArray::ColorFilterArray(const iPoint2D &_size) {
setSize(_size);
}
void ColorFilterArray::setSize(const iPoint2D& _size)
{
size = _size;
if (size.area() > 36) {
// Bayer, FC() supports 2x8 pattern
// X-Trans is 6x6 pattern
// is there anything bigger?
ThrowRDE("ColorFilterArray:setSize if your CFA pattern is really %d pixels "
"in area we may as well give up now",
size.area());
}
if (size.area() <= 0)
return;
cfa.resize(size.area());
fill(cfa.begin(), cfa.end(), CFA_UNKNOWN);
}
CFAColor ColorFilterArray::getColorAt( int x, int y ) const
{
if (cfa.empty())
ThrowRDE("ColorFilterArray:getColorAt: No CFA size set");
// calculate the positive modulo [0 .. size-1]
x = (x % size.x + size.x) % size.x;
y = (y % size.y + size.y) % size.y;
return cfa[x + (size_t)y * size.x];
}
void ColorFilterArray::setCFA( iPoint2D in_size, ... )
{
if (in_size != size) {
setSize(in_size);
}
va_list arguments;
va_start(arguments, in_size);
for (uint32 i = 0; i < size.area(); i++ ) {
cfa[i] = (CFAColor)va_arg(arguments, int);
}
va_end (arguments);
}
void ColorFilterArray::shiftLeft(int n) {
if (cfa.empty())
ThrowRDE("ColorFilterArray:shiftLeft: No CFA size set (or set to zero)");
writeLog(DEBUG_PRIO_EXTRA, "Shift left:%d\n", n);
n %= size.x;
if (n == 0)
return;
vector<CFAColor> tmp(size.area());
for (int y = 0; y < size.y; ++y) {
for (int x = 0; x < size.x; ++x) {
tmp[x + (size_t)y * size.x] = getColorAt(x + n, y);
}
}
cfa = tmp;
}
void ColorFilterArray::shiftDown(int n) {
if (cfa.empty())
ThrowRDE("ColorFilterArray:shiftDown: No CFA size set (or set to zero)");
writeLog(DEBUG_PRIO_EXTRA, "Shift down:%d\n", n);
n %= size.y;
if (n == 0)
return;
vector<CFAColor> tmp(size.area());
for (int y = 0; y < size.y; ++y) {
for (int x = 0; x < size.x; ++x) {
tmp[x + (size_t)y * size.x] = getColorAt(x, y + n);
}
}
cfa = tmp;
}
string ColorFilterArray::asString() const {
string dst;
for (int y = 0; y < size.y; y++) {
for (int x = 0; x < size.x; x++) {
dst += colorToString(getColorAt(x,y));
dst += (x == size.x - 1) ? "\n" : ",";
}
}
return dst;
}
uint32 ColorFilterArray::shiftDcrawFilter(uint32 filter, int x, int y)
{
// filter is a series of 4 bytes that describe a 2x8 matrix. 2 is the width,
// 8 is the height. each byte describes a 2x2 pixel block. so each pixel has
// 2 bits of information. This allows to distinguish 4 different colors.
if (std::abs(x) & 1) {
// A shift in x direction means swapping the first and second half of each
// nibble.
// see http://graphics.stanford.edu/~seander/bithacks.html#SwappingBitsXOR
for (int n = 0; n < 8; ++n) {
int i = n * 4;
int j = i + 2;
uint32 t = ((filter >> i) ^ (filter >> j)) & ((1U << 2) - 1);
filter = filter ^ ((t << i) | (t << j));
}
}
// A shift in y direction means rotating the whole int by 4 bits.
y *= 4;
y = y >= 0 ? y % 32 : 32 - ((-y) % 32);
filter = (filter >> y) | (filter << (32 - y));
return filter;
}
const static map<CFAColor, string> color2String = {
{CFA_RED, "RED"}, {CFA_GREEN, "GREEN"},
{CFA_BLUE, "BLUE"}, {CFA_CYAN, "CYAN"},
{CFA_MAGENTA, "MAGENTA"}, {CFA_YELLOW, "YELLOW"},
{CFA_WHITE, "WHITE"}, {CFA_FUJI_GREEN, "FUJIGREEN"},
{CFA_UNKNOWN, "UNKNOWN"}
};
string ColorFilterArray::colorToString(CFAColor c)
{
try {
return color2String.at(c);
} catch (std::out_of_range&) {
ThrowRDE("ColorFilterArray: Unsupported CFA Color: %u", c);
}
}
void ColorFilterArray::setColorAt(iPoint2D pos, CFAColor c) {
if (pos.x >= size.x || pos.x < 0)
ThrowRDE("ColorFilterArray::SetColor: position out of CFA pattern");
if (pos.y >= size.y || pos.y < 0)
ThrowRDE("ColorFilterArray::SetColor: position out of CFA pattern");
cfa[pos.x + (size_t)pos.y * size.x] = c;
}
static uint32 toDcrawColor( CFAColor c )
{
switch (c) {
case CFA_FUJI_GREEN:
case CFA_RED: return 0;
case CFA_MAGENTA:
case CFA_GREEN: return 1;
case CFA_CYAN:
case CFA_BLUE: return 2;
case CFA_YELLOW: return 3;
default:
throw out_of_range(ColorFilterArray::colorToString(c));
}
}
uint32 ColorFilterArray::getDcrawFilter() const
{
//dcraw magic
if (size.x == 6 && size.y == 6)
return 9;
if (cfa.empty() || size.x > 2 || size.y > 8 || !isPowerOfTwo(size.y))
return 1;
uint32 ret = 0;
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 8; y++) {
uint32 c = toDcrawColor(getColorAt(x,y));
int g = (x >> 1) * 8;
ret |= c << ((x&1)*2 + y*4 + g);
}
}
for (int y = 0; y < size.y; y++) {
for (int x = 0; x < size.x; x++) {
writeLog(DEBUG_PRIO_EXTRA, "%s,", colorToString((CFAColor)toDcrawColor(getColorAt(x,y))).c_str());
}
writeLog(DEBUG_PRIO_EXTRA, "\n");
}
writeLog(DEBUG_PRIO_EXTRA, "DCRAW filter:%x\n",ret);
return ret;
}
} // namespace RawSpeed
<|endoftext|>
|
<commit_before>// SSSSCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <time.h>
#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
#include "boost/lexical_cast.hpp"
#include <assert.h>
#define UINT unsigned int
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
using std::vector; using std::string;
using boost::filesystem::path;
int main(int argc, char* argv[])
{
GF256init();
srand((unsigned)time(NULL));
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc("Program Usage");
desc.add_options()
("help,h", "Print help messages")
("split,s", po::value<vector<string>>()->multitoken(), "Split a file")
("reconstruct,r", po::value<vector<string>>()->multitoken(), "Reconstruct a file from its shares");
//("reconstruct,r", po::value<vector<string>>(&reconInputPaths), "Reconstruct a file from its shares");
//("options,o", "additional options")
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // throws on error
/** --help option
*/
if (vm.count("help"))
{
std::cout << "Basic Command Line Parameter App" << std::endl
<< desc << std::endl;
return SUCCESS;
}
if (vm.count("split")) {
std::cout << "Splitting" << std::endl;
vector<string> const &splitInputs = vm["split"].as<vector<string>>();
if (splitInputs.size() != 3) {
throw po::error("Split usage: [Input File] [Total Share #] [Share Number Required to Reconstruct]");
}
path inputPath(splitInputs[0]);
try {
int n = boost::lexical_cast<int>(splitInputs[1].c_str());
int k = boost::lexical_cast<int>(splitInputs[2].c_str());
if (n <= 0 || k <= 0 || n > 255 || k > 255) {
throw po::error("n and k must be between 1 and 255 (inclusive)");
}
if (n < k) {
throw po::error("n must be larger or equal to k");
}
splitSecretFile(inputPath, n, k);
}
catch (boost::bad_lexical_cast _) {
throw po::error("[Total Share Number] and [Share Number Required to Reconstruct] must be numbers");
}
catch (std::exception &e) {
throw po::error(e.what());
}
return SUCCESS;
}
if (vm.count("reconstruct")) {
std::cout << "Reconstructing" << std::endl;
vector<string> const &reconInputs = vm["reconstruct"].as<vector<string>>();
if (reconInputs.size() != 2)
throw po::error("Reconstruct Usage: [Original File Name (and the folder path containing the shares)] [Output File Name (and folder path)]");
path inputFile(reconInputs[0]);
path outputFile(reconInputs[1]);
try {
reconstructSecretFile(inputFile, outputFile);
}
catch (std::exception &e) {
throw po::error(e.what());
}
}
po::notify(vm); // throws on error, so do after help in case there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return SUCCESS;
return 0;
}<commit_msg>Changed Usage text. displays USAGE if incorrect combination of inputs is detected.<commit_after>// SSSSCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <time.h>
#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"
#include "boost/lexical_cast.hpp"
#include <assert.h>
#define UINT unsigned int
namespace
{
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
using std::vector; using std::string;
using boost::filesystem::path;
int main(int argc, char* argv[])
{
GF256init();
srand((unsigned)time(NULL));
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc("Program Usage");
desc.add_options()
("help,h", "Print help messages")
("split,s", po::value<vector<string>>()->multitoken(), "Split a file")
("reconstruct,r", po::value<vector<string>>()->multitoken(), "Reconstruct a file from its shares");
//("reconstruct,r", po::value<vector<string>>(&reconInputPaths), "Reconstruct a file from its shares");
//("options,o", "additional options")
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // throws on error
/** --help option
*/
if (vm.count("help"))
{
std::cout << "Shamir's Secret Sharing Scheme for Files" << std::endl
<< desc << std::endl;
return SUCCESS;
}
if (vm.count("split")) {
std::cout << "Splitting" << std::endl;
vector<string> const &splitInputs = vm["split"].as<vector<string>>();
if (splitInputs.size() != 3) {
throw po::error("Split usage: [Input File] [Total Share #] [Share Number Required to Reconstruct]");
}
path inputPath(splitInputs[0]);
try {
int n = boost::lexical_cast<int>(splitInputs[1].c_str());
int k = boost::lexical_cast<int>(splitInputs[2].c_str());
if (n <= 0 || k <= 0 || n > 255 || k > 255) {
throw po::error("n and k must be between 1 and 255 (inclusive)");
}
if (n < k) {
throw po::error("n must be larger or equal to k");
}
splitSecretFile(inputPath, n, k);
}
catch (boost::bad_lexical_cast _) {
throw po::error("[Total Share Number] and [Share Number Required to Reconstruct] must be numbers");
}
catch (std::exception &e) {
throw po::error(e.what());
}
return SUCCESS;
}
else if (vm.count("reconstruct")) {
std::cout << "Reconstructing" << std::endl;
vector<string> const &reconInputs = vm["reconstruct"].as<vector<string>>();
if (reconInputs.size() != 2)
throw po::error("Reconstruct Usage: [Original File Name (and the folder path containing the shares)] [Output File Name (and folder path)]");
path inputFile(reconInputs[0]);
path outputFile(reconInputs[1]);
try {
reconstructSecretFile(inputFile, outputFile);
}
catch (std::exception &e) {
throw po::error(e.what());
}
}
else {
//fail to parse input, output Usage
std::cout << "Shamir's Secret Sharing Scheme for Files" << std::endl
<< desc << std::endl;
return SUCCESS;
}
po::notify(vm); // throws on error, so do after help in case there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return SUCCESS;
return 0;
}<|endoftext|>
|
<commit_before>/*
Copyright (C) 2015 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Jolla Ltd 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "search.h"
#include <QDebug>
namespace {
void add_value(QString &s, QString value, QString key, QString &v_1, QString &v_2, QString &v_3, QString &v_4, QString &v_5, QString &v_6, QString &v_7, QString &v_8, int &count)
{
++count;
switch(count)
{
case 1:
v_1 = value;
s.append(" WHERE ");
s.append(key);
break;
case 2:
v_2 = value;
s.append(" AND ");
s.append(key);
break;
case 3:
v_3 = value;
s.append(" AND ");
s.append(key);
break;
case 4:
v_4 = value;
s.append(" AND ");
s.append(key);
break;
case 5:
v_5 = value;
s.append(" AND ");
s.append(key);
break;
case 6:
v_6 = value;
s.append(" AND ");
s.append(key);
break;
case 7:
v_7 = value;
s.append(" AND ");
s.append(key);
break;
case 8:
v_8 = value;
s.append(" AND ");
s.append(key);
break;
default:
qDebug() << "ERROR in " __FILE__ << " " << __LINE__ << ": Too many search terms";
}
}
}
search::search(QSqlDatabase kanji, QSqlDatabase settings, QObject *parent) :
QObject(parent),
_kanji_query(kanji),
_settings_query(settings),
_literal_result(""),
_meaning_result(""),
_saved(""),
_literal(""),
_radical(-1),
_strokecount(-1),
_jlpt(-1),
_meaning(""),
_search_for_saved(false),
_saved_search_value(false),
_skip1(0),
_skip2(0),
_skip3(0),
_search_started(false)
{
}
void search::clear()
{
_kanji_query.clear();
_settings_query.clear();
_literal_result = "";
_meaning_result = "";
_saved = false;
_literal = "";
_radical = -1;
_strokecount = -1;
_jlpt = -1;
_meaning = "";
_search_for_saved = false;
_saved_search_value = false;
_skip1 = 0;
_skip2 = 0;
_skip3 = 0;
_search_started = false;
}
void search::search_literal(QString literal)
{
_literal = literal;
}
void search::search_radical(int radical)
{
_radical = radical;
}
void search::search_strokecount(int strokecount)
{
_strokecount = strokecount;
}
void search::search_jlpt(int jlpt)
{
_jlpt = jlpt;
}
void search::search_meaning(QString meaning)
{
_meaning = meaning;
}
void search::search_saved(bool saved)
{
_search_for_saved = true;
_saved_search_value = saved;
}
void search::search_skip(int skip1, int skip2, int skip3)
{
_skip1 = skip1;
_skip2 = skip2;
_skip3 = skip3;
}
bool search::start_search()
{
if(_literal == "" && _radical == 0 && _strokecount == 0 && _jlpt == 0 && _meaning == "")
{
// Get all kanji
QString s = QString("SELECT literal,meaning FROM kanji");
if(!_kanji_query.exec(s))
{
QString error = s.append(": ").append(_kanji_query.lastError().text());
qWarning() << error;
_search_started = false;
return false;
}
if(!_kanji_query.isSelect())
{
QString error = s.append(": No SELECT");
qWarning() << error;
_search_started = false;
return false;
}
}
else
{
// Search for all fitting kanji
int count = 0;
QString v_1;
QString v_2;
QString v_3;
QString v_4;
QString v_5;
QString v_6;
QString v_7;
QString v_8;
QString s = QString("SELECT literal,meaning FROM kanji");
if(_literal != "")
{
add_value(s,QString("\%%1\%").arg(_literal),QString("literal LIKE ?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_radical != -1)
{
add_value(s,QString("%1").arg(_radical),QString("radical=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_strokecount != -1)
{
add_value(s,QString("%1").arg(_strokecount),QString("strokecount=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_jlpt != -1)
{
add_value(s,QString("%1").arg(_jlpt),QString("JLPT=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_meaning != "")
{
add_value(s,QString("\%%1\%").arg(_meaning),QString("meaning LIKE ?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_skip1 != 0)
{
add_value(s,QString("%1").arg(_skip1),QString("skip_1=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_skip2 != 0)
{
add_value(s,QString("%1").arg(_skip2),QString("skip_2=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_skip3 != 0)
{
add_value(s,QString("%1").arg(_skip3),QString("skip_3=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
_kanji_query.clear();
_kanji_query.prepare(s);
if(count >= 1)
{
_kanji_query.addBindValue(v_1);
qDebug() << v_1;
}
if(count >= 2)
{
_kanji_query.addBindValue(v_2);
}
if(count >= 3)
{
_kanji_query.addBindValue(v_3);
}
if(count >= 4)
{
_kanji_query.addBindValue(v_4);
}
if(count >= 5)
{
_kanji_query.addBindValue(v_5);
}
if(count >= 6)
{
_kanji_query.addBindValue(v_6);
}
if(count >= 7)
{
_kanji_query.addBindValue(v_7);
}
if(count >= 8)
{
_kanji_query.addBindValue(v_8);
}
qDebug() << "DEBUG in " __FILE__ << " " << __LINE__ << ": SELECT statement:" << s;
if(!_kanji_query.exec())
{
QString error = s.append(": ").append(_kanji_query.lastError().text());
qWarning() << error;
_search_started = false;
return false;
}
if(!_kanji_query.isSelect())
{
QString error = s.append(": No SELECT");
qWarning() << error;
_search_started = false;
return false;
}
}
_search_started = true;
return true;
}
bool search::next_hidden()
{
if(!_search_started)
{
return false;
}
if(_kanji_query.next())
{
_literal_result = _kanji_query.value(0).toString();
_meaning_result = _kanji_query.value(1).toString();
QString s = QString("SELECT count(*) FROM saved_kanji WHERE literal=?");
_settings_query.prepare(s);
_settings_query.addBindValue(_literal_result);
if(_settings_query.exec() && _settings_query.isSelect() && _settings_query.next() && _settings_query.value(0).toInt() > 0)
{
_saved = true;
}
else
{
_saved = false;
}
_settings_query.finish();
return true;
}
else
{
_search_started = false;
return false;
}
}
bool search::next()
{
if(!_search_started)
{
return false;
}
if(!_search_for_saved)
{
return next_hidden();
}
else
{
while(next_hidden())
{
if(_saved_search_value == _saved)
{
return true;
}
}
return false;
}
}
QString search::literal()
{
return _literal_result;
}
QString search::meaning()
{
return _meaning_result;
}
bool search::kanji_is_saved()
{
return _saved;
}
<commit_msg>Deleted debug output<commit_after>/*
Copyright (C) 2015 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Jolla Ltd 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "search.h"
#include <QDebug>
namespace {
void add_value(QString &s, QString value, QString key, QString &v_1, QString &v_2, QString &v_3, QString &v_4, QString &v_5, QString &v_6, QString &v_7, QString &v_8, int &count)
{
++count;
switch(count)
{
case 1:
v_1 = value;
s.append(" WHERE ");
s.append(key);
break;
case 2:
v_2 = value;
s.append(" AND ");
s.append(key);
break;
case 3:
v_3 = value;
s.append(" AND ");
s.append(key);
break;
case 4:
v_4 = value;
s.append(" AND ");
s.append(key);
break;
case 5:
v_5 = value;
s.append(" AND ");
s.append(key);
break;
case 6:
v_6 = value;
s.append(" AND ");
s.append(key);
break;
case 7:
v_7 = value;
s.append(" AND ");
s.append(key);
break;
case 8:
v_8 = value;
s.append(" AND ");
s.append(key);
break;
default:
qDebug() << "ERROR in " __FILE__ << " " << __LINE__ << ": Too many search terms";
}
}
}
search::search(QSqlDatabase kanji, QSqlDatabase settings, QObject *parent) :
QObject(parent),
_kanji_query(kanji),
_settings_query(settings),
_literal_result(""),
_meaning_result(""),
_saved(""),
_literal(""),
_radical(-1),
_strokecount(-1),
_jlpt(-1),
_meaning(""),
_search_for_saved(false),
_saved_search_value(false),
_skip1(0),
_skip2(0),
_skip3(0),
_search_started(false)
{
}
void search::clear()
{
_kanji_query.clear();
_settings_query.clear();
_literal_result = "";
_meaning_result = "";
_saved = false;
_literal = "";
_radical = -1;
_strokecount = -1;
_jlpt = -1;
_meaning = "";
_search_for_saved = false;
_saved_search_value = false;
_skip1 = 0;
_skip2 = 0;
_skip3 = 0;
_search_started = false;
}
void search::search_literal(QString literal)
{
_literal = literal;
}
void search::search_radical(int radical)
{
_radical = radical;
}
void search::search_strokecount(int strokecount)
{
_strokecount = strokecount;
}
void search::search_jlpt(int jlpt)
{
_jlpt = jlpt;
}
void search::search_meaning(QString meaning)
{
_meaning = meaning;
}
void search::search_saved(bool saved)
{
_search_for_saved = true;
_saved_search_value = saved;
}
void search::search_skip(int skip1, int skip2, int skip3)
{
_skip1 = skip1;
_skip2 = skip2;
_skip3 = skip3;
}
bool search::start_search()
{
if(_literal == "" && _radical == 0 && _strokecount == 0 && _jlpt == 0 && _meaning == "")
{
// Get all kanji
QString s = QString("SELECT literal,meaning FROM kanji");
if(!_kanji_query.exec(s))
{
QString error = s.append(": ").append(_kanji_query.lastError().text());
qWarning() << error;
_search_started = false;
return false;
}
if(!_kanji_query.isSelect())
{
QString error = s.append(": No SELECT");
qWarning() << error;
_search_started = false;
return false;
}
}
else
{
// Search for all fitting kanji
int count = 0;
QString v_1;
QString v_2;
QString v_3;
QString v_4;
QString v_5;
QString v_6;
QString v_7;
QString v_8;
QString s = QString("SELECT literal,meaning FROM kanji");
if(_literal != "")
{
add_value(s,QString("\%%1\%").arg(_literal),QString("literal LIKE ?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_radical != -1)
{
add_value(s,QString("%1").arg(_radical),QString("radical=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_strokecount != -1)
{
add_value(s,QString("%1").arg(_strokecount),QString("strokecount=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_jlpt != -1)
{
add_value(s,QString("%1").arg(_jlpt),QString("JLPT=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_meaning != "")
{
add_value(s,QString("\%%1\%").arg(_meaning),QString("meaning LIKE ?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_skip1 != 0)
{
add_value(s,QString("%1").arg(_skip1),QString("skip_1=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_skip2 != 0)
{
add_value(s,QString("%1").arg(_skip2),QString("skip_2=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
if(_skip3 != 0)
{
add_value(s,QString("%1").arg(_skip3),QString("skip_3=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count);
}
_kanji_query.clear();
_kanji_query.prepare(s);
if(count >= 1)
{
_kanji_query.addBindValue(v_1);
}
if(count >= 2)
{
_kanji_query.addBindValue(v_2);
}
if(count >= 3)
{
_kanji_query.addBindValue(v_3);
}
if(count >= 4)
{
_kanji_query.addBindValue(v_4);
}
if(count >= 5)
{
_kanji_query.addBindValue(v_5);
}
if(count >= 6)
{
_kanji_query.addBindValue(v_6);
}
if(count >= 7)
{
_kanji_query.addBindValue(v_7);
}
if(count >= 8)
{
_kanji_query.addBindValue(v_8);
}
qDebug() << "DEBUG in " __FILE__ << " " << __LINE__ << ": SELECT statement:" << s;
if(!_kanji_query.exec())
{
QString error = s.append(": ").append(_kanji_query.lastError().text());
qWarning() << error;
_search_started = false;
return false;
}
if(!_kanji_query.isSelect())
{
QString error = s.append(": No SELECT");
qWarning() << error;
_search_started = false;
return false;
}
}
_search_started = true;
return true;
}
bool search::next_hidden()
{
if(!_search_started)
{
return false;
}
if(_kanji_query.next())
{
_literal_result = _kanji_query.value(0).toString();
_meaning_result = _kanji_query.value(1).toString();
QString s = QString("SELECT count(*) FROM saved_kanji WHERE literal=?");
_settings_query.prepare(s);
_settings_query.addBindValue(_literal_result);
if(_settings_query.exec() && _settings_query.isSelect() && _settings_query.next() && _settings_query.value(0).toInt() > 0)
{
_saved = true;
}
else
{
_saved = false;
}
_settings_query.finish();
return true;
}
else
{
_search_started = false;
return false;
}
}
bool search::next()
{
if(!_search_started)
{
return false;
}
if(!_search_for_saved)
{
return next_hidden();
}
else
{
while(next_hidden())
{
if(_saved_search_value == _saved)
{
return true;
}
}
return false;
}
}
QString search::literal()
{
return _literal_result;
}
QString search::meaning()
{
return _meaning_result;
}
bool search::kanji_is_saved()
{
return _saved;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <set>
#include <thread>
#include "cpp_utils/assert.hpp"
#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "server_api.hpp"
#include "server_pages.hpp"
#include "httplib.h"
using namespace budget;
namespace {
bool server_running = false;
void start_server(){
httplib::Server server;
load_pages(server);
load_api(server);
std::string listen = "localhost";
size_t port = 8080;
if(config_contains("server_port")){
port = to_number<size_t>(config_value("server_port"));
}
if(config_contains("server_listen")){
listen = config_value("server_listen");
}
// Listen
server.listen(listen.c_str(), port);
}
void start_cron_loop(){
size_t hours = 0;
while(true){
using namespace std::chrono_literals;
std::this_thread::sleep_for(1h);
++hours;
if(hours % 6 == 0){
std::cout << "Invalidate the currency cache" << std::endl;
budget::invalidate_currency_cache();
}
}
}
} //end of anonymous namespace
void budget::set_server_running(){
// Indicates to the system that it's running in server mode
server_running = true;
}
void budget::server_module::load(){
load_accounts();
load_expenses();
load_earnings();
load_assets();
load_objectives();
load_wishes();
load_fortunes();
load_recurrings(); load_debts();
load_wishes();
}
void budget::server_module::handle(const std::vector<std::string>& args){
cpp_unused(args);
std::cout << "Starting the server" << std::endl;
std::thread server_thread([](){ start_server(); });
std::thread cron_thread([](){ start_cron_loop(); });
server_thread.join();
cron_thread.join();
}
bool budget::is_server_running(){
return server_running;
}
<commit_msg>Clean<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <set>
#include <thread>
#include "cpp_utils/assert.hpp"
#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "server_api.hpp"
#include "server_pages.hpp"
#include "httplib.h"
using namespace budget;
namespace {
bool server_running = false;
void start_server(){
httplib::Server server;
load_pages(server);
load_api(server);
std::string listen = "localhost";
size_t port = 8080;
if(config_contains("server_port")){
port = to_number<size_t>(config_value("server_port"));
}
if(config_contains("server_listen")){
listen = config_value("server_listen");
}
// Listen
server.listen(listen.c_str(), port);
}
void start_cron_loop(){
size_t hours = 0;
while(true){
using namespace std::chrono_literals;
std::this_thread::sleep_for(1h);
++hours;
if(hours % 6 == 0){
std::cout << "Invalidate the currency cache" << std::endl;
budget::invalidate_currency_cache();
}
}
}
} //end of anonymous namespace
void budget::set_server_running(){
// Indicates to the system that it's running in server mode
server_running = true;
}
void budget::server_module::load(){
load_accounts();
load_expenses();
load_earnings();
load_assets();
load_objectives();
load_wishes();
load_fortunes();
load_recurrings();
load_debts();
load_wishes();
}
void budget::server_module::handle(const std::vector<std::string>& args){
cpp_unused(args);
std::cout << "Starting the server" << std::endl;
std::thread server_thread([](){ start_server(); });
std::thread cron_thread([](){ start_cron_loop(); });
server_thread.join();
cron_thread.join();
}
bool budget::is_server_running(){
return server_running;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Author: David Vazquez Garcia <davidvazquez.gijon@gmail.com>
Juan Menendez Blanco <juanmb@gmail.com>
Version: 2.0
Date: 2016/May/26
*******************************************************************************/
#include <Arduino.h>
#include "AccelStepper.h"
#include "sky_pointer.h"
// Calculate the relative movement of a motor for going from 'pos' to 'tgt'
// in the shortest time
int16_t calcSteps(uint16_t pos, uint16_t tgt) {
uint16_t simPos;
int16_t delta1, delta2;
// Obtain the simmetric position
simPos = MOD(pos + USTEPS_REV/2, USTEPS_REV);
// Distance to go (positive / negative)
delta1 = tgt - pos;
// Distance from simmetric position
delta2 = simPos - tgt;
/* Correct delta1 if necessary
The direction can be specified in the move() method by the sign of the
relative distance to go. If positive, the motor turns forward, or
backward otherwhise.
*/
if (pos < USTEPS_REV/2) {
// Transform delta to its (negative) simmetric.
return (delta2 < 0) ? delta1 - USTEPS_REV : delta1;
}
else {
// Transform delta to its (positive) simmetric.
return (delta2 > 0) ? delta1 + USTEPS_REV : delta1;
}
}
// Shield class
SkyPointer::SkyPointer(void) :
azMotor(AccelStepper::DRIVER, XSTEP, XDIR),
altMotor(AccelStepper::DRIVER, YSTEP, YDIR) {
laserOnTime = 0;
homing = false;
absPos = 0;
laserTimeout = LASER_TIMEOUT; // Default laser timeout
}
void SkyPointer::init(void) {
// Enable pin
pinMode(ENABLE, OUTPUT);
digitalWrite(ENABLE, LOW);
// Configure outputs
pinMode(XSTEP, OUTPUT);
pinMode(XDIR, OUTPUT);
pinMode(YSTEP, OUTPUT);
pinMode(YDIR, OUTPUT);
// Photo diode pin
pinMode(PHOTO_PIN, INPUT);
// Laser pin
pinMode(LASER_PIN, OUTPUT);
// Switch laser off at start
laser(false);
// Configure axes logic and dinamics
azMotor.setPinsInverted(false, false, true);
azMotor.setAcceleration(ACCEL);
azMotor.setEnablePin(ENABLE);
altMotor.setPinsInverted(true, false, true);
altMotor.setAcceleration(ACCEL);
altMotor.setEnablePin(ENABLE);
}
// Calculate the relative movement of a motor for going from 'pos' to 'tgt'
// in the shortest time
int16_t SkyPointer::calcAzDelta(uint16_t tgt) {
// Get the motor position
uint16_t pos = MOD(azMotor.currentPosition(), USTEPS_REV);
// Calculate relative motion
int16_t res = calcSteps(pos, tgt);
//Serial.println(res);
// Check that absolute position is in range
if (res != 0) {
if (abs(absPos + res) > SEMIRANGE * USTEPS_REV) {
res = (res > 0) ? res - USTEPS_REV : res + USTEPS_REV;
}
}
absPos += res;
Serial.println(absPos);
return res;
}
int16_t SkyPointer::calcAltDelta(uint16_t tgt) {
// Get the motor position
uint16_t pos = MOD(altMotor.currentPosition(), USTEPS_REV);
// Calculate relative motion
int16_t res = calcSteps(pos, tgt);
return res;
}
void SkyPointer::setLaserTimeout(uint32_t t) {
laserTimeout = t;
}
void SkyPointer::laser(uint8_t enable) {
// Inverted logic: 0 switches laser on, 1 switches it off
digitalWrite(LASER_PIN, !enable);
if (enable) {
laserOnTime = millis();
}
}
uint8_t SkyPointer::isLaserOn(void) {
return !digitalRead(LASER_PIN);
}
void SkyPointer::home() {
digitalWrite(ENABLE, LOW);
altMotor.setMaxSpeed(40);
altMotor.move(-1000);
homing = true;
}
void SkyPointer::move(int16_t az, int16_t alt) {
digitalWrite(ENABLE, LOW);
azMotor.setMaxSpeed(MOVE_SPEED);
altMotor.setMaxSpeed(MOVE_SPEED);
azMotor.move(az);
altMotor.move(alt);
laser(true);
}
void SkyPointer::goTo(uint16_t az, uint16_t alt) {
int16_t delta_az, delta_alt;
//uint16_t pos;
float ratio;
digitalWrite(ENABLE, LOW);
// This assumes that max speed is never reached by any motor in order to
// make a linear motion. For short rotations as the ones done here, it
// is true.
// If max speed was to be reached, the maximum speed for any motor should be
// scaled too by the ratio.
azMotor.setMaxSpeed(GOTO_SPEED);
altMotor.setMaxSpeed(GOTO_SPEED);
// AZ motor
az = MOD(az, USTEPS_REV);
//pos = MOD(azMotor.currentPosition(), USTEPS_REV);
//delta_az = calcSteps(pos, az);
delta_az = calcAzDelta(az);
// ALT motor
alt = MOD(alt, USTEPS_REV);
//pos = MOD(altMotor.currentPosition(), USTEPS_REV);
//delta_alt = calcSteps(pos, alt);
delta_alt = calcAltDelta(alt);
// Assign different accelerations to make a linear motion by making both
// motors arrive at target at the same time. Speeds are kept proportional.
if ((delta_az != 0) && (delta_alt!=0)) {
if (abs(delta_az) >= abs(delta_alt)) {
ratio = (float)(abs(delta_alt)) / abs(delta_az); // ratio < 1
azMotor.setAcceleration(ACCEL);
altMotor.setAcceleration(ACCEL * ratio);
}
if (abs(delta_az) < abs(delta_alt)) {
ratio = (float)(abs(delta_az)) / abs(delta_alt); // ratio < 1
azMotor.setAcceleration(ACCEL * ratio);
altMotor.setAcceleration(ACCEL);
}
}
// Move the motors
azMotor.move(delta_az);
altMotor.move(delta_alt);
laser(true);
}
void SkyPointer::getPos(uint16_t *az, uint16_t *alt) {
*az = MOD(azMotor.currentPosition(), USTEPS_REV);
*alt = MOD(altMotor.currentPosition(), USTEPS_REV);
}
void SkyPointer::stop() {
azMotor.stop();
altMotor.stop();
}
void SkyPointer::releaseMotors() {
digitalWrite(ENABLE, HIGH);
}
void SkyPointer::run() {
azMotor.run();
altMotor.run();
if (isLaserOn()) {
// Switch off the laser if timeout has been reached
if (millis() - laserOnTime > laserTimeout) {
laser(false);
}
} else if (!homing) {
// Switch on the laser if the motors are running
if (azMotor.isRunning() || (altMotor.isRunning())) {
laser(true);
}
}
if (homing && digitalRead(PHOTO_PIN)) {
altMotor.stop();
altMotor.setCurrentPosition(0);
homing = false;
}
}
<commit_msg>Minor cleanup.<commit_after>/*******************************************************************************
Author: David Vazquez Garcia <davidvazquez.gijon@gmail.com>
Juan Menendez Blanco <juanmb@gmail.com>
Version: 2.0
Date: 2016/May/26
*******************************************************************************/
#include <Arduino.h>
#include "AccelStepper.h"
#include "sky_pointer.h"
// Calculate the relative movement of a motor for going from 'pos' to 'tgt'
// in the shortest time
int16_t calcSteps(uint16_t pos, uint16_t tgt) {
uint16_t simPos;
int16_t delta1, delta2;
// Obtain the simmetric position
simPos = MOD(pos + USTEPS_REV/2, USTEPS_REV);
// Distance to go (positive / negative)
delta1 = tgt - pos;
// Distance from simmetric position
delta2 = simPos - tgt;
/* Correct delta1 if necessary
The direction can be specified in the move() method by the sign of the
relative distance to go. If positive, the motor turns forward, or
backward otherwhise.
*/
if (pos < USTEPS_REV/2) {
// Transform delta to its (negative) simmetric.
return (delta2 < 0) ? delta1 - USTEPS_REV : delta1;
}
else {
// Transform delta to its (positive) simmetric.
return (delta2 > 0) ? delta1 + USTEPS_REV : delta1;
}
}
// Shield class
SkyPointer::SkyPointer(void) :
azMotor(AccelStepper::DRIVER, XSTEP, XDIR),
altMotor(AccelStepper::DRIVER, YSTEP, YDIR) {
laserOnTime = 0;
homing = false;
absPos = 0;
laserTimeout = LASER_TIMEOUT; // Default laser timeout
}
void SkyPointer::init(void) {
// Enable pin
pinMode(ENABLE, OUTPUT);
digitalWrite(ENABLE, LOW);
// Configure outputs
pinMode(XSTEP, OUTPUT);
pinMode(XDIR, OUTPUT);
pinMode(YSTEP, OUTPUT);
pinMode(YDIR, OUTPUT);
// Photo diode pin
pinMode(PHOTO_PIN, INPUT);
// Laser pin
pinMode(LASER_PIN, OUTPUT);
// Switch laser off at start
laser(false);
// Configure axes logic and dinamics
azMotor.setPinsInverted(false, false, true);
azMotor.setAcceleration(ACCEL);
azMotor.setEnablePin(ENABLE);
altMotor.setPinsInverted(true, false, true);
altMotor.setAcceleration(ACCEL);
altMotor.setEnablePin(ENABLE);
}
// Calculate the relative movement of a motor for going from 'pos' to 'tgt'
// in the shortest time
int16_t SkyPointer::calcAzDelta(uint16_t tgt) {
// Get the motor position
uint16_t pos = MOD(azMotor.currentPosition(), USTEPS_REV);
// Calculate relative motion
int16_t res = calcSteps(pos, tgt);
//Serial.println(res);
// Check that absolute position is in range
if (res != 0) {
if (abs(absPos + res) > SEMIRANGE * USTEPS_REV) {
res = (res > 0) ? res - USTEPS_REV : res + USTEPS_REV;
}
}
absPos += res;
//Serial.println(absPos);
return res;
}
int16_t SkyPointer::calcAltDelta(uint16_t tgt) {
// Get the motor position
uint16_t pos = MOD(altMotor.currentPosition(), USTEPS_REV);
// Calculate relative motion
int16_t res = calcSteps(pos, tgt);
return res;
}
void SkyPointer::setLaserTimeout(uint32_t t) {
laserTimeout = t;
}
void SkyPointer::laser(uint8_t enable) {
// Inverted logic: 0 switches laser on, 1 switches it off
digitalWrite(LASER_PIN, !enable);
if (enable) {
laserOnTime = millis();
}
}
uint8_t SkyPointer::isLaserOn(void) {
return !digitalRead(LASER_PIN);
}
void SkyPointer::home() {
digitalWrite(ENABLE, LOW);
altMotor.setMaxSpeed(40);
altMotor.move(-1000);
homing = true;
}
void SkyPointer::move(int16_t az, int16_t alt) {
digitalWrite(ENABLE, LOW);
azMotor.setMaxSpeed(MOVE_SPEED);
altMotor.setMaxSpeed(MOVE_SPEED);
azMotor.move(az);
altMotor.move(alt);
laser(true);
}
void SkyPointer::goTo(uint16_t az, uint16_t alt) {
int16_t delta_az, delta_alt;
//uint16_t pos;
float ratio;
digitalWrite(ENABLE, LOW);
// This assumes that max speed is never reached by any motor in order to
// make a linear motion. For short rotations as the ones done here, it
// is true.
// If max speed was to be reached, the maximum speed for any motor should be
// scaled too by the ratio.
azMotor.setMaxSpeed(GOTO_SPEED);
altMotor.setMaxSpeed(GOTO_SPEED);
// AZ motor
az = MOD(az, USTEPS_REV);
//pos = MOD(azMotor.currentPosition(), USTEPS_REV);
//delta_az = calcSteps(pos, az);
delta_az = calcAzDelta(az);
// ALT motor
alt = MOD(alt, USTEPS_REV);
//pos = MOD(altMotor.currentPosition(), USTEPS_REV);
//delta_alt = calcSteps(pos, alt);
delta_alt = calcAltDelta(alt);
// Assign different accelerations to make a linear motion by making both
// motors arrive at target at the same time. Speeds are kept proportional.
if ((delta_az != 0) && (delta_alt!=0)) {
if (abs(delta_az) >= abs(delta_alt)) {
ratio = (float)(abs(delta_alt)) / abs(delta_az); // ratio < 1
azMotor.setAcceleration(ACCEL);
altMotor.setAcceleration(ACCEL * ratio);
}
if (abs(delta_az) < abs(delta_alt)) {
ratio = (float)(abs(delta_az)) / abs(delta_alt); // ratio < 1
azMotor.setAcceleration(ACCEL * ratio);
altMotor.setAcceleration(ACCEL);
}
}
// Move the motors
azMotor.move(delta_az);
altMotor.move(delta_alt);
laser(true);
}
void SkyPointer::getPos(uint16_t *az, uint16_t *alt) {
*az = MOD(azMotor.currentPosition(), USTEPS_REV);
*alt = MOD(altMotor.currentPosition(), USTEPS_REV);
}
void SkyPointer::stop() {
azMotor.stop();
altMotor.stop();
}
void SkyPointer::releaseMotors() {
digitalWrite(ENABLE, HIGH);
}
void SkyPointer::run() {
azMotor.run();
altMotor.run();
if (isLaserOn()) {
// Switch off the laser if timeout has been reached
if (millis() - laserOnTime > laserTimeout) {
laser(false);
}
} else if (!homing) {
// Switch on the laser if the motors are running
if (azMotor.isRunning() || (altMotor.isRunning())) {
laser(true);
}
}
if (homing && digitalRead(PHOTO_PIN)) {
altMotor.stop();
altMotor.setCurrentPosition(0);
homing = false;
}
}
<|endoftext|>
|
<commit_before>#include "sketch.h"
#include "subprocess/subprocess.hpp"
#include <cstdio>
#include <cstring>
#define _USE_MATH_DEFINES
#include <cmath>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include "externs.h"
#include "text.h"
namespace codesketch {
// Sketch variables
SketchState sketchState;
std::vector<SketchState> sketchStateStash;
int sketchSetup;
int mouseX, mouseY;
u8 mouseState;
int frameCount;
// Subprocess
fs::path sketchPath;
subprocess::Process sketchProcess;
// Window recreate
inline void recreateWindow() {
auto winpos = window.getPosition();
window.create(sf::VideoMode(windowWidth, windowHeight),
windowTitle, windowStyle, windowSettings);
window.setPosition(winpos);
}
inline void sketchSendData();
inline void sketchReceiveData();
inline void sketchInit() {
frameCount = 0;
sketchState.fillColor = sf::Color::Black;
sketchState.strokeColor = sf::Color::Black;
sketchState.strokeThickness = 0.0f;
sketchStateStash.clear();
window.clear();
}
bool sketchOpen(const std::string& name) {
fs::path path { name };
if (!fs::exists(path))
return false;
sketchPath = path;
sketchProcess.open(sketchPath.string());
return sketchIsRunning();
}
inline void sketchReadErrors() {
std::string data;
while (sketchProcess.read_stderr_line(data))
printf("[sketch stderr] %s\n", data.c_str());
}
inline void restoreDefaults() {
windowWidth = defaultWindowWidth;
windowHeight = defaultWindowHeight;
windowFramerate = defaultWindowFramerate;
windowSettings.antialiasingLevel = 0;
recreateWindow();
window.setFramerateLimit(windowFramerate);
}
void sketchClose() {
sketchProcess.kill();
sketchPath.clear();
restoreDefaults();
}
inline void sketchReceiveData() {
std::string data;
while (sketchProcess.read_stdout_line(data)) {
std::istringstream cmd(data);
int type;
cmd >> type;
/* Setup exclusive */
if (type == COMMAND_FRAMERATE) {
if (!sketchSetup) {
printf("[sketch warning] Calling framerate from outside setup!\n");
continue;
}
int r;
cmd >> r;
windowFramerate = r;
window.setFramerateLimit(windowFramerate);
}
if (type == COMMAND_SMOOTH) {
if (!sketchSetup) {
printf("[sketch warning] Calling smooth from outside setup!\n");
continue;
}
windowSettings.antialiasingLevel = 8;
recreateWindow();
}
if (type == COMMAND_WINDOW) {
if (!sketchSetup) {
printf("[sketch warning] Calling window from outside setup!\n");
continue;
}
int w, h;
cmd >> w >> h;
windowWidth = w;
windowHeight = h;
recreateWindow();
}
/* -------------- */
if (type == COMMAND_FRAMEEND) {
// Verify incorrect frame ends
// Push and pop imbalance
if (sketchStateStash.size() > 0)
printf("[sketch warning] Push/pop imbalance. For each push must exist a pop!\n");
break;
}
if (type == COMMAND_DEBUG) {
std::string text;
getline(cmd, text);
printf("[sketch debug]: %s\n", text.c_str());
}
if (type == COMMAND_BACKGROUND) {
int r, g, b;
cmd >> r >> g >> b;
window.clear({ (u8)r, (u8)g, (u8)b });
}
if (type == COMMAND_POINT) {
int x, y;
cmd >> x >> y;
float radius = std::max(1.0f, sketchState.strokeThickness) * 0.5f;
sf::CircleShape point { radius };
point.setFillColor(sketchState.strokeColor);
point.setOrigin(radius, radius);
point.setPosition(x, y);
window.draw(point);
}
if (type == COMMAND_LINE) {
int x0, y0, x1, y1;
cmd >> x0 >> y0 >> x1 >> y1;
float angle = std::atan2(y1-y0, x1-x0) * 180.0f / M_PI;
float w = std::sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
float h = std::max(1.0f, sketchState.strokeThickness);
float radius = h * 0.5f;
// Line
sf::RectangleShape line { { w, h } };
line.setFillColor(sketchState.strokeColor);
line.setOrigin(0.0f, h / 2.0f);
line.setPosition(x0, y0);
line.rotate(angle);
// Round ends
sf::CircleShape end0 { radius };
end0.setFillColor(sketchState.strokeColor);
end0.setOrigin(radius, radius);
end0.setPosition(x0, y0);
sf::CircleShape end1 { radius };
end1.setFillColor(sketchState.strokeColor);
end1.setOrigin(radius, radius);
end1.setPosition(x1, y1);
window.draw(line);
window.draw(end0);
window.draw(end1);
}
if (type == COMMAND_RECT) {
int x, y, w, h;
cmd >> x >> y >> w >> h;
sf::RectangleShape rect, strokes[4];
sf::CircleShape corners[4];
// Stroke
for (int i = 0; i < 4; ++i)
strokes[i].setFillColor(sketchState.strokeColor);
// Top
strokes[0].setSize({ (float)w, sketchState.strokeThickness });
strokes[0].setPosition(x, y - sketchState.strokeThickness);
// Bottom
strokes[1].setSize({ (float)w, sketchState.strokeThickness });
strokes[1].setPosition(x, y + h);
// Left
strokes[2].setSize({ sketchState.strokeThickness, (float)h });
strokes[2].setPosition(x - sketchState.strokeThickness, y);
// Right
strokes[3].setSize({ sketchState.strokeThickness, (float)h });
strokes[3].setPosition(x + w, y);
// Round corners
float radius = sketchState.strokeThickness;
for (int i = 0; i < 4; ++i) {
corners[i].setRadius(radius);
corners[i].setFillColor(sketchState.strokeColor);
corners[i].setOrigin(radius, radius);
corners[i].setPosition(x + (i % 2) * w, y + (i / 2) * h);
}
// Fill
rect.setSize({ (float)w, (float)h });
rect.setFillColor(sketchState.fillColor);
rect.setPosition(x, y);
for (int i = 0; i < 4; ++i) {
window.draw(strokes[i]);
window.draw(corners[i]);
}
window.draw(rect);
}
if (type == COMMAND_CIRCLE) {
int x, y, r;
cmd >> x >> y >> r;
float radius = r;
sf::CircleShape circle { radius };
circle.setFillColor(sketchState.fillColor);
circle.setOrigin(radius, radius);
circle.setPosition(x, y);
circle.setOutlineThickness(sketchState.strokeThickness);
circle.setOutlineColor(sketchState.strokeColor);
window.draw(circle);
}
if (type == COMMAND_FILLCOLOR) {
int r, g, b;
cmd >> r >> g >> b;
sketchState.fillColor = { (u8)r, (u8)g, (u8)b };
}
if (type == COMMAND_STROKECOLOR) {
int r, g, b, a;
cmd >> r >> g >> b >> a;
sketchState.strokeColor = { (u8)r, (u8)g, (u8)b, (u8)a };
}
if (type == COMMAND_STROKETHICKNESS) {
int t;
cmd >> t;
sketchState.strokeThickness = t;
}
if (type == COMMAND_TEXT) {
int x, y;
std::string text;
cmd >> x >> y;
getline(cmd, text);
textRender(text, x, y);
}
if (type == COMMAND_TEXTSIZE) {
int s;
cmd >> s;
textSetSize(s);
}
if (type == COMMAND_CAMERA) {
int x, y;
cmd >> x >> y;
auto view = window.getView();
view.setCenter(x + windowWidth / 2.0f, y + windowHeight / 2.0f);
window.setView(view);
}
if (type == COMMAND_PUSH) {
sketchStateStash.push_back(sketchState);
}
if (type == COMMAND_POP) {
if (sketchStateStash.size() > 0) {
sketchState = sketchStateStash.back();
sketchStateStash.pop_back();
} else {
printf("[sketch warning] Trying to pop empty stash!\n");
}
}
}
sketchReadErrors();
}
inline void sketchSendData() {
// Keyboard
char keysstr[keysSize+1] = {};
if (window.hasFocus()) {
for (unsigned i = 0; i < keysSize; ++i)
keysstr[i] = '0'+sf::Keyboard::isKeyPressed(keys[i]);
} else {
for (unsigned i = 0; i < keysSize; ++i)
keysstr[i] = '0';
}
// Mouse
auto mouse = sf::Mouse::getPosition(window);
mouseX = mouse.x;
mouseY = mouse.y;
mouseState = 0;
if (window.hasFocus()) {
for (int i = sf::Mouse::Left; i < sf::Mouse::ButtonCount; ++i)
if (sf::Mouse::isButtonPressed(sf::Mouse::Button(i)))
mouseState |= (1<<i);
}
char data[1024];
sprintf(data, "%d %d %d %d %d %d %s\n",
frameCount, windowWidth, windowHeight, mouseX, mouseY, mouseState, keysstr);
sketchProcess.write(data, strlen(data));
frameCount++;
}
bool sketchIsRunning() {
return sketchProcess.is_active();
}
void sketchRun() {
sketchSendData();
sketchReceiveData();
}
}
<commit_msg>Fixed stderr not being non-blocking<commit_after>#include "sketch.h"
#include "subprocess/subprocess.hpp"
#include <cstdio>
#include <cstring>
#define _USE_MATH_DEFINES
#include <cmath>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include "externs.h"
#include "text.h"
namespace codesketch {
// Sketch variables
SketchState sketchState;
std::vector<SketchState> sketchStateStash;
int sketchSetup;
int mouseX, mouseY;
u8 mouseState;
int frameCount;
// Subprocess
fs::path sketchPath;
subprocess::Process sketchProcess;
// Window recreate
inline void recreateWindow() {
auto winpos = window.getPosition();
window.create(sf::VideoMode(windowWidth, windowHeight),
windowTitle, windowStyle, windowSettings);
window.setPosition(winpos);
}
inline void sketchSendData();
inline void sketchReceiveData();
inline void sketchInit() {
frameCount = 0;
sketchState.fillColor = sf::Color::Black;
sketchState.strokeColor = sf::Color::Black;
sketchState.strokeThickness = 0.0f;
sketchStateStash.clear();
window.clear();
}
bool sketchOpen(const std::string& name) {
fs::path path { name };
if (!fs::exists(path))
return false;
sketchPath = path;
sketchProcess.open(sketchPath.string(), subprocess::OPEN_ALL | subprocess::NONBLOCKING_STDERR);
return sketchIsRunning();
}
inline void sketchReadErrors() {
std::string data;
while (sketchProcess.read_stderr_line(data))
printf("[sketch stderr] %s\n", data.c_str());
}
inline void restoreDefaults() {
windowWidth = defaultWindowWidth;
windowHeight = defaultWindowHeight;
windowFramerate = defaultWindowFramerate;
windowSettings.antialiasingLevel = 0;
recreateWindow();
window.setFramerateLimit(windowFramerate);
}
void sketchClose() {
sketchProcess.kill();
sketchPath.clear();
restoreDefaults();
}
inline void sketchReceiveData() {
std::string data;
while (sketchProcess.read_stdout_line(data)) {
std::istringstream cmd(data);
int type;
cmd >> type;
/* Setup exclusive */
if (type == COMMAND_FRAMERATE) {
if (!sketchSetup) {
printf("[sketch warning] Calling framerate from outside setup!\n");
continue;
}
int r;
cmd >> r;
windowFramerate = r;
window.setFramerateLimit(windowFramerate);
}
if (type == COMMAND_SMOOTH) {
if (!sketchSetup) {
printf("[sketch warning] Calling smooth from outside setup!\n");
continue;
}
windowSettings.antialiasingLevel = 8;
recreateWindow();
}
if (type == COMMAND_WINDOW) {
if (!sketchSetup) {
printf("[sketch warning] Calling window from outside setup!\n");
continue;
}
int w, h;
cmd >> w >> h;
windowWidth = w;
windowHeight = h;
recreateWindow();
}
/* -------------- */
if (type == COMMAND_FRAMEEND) {
// Verify incorrect frame ends
// Push and pop imbalance
if (sketchStateStash.size() > 0)
printf("[sketch warning] Push/pop imbalance. For each push must exist a pop!\n");
break;
}
if (type == COMMAND_DEBUG) {
std::string text;
getline(cmd, text);
printf("[sketch debug]: %s\n", text.c_str());
}
if (type == COMMAND_BACKGROUND) {
int r, g, b;
cmd >> r >> g >> b;
window.clear({ (u8)r, (u8)g, (u8)b });
}
if (type == COMMAND_POINT) {
int x, y;
cmd >> x >> y;
float radius = std::max(1.0f, sketchState.strokeThickness) * 0.5f;
sf::CircleShape point { radius };
point.setFillColor(sketchState.strokeColor);
point.setOrigin(radius, radius);
point.setPosition(x, y);
window.draw(point);
}
if (type == COMMAND_LINE) {
int x0, y0, x1, y1;
cmd >> x0 >> y0 >> x1 >> y1;
float angle = std::atan2(y1-y0, x1-x0) * 180.0f / M_PI;
float w = std::sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
float h = std::max(1.0f, sketchState.strokeThickness);
float radius = h * 0.5f;
// Line
sf::RectangleShape line { { w, h } };
line.setFillColor(sketchState.strokeColor);
line.setOrigin(0.0f, h / 2.0f);
line.setPosition(x0, y0);
line.rotate(angle);
// Round ends
sf::CircleShape end0 { radius };
end0.setFillColor(sketchState.strokeColor);
end0.setOrigin(radius, radius);
end0.setPosition(x0, y0);
sf::CircleShape end1 { radius };
end1.setFillColor(sketchState.strokeColor);
end1.setOrigin(radius, radius);
end1.setPosition(x1, y1);
window.draw(line);
window.draw(end0);
window.draw(end1);
}
if (type == COMMAND_RECT) {
int x, y, w, h;
cmd >> x >> y >> w >> h;
sf::RectangleShape rect, strokes[4];
sf::CircleShape corners[4];
// Stroke
for (int i = 0; i < 4; ++i)
strokes[i].setFillColor(sketchState.strokeColor);
// Top
strokes[0].setSize({ (float)w, sketchState.strokeThickness });
strokes[0].setPosition(x, y - sketchState.strokeThickness);
// Bottom
strokes[1].setSize({ (float)w, sketchState.strokeThickness });
strokes[1].setPosition(x, y + h);
// Left
strokes[2].setSize({ sketchState.strokeThickness, (float)h });
strokes[2].setPosition(x - sketchState.strokeThickness, y);
// Right
strokes[3].setSize({ sketchState.strokeThickness, (float)h });
strokes[3].setPosition(x + w, y);
// Round corners
float radius = sketchState.strokeThickness;
for (int i = 0; i < 4; ++i) {
corners[i].setRadius(radius);
corners[i].setFillColor(sketchState.strokeColor);
corners[i].setOrigin(radius, radius);
corners[i].setPosition(x + (i % 2) * w, y + (i / 2) * h);
}
// Fill
rect.setSize({ (float)w, (float)h });
rect.setFillColor(sketchState.fillColor);
rect.setPosition(x, y);
for (int i = 0; i < 4; ++i) {
window.draw(strokes[i]);
window.draw(corners[i]);
}
window.draw(rect);
}
if (type == COMMAND_CIRCLE) {
int x, y, r;
cmd >> x >> y >> r;
float radius = r;
sf::CircleShape circle { radius };
circle.setFillColor(sketchState.fillColor);
circle.setOrigin(radius, radius);
circle.setPosition(x, y);
circle.setOutlineThickness(sketchState.strokeThickness);
circle.setOutlineColor(sketchState.strokeColor);
window.draw(circle);
}
if (type == COMMAND_FILLCOLOR) {
int r, g, b;
cmd >> r >> g >> b;
sketchState.fillColor = { (u8)r, (u8)g, (u8)b };
}
if (type == COMMAND_STROKECOLOR) {
int r, g, b, a;
cmd >> r >> g >> b >> a;
sketchState.strokeColor = { (u8)r, (u8)g, (u8)b, (u8)a };
}
if (type == COMMAND_STROKETHICKNESS) {
int t;
cmd >> t;
sketchState.strokeThickness = t;
}
if (type == COMMAND_TEXT) {
int x, y;
std::string text;
cmd >> x >> y;
getline(cmd, text);
textRender(text, x, y);
}
if (type == COMMAND_TEXTSIZE) {
int s;
cmd >> s;
textSetSize(s);
}
if (type == COMMAND_CAMERA) {
int x, y;
cmd >> x >> y;
auto view = window.getView();
view.setCenter(x + windowWidth / 2.0f, y + windowHeight / 2.0f);
window.setView(view);
}
if (type == COMMAND_PUSH) {
sketchStateStash.push_back(sketchState);
}
if (type == COMMAND_POP) {
if (sketchStateStash.size() > 0) {
sketchState = sketchStateStash.back();
sketchStateStash.pop_back();
} else {
printf("[sketch warning] Trying to pop empty stash!\n");
}
}
}
sketchReadErrors();
}
inline void sketchSendData() {
// Keyboard
char keysstr[keysSize+1] = {};
if (window.hasFocus()) {
for (unsigned i = 0; i < keysSize; ++i)
keysstr[i] = '0'+sf::Keyboard::isKeyPressed(keys[i]);
} else {
for (unsigned i = 0; i < keysSize; ++i)
keysstr[i] = '0';
}
// Mouse
auto mouse = sf::Mouse::getPosition(window);
mouseX = mouse.x;
mouseY = mouse.y;
mouseState = 0;
if (window.hasFocus()) {
for (int i = sf::Mouse::Left; i < sf::Mouse::ButtonCount; ++i)
if (sf::Mouse::isButtonPressed(sf::Mouse::Button(i)))
mouseState |= (1<<i);
}
char data[1024];
sprintf(data, "%d %d %d %d %d %d %s\n",
frameCount, windowWidth, windowHeight, mouseX, mouseY, mouseState, keysstr);
sketchProcess.write(data, strlen(data));
frameCount++;
}
bool sketchIsRunning() {
return sketchProcess.is_active();
}
void sketchRun() {
sketchSendData();
sketchReceiveData();
}
}
<|endoftext|>
|
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "log.hh"
#include <cstdio>
#include <cstdlib>
#include "helper.hh"
#ifndef DROI
#include <glib.h>
#endif
void Log::push(std::string&s) {
print("<%s>\n",s.c_str());
element.push(s);
}
void Log::push(const char*s)
{
std::string ss(s);
push(ss);
}
void Log::pop() {
std::string s = element.top();
element.pop();
print("</%s>\n",s.c_str());
}
#include <stdarg.h>
void Log::vprint(const char* format,va_list ap,FILE* f,bool urldecode)
{
char* msg=NULL;
if (vasprintf(&msg,format,ap)>0) {
if (urldecode) {
write(unescape_string(msg), f);
} else {
write(msg,f);
}
std::free(msg);
}
fflush(out);
}
void Log::vuprint(const char* format,va_list ap)
{
char* msg=NULL;
if (vasprintf(&msg,format,ap)>0) {
char* m=escape_string(msg);
write(m);
escape_free(m);
std::free(msg);
}
}
void Log::print(const char* format,...)
{
va_list ap;
for (unsigned int i=1; i<element.size(); i++) fprintf(out, " ");
va_start(ap, format);
vprint(format,ap);
va_end(ap);
}
void Log::write(int action,const char *name,const char *msg)
{
fprintf(out,"Action %i, name \"%s\", msg \"%s\"\n",
action,name,msg);
}
void Log::write(const char* msg,FILE* f)
{
fprintf(f,"%s",msg);
}
void Log::write(std::string& msg)
{
write(msg.c_str());
}
void Log::error(const char** format,...)
{
va_list ap0,ap1;
for (unsigned int i=1; i<element.size(); i++) fprintf(out, " ");
va_start(ap0, format[0]);
va_start(ap1, format[1]);
vprint(format[0],ap0);
vprint(format[1],ap1,stderr,true);
va_end(ap0);
va_end(ap1);
}
void Log::debug(const char* msg,...)
{
if (debug_enabled) {
va_list ap;
va_start(ap, msg);
write("<debug msg=\"");
vuprint(msg,ap);
va_end(ap);
write("\"/>\n");
}
}
<commit_msg>use g_vasprintf (mingw)<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "log.hh"
#include <cstdio>
#include <cstdlib>
#include "helper.hh"
#ifndef DROI
#include <glib.h>
#include <glib/gprintf.h>
#else
#define g_vasprintf vasprintf
#endif
void Log::push(std::string&s) {
print("<%s>\n",s.c_str());
element.push(s);
}
void Log::push(const char*s)
{
std::string ss(s);
push(ss);
}
void Log::pop() {
std::string s = element.top();
element.pop();
print("</%s>\n",s.c_str());
}
#include <stdarg.h>
void Log::vprint(const char* format,va_list ap,FILE* f,bool urldecode)
{
char* msg=NULL;
if (g_vasprintf(&msg,format,ap)>0) {
if (urldecode) {
write(unescape_string(msg), f);
} else {
write(msg,f);
}
std::free(msg);
}
fflush(out);
}
void Log::vuprint(const char* format,va_list ap)
{
char* msg=NULL;
if (g_vasprintf(&msg,format,ap)>0) {
char* m=escape_string(msg);
write(m);
escape_free(m);
std::free(msg);
}
}
void Log::print(const char* format,...)
{
va_list ap;
for (unsigned int i=1; i<element.size(); i++) fprintf(out, " ");
va_start(ap, format);
vprint(format,ap);
va_end(ap);
}
void Log::write(int action,const char *name,const char *msg)
{
fprintf(out,"Action %i, name \"%s\", msg \"%s\"\n",
action,name,msg);
}
void Log::write(const char* msg,FILE* f)
{
fprintf(f,"%s",msg);
}
void Log::write(std::string& msg)
{
write(msg.c_str());
}
void Log::error(const char** format,...)
{
va_list ap0,ap1;
for (unsigned int i=1; i<element.size(); i++) fprintf(out, " ");
va_start(ap0, format[0]);
va_start(ap1, format[1]);
vprint(format[0],ap0);
vprint(format[1],ap1,stderr,true);
va_end(ap0);
va_end(ap1);
}
void Log::debug(const char* msg,...)
{
if (debug_enabled) {
va_list ap;
va_start(ap, msg);
write("<debug msg=\"");
vuprint(msg,ap);
va_end(ap);
write("\"/>\n");
}
}
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2005,2006 Erik de Castro Lopo <erikd@mega-nerd.com>
**
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the author nor the names of any 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.
*/
/*
** The above modified BSD style license (GPL and LGPL compatible) applies to
** this file. It does not apply to libsndfile itself which is released under
** the GNU LGPL or the libsndfile test suite which is released under the GNU
** GPL.
** This means that this header file can be used under this modified BSD style
** license, but the LGPL still holds for the libsndfile library itself.
*/
/*
** sndfile.hh -- A lightweight C++ wrapper for the libsndfile API.
**
** All the methods are inlines and all functionality is contained in this
** file. There is no separate implementation file.
**
** API documentation is in the doc/ directory of the source code tarball
** and at http://www.mega-nerd.com/libsndfile/api.html.
*/
#ifndef SNDFILE_HH
#define SNDFILE_HH
#include <sndfile.h>
#include <string>
#include <new> // for std::nothrow
class SndfileHandle
{ private :
struct SNDFILE_ref
{ SNDFILE_ref (void) ;
~SNDFILE_ref (void) ;
SNDFILE *sf ;
SF_INFO sfinfo ;
int ref ;
} ;
SNDFILE_ref *p ;
public :
/* Default constructor */
SndfileHandle (void) : p (NULL) {} ;
SndfileHandle (const char *path, int mode = SFM_READ,
int format = 0, int channels = 0, int samplerate = 0) ;
SndfileHandle (std::string const & path, int mode = SFM_READ,
int format = 0, int channels = 0, int samplerate = 0) ;
~SndfileHandle (void) ;
SndfileHandle (const SndfileHandle &orig) ;
SndfileHandle & operator = (const SndfileHandle &rhs) ;
/* Mainly for debugging/testing. */
int refCount (void) const { return (p == NULL) ? 0 : p->ref ; }
operator bool () const { return (p != NULL) ; }
bool operator == (const SndfileHandle &rhs) const { return (p == rhs.p) ; }
sf_count_t frames (void) const { return p ? p->sfinfo.frames : 0 ; }
int format (void) const { return p ? p->sfinfo.format : 0 ; }
int channels (void) const { return p ? p->sfinfo.channels : 0 ; }
int samplerate (void) const { return p ? p->sfinfo.samplerate : 0 ; }
int error (void) const ;
const char * strError (void) const ;
int command (int cmd, void *data, int datasize) ;
sf_count_t seek (sf_count_t frames, int whence) ;
void writeSync (void) ;
int setString (int str_type, const char* str) ;
const char* getString (int str_type) const ;
static int formatCheck (int format, int channels, int samplerate) ;
sf_count_t read (short *ptr, sf_count_t items) ;
sf_count_t read (int *ptr, sf_count_t items) ;
sf_count_t read (float *ptr, sf_count_t items) ;
sf_count_t read (double *ptr, sf_count_t items) ;
sf_count_t write (const short *ptr, sf_count_t items) ;
sf_count_t write (const int *ptr, sf_count_t items) ;
sf_count_t write (const float *ptr, sf_count_t items) ;
sf_count_t write (const double *ptr, sf_count_t items) ;
sf_count_t readf (short *ptr, sf_count_t frames) ;
sf_count_t readf (int *ptr, sf_count_t frames) ;
sf_count_t readf (float *ptr, sf_count_t frames) ;
sf_count_t readf (double *ptr, sf_count_t frames) ;
sf_count_t writef (const short *ptr, sf_count_t frames) ;
sf_count_t writef (const int *ptr, sf_count_t frames) ;
sf_count_t writef (const float *ptr, sf_count_t frames) ;
sf_count_t writef (const double *ptr, sf_count_t frames) ;
sf_count_t readRaw (void *ptr, sf_count_t bytes) ;
sf_count_t writeRaw (const void *ptr, sf_count_t bytes) ;
} ;
/*==============================================================================
** Nothing but implementation below.
*/
inline
SndfileHandle::SNDFILE_ref::SNDFILE_ref (void)
: ref (1)
{}
inline
SndfileHandle::SNDFILE_ref::~SNDFILE_ref (void)
{ if (sf != NULL) sf_close (sf) ; }
inline
SndfileHandle::SndfileHandle (const char *path, int mode, int fmt, int chans, int srate)
: p (NULL)
{
p = new (std::nothrow) SNDFILE_ref () ;
if (p != NULL)
{ p->ref = 1 ;
p->sfinfo.frames = 0 ;
p->sfinfo.channels = chans ;
p->sfinfo.format = fmt ;
p->sfinfo.samplerate = srate ;
p->sfinfo.sections = 0 ;
p->sfinfo.seekable = 0 ;
if ((p->sf = sf_open (path, mode, &p->sfinfo)) == NULL)
{ delete p ;
p = NULL ;
} ;
} ;
} /* SndfileHandle const char * constructor */
inline
SndfileHandle::SndfileHandle (std::string const & path, int mode, int fmt, int chans, int srate)
: p (NULL)
{
p = new (std::nothrow) SNDFILE_ref () ;
if (p != NULL)
{ p->ref = 1 ;
p->sfinfo.frames = 0 ;
p->sfinfo.channels = chans ;
p->sfinfo.format = fmt ;
p->sfinfo.samplerate = srate ;
p->sfinfo.sections = 0 ;
p->sfinfo.seekable = 0 ;
if ((p->sf = sf_open (path.c_str (), mode, &p->sfinfo)) == NULL)
{ delete p ;
p = NULL ;
} ;
} ;
} /* SndfileHandle std::string constructor */
inline
SndfileHandle::~SndfileHandle (void)
{ if (p != NULL && --p->ref == 0)
delete p ;
} /* SndfileHandle destructor */
inline
SndfileHandle::SndfileHandle (const SndfileHandle &orig)
: p (orig.p)
{ if (p != NULL)
++p->ref ;
} /* SndfileHandle copy constructor */
inline SndfileHandle &
SndfileHandle::operator = (const SndfileHandle &rhs)
{
if (&rhs == this)
return *this ;
if (p != NULL && --p->ref == 0)
delete p ;
p = rhs.p ;
if (p != NULL)
++p->ref ;
return *this ;
} /* SndfileHandle assignment operator */
inline int
SndfileHandle::error (void) const
{ return sf_error (p->sf) ; }
inline const char *
SndfileHandle::strError (void) const
{ return sf_strerror (p->sf) ; }
inline int
SndfileHandle::command (int cmd, void *data, int datasize)
{ return sf_command (p->sf, cmd, data, datasize) ; }
inline sf_count_t
SndfileHandle::seek (sf_count_t frame_count, int whence)
{ return sf_seek (p->sf, frame_count, whence) ; }
inline void
SndfileHandle::writeSync (void)
{ sf_write_sync (p->sf) ; }
inline int
SndfileHandle::setString (int str_type, const char* str)
{ return sf_set_string (p->sf, str_type, str) ; }
inline const char*
SndfileHandle::getString (int str_type) const
{ return sf_get_string (p->sf, str_type) ; }
inline int
SndfileHandle::formatCheck(int fmt, int chans, int srate)
{
SF_INFO sfinfo ;
sfinfo.frames = 0 ;
sfinfo.channels = chans ;
sfinfo.format = fmt ;
sfinfo.samplerate = srate ;
sfinfo.sections = 0 ;
sfinfo.seekable = 0 ;
return sf_format_check (&sfinfo) ;
}
/*---------------------------------------------------------------------*/
inline sf_count_t
SndfileHandle::read (short *ptr, sf_count_t items)
{ return sf_read_short (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::read (int *ptr, sf_count_t items)
{ return sf_read_int (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::read (float *ptr, sf_count_t items)
{ return sf_read_float (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::read (double *ptr, sf_count_t items)
{ return sf_read_double (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::write (const short *ptr, sf_count_t items)
{ return sf_write_short (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::write (const int *ptr, sf_count_t items)
{ return sf_write_int (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::write (const float *ptr, sf_count_t items)
{ return sf_write_float (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::write (const double *ptr, sf_count_t items)
{ return sf_write_double (p->sf, ptr, items) ; }
inline sf_count_t
SndfileHandle::readf (short *ptr, sf_count_t frame_count)
{ return sf_readf_short (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::readf (int *ptr, sf_count_t frame_count)
{ return sf_readf_int (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::readf (float *ptr, sf_count_t frame_count)
{ return sf_readf_float (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::readf (double *ptr, sf_count_t frame_count)
{ return sf_readf_double (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::writef (const short *ptr, sf_count_t frame_count)
{ return sf_writef_short (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::writef (const int *ptr, sf_count_t frame_count)
{ return sf_writef_int (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::writef (const float *ptr, sf_count_t frame_count)
{ return sf_writef_float (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::writef (const double *ptr, sf_count_t frame_count)
{ return sf_writef_double (p->sf, ptr, frame_count) ; }
inline sf_count_t
SndfileHandle::readRaw (void *ptr, sf_count_t bytes)
{ return sf_read_raw (p->sf, ptr, bytes) ; }
inline sf_count_t
SndfileHandle::writeRaw (const void *ptr, sf_count_t bytes)
{ return sf_write_raw (p->sf, ptr, bytes) ; }
#endif /* SNDFILE_HH */
/*
** Do not edit or modify anything in this comment block.
** The following line is a file identity tag for the GNU Arch
** revision control system.
**
** arch-tag: a0e9d996-73d7-47c4-a78d-79a3232a9eef
*/
<commit_msg>Add file sndfile.hh.<commit_after>/*
** Copyright (C) 2005 Erik de Castro Lopo <erikd@mega-nerd.com>
**
** This program 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 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 Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
** sndfile.hh -- A C++ wrapper for the libsndfile API.
**
** API documentation is in the doc/ directory of the source code tarball
** and at http://www.mega-nerd.com/libsndfile/api.html.
*/
#ifndef SNDFILE_HH
#define SNDFILE_HH
#include <sndfile.h>
class SndFile
{ private :
SNDFILE *psf ;
public :
SF_INFO sfinfo ;
/* Default constructor */
SndFile (void) : psf (NULL) {}
~SndFile (void) ;
bool OpenRead (const char *path) ;
bool OpenWrite (const char *path) ;
bool OpenReadWrite (const char *path) ;
int Error (void) ;
const char * StrError (void) ;
int Command (int command, void *data, int datasize) ;
sf_count_t Seek (sf_count_t frames, int whence) ;
int SetString (int str_type, const char* str) ;
const char* GetString (int str_type) ;
sf_count_t Read (short *ptr, sf_count_t items) ;
sf_count_t Read (int *ptr, sf_count_t items) ;
sf_count_t Read (float *ptr, sf_count_t items) ;
sf_count_t Read (double *ptr, sf_count_t items) ;
sf_count_t Write (const short *ptr, sf_count_t items) ;
sf_count_t Write (const int *ptr, sf_count_t items) ;
sf_count_t Write (const float *ptr, sf_count_t items) ;
sf_count_t Write (const double *ptr, sf_count_t items) ;
sf_count_t ReadF (short *ptr, sf_count_t frames) ;
sf_count_t ReadF (int *ptr, sf_count_t frames) ;
sf_count_t ReadF (float *ptr, sf_count_t frames) ;
sf_count_t ReadF (double *ptr, sf_count_t frames) ;
sf_count_t WriteF (const short *ptr, sf_count_t frames) ;
sf_count_t WriteF (const int *ptr, sf_count_t frames) ;
sf_count_t WriteF (const float *ptr, sf_count_t frames) ;
sf_count_t WriteF (const double *ptr, sf_count_t frames) ;
int Close (void) ;
} ;
SndFile::SndFile (const char *path, int mode, SF_INFO *sfinfo)
{ psf = sf_open (path, mode, sfinfo) ;
} /* SndFile constructor */
SndFile::~SndFile (void)
{ if (psf != NULL)
sf_close (psf) ;
psf = NULL ;
} /* SndFile destructor */
bool
SndFile::OpenRead (const char *path)
{ psf = sf_open (path, SFM_READ, &sfinfo) ;
if (psf == NULL)
return false ;
return true ;
} /* SndFile::OpenRead */
bool
SndFile::OpenWrite (const char *path)
{ psf = sf_open (path, SFM_WRITE, &sfinfo) ;
if (psf == NULL)
return false ;
return true ;
} /* SndFile::OpenWrite */
bool
SndFile::OpenReadWrite (const char *path)
{ psf = sf_open (path, SFM_RDWR, &sfinfo) ;
if (psf == NULL)
return false ;
return true ;
} /* SndFile::OpenReadWrite */
#endif /* SNDFILE_HH */
/*
** Do not edit or modify anything in this comment block.
** The following line is a file identity tag for the GNU Arch
** revision control system.
**
** arch-tag: a0e9d996-73d7-47c4-a78d-79a3232a9eef
*/
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
void permission(const struct stat buf, dirent *dirp);
string addC_str(const char *name, char d_name[]);
//function for ls and ls -a
void ls(const char* path, bool isA){
DIR *dirp;
if(NULL == (dirp = opendir(path))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while( (filespecs = readdir(dirp) ) != NULL){
if(isA){
cout << filespecs->d_name << " ";
}
else{
if (strcmp(filespecs->d_name, ".")!=0
&& strcmp(filespecs->d_name, "..")!=0
&& strcmp(filespecs->d_name, ".git") != 0){
cout << filespecs -> d_name << " " ;
}
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
//function for ls -l and also when ls -a -l is called
void ls_l(const char* dir, bool isA, bool isR){
DIR *dirp;
if(NULL == (dirp = opendir(dir))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs;
struct stat s;
//stat(dir, &s);
errno = 0;
while( (filespecs = readdir(dirp) ) != NULL){
stat(dir, &s);
if(isA){
permission(s, filespecs);
}
else if(isR){
}
else{
if (strcmp(filespecs->d_name, ".")!=0
&& strcmp(filespecs->d_name, "..")!=0
&& strcmp(filespecs->d_name, ".git") != 0){
permission(s, filespecs);
}
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
//function for -R
void ls_R(const char* dir){
DIR *dirp;
if(NULL == (dirp = opendir(dir))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while( (filespecs=readdir(dirp)) != NULL){
if(filespecs-> d_name[0] != '.'){
string path;
path += addC_str(dir, filespecs->d_name);
cout << filespecs->d_name << ":" << endl;
if(filespecs-> d_type == DT_DIR)
ls_R(path.c_str());
}
else{
cout << filespecs->d_name << endl;
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
//try to get print info function working so I can delete other functions
void printDir(const char *dir){
DIR *dirp;
if(NULL == (dirp = opendir(dir))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs;
struct stat s;
//stat(dir, &s);
errno = 0;
while( (filespecs = readdir(dirp) ) != NULL){
if (strcmp(filespecs->d_name, ".")!=0 && strcmp(filespecs->d_name, "..")!=0
&& strcmp(filespecs->d_name, ".git") != 0){
stat(dir, &s);
permission(s, filespecs);
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
//permissions to be outputted by -l
void permission(const struct stat buf, dirent *dirp){
//create a struct with for the time
struct tm* file_t;
file_t = localtime( &buf.st_mtime);
char buffer[100];
strftime(buffer, 100, "%h %e %R", file_t);
//output all stat
(buf.st_mode & S_IFDIR)? cout << "d":
(buf.st_mode & S_IFCHR) ? cout<< 'c':
(buf.st_mode & S_IFBLK) ? cout<< 'b':
(buf.st_mode & S_IFIFO) ? cout<< 'f':
(buf.st_mode & S_IFSOCK) ? cout<<'s':
(buf.st_mode & S_IFLNK) ? cout<< 'l':
(buf.st_mode & S_IRUSR)? cout << "r": cout << "-";
(buf.st_mode & S_IWUSR)? cout << "w": cout << "-";
(buf.st_mode & S_IXUSR)? cout << "x": cout << "-";
(buf.st_mode & S_IRGRP)? cout << "r": cout << "-";
(buf.st_mode & S_IWGRP)? cout << "w": cout << "-";
(buf.st_mode & S_IXGRP)? cout << "x": cout << "-";
(buf.st_mode & S_IROTH)? cout << "r": cout << "-";
(buf.st_mode & S_IWOTH)? cout << "w": cout << "-";
(buf.st_mode & S_IXOTH)? cout << "x": cout << "-";
cout << " ";
cout << " " << buf.st_nlink << " ";
cout << getpwuid(buf.st_uid)-> pw_name << " ";
cout << getgrgid(buf.st_gid) -> gr_name << " ";
cout << buf.st_size << " " << buffer << " " << dirp->d_name << endl;
}
int main(int argc, char* argv[]){
//make a vector for the directory names and filenames inputted
//into command line
vector<char*> dir_names;
vector<char*> file_names;
//char* path;
//set flags
int flags=0;
int numFile=1;
//booleans to keep track of which flags are called
bool isA=false;
bool isL=false;
bool isR=false;
//check if the arguments are flags or filenames
for(int pos=1; pos<argc; pos++){
if(!strcmp(argv[pos],"-a")){
isA=true;
flags= flags | FLAG_a;
//ls_a(path);
}
else if(!strcmp(argv[pos], "-l")){
isL=true;
flags = flags | FLAG_l;
}
else if(!strcmp(argv[pos], "-R")){
isR=true;
flags = flags | FLAG_R;
}
else if(!strcmp(argv[pos],"-al") || !strcmp(argv[pos],"-la")){
isA=true;
isL=true;
flags= flags | FLAG_a && FLAG_l;
//ls_a(path);
}
else if(!strcmp(argv[pos],"-aR") || !strcmp(argv[pos],"-Ra")){
isA=true;
flags= flags | FLAG_a;
//ls_a(path);
}
//if it is a file or directory
else{
if(numFile == 1){
char *dir_name = argv[pos];
dir_names[0] = dir_name;
numFile++;
}
else{ dir_names.push_back(argv[pos]); }
}
}
cout << "Outputting argv: ";
for(unsigned i=0; argv[i] != '\0'; i++)
cout << argv[i] << " ";
cout << endl;
for(unsigned int i=0; i < dir_names.size(); i++)
cout << "Here is directory names: " << dir_names[0] << endl;
//cout << flag << endl;
if(argc == 1)
ls(".", isA);
if(isA) ls(".", isA);
if(isL)
ls_l(".", isA, isR);
if(isR)
ls_R(".");
return 0;
}
//function to add path names together
string addC_str(const char *name, char d_name[]){
return string(name) + "/" + string(d_name);
}
<commit_msg>trying to add total for ls -l<commit_after>#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
void permission(int &total,const struct stat buf);
string addC_str(const char *name, char d_name[]);
void getTotal(int &total, struct stat buf, dirent *dirp);
void printInfo(int &total, struct stat buf, dirent *dirp);
//function for ls and ls -a
void ls(const char* path, bool isA){
DIR *dirp;
if(NULL == (dirp = opendir(path))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while( (filespecs = readdir(dirp) ) != NULL){
if(isA){
cout << filespecs->d_name << " ";
}
else{
if (strcmp(filespecs->d_name, ".")!=0
&& strcmp(filespecs->d_name, "..")!=0
&& strcmp(filespecs->d_name, ".git") != 0){
cout << filespecs -> d_name << " " ;
}
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
//function for ls -l and also when ls -a -l is called
void ls_l(const char* dir, bool isA, bool isR){
DIR *dirp;
if(NULL == (dirp = opendir(dir))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs1;
struct dirent *filespecs2;
struct stat s;
// stat(dir, &s);
errno = 0;
int total=0;
while( (filespecs1=readdir(dirp)) != NULL){
stat(dir, &s);
getTotal(total, s, filespecs1);
}
cout << "Total: " << total/2 << endl;
while( (filespecs2 = readdir(dirp) ) != NULL){
stat(dir, &s);
if(isA){
//cout << "Total: " << total/2 << endl;
printInfo(total,s,filespecs2);
}
else if(isR){
//TO DO
}
else{
if (strcmp(filespecs2->d_name, ".")!=0
&& strcmp(filespecs2->d_name, "..")!=0
&& strcmp(filespecs2->d_name, ".git") != 0){
//cout << "Total: " << total/2 << endl;
printInfo(total,s, filespecs2);
}
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
//function for -R
void ls_R(const char* dir){
DIR *dirp;
if(NULL == (dirp = opendir(dir))){
perror("There was an error with opendir().");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while( (filespecs=readdir(dirp)) != NULL){
if(filespecs-> d_name[0] != '.'){
string path;
path += addC_str(dir, filespecs->d_name);
cout << filespecs->d_name << ":" << endl;
if(filespecs-> d_type == DT_DIR)
ls_R(path.c_str());
}
else{
cout << filespecs->d_name << endl;
}
}
if(errno != 0){
perror("There was an error with readdir().");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir().");
exit(1);
}
return;
}
void printInfo(int &total, struct stat buf, dirent *dirp){
stat(dirp->d_name, &buf);
//create a struct with for the time
struct tm* timeinfo;
timeinfo = localtime( &buf.st_mtime);
char buffer[20];
strftime(buffer, 20, "%b %d %H:%M", timeinfo);
struct passwd *pw;
if(!(pw = getpwuid(buf.st_uid)))
perror("there was an error with getpwuid");
struct group *gp;
if(!(gp= getgrgid(buf.st_gid)))
perror("there was an error with getgrgid");
permission(total, buf);
cout << " " << buf.st_nlink << " ";
cout << pw-> pw_name << " ";
cout << gp -> gr_name << " ";
cout << buf.st_size << " " << buffer << " " << dirp->d_name << endl;
}
void getTotal(int &total, struct stat buf, dirent *dirp){
total += buf.st_blocks;
return;
}
//permissions to be outputted by -l
void permission(int &total,struct stat buf){
//output all stat
(buf.st_mode & S_IFDIR)? cout << "d":
(buf.st_mode & S_IFCHR) ? cout<< 'c':
(buf.st_mode & S_IFBLK) ? cout<< 'b':
(buf.st_mode & S_IFIFO) ? cout<< 'f':
(buf.st_mode & S_IFSOCK) ? cout<<'s':
(buf.st_mode & S_IFLNK) ? cout<< 'l':
(buf.st_mode & S_IRUSR)? cout << "r": cout << "-";
(buf.st_mode & S_IWUSR)? cout << "w": cout << "-";
(buf.st_mode & S_IXUSR)? cout << "x": cout << "-";
(buf.st_mode & S_IRGRP)? cout << "r": cout << "-";
(buf.st_mode & S_IWGRP)? cout << "w": cout << "-";
(buf.st_mode & S_IXGRP)? cout << "x": cout << "-";
(buf.st_mode & S_IROTH)? cout << "r": cout << "-";
(buf.st_mode & S_IWOTH)? cout << "w": cout << "-";
(buf.st_mode & S_IXOTH)? cout << "x": cout << "-";
cout << " ";
total += buf.st_blocks;
}
int main(int argc, char* argv[]){
//make a vector for the directory names and filenames inputted
//into command line
vector<char*> dir_names;
vector<char*> file_names;
//char* path;
//set flags
int flags=0;
int numFile=1;
//booleans to keep track of which flags are called
bool isA=false;
bool isL=false;
bool isR=false;
//check if the arguments are flags or filenames
for(int pos=1; pos<argc; pos++){
if(!strcmp(argv[pos],"-a")){
isA=true;
flags= flags | FLAG_a;
//ls_a(path);
}
else if(!strcmp(argv[pos], "-l")){
isL=true;
flags = flags | FLAG_l;
}
else if(!strcmp(argv[pos], "-R")){
isR=true;
flags = flags | FLAG_R;
}
else if(!strcmp(argv[pos],"-al") || !strcmp(argv[pos],"-la")){
isA=true;
isL=true;
flags= flags | FLAG_a && FLAG_l;
//ls_a(path);
}
else if(!strcmp(argv[pos],"-aR") || !strcmp(argv[pos],"-Ra")){
isA=true;
flags= flags | FLAG_a;
//ls_a(path);
}
//if it is a file or directory
else{
if(numFile == 1){
char *dir_name = argv[pos];
dir_names[0] = dir_name;
numFile++;
}
else{ dir_names.push_back(argv[pos]); }
}
}
cout << "Outputting argv: ";
for(unsigned i=0; argv[i] != '\0'; i++)
cout << argv[i] << " ";
cout << endl;
for(unsigned int i=0; i < dir_names.size(); i++)
cout << "Here is directory names: " << dir_names[0] << endl;
//cout << flag << endl;
if(argc == 1)
ls(".", isA);
if(isA) ls(".", isA);
if(isL)
ls_l(".", isA, isR);
if(isR)
ls_R(".");
return 0;
}
//function to add path names together
string addC_str(const char *name, char d_name[]){
return string(name) + "/" + string(d_name);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <dirent.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
using namespace std;
#define NOFLAG 0
#define a 2
#define l 4
#define R 8
void noFlagLs()
{
char const *dirName = ".";
DIR *dirp;
if(!(dirp = opendir(dirName)))
{
cerr << "Error(" << errno << ") opening" << dirName << endl;
//ADD PERROR STATEMENT!!!!!!
}
dirent *direntp;
//ADD PERROR STATEMENT!!!!!!
while((direntp = readdir(dirp)))
{
if((direntp->d_name)[0] != '.')
cout << direntp->d_name << " ";
}
//ADD PERROR STATEMENT!!!!!!
closedir(dirp);
cout << endl;
}
void aFlagLs()
{
char const *dirName = ".";
DIR *dirp;
if(!(dirp = opendir(dirName)))
{
//ADD PERROR STATEMENT!!!!!!
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
//ADD PERROR STATEMENT!!!!!!
while((direntp = readdir(dirp)))
{
cout << direntp->d_name << " ";
}
//ADD PERROR STATEMENT!!!!!!
closedir(dirp);
cout << endl;
}
void lFlagLs()
{
char const *dirName = ".";
DIR *dirp;
if(!(dirp = opendir(dirName)))
{
//ADD PERROR STATEMENT!!!!!!
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
//ADD PERROR STATEMENT!!!!!!
struct stat s;
while((direntp = readdir(dirp)))
{
if((direntp->d_name)[0] != '.')
{
if((stat(direntp->d_name,&s)) == -1)
perror("stat not called properly");
else
{
if(S_ISDIR(s.st_mode))
cout << 'd';
else
cout << '-';
if(s.st_mode & S_IRUSR)
cout << 'r';
else
cout << '-';
if(s.st_mode & S_IWUSR)
cout << 'w';
else
cout << '-';
if(s.st_mode & S_IXUSR)
cout << 'x';
else
cout << '-';
cout << " " << direntp->d_name;
cout << endl;
}
}
}
//ADD PERROR STATEMENT!!!!!!
closedir(dirp);
cout << endl;
}
int main(int argc, char **argv)
{
if(argc == 1)
noFlagLs();
if(argc >= 2)
{
if(argv[1][0] == '-')
{
for(int i = 1; i < argc; ++i)
{
for(int j = 0; argv[i][j] != '\0'; ++j)
{
if(argv[i][j] == 'a')
{
aFlagLs();
}
if(argv[i][j] == 'l')
{
lFlagLs();
}
// else if(argv[i][j] == 'l')
// else
// {
// }
}
}
}
}
else
{
return 0;
}
}
<commit_msg>final<commit_after>#include <iostream>
#include <string>
#include <dirent.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
using namespace std;
#define NOFLAG 0
#define a 2
#define l 4
#define R 8
void noFlagLs()
{
char const *dirName = ".";
DIR *dirp;
if(!(dirp = opendir(dirName)))
{
cerr << "Error(" << errno << ") opening" << dirName << endl;
//ADD PERROR STATEMENT!!!!!!
}
dirent *direntp;
//ADD PERROR STATEMENT!!!!!!
while((direntp = readdir(dirp)))
{
if((direntp->d_name)[0] != '.')
cout << direntp->d_name << " ";
}
//ADD PERROR STATEMENT!!!!!!
closedir(dirp);
cout << endl;
}
void aFlagLs()
{
char const *dirName = ".";
DIR *dirp;
if(!(dirp = opendir(dirName)))
{
//ADD PERROR STATEMENT!!!!!!
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
//ADD PERROR STATEMENT!!!!!!
while((direntp = readdir(dirp)))
{
cout << direntp->d_name << " ";
}
//ADD PERROR STATEMENT!!!!!!
closedir(dirp);
cout << endl;
}
void lFlagLs()
{
char const *dirName = ".";
DIR *dirp;
if(!(dirp = opendir(dirName)))
{
//ADD PERROR STATEMENT!!!!!!
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
//ADD PERROR STATEMENT!!!!!!
struct stat s;
while((direntp = readdir(dirp)))
{
if((direntp->d_name)[0] != '.')
{
if((stat(direntp->d_name,&s)) == -1)
perror("stat not called properly");
else
{
if(S_ISDIR(s.st_mode))
cout << 'd';
else
cout << '-';
if(s.st_mode & S_IRUSR)
cout << 'r';
else
cout << '-';
if(s.st_mode & S_IWUSR)
cout << 'w';
else
cout << '-';
if(s.st_mode & S_IXUSR)
cout << 'x';
else
cout << '-';
if(s.st_mode & S_IRGRP)
cout << 'r';
else
cout << '-';
if(s.st_mode & S_IWGRP)
cout << 'w';
else
cout << '-';
if(s.st_mode & S_IXGRP)
cout << 'x';
else
cout << '-';
if(s.st_mode & S_IROTH)
cout << 'r';
else
cout << '-';
if(s.st_mode & S_IWOTH)
cout << 'w';
else
cout << '-';
if(s.st_mode & S_IXOTH)
cout << 'x';
else
cout << '-';
cout << " " << direntp->d_name;
cout << endl;
}
}
}
//ADD PERROR STATEMENT!!!!!!
closedir(dirp);
cout << endl;
}
int main(int argc, char **argv)
{
if(argc == 1)
noFlagLs();
if(argc >= 2)
{
if(argv[1][0] == '-')
{
for(int i = 1; i < argc; ++i)
{
for(int j = 0; argv[i][j] != '\0'; ++j)
{
if(argv[i][j] == 'a')
{
aFlagLs();
}
if(argv[i][j] == 'l')
{
lFlagLs();
}
// else if(argv[i][j] == 'l')
// else
// {
// }
}
}
}
}
else
{
return 0;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <vector>
#include <algorithm>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <ctime>
using namespace std;
#define FLAG_a 1 // Flag value definitons
#define FLAG_l 2
#define FLAG_R 4
#define D_COLOR "\x1b[38;5;27m" // Print color definitions
#define E_COLOR "\x1b[38;5;34m"
#define H_COLOR "\x1b[47m"
#define RESET_C "\x1b[0m"
bool compare(const string& s1, const string& s2) // Comparison for sort function
{
return strcasecmp(s1.c_str(), s2.c_str()) <= 0;
}
vector<string> listDir(int flag, string init)
{
vector<string> dir;
vector<string> files;
vector<struct stat> info;
struct stat statbuf;
struct stat lstatbuf;
struct pswd *pwd;
struct group *grp;
string dir_path(init);
dir_path.append("/"); // Format for directory output
string copy(dir_path);
const char* directory_name = init.c_str();
DIR *dir_ptr = opendir(directory_name);
if(dir_ptr == NULL)
{
perror("opendir"); // Error checking
return dir;
}
dirent *dirent_ptr;
while(dirent_ptr = readdir(dir_ptr))
files.push_back(dirent_ptr->d_name);
if(errno != 0)
{
perror("readdir"); // Error while reading directory
exit(1); // Exit after error
}
sort(files.begin(), files.end(), compare);
for(unsigned int i = 0; i < files.size(); ++i)
{
dir_path.append(files.at(i));
if((lstat(dir_path.c_str(), &lstatbuf) == -1))
{
perror("lstat");
exit(1);
}
if(S_ISLNK(lstatbuf.st_mode))
{
info.push_back(lstatbuf);
dir_path = copy;
continue;
}
if((stat(dir_path.c_str(), &statbuf)) == -1)
{
perror("stat");
exit(1);
}
info.push_back(statbuf);
if((files.at(i) != ".") && (files.at(i) != "..") && (S_ISDIR(statbuf.st_mode)))
{
dir.push_back(dir_path);
}
dir_path = copy;
}
// Determine which type of output is to follow
if((flag & FLAG_a) && !(flag & FLAG_l))
{
unsigned width = 80; // Output
unsigned longest = 0; // format
for(unsigned int i = 0; i < files.size(); ++i)
{
if(files.at(i).size() > longest)
longest = files.at(i).size();
}
longest += 1; // Space b/w largest entries
unsigned columns = width/longest;
unsigned curr = 0;
for(unsigned int i = 0; i < files.size(); ++i)
{
dir_path.append(files.at(i));
if((stat(dir_path.c_str(), &statbuf)) == -1)
{
perror("stat");
exit(1);
}
if(files.at(i)[0] == '.') // If hidden file
{
cout << H_COLOR;
}
if(S_ISDIR(statbuf.st_mode)) // If directory
{
cout << D_COLOR;
cout << files.at(i) << "/";
curr = files.at(i).size() + 1;
}
else
{
if(statbuf.st_mode & S_IEXEC) // If executable
{
cout << E_COLOR;
}
cout << files.at(i);
curr = files.at(i).size();
}
cout << RESET_C; // Reset color output
cout << string(longest - curr, ' ');
columns--;
if(columns == 0)
{
cout << endl;
columns == width/longest;
}
dir_path = copy;
}
cout << endl;
}
return dir;
}
void allDir(int flag, string init)
{
cout << init << ":" << endl;
vector<string> dir = listDir(flag, init);
if(dir.empty())
return;
cout << endl;
for(unsigned int i = 0; i < dir.size(); ++i) // Recursion happens here
{
allDir(flag, dir.at(i));
}
return;
}
int main(int argc, char** argv)
{
int flag = 0;
vector<string> files;
for(unsigned int i = 1; i < argc; ++i)
{
if(argv[i][0] == '-') // Is a flag
{
for(int j =1; argv[i][j] != 0; ++j)
{
if(argv[i][j] == 'a')
flag |= FLAG_a;
else if(argv[i][j] == 'l')
flag |= FLAG_l;
else if(argv[i][j] == 'R')
flag |= FLAG_R;
else // Invalid flags were passed
{
cerr << "ls: invalid option -- \'" << argv[i][j] << "\'\n";
exit(1);
}
}
}
else files.push_back(argv[i]);
}
sort(files.begin(), files.end(), compare);
if(files.empty())
{
if(flag & FLAG_R)
allDir(flag, ".");
else
listDir(flag, ".");
}
else
{
for(unsigned int i = 0; i < files.size(); ++i)
{
if(flag & FLAG_R)
{
allDir(flag, files.at(i));
if(!(i+1 == files.size()))
cout << endl;
}
else
{
if(files.size() > 1)
cout << files.at(i) << ":" << endl;
listDir(flag, files.at(i));
if(!(i+1 == files.size()))
cout << endl;
}
}
}
return 0;
}
<commit_msg>Finalized other flags and no flags.Program seems to be complete. Testing soon<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <vector>
#include <algorithm>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <ctime>
using namespace std;
#define FLAG_a 1 // Flag value definitons
#define FLAG_l 2
#define FLAG_R 4
#define D_COLOR "\x1b[38;5;27m" // Print color definitions
#define E_COLOR "\x1b[38;5;34m"
#define H_COLOR "\x1b[47m"
#define RESET_C "\x1b[0m"
bool compare(const string& s1, const string& s2) // Comparison for sort function
{
return strcasecmp(s1.c_str(), s2.c_str()) <= 0;
}
vector<string> listDir(int flag, string init)
{
vector<string> dir;
vector<string> files;
vector<struct stat> info;
struct stat statbuf;
struct stat lstatbuf;
struct passwd *pwd;
struct group *grp;
string dir_path(init);
dir_path.append("/"); // Format for directory output
string copy(dir_path);
const char* directory_name = init.c_str();
DIR *dir_ptr = opendir(directory_name);
if(dir_ptr == NULL)
{
perror("opendir"); // Error checking
return dir;
}
dirent *dirent_ptr;
while(dirent_ptr = readdir(dir_ptr))
files.push_back(dirent_ptr->d_name);
if(errno != 0)
{
perror("readdir"); // Error while reading directory
exit(1); // Exit after error
}
sort(files.begin(), files.end(), compare);
for(unsigned int i = 0; i < files.size(); ++i)
{
dir_path.append(files.at(i));
if((lstat(dir_path.c_str(), &lstatbuf) == -1))
{
perror("lstat");
exit(1);
}
if(S_ISLNK(lstatbuf.st_mode))
{
info.push_back(lstatbuf);
dir_path = copy;
continue;
}
if((stat(dir_path.c_str(), &statbuf)) == -1)
{
perror("stat");
exit(1);
}
info.push_back(statbuf);
if((files.at(i) != ".") && (files.at(i) != "..") && (S_ISDIR(statbuf.st_mode)))
{
dir.push_back(dir_path);
}
dir_path = copy;
}
// Determine which type of output is to follow
if((flag & FLAG_a) && !(flag & FLAG_l))
{
unsigned width = 80; // Output
unsigned longest = 0; // format
for(unsigned int i = 0; i < files.size(); ++i)
{
if(files.at(i).size() > longest)
longest = files.at(i).size();
}
longest += 1; // Space b/w largest entries
unsigned columns = width/longest;
unsigned curr = 0;
for(unsigned int i = 0; i < files.size(); ++i)
{
dir_path.append(files.at(i));
if((stat(dir_path.c_str(), &statbuf)) == -1)
{
perror("stat");
exit(1);
}
if(files.at(i)[0] == '.') // If hidden file
{
cout << H_COLOR;
}
if(S_ISDIR(statbuf.st_mode)) // If directory
{
cout << D_COLOR;
cout << files.at(i) << "/";
curr = files.at(i).size() + 1;
}
else
{
if(statbuf.st_mode & S_IEXEC) // If executable
{
cout << E_COLOR;
}
cout << files.at(i);
curr = files.at(i).size();
}
cout << RESET_C; // Reset color output
cout << string(longest - curr, ' ');
columns--;
if(columns == 0)
{
cout << endl;
columns == width/longest;
}
dir_path = copy;
}
cout << endl;
}
else if(flag & FLAG_l)
{
int block = 0;
for(unsigned int i = 0; i < files.size(); ++i)
{
if(!(flag & FLAG_a) && files.at(i)[0] == '.')
continue;
else
block += info.at(i).st_blocks;
}
cout << "total: " << block/2 << endl;
for(unsigned int i = 0; i < files.size(); ++i)
{
if(files.at(i)[0] == '.' && !(flag && FLAG_a))
continue;
else
{
if(S_ISDIR(info.at(i).st_mode))
cout << 'd';
else if(S_ISLNK(info.at(i).st_mode))
cout << 'l';
else
cout << '-';
//Permissions
//user
if(info.at(i).st_mode & S_IRUSR)
cout << 'r';
else cout << '-';
if(info.at(i).st_mode & S_IWUSR)
cout << 'w';
else cout << '-';
if(info.at(i).st_mode & S_IXUSR)
cout << 'x';
else cout << '-';
//Group
if(info.at(i).st_mode & S_IRGRP)
cout << 'r';
else cout << '-';
if(info.at(i).st_mode & S_IWGRP)
cout << 'w';
else cout << '-';
if(info.at(i).st_mode & S_IXGRP)
cout << 'x';
else cout << '-';
//Other
if(info.at(i).st_mode & S_IROTH)
cout << 'r';
else cout << '-';
if(info.at(i).st_mode & S_IWOTH)
cout << 'w';
else cout << '-';
if(info.at(i).st_mode & S_IXOTH)
cout << 'x';
else cout << '-';
cout << " " << info.at(i).st_nlink << " ";
pwd = getpwuid(info.at(i).st_uid);
cout << pwd->pw_name << " ";
grp = getgrgid(info.at(i).st_gid);
cout << grp->gr_name << " ";
cout << info.at(i).st_size << " ";
time_t time = info.at(i).st_mtime;
string time_s = ctime(&time);
cout << time_s.substr(4, 12) << " ";
if(files.at(i)[0] == '.')
cout << H_COLOR;
if(S_ISDIR(info.at(i).st_mode))
{
cout << D_COLOR;
cout << files.at(i);
cout << '/';
}
else
{
if(S_ISLNK(info.at(i).st_mode));
else if(info.at(i).st_mode & S_IEXEC)
cout << E_COLOR;
cout << files.at(i);
}
cout << RESET_C;
if(!(i + 1 == files.size()))
cout << endl;
}
}
cout << endl;
}
else
{
unsigned width = 80;
unsigned longest = 0;
for(unsigned int i = 0; i < files.size(); ++i)
{
if(files.at(i).size() > longest)
longest = files.at(i).size();
}
longest += 2;
unsigned columns = width/longest;
unsigned curr = 0;
for(unsigned int i = 0; i < files.size(); ++i)
{
if(files.at(i)[0] == '.')
continue;
else
{
dir_path.append(files.at(i));
if((stat(dir_path.c_str(), &statbuf)) == -1)
{
perror("stat");
exit(1);
}
if(S_ISDIR(statbuf.st_mode))
{
cout << D_COLOR;
cout << files.at(i) << "/";
curr = files.at(i).size() + 1;
cout << RESET_C;
}
else
{
if(statbuf.st_mode & S_IEXEC)
cout << E_COLOR;
cout << files.at(i);
curr = files.at(i).size();
cout << RESET_C;
}
cout << string(longest - curr, ' ');
columns--;
if(columns == 0)
{
columns = width/longest;
}
dir_path = copy;
}
if((columns == width/longest && columns != 0) || (i+1) == files.size())
cout << endl;
}
}
return dir;
}
void allDir(int flag, string init)
{
cout << init << ":" << endl;
vector<string> dir = listDir(flag, init);
if(dir.empty())
return;
cout << endl;
for(unsigned int i = 0; i < dir.size(); ++i) // Recursion happens here
{
allDir(flag, dir.at(i));
}
return;
}
int main(int argc, char** argv)
{
int flag = 0;
vector<string> files;
for(unsigned int i = 1; i < argc; ++i)
{
if(argv[i][0] == '-') // Is a flag
{
for(int j =1; argv[i][j] != 0; ++j)
{
if(argv[i][j] == 'a')
flag |= FLAG_a;
else if(argv[i][j] == 'l')
flag |= FLAG_l;
else if(argv[i][j] == 'R')
flag |= FLAG_R;
else // Invalid flags were passed
{
cerr << "ls: invalid option -- \'" << argv[i][j] << "\'\n";
exit(1);
}
}
}
else files.push_back(argv[i]);
}
sort(files.begin(), files.end(), compare);
if(files.empty())
{
if(flag & FLAG_R)
allDir(flag, ".");
else
listDir(flag, ".");
}
else
{
for(unsigned int i = 0; i < files.size(); ++i)
{
if(flag & FLAG_R)
{
allDir(flag, files.at(i));
if(!(i+1 == files.size()))
cout << endl;
}
else
{
if(files.size() > 1)
cout << files.at(i) << ":" << endl;
listDir(flag, files.at(i));
if(!(i+1 == files.size()))
cout << endl;
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <pwd.h>
#include <grp.h>
#include <algorithm>
#include <string.h>
#include <deque>
#include <time.h>
#include <vector>
#include <sys/stat.h>
#include <dirent.h>
using namespace std;
class Entry{
string path;
string name;
string info;
public:
Entry(string p, string n, string i){
path = p;
name = n;
info = i;
}
string get_name(){
return this->name;
}
string get_info(){
return this->info;
}
bool operator < (const Entry& e) const{
string x = this->name;
string y = e.name;
if(x == "."){
return true;
}
else if(y == "."){
return false;
}
if(x.at(0) == '.'){
x = x.substr(1,x.size());
}
if(y.at(0) == '.'){
y = y.substr(1,y.size());
}
int k = 0;
for(unsigned int i = 0; i < x.size(); i++){
char im = tolower(x.at(i));
char ex = tolower(y.at(i));
if(im < ex){
return true;
}
else if(im > ex){
if(im > ex && ex == toupper(ex)){
return true;
}
return false;
}
else if(im == ex){
k++;
}
}
return true;
}
};
bool multiCheck(string tmp, bool flags[]){
string chk = "alR";
for(unsigned int i = 1; i < tmp.size(); i++){
if(chk.find(tmp.at(i)) < 0 ||
chk.find(tmp.at(i)) >= tmp.size()){
return false;
}
else if(tmp.at(i) == 'a'){
flags[0] = true;
}
else if(tmp.at(i) == 'l'){
flags[1] = true;
}
else if(tmp.at(i) == 'R' ){
flags[2] = true;
}
}
return true;
}
string getInfo(string path, struct stat buf){
string ret;
vector<string> mnth;
mnth.push_back("Jan");
mnth.push_back("Feb");
mnth.push_back("Mar");
mnth.push_back("Apr");
mnth.push_back("May");
mnth.push_back("Jun");
mnth.push_back("Jul");
mnth.push_back("Aug");
mnth.push_back("Sep");
mnth.push_back("Oct");
mnth.push_back("Nov");
mnth.push_back("Dec");
if(S_ISLNK(buf.st_mode)){
ret.append("l");
}
else if(S_ISDIR(buf.st_mode)){
ret.append("d");
}
else if(S_ISREG(buf.st_mode)){
ret.append("-");
}
ret.append(" ");
int l = buf.st_nlink;
ret.append(to_string(l));
ret.append(" ");
struct passwd *pw = getpwuid(buf.st_uid);
ret.append(pw->pw_name);
ret.append(" ");
struct group *gr = getgrgid(buf.st_gid);
ret.append(gr->gr_name);
ret.append(" ");
int t = buf.st_size;
ret.append(to_string(t));
ret.append(" ");
time_t secs = buf.st_mtime;
struct tm * ptm;
ptm = localtime(&secs);
ret.append(mnth.at(ptm->tm_mon));
ret.append(" ");
ret.append(to_string(ptm->tm_mday));
ret.append(" ");
ret.append(to_string(ptm->tm_hour));
ret.append(":");
ret.append(to_string(ptm->tm_min));
ret.append(" ");
return ret;
}
void print_ls(bool flags[], deque<string> paths, string path){
if(paths.empty()){
return;
}
int cnt = 0;
struct stat buf;
string tmp = paths.front();
string ftmp;
DIR *dirp = opendir(tmp.c_str());
dirent *direntp;
vector<Entry> fileObj;
if(flags[2]){
cout << paths.front() << ":" << endl;
}
while((direntp = readdir(dirp))){
ftmp = direntp->d_name;
string tmpPath = paths.front();
tmpPath.append("/");
tmpPath.append(ftmp);
stat(tmpPath.c_str(), &buf);
string i;
if(flags[1] && flags [0]){
//return string instead of cout
i = getInfo(tmpPath, buf);
}
if(flags[1] && !flags[0] && ftmp.at(0) != '.'){
//return string instead pf cout
i = getInfo(tmpPath, buf);
}
if(flags[0]){
Entry e(tmpPath, direntp->d_name, i);
fileObj.push_back(e);
cnt++;
}
else if(!flags[0] && ftmp.at(0) != '.'){
Entry e(tmpPath, direntp->d_name, i);
fileObj.push_back(e);
cnt++;
}
//construct class obj and push into data structure
if(S_ISDIR(buf.st_mode) && ftmp != "." && ftmp != ".."
&& flags[2]){
if(tmp != ".git"){
if(flags[0]){
paths.push_back(tmpPath);
}
else if(!flags[0] && ftmp.at(0) != '.'){
paths.push_back(tmpPath);
}
}
}
}
sort(fileObj.begin(), fileObj.end());
for(unsigned int i = 0; i < fileObj.size(); i++){
if(flags[1]){
cout << fileObj.at(i).get_info();
}
cout << fileObj.at(i).get_name() << endl;
}
sort(begin(paths), end(paths));
fileObj.clear();
closedir(dirp);
paths.pop_front();
cout << endl;
print_ls(flags, paths, path);
return;
}
int main(int argc, char* argv[]){
unsigned int flagCount = argc - 2;
//int flagCount = argc;
bool flags[3];
flags[0] = false;
flags[1] = false;
flags[2] = false;
bool valid = true;
vector<string> files;
deque<string> paths;
for(unsigned int i = 1; i < flagCount + 2; i++){
string tmp = argv[i];
if(tmp == "-a"){
flags[0] = true;
}
else if(tmp == "-l"){
flags[1] = true;
}
else if(tmp == "-R"){
flags[2] = true;
}
else if(argv[i][0] == '-'){
if(!multiCheck(tmp, flags)){
valid = false;
}
}
else{
files.push_back(argv[i]);
}
}
sort(files.begin(), files.end());
struct stat buf;
if(valid && files.size() <=0){
paths.push_back(".");
string pth = ".";
print_ls(flags, paths, pth);
paths.pop_front();
}
else if(valid && files.size() > 0){
//sort files by name
for(unsigned int i = 0; i < files.size(); i++){
string pth;
if(files.at(i).at(0) == '.'){
paths.push_back(files.at(i));
pth = files.at(i);
if(files.size() > 1){
cout << pth << ":" << endl;
}
print_ls(flags, paths, pth);
paths.pop_front();
}
else if(files.at(i).at(0) == '/'){
paths.push_back(files.at(i));
pth = files.at(i);
if(files.size() > 1){
cout << pth << ":" << endl;
}
print_ls(flags, paths, pth);
paths.pop_front();
}
else{
string x = "./";
x.append(files.at(i));
if(-1 == stat(x.c_str(), &buf)){
perror("stat");
}
else if(S_ISREG(buf.st_mode)){
cout << files.at(i) << endl << endl;
}
else{
paths.push_back("./" + files.at(i));
//pth = "./" + files.at(i);
if(files.size() > 1){
//cout << pth << ":" << endl;
cout << files.at(i) << ":" << endl;
}
print_ls(flags, paths, pth);
paths.pop_front();
}
}
}
}
else{
cerr << "No such flag" << endl;
}
return 0;
}
<commit_msg>fixed various order output issues<commit_after>#include <iostream>
#include <pwd.h>
#include <grp.h>
#include <algorithm>
#include <string.h>
#include <deque>
#include <time.h>
#include <vector>
#include <sys/stat.h>
#include <dirent.h>
using namespace std;
class Entry{
string path;
string name;
string info;
public:
Entry(string p, string n, string i){
path = p;
name = n;
info = i;
}
string get_name(){
return this->name;
}
string get_info(){
return this->info;
}
bool operator < (const Entry& e) const{
string x = this->name;
string y = e.name;
string tmpx = this->name;
string tmpy = this->name;
//cout << x << " " << y << endl;
if(x == "."){
return true;
}
else if(y == "."){
return false;
}
if(x.at(0) == '.'){
x = x.substr(1,x.size());
}
if(y.at(0) == '.'){
y = y.substr(1,y.size());
}
unsigned int k = 0;
for(unsigned int i = 0; i < x.size(); i++){
char im = tolower(x.at(i));
char ex = tolower(y.at(k));
if(im < ex){
//cout << "T1" << endl;
return true;
}
else if(im > ex){
if(im > ex && ex == toupper(ex)){
//cout << "T2" << endl;
return true;
}
return false;
}
else if(im == ex){
/*cout << x << " " << y << endl;
cout << "!" << im << " " << x.at(i) << endl;
if(im != x.at(i) && x.size() == y.size()){
cout << "F1" << endl;
return false;
}
else if(im != x.at(i)){
cout << "T1" << endl;
return true;
}
//cout << "!" << im << " " << y.at(i) << endl;
if(ex != y.at(i)){
//cout << "F2" << endl;
return true;
}*/
if(x.size() < y.size()){
return true;
}
else if(x.size() > y.size()){
return false;
}
else if(x.size() == y.size()){
if(toupper(im) != x.at(i)
&& toupper(ex) == y.at(i)){
return true;
}
else if(toupper(im) == x.at(i)
&& toupper(ex) != y.at(i)){
return false;
}
if(tmpx.at(0) == '.'){
return false;
}
else if(tmpy.at(0) == '.'){
return true;
}
}
k++;
if(k == y.size()){
//cout << "T3" << endl;
return true;
}
}
}
//cout << "T4" << endl;
return true;
}
};
bool multiCheck(string tmp, bool flags[]){
string chk = "alR";
for(unsigned int i = 1; i < tmp.size(); i++){
if(chk.find(tmp.at(i)) < 0 ||
chk.find(tmp.at(i)) >= tmp.size()){
return false;
}
else if(tmp.at(i) == 'a'){
flags[0] = true;
}
else if(tmp.at(i) == 'l'){
flags[1] = true;
}
else if(tmp.at(i) == 'R' ){
flags[2] = true;
}
}
return true;
}
string getInfo(string path, struct stat buf){
string ret;
vector<string> mnth;
mnth.push_back("Jan");
mnth.push_back("Feb");
mnth.push_back("Mar");
mnth.push_back("Apr");
mnth.push_back("May");
mnth.push_back("Jun");
mnth.push_back("Jul");
mnth.push_back("Aug");
mnth.push_back("Sep");
mnth.push_back("Oct");
mnth.push_back("Nov");
mnth.push_back("Dec");
if(S_ISLNK(buf.st_mode)){
ret.append("l");
}
else if(S_ISDIR(buf.st_mode)){
ret.append("d");
}
else if(S_ISREG(buf.st_mode)){
ret.append("-");
}
ret.append(" ");
int l = buf.st_nlink;
ret.append(to_string(l));
ret.append(" ");
struct passwd *pw = getpwuid(buf.st_uid);
ret.append(pw->pw_name);
ret.append(" ");
struct group *gr = getgrgid(buf.st_gid);
ret.append(gr->gr_name);
ret.append(" ");
int t = buf.st_size;
ret.append(to_string(t));
ret.append(" ");
time_t secs = buf.st_mtime;
struct tm * ptm;
ptm = localtime(&secs);
ret.append(mnth.at(ptm->tm_mon));
ret.append(" ");
ret.append(to_string(ptm->tm_mday));
ret.append(" ");
ret.append(to_string(ptm->tm_hour));
ret.append(":");
ret.append(to_string(ptm->tm_min));
ret.append(" ");
return ret;
}
void print_ls(bool flags[], deque<string> paths, string path){
if(paths.empty()){
return;
}
int cnt = 0;
struct stat buf;
string tmp = paths.front();
string ftmp;
DIR *dirp = opendir(tmp.c_str());
dirent *direntp;
vector<Entry> fileObj;
if(flags[2]){
cout << paths.front() << ":" << endl;
}
while((direntp = readdir(dirp))){
ftmp = direntp->d_name;
string tmpPath = paths.front();
tmpPath.append("/");
tmpPath.append(ftmp);
stat(tmpPath.c_str(), &buf);
string i;
if(flags[1] && flags [0]){
//return string instead of cout
i = getInfo(tmpPath, buf);
}
if(flags[1] && !flags[0] && ftmp.at(0) != '.'){
//return string instead pf cout
i = getInfo(tmpPath, buf);
}
if(flags[0]){
Entry e(tmpPath, direntp->d_name, i);
fileObj.push_back(e);
cnt++;
}
else if(!flags[0] && ftmp.at(0) != '.'){
Entry e(tmpPath, direntp->d_name, i);
fileObj.push_back(e);
cnt++;
}
//construct class obj and push into data structure
if(S_ISDIR(buf.st_mode) && ftmp != "." && ftmp != ".."
&& flags[2]){
if(tmp != ".git"){
if(flags[0]){
paths.push_back(tmpPath);
}
else if(!flags[0] && ftmp.at(0) != '.'){
paths.push_back(tmpPath);
}
}
}
}
sort(fileObj.begin(), fileObj.end());
for(unsigned int i = 0; i < fileObj.size(); i++){
if(flags[1]){
cout << fileObj.at(i).get_info();
}
cout << fileObj.at(i).get_name() << endl;
}
sort(begin(paths), end(paths));
fileObj.clear();
closedir(dirp);
paths.pop_front();
cout << endl;
print_ls(flags, paths, path);
return;
}
int main(int argc, char* argv[]){
unsigned int flagCount = argc - 2;
//int flagCount = argc;
bool flags[3];
flags[0] = false;
flags[1] = false;
flags[2] = false;
bool valid = true;
vector<string> files;
deque<string> paths;
for(unsigned int i = 1; i < flagCount + 2; i++){
string tmp = argv[i];
if(tmp == "-a"){
flags[0] = true;
}
else if(tmp == "-l"){
flags[1] = true;
}
else if(tmp == "-R"){
flags[2] = true;
}
else if(argv[i][0] == '-'){
if(!multiCheck(tmp, flags)){
valid = false;
}
}
else{
files.push_back(argv[i]);
}
}
sort(files.begin(), files.end());
struct stat buf;
if(valid && files.size() <=0){
paths.push_back(".");
string pth = ".";
print_ls(flags, paths, pth);
paths.pop_front();
}
else if(valid && files.size() > 0){
//sort files by name
for(unsigned int i = 0; i < files.size(); i++){
string pth;
if(files.at(i).at(0) == '.'){
paths.push_back(files.at(i));
pth = files.at(i);
if(files.size() > 1){
cout << pth << ":" << endl;
}
print_ls(flags, paths, pth);
paths.pop_front();
}
else if(files.at(i).at(0) == '/'){
paths.push_back(files.at(i));
pth = files.at(i);
if(files.size() > 1){
cout << pth << ":" << endl;
}
print_ls(flags, paths, pth);
paths.pop_front();
}
else{
string x = "./";
x.append(files.at(i));
if(-1 == stat(x.c_str(), &buf)){
perror("stat");
}
else if(S_ISREG(buf.st_mode)){
cout << files.at(i) << endl << endl;
}
else{
paths.push_back("./" + files.at(i));
//pth = "./" + files.at(i);
if(files.size() > 1){
//cout << pth << ":" << endl;
cout << files.at(i) << ":" << endl;
}
print_ls(flags, paths, pth);
paths.pop_front();
}
}
}
}
else{
cerr << "No such flag" << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
if (flags.at(i).at(1) == 'a')
isA = true;
else if (flags.at(i).at(1) == 'l')
isL = true;
else if (flags.at(i).at(1) == 'R')
isR = true;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
else {
if (isDirectory(argv[i])) {
directories.push_back(argv[i]);
}
}
}
if (directories.size() == 0) {
if (errno == lsWithFlags(".", flags)) {
return errno;
}
}
}
}
<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true;
else if (flags.at(i).at(k) == 'l')
isL = true;
else if (flags.at(i).at(k) == 'R')
isR = true;
}
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
else {
if (isDirectory(argv[i])) {
directories.push_back(argv[i]);
}
}
}
if (directories.size() == 0) {
if (errno == lsWithFlags(".", flags)) {
return errno;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 "collected_col_matrix_store.h"
#include "dense_matrix.h"
namespace fm
{
namespace eigen
{
namespace
{
std::string cat_mat_names(
const std::vector<detail::matrix_store::const_ptr> &mats)
{
std::string ret;
for (size_t i = 0; i < mats.size() - 1; i++)
ret += mats[i]->get_name() + ", ";
ret += mats.back()->get_name();
return ret;
}
class merge_cols_op: public detail::portion_mapply_op
{
public:
merge_cols_op(size_t num_rows, size_t num_cols,
const scalar_type &type): detail::portion_mapply_op(
num_rows, num_cols, type) {
}
virtual void run(const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const;
virtual portion_mapply_op::const_ptr transpose() const;
virtual std::string to_string(
const std::vector<detail::matrix_store::const_ptr> &mats) const {
return cat_mat_names(mats);
}
};
class merge_rows_op: public detail::portion_mapply_op
{
public:
merge_rows_op(size_t num_rows, size_t num_cols,
const scalar_type &type): detail::portion_mapply_op(
num_rows, num_cols, type) {
}
virtual void run(const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const;
virtual portion_mapply_op::const_ptr transpose() const;
virtual std::string to_string(
const std::vector<detail::matrix_store::const_ptr> &mats) const {
return cat_mat_names(mats);
}
};
detail::portion_mapply_op::const_ptr merge_rows_op::transpose() const
{
return detail::portion_mapply_op::const_ptr(new merge_cols_op(
get_out_num_cols(), get_out_num_rows(), get_output_type()));
}
detail::portion_mapply_op::const_ptr merge_cols_op::transpose() const
{
return detail::portion_mapply_op::const_ptr(new merge_rows_op(
get_out_num_cols(), get_out_num_rows(), get_output_type()));
}
void merge_rows_op::run(
const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const
{
assert(out.store_layout() == matrix_layout_t::L_ROW);
detail::local_row_matrix_store &row_out
= static_cast<detail::local_row_matrix_store &>(out);
size_t out_idx = 0;
for (size_t i = 0; i < ins.size(); i++) {
assert(ins[i]->store_layout() == matrix_layout_t::L_ROW);
const detail::local_row_matrix_store &row_in
= static_cast<const detail::local_row_matrix_store &>(*ins[i]);
for (size_t idx = 0; idx < row_in.get_num_rows(); idx++) {
assert(out_idx < out.get_num_rows());
memcpy(row_out.get_row(out_idx), row_in.get_row(idx),
row_in.get_num_cols() * row_in.get_entry_size());
out_idx++;
}
}
assert(out_idx == out.get_num_rows());
}
void merge_cols_op::run(
const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const
{
assert(out.store_layout() == matrix_layout_t::L_COL);
detail::local_col_matrix_store &col_out
= static_cast<detail::local_col_matrix_store &>(out);
size_t out_idx = 0;
for (size_t i = 0; i < ins.size(); i++) {
assert(ins[i]->store_layout() == matrix_layout_t::L_COL);
const detail::local_col_matrix_store &col_in
= static_cast<const detail::local_col_matrix_store &>(*ins[i]);
for (size_t idx = 0; idx < col_in.get_num_cols(); idx++) {
assert(out_idx < out.get_num_cols());
memcpy(col_out.get_col(out_idx), col_in.get_col(idx),
col_in.get_num_rows() * col_in.get_entry_size());
out_idx++;
}
}
assert(out_idx == out.get_num_cols());
}
}
collected_matrix_store::ptr collected_matrix_store::create(
const std::vector<detail::matrix_store::const_ptr> &mats,
size_t num_cols)
{
assert(!mats.empty());
size_t num_rows = mats[0]->get_num_rows();
const scalar_type &type = mats[0]->get_type();
for (size_t i = 0; i < mats.size(); i++) {
if (num_rows != mats[i]->get_num_rows()) {
BOOST_LOG_TRIVIAL(error)
<< "collected cols have different numbers of rows";
return collected_matrix_store::ptr();
}
if (type != mats[i]->get_type()) {
BOOST_LOG_TRIVIAL(error) << "collected cols have different types";
return collected_matrix_store::ptr();
}
}
return ptr(new collected_matrix_store(mats, num_cols));
}
collected_matrix_store::collected_matrix_store(
const std::vector<detail::matrix_store::const_ptr> &mats,
size_t num_cols): virtual_matrix_store(mats[0]->get_num_rows(),
num_cols, mats[0]->is_in_mem(), mats[0]->get_type())
{
size_t num_rows = mats[0]->get_num_rows();
const scalar_type &type = mats[0]->get_type();
num_nodes = mats[0]->get_num_nodes();
for (size_t i = 0; i < mats.size(); i++) {
// The input matrix might be collected_matrix_store.
// For the sake of performance, we want to collect the original
// matrix stores.
const collected_matrix_store *tmp
= dynamic_cast<const collected_matrix_store *>(
mats[i].get());
if (tmp)
orig_mats.insert(orig_mats.end(), tmp->orig_mats.begin(),
tmp->orig_mats.end());
else
orig_mats.push_back(mats[i]);
for (size_t j = 0; j < mats[i]->get_num_cols(); j++)
rc_idxs.push_back(rc_idx(i, j));
}
assert(rc_idxs.size() <= num_cols);
merged_mat = fm::detail::__mapply_portion_virtual(orig_mats,
detail::portion_mapply_op::const_ptr(new merge_cols_op(
num_rows, rc_idxs.size(), type)),
mats[0]->store_layout());
}
collected_matrix_store::collected_matrix_store(size_t num_rows,
size_t num_cols, bool in_mem, const scalar_type &type,
size_t num_nodes): virtual_matrix_store(num_rows, num_cols, in_mem, type)
{
this->num_nodes = num_nodes;
}
detail::matrix_store::const_ptr collected_matrix_store::get_cols(
const std::vector<off_t> &idxs) const
{
assert(std::is_sorted(idxs.begin(), idxs.end()));
std::vector<detail::matrix_store::const_ptr> ret_mats;
size_t col_idx = 0;
size_t mat_idx = rc_idxs[col_idx].mat_idx;
std::vector<off_t> inner_idxs;
while (col_idx < idxs.size()) {
// If the current still belongs to the same matrix, record the column
// index and continue.
if (rc_idxs[col_idx].mat_idx == mat_idx)
inner_idxs.push_back(rc_idxs[col_idx].inner_idx);
else {
// We now get to another matrix.
ret_mats.push_back(orig_mats[mat_idx]->get_cols(inner_idxs));
mat_idx = rc_idxs[col_idx].mat_idx;
inner_idxs.clear();
inner_idxs.push_back(rc_idxs[col_idx].inner_idx);
}
col_idx++;
}
ret_mats.push_back(orig_mats[mat_idx]->get_cols(inner_idxs));
size_t num_cols = 0;
for (size_t i = 0; i < ret_mats.size(); i++)
num_cols += ret_mats[i]->get_num_cols();
assert(num_cols == idxs.size());
return collected_matrix_store::create(ret_mats, num_cols);
}
detail::matrix_store::const_ptr collected_matrix_store::transpose() const
{
collected_matrix_store *store = new collected_matrix_store(
get_num_cols(), get_num_rows(), is_in_mem(), get_type(),
get_num_nodes());
store->merged_mat = merged_mat->transpose();
store->orig_mats.resize(orig_mats.size());
store->rc_idxs = rc_idxs;
for (size_t i = 0; i < orig_mats.size(); i++)
store->orig_mats[i] = orig_mats[i]->transpose();
return detail::matrix_store::const_ptr(store);
}
}
}
<commit_msg>[Matrix]: fix a bug in collected matrix store in eigensolver.<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 "collected_col_matrix_store.h"
#include "dense_matrix.h"
namespace fm
{
namespace eigen
{
namespace
{
std::string cat_mat_names(
const std::vector<detail::matrix_store::const_ptr> &mats)
{
std::string ret;
for (size_t i = 0; i < mats.size() - 1; i++)
ret += mats[i]->get_name() + ", ";
ret += mats.back()->get_name();
return ret;
}
class merge_cols_op: public detail::portion_mapply_op
{
public:
merge_cols_op(size_t num_rows, size_t num_cols,
const scalar_type &type): detail::portion_mapply_op(
num_rows, num_cols, type) {
}
virtual void run(const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const;
virtual portion_mapply_op::const_ptr transpose() const;
virtual std::string to_string(
const std::vector<detail::matrix_store::const_ptr> &mats) const {
return cat_mat_names(mats);
}
};
class merge_rows_op: public detail::portion_mapply_op
{
public:
merge_rows_op(size_t num_rows, size_t num_cols,
const scalar_type &type): detail::portion_mapply_op(
num_rows, num_cols, type) {
}
virtual void run(const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const;
virtual portion_mapply_op::const_ptr transpose() const;
virtual std::string to_string(
const std::vector<detail::matrix_store::const_ptr> &mats) const {
return cat_mat_names(mats);
}
};
detail::portion_mapply_op::const_ptr merge_rows_op::transpose() const
{
return detail::portion_mapply_op::const_ptr(new merge_cols_op(
get_out_num_cols(), get_out_num_rows(), get_output_type()));
}
detail::portion_mapply_op::const_ptr merge_cols_op::transpose() const
{
return detail::portion_mapply_op::const_ptr(new merge_rows_op(
get_out_num_cols(), get_out_num_rows(), get_output_type()));
}
void merge_rows_op::run(
const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const
{
assert(out.store_layout() == matrix_layout_t::L_ROW);
detail::local_row_matrix_store &row_out
= static_cast<detail::local_row_matrix_store &>(out);
size_t out_idx = 0;
for (size_t i = 0; i < ins.size(); i++) {
assert(ins[i]->store_layout() == matrix_layout_t::L_ROW);
const detail::local_row_matrix_store &row_in
= static_cast<const detail::local_row_matrix_store &>(*ins[i]);
for (size_t idx = 0; idx < row_in.get_num_rows(); idx++) {
assert(out_idx < out.get_num_rows());
memcpy(row_out.get_row(out_idx), row_in.get_row(idx),
row_in.get_num_cols() * row_in.get_entry_size());
out_idx++;
}
}
assert(out_idx == out.get_num_rows());
}
void merge_cols_op::run(
const std::vector<detail::local_matrix_store::const_ptr> &ins,
detail::local_matrix_store &out) const
{
assert(out.store_layout() == matrix_layout_t::L_COL);
detail::local_col_matrix_store &col_out
= static_cast<detail::local_col_matrix_store &>(out);
size_t out_idx = 0;
for (size_t i = 0; i < ins.size(); i++) {
assert(ins[i]->store_layout() == matrix_layout_t::L_COL);
const detail::local_col_matrix_store &col_in
= static_cast<const detail::local_col_matrix_store &>(*ins[i]);
for (size_t idx = 0; idx < col_in.get_num_cols(); idx++) {
assert(out_idx < out.get_num_cols());
memcpy(col_out.get_col(out_idx), col_in.get_col(idx),
col_in.get_num_rows() * col_in.get_entry_size());
out_idx++;
}
}
assert(out_idx == out.get_num_cols());
}
}
collected_matrix_store::ptr collected_matrix_store::create(
const std::vector<detail::matrix_store::const_ptr> &mats,
size_t num_cols)
{
assert(!mats.empty());
size_t num_rows = mats[0]->get_num_rows();
const scalar_type &type = mats[0]->get_type();
for (size_t i = 0; i < mats.size(); i++) {
if (num_rows != mats[i]->get_num_rows()) {
BOOST_LOG_TRIVIAL(error)
<< "collected cols have different numbers of rows";
return collected_matrix_store::ptr();
}
if (type != mats[i]->get_type()) {
BOOST_LOG_TRIVIAL(error) << "collected cols have different types";
return collected_matrix_store::ptr();
}
}
return ptr(new collected_matrix_store(mats, num_cols));
}
static bool all_in_mem(
const std::vector<detail::matrix_store::const_ptr> &mats)
{
bool in_mem = true;
for (size_t i = 0; i < mats.size(); i++)
if (!mats[i]->is_in_mem())
in_mem = false;
return in_mem;
}
collected_matrix_store::collected_matrix_store(
const std::vector<detail::matrix_store::const_ptr> &mats,
size_t num_cols): virtual_matrix_store(mats[0]->get_num_rows(),
num_cols, all_in_mem(mats), mats[0]->get_type())
{
size_t num_rows = mats[0]->get_num_rows();
const scalar_type &type = mats[0]->get_type();
num_nodes = mats[0]->get_num_nodes();
for (size_t i = 0; i < mats.size(); i++) {
// The input matrix might be collected_matrix_store.
// For the sake of performance, we want to collect the original
// matrix stores.
const collected_matrix_store *tmp
= dynamic_cast<const collected_matrix_store *>(
mats[i].get());
if (tmp)
orig_mats.insert(orig_mats.end(), tmp->orig_mats.begin(),
tmp->orig_mats.end());
else
orig_mats.push_back(mats[i]);
for (size_t j = 0; j < mats[i]->get_num_cols(); j++)
rc_idxs.push_back(rc_idx(i, j));
}
assert(rc_idxs.size() <= num_cols);
merged_mat = fm::detail::__mapply_portion_virtual(orig_mats,
detail::portion_mapply_op::const_ptr(new merge_cols_op(
num_rows, rc_idxs.size(), type)),
mats[0]->store_layout());
}
collected_matrix_store::collected_matrix_store(size_t num_rows,
size_t num_cols, bool in_mem, const scalar_type &type,
size_t num_nodes): virtual_matrix_store(num_rows, num_cols, in_mem, type)
{
this->num_nodes = num_nodes;
}
detail::matrix_store::const_ptr collected_matrix_store::get_cols(
const std::vector<off_t> &idxs) const
{
assert(std::is_sorted(idxs.begin(), idxs.end()));
std::vector<detail::matrix_store::const_ptr> ret_mats;
size_t col_idx = 0;
size_t mat_idx = rc_idxs[col_idx].mat_idx;
std::vector<off_t> inner_idxs;
while (col_idx < idxs.size()) {
// If the current still belongs to the same matrix, record the column
// index and continue.
if (rc_idxs[col_idx].mat_idx == mat_idx)
inner_idxs.push_back(rc_idxs[col_idx].inner_idx);
else {
// We now get to another matrix.
ret_mats.push_back(orig_mats[mat_idx]->get_cols(inner_idxs));
mat_idx = rc_idxs[col_idx].mat_idx;
inner_idxs.clear();
inner_idxs.push_back(rc_idxs[col_idx].inner_idx);
}
col_idx++;
}
ret_mats.push_back(orig_mats[mat_idx]->get_cols(inner_idxs));
size_t num_cols = 0;
for (size_t i = 0; i < ret_mats.size(); i++)
num_cols += ret_mats[i]->get_num_cols();
assert(num_cols == idxs.size());
return collected_matrix_store::create(ret_mats, num_cols);
}
detail::matrix_store::const_ptr collected_matrix_store::transpose() const
{
collected_matrix_store *store = new collected_matrix_store(
get_num_cols(), get_num_rows(), is_in_mem(), get_type(),
get_num_nodes());
store->merged_mat = merged_mat->transpose();
store->orig_mats.resize(orig_mats.size());
store->rc_idxs = rc_idxs;
for (size_t i = 0; i < orig_mats.size(); i++)
store->orig_mats[i] = orig_mats[i]->transpose();
return detail::matrix_store::const_ptr(store);
}
}
}
<|endoftext|>
|
<commit_before>#ifndef ITER_COMBINATIONS_HPP_
#define ITER_COMBINATIONS_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <vector>
#include <type_traits>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container>
class Combinator;
template <typename Container>
Combinator<Container> combinations(Container&&, std::size_t);
template <typename T>
Combinator<std::initializer_list<T>> combinations(
std::initializer_list<T>, std::size_t);
template <typename Container>
class Combinator {
private:
Container container;
std::size_t length;
friend Combinator combinations<Container>(Container&&,std::size_t);
template <typename T>
friend Combinator<std::initializer_list<T>> combinations(
std::initializer_list<T>, std::size_t);
Combinator(Container&& in_container, std::size_t in_length)
: container(std::forward<Container>(in_container)),
length{in_length}
{ }
using IndexVector = std::vector<iterator_type<Container>>;
using CombIteratorDeref = IterIterWrapper<IndexVector>;
public:
class Iterator :
public std::iterator<std::input_iterator_tag, CombIteratorDeref>
{
private:
constexpr static const int COMPLETE = -1;
typename std::remove_reference<Container>::type *container_p;
CombIteratorDeref indices;
int steps{};
public:
Iterator(Container& in_container, std::size_t n)
: container_p{&in_container},
indices{n}
{
if (n == 0) {
this->steps = COMPLETE;
return;
}
size_t inc = 0;
for (auto& iter : this->indices.get()) {
auto it = std::begin(*this->container_p);
dumb_advance(it, std::end(*this->container_p), inc);
if (it != std::end(*this->container_p)) {
iter = it;
++inc;
} else {
this->steps = COMPLETE;
break;
}
}
}
CombIteratorDeref& operator*() {
return this->indices;
}
Iterator& operator++() {
for (auto iter = indices.get().rbegin();
iter != indices.get().rend();
++iter) {
++(*iter);
//what we have to check here is if the distance between
//the index and the end of indices is >= the distance
//between the item and end of item
auto dist = std::distance(
this->indices.get().rbegin(),iter);
if (!(dumb_next(*iter, dist) !=
std::end(*this->container_p))) {
if ( (iter + 1) != indices.get().rend()) {
size_t inc = 1;
for (auto down = iter;
down != indices.get().rbegin()-1;
--down) {
(*down) = dumb_next(*(iter + 1), 1 + inc);
++inc;
}
} else {
this->steps = COMPLETE;
break;
}
} else {
break;
}
//we break because none of the rest of the items need
//to be incremented
}
if (this->steps != COMPLETE) {
++this->steps;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->steps == other.steps;
}
};
Iterator begin() {
return {this->container, this->length};
}
Iterator end() {
return {this->container, 0};
}
};
template <typename Container>
Combinator<Container> combinations(
Container&& container, std::size_t length) {
return {std::forward<Container>(container), length};
}
template <typename T>
Combinator<std::initializer_list<T>> combinations(
std::initializer_list<T> il, std::size_t length) {
return {std::move(il), length};
}
}
#endif
<commit_msg>adds operator-> to combinations iter<commit_after>#ifndef ITER_COMBINATIONS_HPP_
#define ITER_COMBINATIONS_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <vector>
#include <type_traits>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container>
class Combinator;
template <typename Container>
Combinator<Container> combinations(Container&&, std::size_t);
template <typename T>
Combinator<std::initializer_list<T>> combinations(
std::initializer_list<T>, std::size_t);
template <typename Container>
class Combinator {
private:
Container container;
std::size_t length;
friend Combinator combinations<Container>(Container&&,std::size_t);
template <typename T>
friend Combinator<std::initializer_list<T>> combinations(
std::initializer_list<T>, std::size_t);
Combinator(Container&& in_container, std::size_t in_length)
: container(std::forward<Container>(in_container)),
length{in_length}
{ }
using IndexVector = std::vector<iterator_type<Container>>;
using CombIteratorDeref = IterIterWrapper<IndexVector>;
public:
class Iterator :
public std::iterator<std::input_iterator_tag, CombIteratorDeref>
{
private:
constexpr static const int COMPLETE = -1;
typename std::remove_reference<Container>::type *container_p;
CombIteratorDeref indices;
int steps{};
public:
Iterator(Container& in_container, std::size_t n)
: container_p{&in_container},
indices{n}
{
if (n == 0) {
this->steps = COMPLETE;
return;
}
size_t inc = 0;
for (auto& iter : this->indices.get()) {
auto it = std::begin(*this->container_p);
dumb_advance(it, std::end(*this->container_p), inc);
if (it != std::end(*this->container_p)) {
iter = it;
++inc;
} else {
this->steps = COMPLETE;
break;
}
}
}
CombIteratorDeref& operator*() {
return this->indices;
}
CombIteratorDeref* operator->() {
return &this->indices;
}
Iterator& operator++() {
for (auto iter = indices.get().rbegin();
iter != indices.get().rend();
++iter) {
++(*iter);
//what we have to check here is if the distance between
//the index and the end of indices is >= the distance
//between the item and end of item
auto dist = std::distance(
this->indices.get().rbegin(),iter);
if (!(dumb_next(*iter, dist) !=
std::end(*this->container_p))) {
if ( (iter + 1) != indices.get().rend()) {
size_t inc = 1;
for (auto down = iter;
down != indices.get().rbegin()-1;
--down) {
(*down) = dumb_next(*(iter + 1), 1 + inc);
++inc;
}
} else {
this->steps = COMPLETE;
break;
}
} else {
break;
}
//we break because none of the rest of the items need
//to be incremented
}
if (this->steps != COMPLETE) {
++this->steps;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->steps == other.steps;
}
};
Iterator begin() {
return {this->container, this->length};
}
Iterator end() {
return {this->container, 0};
}
};
template <typename Container>
Combinator<Container> combinations(
Container&& container, std::size_t length) {
return {std::forward<Container>(container), length};
}
template <typename T>
Combinator<std::initializer_list<T>> combinations(
std::initializer_list<T> il, std::size_t length) {
return {std::move(il), length};
}
}
#endif
<|endoftext|>
|
<commit_before>#include "sys/mman.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "sys/time.h"
#include "time.h"
#include "fcntl.h"
#include "dlfcn.h"
#include "errno.h"
#include "pthread.h"
#include "stdint.h"
#ifdef __i386__
extern "C" uint64_t
cdeclCall(void* function, void* stack, unsigned stackSize,
unsigned returnType);
namespace {
inline uint64_t
dynamicCall(void* function, uint32_t* arguments, uint8_t*,
unsigned, unsigned argumentsSize, unsigned returnType)
{
return cdeclCall(function, arguments, argumentsSize, returnType);
}
} // namespace
#elif defined __x86_64__
extern "C" uint64_t
amd64Call(void* function, void* stack, unsigned stackSize,
void* gprTable, void* sseTable, unsigned returnType);
#include "system.h"
namespace {
uint64_t
dynamicCall(void* function, uint64_t* arguments, uint8_t* argumentTypes,
unsigned argumentCount, unsigned, unsigned returnType)
{
const unsigned GprCount = 6;
uint64_t gprTable[GprCount];
unsigned gprIndex = 0;
const unsigned SseCount = 8;
uint64_t sseTable[SseCount];
unsigned sseIndex = 0;
uint64_t stack[argumentCount];
unsigned stackIndex = 0;
for (unsigned i = 0; i < argumentCount; ++i) {
switch (argumentTypes[i]) {
case FLOAT_TYPE:
case DOUBLE_TYPE: {
if (sseIndex < SseCount) {
sseTable[sseIndex++] = arguments[i];
} else {
stack[stackIndex++] = arguments[i];
}
} break;
default: {
if (gprIndex < GprCount) {
gprTable[gprIndex++] = arguments[i];
} else {
stack[stackIndex++] = arguments[i];
}
} break;
}
}
return amd64Call(function, stack, stackIndex * 8, (gprIndex ? gprTable : 0),
(sseIndex ? sseTable : 0), returnType);
}
} // namespace
#else
# error unsupported platform
#endif
using namespace vm;
namespace {
void*
run(void* t)
{
static_cast<System::Thread*>(t)->run();
return 0;
}
int64_t
now()
{
timeval tv = { 0, 0 };
gettimeofday(&tv, 0);
return (static_cast<int64_t>(tv.tv_sec) * 1000) +
(static_cast<int64_t>(tv.tv_usec) / 1000);
}
const bool Verbose = false;
class MySystem: public System {
public:
class Thread: public System::Thread {
public:
Thread(System* s, System::Runnable* r): s(s), r(r) { }
virtual void run() {
r->run(this);
}
virtual void join() {
int rv = pthread_join(thread, 0);
assert(s, rv == 0);
}
virtual void dispose() {
if (r) {
r->dispose();
}
s->free(this);
}
System* s;
System::Runnable* r;
pthread_t thread;
};
class Monitor: public System::Monitor {
public:
Monitor(System* s): s(s), context(0), depth(0) {
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condition, 0);
}
virtual bool tryAcquire(void* context) {
if (this->context == context) {
++ depth;
return true;
} else {
switch (pthread_mutex_trylock(&mutex)) {
case EBUSY:
return false;
case 0:
this->context = context;
++ depth;
return true;
default:
sysAbort(s);
}
}
}
virtual void acquire(void* context) {
if (this->context != context) {
pthread_mutex_lock(&mutex);
this->context = context;
}
++ depth;
}
virtual void release(void* context) {
if (this->context == context) {
if (-- depth == 0) {
this->context = 0;
pthread_mutex_unlock(&mutex);
}
} else {
sysAbort(s);
}
}
virtual void wait(void* context, int64_t time) {
if (this->context == context) {
unsigned depth = this->depth;
this->depth = 0;
this->context = 0;
if (time) {
int64_t then = now() + time;
timespec ts = { then / 1000, (then % 1000) * 1000 * 1000 };
int rv = pthread_cond_timedwait(&condition, &mutex, &ts);
assert(s, rv == 0);
} else {
int rv = pthread_cond_wait(&condition, &mutex);
assert(s, rv == 0);
}
this->context = context;
this->depth = depth;
} else {
sysAbort(s);
}
}
virtual void notify(void* context) {
if (this->context == context) {
int rv = pthread_cond_signal(&condition);
assert(s, rv == 0);
} else {
sysAbort(s);
}
}
virtual void notifyAll(void* context) {
if (this->context == context) {
int rv = pthread_cond_broadcast(&condition);
assert(s, rv == 0);
} else {
sysAbort(s);
}
}
virtual void* owner() {
return context;
}
virtual void dispose() {
assert(s, context == 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition);
s->free(this);
}
System* s;
pthread_mutex_t mutex;
pthread_cond_t condition;
void* context;
unsigned depth;
};
class Library: public System::Library {
public:
Library(System* s, void* p, System::Library* next):
s(s),
p(p),
next_(next)
{ }
virtual void* resolve(const char* function) {
return dlsym(p, function);
}
virtual System::Library* next() {
return next_;
}
virtual void dispose() {
if (Verbose) {
fprintf(stderr, "close %p\n", p);
}
dlclose(p);
if (next_) {
next_->dispose();
}
s->free(this);
}
System* s;
void* p;
System::Library* next_;
};
MySystem(unsigned limit): limit(limit), count(0) {
pthread_mutex_init(&mutex, 0);
}
virtual bool success(Status s) {
return s == 0;
}
virtual void* tryAllocate(unsigned size) {
pthread_mutex_lock(&mutex);
if (Verbose) {
fprintf(stderr, "try %d; count: %d; limit: %d\n",
size, count, limit);
}
if (count + size > limit) {
pthread_mutex_unlock(&mutex);
return 0;
} else {
uintptr_t* up = static_cast<uintptr_t*>
(malloc(size + sizeof(uintptr_t)));
if (up == 0) {
pthread_mutex_unlock(&mutex);
sysAbort(this);
} else {
*up = size;
count += *up;
pthread_mutex_unlock(&mutex);
return up + 1;
}
}
}
virtual void free(const void* p) {
pthread_mutex_lock(&mutex);
if (p) {
const uintptr_t* up = static_cast<const uintptr_t*>(p) - 1;
if (count < *up) {
abort();
}
count -= *up;
if (Verbose) {
fprintf(stderr, "free " LD "; count: %d; limit: %d\n",
*up, count, limit);
}
::free(const_cast<uintptr_t*>(up));
}
pthread_mutex_unlock(&mutex);
}
virtual Status attach(System::Thread** tp) {
Thread* t = new (System::allocate(sizeof(Thread))) Thread(this, 0);
t->thread = pthread_self();
*tp = t;
return 0;
}
virtual Status start(Runnable* r) {
Thread* t = new (System::allocate(sizeof(Thread))) Thread(this, r);
int rv = pthread_create(&(t->thread), 0, run, t);
assert(this, rv == 0);
return 0;
}
virtual Status make(System::Monitor** m) {
*m = new (System::allocate(sizeof(Monitor))) Monitor(this);
return 0;
}
virtual void sleep(int64_t milliseconds) {
timespec ts = { milliseconds / 1000, (milliseconds % 1000) * 1000 * 1000 };
nanosleep(&ts, 0);
}
virtual uint64_t call(void* function, uintptr_t* arguments, uint8_t* types,
unsigned count, unsigned size, unsigned returnType)
{
return dynamicCall(function, arguments, types, count, size, returnType);
}
virtual Status load(System::Library** lib,
const char* name,
System::Library* next)
{
unsigned size = strlen(name) + 7;
char buffer[size];
snprintf(buffer, size, "lib%s.so", name);
void* p = dlopen(buffer, RTLD_LAZY);
if (p) {
if (Verbose) {
fprintf(stderr, "open %s as %p\n", buffer, p);
}
*lib = new (System::allocate(sizeof(Library))) Library(this, p, next);
return 0;
} else {
return 1;
}
}
virtual void abort() {
::abort();
}
virtual void dispose() {
pthread_mutex_destroy(&mutex);
::free(this);
}
pthread_mutex_t mutex;
unsigned limit;
unsigned count;
};
} // namespace
namespace vm {
System*
makeSystem(unsigned heapSize)
{
return new (malloc(sizeof(MySystem))) MySystem(heapSize);
}
} // namespace vm
<commit_msg>fix i386 build error<commit_after>#include "sys/mman.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "sys/time.h"
#include "time.h"
#include "fcntl.h"
#include "dlfcn.h"
#include "errno.h"
#include "pthread.h"
#include "stdint.h"
#include "system.h"
#ifdef __i386__
extern "C" uint64_t
cdeclCall(void* function, void* stack, unsigned stackSize,
unsigned returnType);
namespace {
inline uint64_t
dynamicCall(void* function, uint32_t* arguments, uint8_t*,
unsigned, unsigned argumentsSize, unsigned returnType)
{
return cdeclCall(function, arguments, argumentsSize, returnType);
}
} // namespace
#elif defined __x86_64__
extern "C" uint64_t
amd64Call(void* function, void* stack, unsigned stackSize,
void* gprTable, void* sseTable, unsigned returnType);
namespace {
uint64_t
dynamicCall(void* function, uint64_t* arguments, uint8_t* argumentTypes,
unsigned argumentCount, unsigned, unsigned returnType)
{
const unsigned GprCount = 6;
uint64_t gprTable[GprCount];
unsigned gprIndex = 0;
const unsigned SseCount = 8;
uint64_t sseTable[SseCount];
unsigned sseIndex = 0;
uint64_t stack[argumentCount];
unsigned stackIndex = 0;
for (unsigned i = 0; i < argumentCount; ++i) {
switch (argumentTypes[i]) {
case FLOAT_TYPE:
case DOUBLE_TYPE: {
if (sseIndex < SseCount) {
sseTable[sseIndex++] = arguments[i];
} else {
stack[stackIndex++] = arguments[i];
}
} break;
default: {
if (gprIndex < GprCount) {
gprTable[gprIndex++] = arguments[i];
} else {
stack[stackIndex++] = arguments[i];
}
} break;
}
}
return amd64Call(function, stack, stackIndex * 8, (gprIndex ? gprTable : 0),
(sseIndex ? sseTable : 0), returnType);
}
} // namespace
#else
# error unsupported platform
#endif
using namespace vm;
namespace {
void*
run(void* t)
{
static_cast<System::Thread*>(t)->run();
return 0;
}
int64_t
now()
{
timeval tv = { 0, 0 };
gettimeofday(&tv, 0);
return (static_cast<int64_t>(tv.tv_sec) * 1000) +
(static_cast<int64_t>(tv.tv_usec) / 1000);
}
const bool Verbose = false;
class MySystem: public System {
public:
class Thread: public System::Thread {
public:
Thread(System* s, System::Runnable* r): s(s), r(r) { }
virtual void run() {
r->run(this);
}
virtual void join() {
int rv = pthread_join(thread, 0);
assert(s, rv == 0);
}
virtual void dispose() {
if (r) {
r->dispose();
}
s->free(this);
}
System* s;
System::Runnable* r;
pthread_t thread;
};
class Monitor: public System::Monitor {
public:
Monitor(System* s): s(s), context(0), depth(0) {
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condition, 0);
}
virtual bool tryAcquire(void* context) {
if (this->context == context) {
++ depth;
return true;
} else {
switch (pthread_mutex_trylock(&mutex)) {
case EBUSY:
return false;
case 0:
this->context = context;
++ depth;
return true;
default:
sysAbort(s);
}
}
}
virtual void acquire(void* context) {
if (this->context != context) {
pthread_mutex_lock(&mutex);
this->context = context;
}
++ depth;
}
virtual void release(void* context) {
if (this->context == context) {
if (-- depth == 0) {
this->context = 0;
pthread_mutex_unlock(&mutex);
}
} else {
sysAbort(s);
}
}
virtual void wait(void* context, int64_t time) {
if (this->context == context) {
unsigned depth = this->depth;
this->depth = 0;
this->context = 0;
if (time) {
int64_t then = now() + time;
timespec ts = { then / 1000, (then % 1000) * 1000 * 1000 };
int rv = pthread_cond_timedwait(&condition, &mutex, &ts);
assert(s, rv == 0);
} else {
int rv = pthread_cond_wait(&condition, &mutex);
assert(s, rv == 0);
}
this->context = context;
this->depth = depth;
} else {
sysAbort(s);
}
}
virtual void notify(void* context) {
if (this->context == context) {
int rv = pthread_cond_signal(&condition);
assert(s, rv == 0);
} else {
sysAbort(s);
}
}
virtual void notifyAll(void* context) {
if (this->context == context) {
int rv = pthread_cond_broadcast(&condition);
assert(s, rv == 0);
} else {
sysAbort(s);
}
}
virtual void* owner() {
return context;
}
virtual void dispose() {
assert(s, context == 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition);
s->free(this);
}
System* s;
pthread_mutex_t mutex;
pthread_cond_t condition;
void* context;
unsigned depth;
};
class Library: public System::Library {
public:
Library(System* s, void* p, System::Library* next):
s(s),
p(p),
next_(next)
{ }
virtual void* resolve(const char* function) {
return dlsym(p, function);
}
virtual System::Library* next() {
return next_;
}
virtual void dispose() {
if (Verbose) {
fprintf(stderr, "close %p\n", p);
}
dlclose(p);
if (next_) {
next_->dispose();
}
s->free(this);
}
System* s;
void* p;
System::Library* next_;
};
MySystem(unsigned limit): limit(limit), count(0) {
pthread_mutex_init(&mutex, 0);
}
virtual bool success(Status s) {
return s == 0;
}
virtual void* tryAllocate(unsigned size) {
pthread_mutex_lock(&mutex);
if (Verbose) {
fprintf(stderr, "try %d; count: %d; limit: %d\n",
size, count, limit);
}
if (count + size > limit) {
pthread_mutex_unlock(&mutex);
return 0;
} else {
uintptr_t* up = static_cast<uintptr_t*>
(malloc(size + sizeof(uintptr_t)));
if (up == 0) {
pthread_mutex_unlock(&mutex);
sysAbort(this);
} else {
*up = size;
count += *up;
pthread_mutex_unlock(&mutex);
return up + 1;
}
}
}
virtual void free(const void* p) {
pthread_mutex_lock(&mutex);
if (p) {
const uintptr_t* up = static_cast<const uintptr_t*>(p) - 1;
if (count < *up) {
abort();
}
count -= *up;
if (Verbose) {
fprintf(stderr, "free " LD "; count: %d; limit: %d\n",
*up, count, limit);
}
::free(const_cast<uintptr_t*>(up));
}
pthread_mutex_unlock(&mutex);
}
virtual Status attach(System::Thread** tp) {
Thread* t = new (System::allocate(sizeof(Thread))) Thread(this, 0);
t->thread = pthread_self();
*tp = t;
return 0;
}
virtual Status start(Runnable* r) {
Thread* t = new (System::allocate(sizeof(Thread))) Thread(this, r);
int rv = pthread_create(&(t->thread), 0, run, t);
assert(this, rv == 0);
return 0;
}
virtual Status make(System::Monitor** m) {
*m = new (System::allocate(sizeof(Monitor))) Monitor(this);
return 0;
}
virtual void sleep(int64_t milliseconds) {
timespec ts = { milliseconds / 1000, (milliseconds % 1000) * 1000 * 1000 };
nanosleep(&ts, 0);
}
virtual uint64_t call(void* function, uintptr_t* arguments, uint8_t* types,
unsigned count, unsigned size, unsigned returnType)
{
return dynamicCall(function, arguments, types, count, size, returnType);
}
virtual Status load(System::Library** lib,
const char* name,
System::Library* next)
{
unsigned size = strlen(name) + 7;
char buffer[size];
snprintf(buffer, size, "lib%s.so", name);
void* p = dlopen(buffer, RTLD_LAZY);
if (p) {
if (Verbose) {
fprintf(stderr, "open %s as %p\n", buffer, p);
}
*lib = new (System::allocate(sizeof(Library))) Library(this, p, next);
return 0;
} else {
return 1;
}
}
virtual void abort() {
::abort();
}
virtual void dispose() {
pthread_mutex_destroy(&mutex);
::free(this);
}
pthread_mutex_t mutex;
unsigned limit;
unsigned count;
};
} // namespace
namespace vm {
System*
makeSystem(unsigned heapSize)
{
return new (malloc(sizeof(MySystem))) MySystem(heapSize);
}
} // namespace vm
<|endoftext|>
|
<commit_before>/*----------------------------------------------------*/
/*--Author: Harrys Kon (Charalambos Konstantinou)-----*/
/*--W: https://harrys.fyi/----------------------------*/
/*--E: konharrys@gmail.com----------------------------*/
/*----------------------------------------------------*/
#include "systab.h"
SysTable::SysTable(Typs s, Typt t)
{
if( s==S14 ) {
if (t == BUS) {
const static double v[] =
{
1, 1, 1.060, 0, 0, 0, 0, 0, 0, 0,
2, 2, 1.045, 0, 40, 42.4, 21.7, 12.7, -40, 50,
3, 2, 1.010, 0, 0, 23.4, 94.2, 19.0, 0, 40,
4, 3, 1.0, 0, 0, 0, 47.8, -3.9, 0, 0,
5, 3, 1.0, 0, 0, 0, 7.6, 1.6, 0, 0,
6, 2, 1.070, 0, 0, 12.2, 11.2, 7.5, -6, 24,
7, 3, 1.0, 0, 0, 0, 0.0, 0.0, 0, 0,
8, 2, 1.090, 0, 0, 17.4, 0.0, 0.0, -6, 24,
9, 3, 1.0, 0, 0, 0, 29.5, 16.6, 0, 0,
10, 3, 1.0, 0, 0, 0, 9.0, 5.8, 0, 0,
11, 3, 1.0, 0, 0, 0, 3.5, 1.8, 0, 0,
12, 3, 1.0, 0, 0, 0, 6.1, 1.6, 0, 0,
13, 3, 1.0, 0, 0, 0, 13.5, 5.8, 0, 0,
14, 3, 1.0, 0, 0, 0, 14.9, 5.0, 0, 0
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 10;
}
else if (t == LINE){
const static double v[] =
{
1, 2, 0.01938, 0.05917, 0.0264, 1,
1, 5, 0.05403, 0.22304, 0.0246, 1,
2, 3, 0.04699, 0.19797, 0.0219, 1,
2, 4, 0.05811, 0.17632, 0.0170, 1,
2, 5, 0.05695, 0.17388, 0.0173, 1,
3, 4, 0.06701, 0.17103, 0.0064, 1,
4, 5, 0.01335, 0.04211, 0.0, 1,
4, 7, 0.0, 0.20912, 0.0, 0.978,
4, 9, 0.0, 0.55618, 0.0, 0.969,
5, 6, 0.0, 0.25202, 0.0, 0.932,
6, 11, 0.09498, 0.19890, 0.0, 1,
6, 12, 0.12291, 0.25581, 0.0, 1,
6, 13, 0.06615, 0.13027, 0.0, 1,
7, 8, 0.0, 0.17615, 0.0, 1,
7, 9, 0.0, 0.11001, 0.0, 1,
9, 10, 0.03181, 0.08450, 0.0, 1,
9, 14, 0.12711, 0.27038, 0.0, 1,
10, 11, 0.08205, 0.19207, 0.0, 1,
12, 13, 0.22092, 0.19988, 0.0, 1,
13, 14, 0.17093, 0.34802, 0.0, 1
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 6;
}
}
else if( s==S30 ) {
if (t == BUS) {
const static double v[] =
{
1, 1, 1.06 , 0, 0, 0 , 0 , 0 , 0 , 0,
2, 2, 1.043, 0, 40, 50.0, 21.7, 12.7, -40, 50,
3, 3, 1.0 , 0, 0, 0 , 2.4, 1.2, 0 , 0,
4, 3, 1.06 , 0, 0, 0 , 7.6, 1.6, 0 , 0,
5, 2, 1.01 , 0, 0, 37.0, 94.2, 19.0, -40, 40,
6, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
7, 3, 1.0 , 0, 0, 0 , 22.8, 10.9, 0 , 0,
8, 2, 1.01 , 0, 0, 37.3, 30.0, 30.0, -10, 40,
9, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
10, 3, 1.0 , 0, 0, 0 , 5.8, 2.0, 0 , 0,
11, 2, 1.082, 0, 0, 16.2, 0.0, 0.0, -6 , 24,
12, 3, 1.0 , 0, 0, 0 , 11.2, 7.5, 0 , 0,
13, 2, 1.071, 0, 0, 10.6, 0.0, 0.0, -6 , 24,
14, 3, 1.0 , 0, 0, 0 , 6.2, 1.6, 0 , 0,
15, 3, 1.0 , 0, 0, 0 , 8.2, 2.5, 0 , 0,
16, 3, 1.0 , 0, 0, 0 , 3.5, 1.8, 0 , 0,
17, 3, 1.0 , 0, 0, 0 , 9.0, 5.8, 0 , 0,
18, 3, 1.0 , 0, 0, 0 , 3.2, 0.9, 0 , 0,
19, 3, 1.0 , 0, 0, 0 , 9.5, 3.4, 0 , 0,
20, 3, 1.0 , 0, 0, 0 , 2.2, 0.7, 0 , 0,
21, 3, 1.0 , 0, 0, 0 , 17.5, 11.2, 0 , 0,
22, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
23, 3, 1.0 , 0, 0, 0 , 3.2, 1.6, 0 , 0,
24, 3, 1.0 , 0, 0, 0 , 8.7, 6.7, 0 , 0,
25, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
26, 3, 1.0 , 0, 0, 0 , 3.5, 2.3, 0 , 0,
27, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
28, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
29, 3, 1.0 , 0, 0, 0 , 2.4, 0.9, 0 , 0,
30, 3, 1.0 , 0, 0, 0 , 10.6, 1.9, 0 , 0
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 10;
}
else if (t == LINE){
const static double v[] =
{
1 , 2, 0.0192, 0.0575, 0.0264, 1,
1 , 3, 0.0452, 0.1652, 0.0204, 1,
2 , 4, 0.0570, 0.1737, 0.0184, 1,
3 , 4, 0.0132, 0.0379, 0.0042, 1,
2 , 5, 0.0472, 0.1983, 0.0209, 1,
2 , 6, 0.0581, 0.1763, 0.0187, 1,
4 , 6, 0.0119, 0.0414, 0.0045, 1,
5 , 7, 0.0460, 0.1160, 0.0102, 1,
6 , 7, 0.0267, 0.0820, 0.0085, 1,
6 , 8, 0.0120, 0.0420, 0.0045, 1,
6 , 9, 0.0 , 0.2080, 0.0 , 0.978,
6 , 10, 0.0 , 0.5560, 0.0 , 0.969,
9 , 11, 0.0 , 0.2080, 0.0 , 1,
9 , 10, 0.0 , 0.1100, 0.0 , 1,
4 , 12, 0.0 , 0.2560, 0.0 , 0.932,
12, 13, 0.0 , 0.1400, 0.0 , 1,
12, 14, 0.1231, 0.2559, 0.0 , 1,
12, 15, 0.0662, 0.1304, 0.0 , 1,
12, 16, 0.0945, 0.1987, 0.0 , 1,
14, 15, 0.2210, 0.1997, 0.0 , 1,
16, 17, 0.0824, 0.1923, 0.0 , 1,
15, 18, 0.1073, 0.2185, 0.0 , 1,
18, 19, 0.0639, 0.1292, 0.0 , 1,
19, 20, 0.0340, 0.0680, 0.0 , 1,
10, 20, 0.0936, 0.2090, 0.0 , 1,
10, 17, 0.0324, 0.0845, 0.0 , 1,
10, 21, 0.0348, 0.0749, 0.0 , 1,
10, 22, 0.0727, 0.1499, 0.0 , 1,
21, 23, 0.0116, 0.0236, 0.0 , 1,
15, 23, 0.1000, 0.2020, 0.0 , 1,
22, 24, 0.1150, 0.1790, 0.0 , 1,
23, 24, 0.1320, 0.2700, 0.0 , 1,
24, 25, 0.1885, 0.3292, 0.0 , 1,
25, 26, 0.2544, 0.3800, 0.0 , 1,
25, 27, 0.1093, 0.2087, 0.0 , 1,
28, 27, 0.0 , 0.3960, 0.0 , 0.968,
27, 29, 0.2198, 0.4153, 0.0 , 1,
27, 30, 0.3202, 0.6027, 0.0 , 1,
29, 30, 0.2399, 0.4533, 0.0 , 1,
8 , 28, 0.0636, 0.2000, 0.0214, 1,
6 , 28, 0.0169, 0.0599, 0.065 , 1
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 6;
}
}
}
<commit_msg>description for IEEE data<commit_after>/*----------------------------------------------------*/
/*--Author: Harrys Kon (Charalambos Konstantinou)-----*/
/*--W: https://harrys.fyi/----------------------------*/
/*--E: konharrys@gmail.com----------------------------*/
/*----------------------------------------------------*/
// Line and bus data for IEEE- 14 & 30 bus systems
#include "systab.h"
SysTable::SysTable(Typs s, Typt t)
{
if( s==S14 ) {
if (t == BUS) {
const static double v[] =
{
1, 1, 1.060, 0, 0, 0, 0, 0, 0, 0,
2, 2, 1.045, 0, 40, 42.4, 21.7, 12.7, -40, 50,
3, 2, 1.010, 0, 0, 23.4, 94.2, 19.0, 0, 40,
4, 3, 1.0, 0, 0, 0, 47.8, -3.9, 0, 0,
5, 3, 1.0, 0, 0, 0, 7.6, 1.6, 0, 0,
6, 2, 1.070, 0, 0, 12.2, 11.2, 7.5, -6, 24,
7, 3, 1.0, 0, 0, 0, 0.0, 0.0, 0, 0,
8, 2, 1.090, 0, 0, 17.4, 0.0, 0.0, -6, 24,
9, 3, 1.0, 0, 0, 0, 29.5, 16.6, 0, 0,
10, 3, 1.0, 0, 0, 0, 9.0, 5.8, 0, 0,
11, 3, 1.0, 0, 0, 0, 3.5, 1.8, 0, 0,
12, 3, 1.0, 0, 0, 0, 6.1, 1.6, 0, 0,
13, 3, 1.0, 0, 0, 0, 13.5, 5.8, 0, 0,
14, 3, 1.0, 0, 0, 0, 14.9, 5.0, 0, 0
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 10;
}
else if (t == LINE){
const static double v[] =
{
1, 2, 0.01938, 0.05917, 0.0264, 1,
1, 5, 0.05403, 0.22304, 0.0246, 1,
2, 3, 0.04699, 0.19797, 0.0219, 1,
2, 4, 0.05811, 0.17632, 0.0170, 1,
2, 5, 0.05695, 0.17388, 0.0173, 1,
3, 4, 0.06701, 0.17103, 0.0064, 1,
4, 5, 0.01335, 0.04211, 0.0, 1,
4, 7, 0.0, 0.20912, 0.0, 0.978,
4, 9, 0.0, 0.55618, 0.0, 0.969,
5, 6, 0.0, 0.25202, 0.0, 0.932,
6, 11, 0.09498, 0.19890, 0.0, 1,
6, 12, 0.12291, 0.25581, 0.0, 1,
6, 13, 0.06615, 0.13027, 0.0, 1,
7, 8, 0.0, 0.17615, 0.0, 1,
7, 9, 0.0, 0.11001, 0.0, 1,
9, 10, 0.03181, 0.08450, 0.0, 1,
9, 14, 0.12711, 0.27038, 0.0, 1,
10, 11, 0.08205, 0.19207, 0.0, 1,
12, 13, 0.22092, 0.19988, 0.0, 1,
13, 14, 0.17093, 0.34802, 0.0, 1
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 6;
}
}
else if( s==S30 ) {
if (t == BUS) {
const static double v[] =
{
1, 1, 1.06 , 0, 0, 0 , 0 , 0 , 0 , 0,
2, 2, 1.043, 0, 40, 50.0, 21.7, 12.7, -40, 50,
3, 3, 1.0 , 0, 0, 0 , 2.4, 1.2, 0 , 0,
4, 3, 1.06 , 0, 0, 0 , 7.6, 1.6, 0 , 0,
5, 2, 1.01 , 0, 0, 37.0, 94.2, 19.0, -40, 40,
6, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
7, 3, 1.0 , 0, 0, 0 , 22.8, 10.9, 0 , 0,
8, 2, 1.01 , 0, 0, 37.3, 30.0, 30.0, -10, 40,
9, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
10, 3, 1.0 , 0, 0, 0 , 5.8, 2.0, 0 , 0,
11, 2, 1.082, 0, 0, 16.2, 0.0, 0.0, -6 , 24,
12, 3, 1.0 , 0, 0, 0 , 11.2, 7.5, 0 , 0,
13, 2, 1.071, 0, 0, 10.6, 0.0, 0.0, -6 , 24,
14, 3, 1.0 , 0, 0, 0 , 6.2, 1.6, 0 , 0,
15, 3, 1.0 , 0, 0, 0 , 8.2, 2.5, 0 , 0,
16, 3, 1.0 , 0, 0, 0 , 3.5, 1.8, 0 , 0,
17, 3, 1.0 , 0, 0, 0 , 9.0, 5.8, 0 , 0,
18, 3, 1.0 , 0, 0, 0 , 3.2, 0.9, 0 , 0,
19, 3, 1.0 , 0, 0, 0 , 9.5, 3.4, 0 , 0,
20, 3, 1.0 , 0, 0, 0 , 2.2, 0.7, 0 , 0,
21, 3, 1.0 , 0, 0, 0 , 17.5, 11.2, 0 , 0,
22, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
23, 3, 1.0 , 0, 0, 0 , 3.2, 1.6, 0 , 0,
24, 3, 1.0 , 0, 0, 0 , 8.7, 6.7, 0 , 0,
25, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
26, 3, 1.0 , 0, 0, 0 , 3.5, 2.3, 0 , 0,
27, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
28, 3, 1.0 , 0, 0, 0 , 0.0, 0.0, 0 , 0,
29, 3, 1.0 , 0, 0, 0 , 2.4, 0.9, 0 , 0,
30, 3, 1.0 , 0, 0, 0 , 10.6, 1.9, 0 , 0
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 10;
}
else if (t == LINE){
const static double v[] =
{
1 , 2, 0.0192, 0.0575, 0.0264, 1,
1 , 3, 0.0452, 0.1652, 0.0204, 1,
2 , 4, 0.0570, 0.1737, 0.0184, 1,
3 , 4, 0.0132, 0.0379, 0.0042, 1,
2 , 5, 0.0472, 0.1983, 0.0209, 1,
2 , 6, 0.0581, 0.1763, 0.0187, 1,
4 , 6, 0.0119, 0.0414, 0.0045, 1,
5 , 7, 0.0460, 0.1160, 0.0102, 1,
6 , 7, 0.0267, 0.0820, 0.0085, 1,
6 , 8, 0.0120, 0.0420, 0.0045, 1,
6 , 9, 0.0 , 0.2080, 0.0 , 0.978,
6 , 10, 0.0 , 0.5560, 0.0 , 0.969,
9 , 11, 0.0 , 0.2080, 0.0 , 1,
9 , 10, 0.0 , 0.1100, 0.0 , 1,
4 , 12, 0.0 , 0.2560, 0.0 , 0.932,
12, 13, 0.0 , 0.1400, 0.0 , 1,
12, 14, 0.1231, 0.2559, 0.0 , 1,
12, 15, 0.0662, 0.1304, 0.0 , 1,
12, 16, 0.0945, 0.1987, 0.0 , 1,
14, 15, 0.2210, 0.1997, 0.0 , 1,
16, 17, 0.0824, 0.1923, 0.0 , 1,
15, 18, 0.1073, 0.2185, 0.0 , 1,
18, 19, 0.0639, 0.1292, 0.0 , 1,
19, 20, 0.0340, 0.0680, 0.0 , 1,
10, 20, 0.0936, 0.2090, 0.0 , 1,
10, 17, 0.0324, 0.0845, 0.0 , 1,
10, 21, 0.0348, 0.0749, 0.0 , 1,
10, 22, 0.0727, 0.1499, 0.0 , 1,
21, 23, 0.0116, 0.0236, 0.0 , 1,
15, 23, 0.1000, 0.2020, 0.0 , 1,
22, 24, 0.1150, 0.1790, 0.0 , 1,
23, 24, 0.1320, 0.2700, 0.0 , 1,
24, 25, 0.1885, 0.3292, 0.0 , 1,
25, 26, 0.2544, 0.3800, 0.0 , 1,
25, 27, 0.1093, 0.2087, 0.0 , 1,
28, 27, 0.0 , 0.3960, 0.0 , 0.968,
27, 29, 0.2198, 0.4153, 0.0 , 1,
27, 30, 0.3202, 0.6027, 0.0 , 1,
29, 30, 0.2399, 0.4533, 0.0 , 1,
8 , 28, 0.0636, 0.2000, 0.0214, 1,
6 , 28, 0.0169, 0.0599, 0.065 , 1
};
data = v;
sz = sizeof(v)/sizeof(v[0]);
cnum = 6;
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; //Print out Hello World
cout << "Aaron Skomra" << endl; //Edit Hello World to print out your name
cout << "David Snyder" << endl;
return 0;
}
<commit_msg>edited helloworld.cpp to print my name<commit_after>#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; //Print out Hello World
cout << "Aaron Skomra" << endl; //Edit Hello World to print out your name
//Printing "David Snyder" to the command line
cout << "David Snyder" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright (C) 2012,2013 IBM Corp.
* 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <ctime>
#include <iostream>
#include "timing.h"
#include <tr1/unordered_map>
#include <vector>
#include <algorithm>
#include <utility>
#include <cmath>
#include <cstring>
using namespace std;
//! A simple class to toggle timing information on and off
class FHEtimer {
public:
bool isOn; // a broken semaphore
clock_t counter;
long numCalls;
FHEtimer() { isOn=false; counter=0; numCalls=0; }
};
bool string_compare(const char *a, const char *b)
{
return strcmp(a, b) < 0;
}
bool FHEtimersOn=false;
typedef tr1::unordered_map<const char*,FHEtimer>timerMap;
static timerMap timers;
// Reset a timer for some label to zero
void resetFHEtimer(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not aready there
t.numCalls = 0;
t.counter = 0;
if (t.isOn) t.counter -= std::clock();
}
// Start a timer
void startFHEtimer(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not aready there
if (!t.isOn) {
t.isOn = true;
t.numCalls++;
t.counter -= std::clock();
}
}
// Stop a timer
void stopFHEtimer(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not aready there
if (t.isOn) {
t.isOn = false;
t.counter += std::clock();
}
}
// Read the value of a timer (in seconds)
double getTime4func(const char *fncName) // returns time in seconds
{
FHEtimer& t = timers[fncName]; // insert to map if not aready there
// If the counter is currently counting, add the clock() value
clock_t c = t.isOn? (t.counter + std::clock()) : t.counter;
return ((double)c)/CLOCKS_PER_SEC;
}
// Returns number of calls for that timer
long getNumCalls4func(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not aready there
return t.numCalls;
}
void resetAllTimers()
{
for (timerMap::iterator it = timers.begin(); it != timers.end(); ++it)
resetFHEtimer(it->first);
}
// Print the value of all timers to stream
void printAllTimers(std::ostream& str)
{
vector<const char *> vec;
for (timerMap::iterator it = timers.begin(); it != timers.end(); ++it) {
vec.push_back(it->first);
}
sort(vec.begin(), vec.end(), string_compare);
for (vector<const char *>::iterator it = vec.begin(); it != vec.end(); ++it) {
double t = getTime4func(*it);
long n = getNumCalls4func(*it);
double ave;
if (n > 0) {
ave = t/n;
}
else {
ave = NAN;
}
str << " " << (*it) << ": " << t << " / " << n << " = " << ave << "\n";
}
}
<commit_msg>corrected minor typo<commit_after>/* Copyright (C) 2012,2013 IBM Corp.
* 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <ctime>
#include <iostream>
#include "timing.h"
#include <tr1/unordered_map>
#include <vector>
#include <algorithm>
#include <utility>
#include <cmath>
#include <cstring>
using namespace std;
//! A simple class to toggle timing information on and off
class FHEtimer {
public:
bool isOn; // a broken semaphore
clock_t counter;
long numCalls;
FHEtimer() { isOn=false; counter=0; numCalls=0; }
};
bool string_compare(const char *a, const char *b)
{
return strcmp(a, b) < 0;
}
bool FHEtimersOn=false;
typedef tr1::unordered_map<const char*,FHEtimer>timerMap;
static timerMap timers;
// Reset a timer for some label to zero
void resetFHEtimer(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not already there
t.numCalls = 0;
t.counter = 0;
if (t.isOn) t.counter -= std::clock();
}
// Start a timer
void startFHEtimer(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not already there
if (!t.isOn) {
t.isOn = true;
t.numCalls++;
t.counter -= std::clock();
}
}
// Stop a timer
void stopFHEtimer(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not already there
if (t.isOn) {
t.isOn = false;
t.counter += std::clock();
}
}
// Read the value of a timer (in seconds)
double getTime4func(const char *fncName) // returns time in seconds
{
FHEtimer& t = timers[fncName]; // insert to map if not already there
// If the counter is currently counting, add the clock() value
clock_t c = t.isOn? (t.counter + std::clock()) : t.counter;
return ((double)c)/CLOCKS_PER_SEC;
}
// Returns number of calls for that timer
long getNumCalls4func(const char *fncName)
{
FHEtimer& t = timers[fncName]; // insert to map if not already there
return t.numCalls;
}
void resetAllTimers()
{
for (timerMap::iterator it = timers.begin(); it != timers.end(); ++it)
resetFHEtimer(it->first);
}
// Print the value of all timers to stream
void printAllTimers(std::ostream& str)
{
vector<const char *> vec;
for (timerMap::iterator it = timers.begin(); it != timers.end(); ++it) {
vec.push_back(it->first);
}
sort(vec.begin(), vec.end(), string_compare);
for (vector<const char *>::iterator it = vec.begin(); it != vec.end(); ++it) {
double t = getTime4func(*it);
long n = getNumCalls4func(*it);
double ave;
if (n > 0) {
ave = t/n;
}
else {
ave = NAN;
}
str << " " << (*it) << ": " << t << " / " << n << " = " << ave << "\n";
}
}
<|endoftext|>
|
<commit_before>#include "Board.h"
#include "Patterns/PatternMatcher.h"
Board::Board(int boardSize)
{
InitialiseEmpty(boardSize);
}
Board::Board(Colour colourToMove, const std::vector<std::string>& s)
{
InitialiseEmpty(s.size());
// Ensure that it's square.
assert(s.size() == s[0].size());
int loc;
char c;
for (int i = 0; i < _boardSize; i++)
{
for (int j = 0; j < _boardSize; j++)
{
loc = (_boardSize-i-1)*_boardSize + j;
c = s[i][j];
Colour col = c == 'B' ? Black : c == 'W' ? White : None;
if (col != None)
MakeMove({ col, loc });
}
}
_colourToMove = colourToMove;
}
Board::Board(Colour colourToMove, int boardSize, const MoveHistory& history)
{
assert(boardSize > 0 && boardSize < MaxBoardSize);
InitialiseEmpty(boardSize);
auto moves = history.Moves();
for (Move move : moves)
MakeMove(move);
_colourToMove = colourToMove;
}
Board::~Board()
{
if (_points != nullptr)
{
delete[] _points;
_points = nullptr;
}
}
// Clone fields from other.
void Board::CloneFrom(const Board& other)
{
assert(_boardSize == other._boardSize);
_colourToMove = other._colourToMove;
_turnNumber = other._turnNumber;
_hashes = other._hashes;
memcpy(_passes, other._passes, 2*sizeof(bool));
for (int i = 0; i < _boardArea; i++)
{
Point& pt = _points[i];
const Point& opt = other._points[i];
pt.Col = opt.Col;
pt.GroupSize = opt.GroupSize;
pt.Liberties = opt.Liberties;
}
}
// Check the legality of the specified move in this position.
MoveInfo Board::CheckMove(int loc) const
{
return CheckMove(this->_colourToMove, loc);
}
// Check the legality of the specified move in this position.
MoveInfo Board::CheckMove(Colour col, int loc) const
{
// Passing is always legal.
if (loc == PassCoord)
return Legal;
// Check occupancy.
const Point& pt = this->_points[loc];
MoveInfo res = pt.Col == None ? Legal : Occupied;
if (res == Legal)
{
// Check for suicide and ko.
int liberties = 0;
int captureLoc;
size_t capturesWithRepetition = 0; // Note: captured neighbours could be in the same group!
size_t friendlyNeighbours = 0;
bool friendInAtari = false;
for (const Point* const n : pt.Neighbours)
{
if (n->Col == None)
{
++liberties;
}
else if (n->Col == col)
{
liberties += n->Liberties-1;
friendlyNeighbours += n->Liberties > 1 ? 1 : 0;
friendInAtari = friendInAtari || n->Liberties == 1;
}
else
{
if (n->Liberties == 1)
{
++liberties;
captureLoc = n->Coord;
capturesWithRepetition += n->GroupSize;
}
else if (n->Liberties == 2)
{
res |= Atari;
}
}
}
bool suicide = liberties == 0;
bool repetition = capturesWithRepetition == 1 && IsKoRepetition(col, loc, captureLoc);
res = suicide ? Suicide : repetition ? Ko : Legal;
// Do some extra work to further classify the move.
if (liberties == 1) res |= SelfAtari;
if (capturesWithRepetition > 0) res |= Capture;
if (friendlyNeighbours == pt.Neighbours.size()) res |= FillsEye;
if (friendInAtari && liberties > 1) res |= Save;
}
return res;
}
// Get all moves available for the current colour.
std::vector<Move> Board::GetMoves(bool duringPlayout) const
{
std::vector<Move> moves;
if (!GameOver())
{
PatternMatcher matcher;
for (int i = 0; i < _boardArea; i++)
{
MoveInfo info = CheckMove(i);
if (info & Legal)
{
if (!duringPlayout)
{
if (matcher.HasMatch(*this, 3, i))
{
info |= Pat3Match;
}
if (matcher.HasMatch(*this, 5, i))
{
info |= Pat5Match;
}
}
if (!duringPlayout || !(info & FillsEye))
{
moves.push_back({this->_colourToMove, i, info});
}
}
}
// Passing is always legal but don't consider it during a playout unless there
// are no other moves available.
if (!duringPlayout || moves.size() == 0)
{
moves.push_back({this->_colourToMove, PassCoord, Legal});
}
}
return moves;
}
// Update the board state with the specified move.
void Board::MakeMove(const Move& move)
{
assert(!GameOver());
assert(CheckMove(move.Col, move.Coord) & Legal);
auto z = Zobrist::Instance();
uint64_t nextHash = _hashes[_turnNumber-1];
if (move.Coord != PassCoord)
{
nextHash ^= z->Key(move.Col, move.Coord);
Point& pt = this->_points[move.Coord];
pt.Col = move.Col;
// Cache which points need updating.
bool requireUpdate[_boardArea] = {false};
requireUpdate[pt.Coord] = true;
// First detect stones which will get captured and remove them.
for (Point* const n : pt.Neighbours)
{
if (n->Col != None)
{
if (n->Col != move.Col && n->Liberties == 1)
{
uint64_t groupHash = 0;
FFCapture(n, requireUpdate, groupHash);
nextHash ^= groupHash;
}
else
{
requireUpdate[n->Coord] = true;
}
}
}
// Update the liberties of the affected stones.
for (int i = 0; i < _boardArea; i++)
{
if (requireUpdate[i])
{
int liberties = 0;
int groupSize = 0;
bool inGroup[_boardArea] = {false};
bool considered[_boardArea] = {false};
FFLiberties(&_points[i], liberties, groupSize, requireUpdate, inGroup, considered);
}
}
}
// Update the colour to move.
if (move.Col == this->_colourToMove)
{
this->_colourToMove = this->_colourToMove == Black ? White : Black;
nextHash ^= CurrentRules.Ko == Situational ? z->BlackTurn() : 0;
}
_hashes.push_back(nextHash);
_passes[(int)move.Col-1] = move.Coord == PassCoord;
++_turnNumber;
}
// Compute the score of the current position.
// Area scoring is used and we assume that all empty points are fully surrounded by one
// colour.
// The score is determined from black's perspective (positive score indicates black win).
int Board::Score() const
{
double score = -CurrentRules.Komi;
for (int i = 0; i < _boardArea; i++)
{
const Point& pt = _points[i];
if (pt.Col == None)
{
// Look at a neighbour.
Point const* const n = pt.Neighbours[0];
score += n->Col == Black ? 1 : -1;
}
else
{
score += pt.Col == Black ? 1 : -1;
}
}
return score > 0 ? 1 : score < 0 ? -1 : 0;
}
std::string Board::ToString() const
{
std::string s;
Colour col;
for (int r = _boardSize-1; r >= 0; r--)
{
for (int c = 0; c < _boardSize; c++)
{
col = _points[r*_boardSize+c].Col;
s += col == None ? '.' : col == Black ? 'B' : 'W';
}
s += '\n';
}
return s;
}
// Initialise an empty board of the specified size.
void Board::InitialiseEmpty(int boardSize)
{
assert(boardSize > 0 && boardSize < MaxBoardSize);
_colourToMove = Black;
_boardSize = boardSize;
_boardArea = _boardSize*_boardSize;
_points = new Point[_boardArea];
for (int i = 0; i < _boardArea; i++)
_points[i] = { None, 0, 0 };
this->InitialiseNeighbours();
_hashes.push_back(CurrentRules.Ko == Situational ? Zobrist::Instance()->BlackTurn() : 0);
}
// Initialise the neighbours for each point.
void Board::InitialiseNeighbours()
{
int r, c;
for (int i = 0; i < _boardArea; i++)
{
r = i / _boardSize, c = i % _boardSize;
_points[i].Coord = i;
_points[i].Neighbours.clear();
if (r > 0) _points[i].Neighbours.push_back(&_points[i-_boardSize]);
if (r < _boardSize-1) _points[i].Neighbours.push_back(&_points[i+_boardSize]);
if (c > 0) _points[i].Neighbours.push_back(&_points[i-1]);
if (c < _boardSize-1) _points[i].Neighbours.push_back(&_points[i+1]);
}
}
// Check whether the specified move and capture would result in a board repetition.
bool Board::IsKoRepetition(Colour col, int loc, int captureLoc) const
{
Colour enemyCol = col == Black ? White : Black;
auto z = Zobrist::Instance();
uint64_t nextHash =
_hashes[_turnNumber-1]
^ z->Key(col, loc)
^ z->Key(enemyCol, captureLoc)
^ (CurrentRules.Ko == Situational ? z->BlackTurn() : 0);
// Has this hash occurred previously?
bool repeat = false;
for (int i = _turnNumber-1; i >= 0 && !repeat; i--)
repeat = _hashes[i] == nextHash;
return repeat;
}
// Flood fill algorithm which updates the liberties for all stones in the group containing
// the specified point.
void Board::FFLiberties(Point* const pt, int& liberties, int& groupSize, bool* requireUpdate, bool* inGroup, bool* considered, bool root)
{
inGroup[pt->Coord] = true;
++groupSize;
for (Point* const n : pt->Neighbours)
{
if (n->Col == pt->Col && !inGroup[n->Coord])
{
FFLiberties(n, liberties, groupSize, requireUpdate, inGroup, considered, false);
}
else if (n->Col == None && !considered[n->Coord])
{
++liberties;
considered[n->Coord] = true;
}
}
if (root)
{
for (int i = 0; i < _boardArea; i++)
{
if (inGroup[i])
{
Point& groupPt = _points[i];
groupPt.Liberties = liberties;
groupPt.GroupSize = groupSize;
requireUpdate[groupPt.Coord] = false;
}
}
}
}
// Flood fill algorithm which removes all stones in the group containing the specified point.
// Points which are affected by this capture get flagged as requiring an update.
void Board::FFCapture(Point* const pt, bool* requireUpdate, uint64_t& groupHash)
{
Colour origCol = pt->Col;
pt->Col = None;
pt->Liberties = 0;
groupHash ^= Zobrist::Instance()->Key(origCol, pt->Coord);
for (Point* const n : pt->Neighbours)
{
if (n->Col == origCol)
{
FFCapture(n, requireUpdate, groupHash);
}
else if (n->Col != None)
{
requireUpdate[n->Coord] = true;
}
}
}
<commit_msg>Fixed bug in CheckMove method where moves were never classified as atari.<commit_after>#include "Board.h"
#include "Patterns/PatternMatcher.h"
Board::Board(int boardSize)
{
InitialiseEmpty(boardSize);
}
Board::Board(Colour colourToMove, const std::vector<std::string>& s)
{
InitialiseEmpty(s.size());
// Ensure that it's square.
assert(s.size() == s[0].size());
int loc;
char c;
for (int i = 0; i < _boardSize; i++)
{
for (int j = 0; j < _boardSize; j++)
{
loc = (_boardSize-i-1)*_boardSize + j;
c = s[i][j];
Colour col = c == 'B' ? Black : c == 'W' ? White : None;
if (col != None)
MakeMove({ col, loc });
}
}
_colourToMove = colourToMove;
}
Board::Board(Colour colourToMove, int boardSize, const MoveHistory& history)
{
assert(boardSize > 0 && boardSize < MaxBoardSize);
InitialiseEmpty(boardSize);
auto moves = history.Moves();
for (Move move : moves)
MakeMove(move);
_colourToMove = colourToMove;
}
Board::~Board()
{
if (_points != nullptr)
{
delete[] _points;
_points = nullptr;
}
}
// Clone fields from other.
void Board::CloneFrom(const Board& other)
{
assert(_boardSize == other._boardSize);
_colourToMove = other._colourToMove;
_turnNumber = other._turnNumber;
_hashes = other._hashes;
memcpy(_passes, other._passes, 2*sizeof(bool));
for (int i = 0; i < _boardArea; i++)
{
Point& pt = _points[i];
const Point& opt = other._points[i];
pt.Col = opt.Col;
pt.GroupSize = opt.GroupSize;
pt.Liberties = opt.Liberties;
}
}
// Check the legality of the specified move in this position.
MoveInfo Board::CheckMove(int loc) const
{
return CheckMove(this->_colourToMove, loc);
}
// Check the legality of the specified move in this position.
MoveInfo Board::CheckMove(Colour col, int loc) const
{
// Passing is always legal.
if (loc == PassCoord)
return Legal;
// Check occupancy.
const Point& pt = this->_points[loc];
MoveInfo res = pt.Col == None ? Legal : Occupied;
if (res == Legal)
{
// Check for suicide and ko.
int liberties = 0;
int captureLoc;
size_t capturesWithRepetition = 0; // Note: captured neighbours could be in the same group!
size_t friendlyNeighbours = 0;
bool friendInAtari = false;
bool isAtari = false;
for (const Point* const n : pt.Neighbours)
{
if (n->Col == None)
{
++liberties;
}
else if (n->Col == col)
{
liberties += n->Liberties-1;
friendlyNeighbours += n->Liberties > 1 ? 1 : 0;
friendInAtari = friendInAtari || n->Liberties == 1;
}
else
{
if (n->Liberties == 1)
{
++liberties;
captureLoc = n->Coord;
capturesWithRepetition += n->GroupSize;
}
else if (n->Liberties == 2)
{
isAtari = true;
}
}
}
bool suicide = liberties == 0;
bool repetition = capturesWithRepetition == 1 && IsKoRepetition(col, loc, captureLoc);
res = suicide ? Suicide : repetition ? Ko : Legal;
if (res & Legal)
{
// Do some extra work to further classify the move.
if (isAtari) res |= Atari;
if (liberties == 1) res |= SelfAtari;
if (capturesWithRepetition > 0) res |= Capture;
if (friendlyNeighbours == pt.Neighbours.size()) res |= FillsEye;
if (friendInAtari && liberties > 1) res |= Save;
}
}
return res;
}
// Get all moves available for the current colour.
std::vector<Move> Board::GetMoves(bool duringPlayout) const
{
std::vector<Move> moves;
if (!GameOver())
{
PatternMatcher matcher;
for (int i = 0; i < _boardArea; i++)
{
MoveInfo info = CheckMove(i);
if (info & Legal)
{
if (!duringPlayout)
{
if (matcher.HasMatch(*this, 3, i))
{
info |= Pat3Match;
}
if (matcher.HasMatch(*this, 5, i))
{
info |= Pat5Match;
}
}
if (!duringPlayout || !(info & FillsEye))
{
moves.push_back({this->_colourToMove, i, info});
}
}
}
// Passing is always legal but don't consider it during a playout unless there
// are no other moves available.
if (!duringPlayout || moves.size() == 0)
{
moves.push_back({this->_colourToMove, PassCoord, Legal});
}
}
return moves;
}
// Update the board state with the specified move.
void Board::MakeMove(const Move& move)
{
assert(!GameOver());
assert(CheckMove(move.Col, move.Coord) & Legal);
auto z = Zobrist::Instance();
uint64_t nextHash = _hashes[_turnNumber-1];
if (move.Coord != PassCoord)
{
nextHash ^= z->Key(move.Col, move.Coord);
Point& pt = this->_points[move.Coord];
pt.Col = move.Col;
// Cache which points need updating.
bool requireUpdate[_boardArea] = {false};
requireUpdate[pt.Coord] = true;
// First detect stones which will get captured and remove them.
for (Point* const n : pt.Neighbours)
{
if (n->Col != None)
{
if (n->Col != move.Col && n->Liberties == 1)
{
uint64_t groupHash = 0;
FFCapture(n, requireUpdate, groupHash);
nextHash ^= groupHash;
}
else
{
requireUpdate[n->Coord] = true;
}
}
}
// Update the liberties of the affected stones.
for (int i = 0; i < _boardArea; i++)
{
if (requireUpdate[i])
{
int liberties = 0;
int groupSize = 0;
bool inGroup[_boardArea] = {false};
bool considered[_boardArea] = {false};
FFLiberties(&_points[i], liberties, groupSize, requireUpdate, inGroup, considered);
}
}
}
// Update the colour to move.
if (move.Col == this->_colourToMove)
{
this->_colourToMove = this->_colourToMove == Black ? White : Black;
nextHash ^= CurrentRules.Ko == Situational ? z->BlackTurn() : 0;
}
_hashes.push_back(nextHash);
_passes[(int)move.Col-1] = move.Coord == PassCoord;
++_turnNumber;
}
// Compute the score of the current position.
// Area scoring is used and we assume that all empty points are fully surrounded by one
// colour.
// The score is determined from black's perspective (positive score indicates black win).
int Board::Score() const
{
double score = -CurrentRules.Komi;
for (int i = 0; i < _boardArea; i++)
{
const Point& pt = _points[i];
if (pt.Col == None)
{
// Look at a neighbour.
Point const* const n = pt.Neighbours[0];
score += n->Col == Black ? 1 : -1;
}
else
{
score += pt.Col == Black ? 1 : -1;
}
}
return score > 0 ? 1 : score < 0 ? -1 : 0;
}
std::string Board::ToString() const
{
std::string s;
Colour col;
for (int r = _boardSize-1; r >= 0; r--)
{
for (int c = 0; c < _boardSize; c++)
{
col = _points[r*_boardSize+c].Col;
s += col == None ? '.' : col == Black ? 'B' : 'W';
}
s += '\n';
}
return s;
}
// Initialise an empty board of the specified size.
void Board::InitialiseEmpty(int boardSize)
{
assert(boardSize > 0 && boardSize < MaxBoardSize);
_colourToMove = Black;
_boardSize = boardSize;
_boardArea = _boardSize*_boardSize;
_points = new Point[_boardArea];
for (int i = 0; i < _boardArea; i++)
_points[i] = { None, 0, 0 };
this->InitialiseNeighbours();
_hashes.push_back(CurrentRules.Ko == Situational ? Zobrist::Instance()->BlackTurn() : 0);
}
// Initialise the neighbours for each point.
void Board::InitialiseNeighbours()
{
int r, c;
for (int i = 0; i < _boardArea; i++)
{
r = i / _boardSize, c = i % _boardSize;
_points[i].Coord = i;
_points[i].Neighbours.clear();
if (r > 0) _points[i].Neighbours.push_back(&_points[i-_boardSize]);
if (r < _boardSize-1) _points[i].Neighbours.push_back(&_points[i+_boardSize]);
if (c > 0) _points[i].Neighbours.push_back(&_points[i-1]);
if (c < _boardSize-1) _points[i].Neighbours.push_back(&_points[i+1]);
}
}
// Check whether the specified move and capture would result in a board repetition.
bool Board::IsKoRepetition(Colour col, int loc, int captureLoc) const
{
Colour enemyCol = col == Black ? White : Black;
auto z = Zobrist::Instance();
uint64_t nextHash =
_hashes[_turnNumber-1]
^ z->Key(col, loc)
^ z->Key(enemyCol, captureLoc)
^ (CurrentRules.Ko == Situational ? z->BlackTurn() : 0);
// Has this hash occurred previously?
bool repeat = false;
for (int i = _turnNumber-1; i >= 0 && !repeat; i--)
repeat = _hashes[i] == nextHash;
return repeat;
}
// Flood fill algorithm which updates the liberties for all stones in the group containing
// the specified point.
void Board::FFLiberties(Point* const pt, int& liberties, int& groupSize, bool* requireUpdate, bool* inGroup, bool* considered, bool root)
{
inGroup[pt->Coord] = true;
++groupSize;
for (Point* const n : pt->Neighbours)
{
if (n->Col == pt->Col && !inGroup[n->Coord])
{
FFLiberties(n, liberties, groupSize, requireUpdate, inGroup, considered, false);
}
else if (n->Col == None && !considered[n->Coord])
{
++liberties;
considered[n->Coord] = true;
}
}
if (root)
{
for (int i = 0; i < _boardArea; i++)
{
if (inGroup[i])
{
Point& groupPt = _points[i];
groupPt.Liberties = liberties;
groupPt.GroupSize = groupSize;
requireUpdate[groupPt.Coord] = false;
}
}
}
}
// Flood fill algorithm which removes all stones in the group containing the specified point.
// Points which are affected by this capture get flagged as requiring an update.
void Board::FFCapture(Point* const pt, bool* requireUpdate, uint64_t& groupHash)
{
Colour origCol = pt->Col;
pt->Col = None;
pt->Liberties = 0;
groupHash ^= Zobrist::Instance()->Key(origCol, pt->Coord);
for (Point* const n : pt->Neighbours)
{
if (n->Col == origCol)
{
FFCapture(n, requireUpdate, groupHash);
}
else if (n->Col != None)
{
requireUpdate[n->Coord] = true;
}
}
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* ctrl_radialslider.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <math.h>
#include "ctrl_radialslider.hpp"
#include "../events/evt_mouse.hpp"
#include "../src/generic_bitmap.hpp"
#include "../src/generic_window.hpp"
#include "../src/os_factory.hpp"
#include "../src/os_graphics.hpp"
#include "../utils/position.hpp"
#include "../utils/var_percent.hpp"
CtrlRadialSlider::CtrlRadialSlider( intf_thread_t *pIntf,
const GenericBitmap &rBmpSeq, int numImg,
VarPercent &rVariable, float minAngle,
float maxAngle, const UString &rHelp,
VarBool *pVisible ):
CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ), m_numImg( numImg ),
m_rVariable( rVariable ), m_minAngle( minAngle ), m_maxAngle( maxAngle ),
m_cmdUpDown( this ), m_cmdDownUp( this ),
m_cmdMove( this ), m_position( 0 )
{
// Build the images of the sequence
m_pImgSeq = OSFactory::instance( getIntf() )->createOSGraphics(
rBmpSeq.getWidth(), rBmpSeq.getHeight() );
m_pImgSeq->drawBitmap( rBmpSeq, 0, 0 );
m_width = rBmpSeq.getWidth();
m_height = rBmpSeq.getHeight() / numImg;
// States
m_fsm.addState( "up" );
m_fsm.addState( "down" );
// Transitions
m_fsm.addTransition( "up", "mouse:left:down", "down", &m_cmdUpDown );
m_fsm.addTransition( "down", "mouse:left:up", "up", &m_cmdDownUp );
m_fsm.addTransition( "down", "motion", "down", &m_cmdMove );
// Initial state
m_fsm.setState( "up" );
// Observe the variable
m_rVariable.addObserver( this );
}
CtrlRadialSlider::~CtrlRadialSlider()
{
m_rVariable.delObserver( this );
delete m_pImgSeq;
}
void CtrlRadialSlider::handleEvent( EvtGeneric &rEvent )
{
// Save the event to use it in callbacks
m_pEvt = &rEvent;
m_fsm.handleTransition( rEvent.getAsString() );
}
bool CtrlRadialSlider::mouseOver( int x, int y ) const
{
return m_pImgSeq->hit( x, y + m_position * m_height );
}
void CtrlRadialSlider::draw( OSGraphics &rImage, int xDest, int yDest )
{
rImage.drawGraphics( *m_pImgSeq, 0, m_position * m_height, xDest, yDest,
m_width, m_height );
}
void CtrlRadialSlider::onUpdate( Subject<VarPercent> &rVariable,
void *arg )
{
m_position = (int)( m_rVariable.get() * m_numImg );
notifyLayout( m_width, m_height );
}
void CtrlRadialSlider::CmdUpDown::execute()
{
EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;
// Change the position of the cursor, in non-blocking mode
m_pParent->setCursor( pEvtMouse->getXPos(), pEvtMouse->getYPos(), false );
m_pParent->captureMouse();
}
void CtrlRadialSlider::CmdDownUp::execute()
{
m_pParent->releaseMouse();
}
void CtrlRadialSlider::CmdMove::execute()
{
EvtMouse *pEvtMouse = static_cast<EvtMouse*>(m_pParent->m_pEvt);
// Change the position of the cursor, in blocking mode
m_pParent->setCursor( pEvtMouse->getXPos(), pEvtMouse->getYPos(), true );
}
void CtrlRadialSlider::setCursor( int posX, int posY, bool blocking )
{
// Get the position of the control
const Position *pPos = getPosition();
if( !pPos )
{
return;
}
// Compute the position relative to the center
int x = posX - pPos->getLeft() - m_width / 2;
int y = posY - pPos->getTop() - m_width / 2;
// Compute the polar coordinates. angle is -(-j,OM)
float r = sqrt((float)(x*x + y*y));
if( r == 0 )
{
return;
}
float angle = acos(y/r);
if( x > 0 )
{
angle = 2*M_PI - angle;
}
if( angle >= m_minAngle && angle <= m_maxAngle )
{
float newVal = (angle - m_minAngle) / (m_maxAngle - m_minAngle);
// Avoid too fast moves of the cursor if blocking mode
if( !blocking || fabs( m_rVariable.get() - newVal ) < 0.5 )
{
m_rVariable.set( newVal );
}
}
}
<commit_msg>skins2: fix RadiaSlider (typo)<commit_after>/*****************************************************************************
* ctrl_radialslider.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <math.h>
#include "ctrl_radialslider.hpp"
#include "../events/evt_mouse.hpp"
#include "../src/generic_bitmap.hpp"
#include "../src/generic_window.hpp"
#include "../src/os_factory.hpp"
#include "../src/os_graphics.hpp"
#include "../utils/position.hpp"
#include "../utils/var_percent.hpp"
CtrlRadialSlider::CtrlRadialSlider( intf_thread_t *pIntf,
const GenericBitmap &rBmpSeq, int numImg,
VarPercent &rVariable, float minAngle,
float maxAngle, const UString &rHelp,
VarBool *pVisible ):
CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ), m_numImg( numImg ),
m_rVariable( rVariable ), m_minAngle( minAngle ), m_maxAngle( maxAngle ),
m_cmdUpDown( this ), m_cmdDownUp( this ),
m_cmdMove( this ), m_position( 0 )
{
// Build the images of the sequence
m_pImgSeq = OSFactory::instance( getIntf() )->createOSGraphics(
rBmpSeq.getWidth(), rBmpSeq.getHeight() );
m_pImgSeq->drawBitmap( rBmpSeq, 0, 0 );
m_width = rBmpSeq.getWidth();
m_height = rBmpSeq.getHeight() / numImg;
// States
m_fsm.addState( "up" );
m_fsm.addState( "down" );
// Transitions
m_fsm.addTransition( "up", "mouse:left:down", "down", &m_cmdUpDown );
m_fsm.addTransition( "down", "mouse:left:up", "up", &m_cmdDownUp );
m_fsm.addTransition( "down", "motion", "down", &m_cmdMove );
// Initial state
m_fsm.setState( "up" );
// Observe the variable
m_rVariable.addObserver( this );
}
CtrlRadialSlider::~CtrlRadialSlider()
{
m_rVariable.delObserver( this );
delete m_pImgSeq;
}
void CtrlRadialSlider::handleEvent( EvtGeneric &rEvent )
{
// Save the event to use it in callbacks
m_pEvt = &rEvent;
m_fsm.handleTransition( rEvent.getAsString() );
}
bool CtrlRadialSlider::mouseOver( int x, int y ) const
{
return m_pImgSeq->hit( x, y + m_position * m_height );
}
void CtrlRadialSlider::draw( OSGraphics &rImage, int xDest, int yDest )
{
rImage.drawGraphics( *m_pImgSeq, 0, m_position * m_height, xDest, yDest,
m_width, m_height );
}
void CtrlRadialSlider::onUpdate( Subject<VarPercent> &rVariable,
void *arg )
{
m_position = (int)( m_rVariable.get() * m_numImg );
notifyLayout( m_width, m_height );
}
void CtrlRadialSlider::CmdUpDown::execute()
{
EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;
// Change the position of the cursor, in non-blocking mode
m_pParent->setCursor( pEvtMouse->getXPos(), pEvtMouse->getYPos(), false );
m_pParent->captureMouse();
}
void CtrlRadialSlider::CmdDownUp::execute()
{
m_pParent->releaseMouse();
}
void CtrlRadialSlider::CmdMove::execute()
{
EvtMouse *pEvtMouse = static_cast<EvtMouse*>(m_pParent->m_pEvt);
// Change the position of the cursor, in blocking mode
m_pParent->setCursor( pEvtMouse->getXPos(), pEvtMouse->getYPos(), true );
}
void CtrlRadialSlider::setCursor( int posX, int posY, bool blocking )
{
// Get the position of the control
const Position *pPos = getPosition();
if( !pPos )
{
return;
}
// Compute the position relative to the center
int x = posX - pPos->getLeft() - m_width / 2;
int y = posY - pPos->getTop() - m_height / 2;
// Compute the polar coordinates. angle is -(-j,OM)
float r = sqrt((float)(x*x + y*y));
if( r == 0 )
{
return;
}
float angle = acos(y/r);
if( x > 0 )
{
angle = 2*M_PI - angle;
}
if( angle >= m_minAngle && angle <= m_maxAngle )
{
float newVal = (angle - m_minAngle) / (m_maxAngle - m_minAngle);
// Avoid too fast moves of the cursor if blocking mode
if( !blocking || fabs( m_rVariable.get() - newVal ) < 0.5 )
{
m_rVariable.set( newVal );
}
}
}
<|endoftext|>
|
<commit_before>/*
* compose
* compose a function call
* This macro takes as input a Method object and composes
* a function call by inspecting the types and argument names
*/
{% macro compose(fun) %}
{# ----------- Return type ------------- #}
{%- if not fun.rtp|void and not fun.constructor -%} retval = {% endif -%}
{%- if fun.constructor -%}{{fun.clss}} obj = {% endif -%}
{%- if fun.clss and not fun.constructor -%}inst.{%- else -%} cv:: {%- endif -%}
{{fun.name}}(
{#- ----------- Required ------------- -#}
{%- for arg in fun.req -%}
{%- if arg.ref == '*' -%}&{%- endif -%}
{{arg.name}}
{%- if not loop.last %}, {% endif %}
{% endfor %}
{#- ----------- Optional ------------- -#}
{% if fun.req and fun.opt %}, {% endif %}
{%- for opt in fun.opt -%}
{%- if opt.ref == '*' -%}&{%- endif -%}
{{opt.name}}
{%- if not loop.last -%}, {% endif %}
{%- endfor -%}
);
{%- endmacro %}
/*
* composeMatlab
* compose a Matlab function call
* This macro takes as input a Method object and composes
* a Matlab function call by inspecting the types and argument names
*/
{% macro composeMatlab(fun) %}
{# ----------- Return type ------------- #}
{%- if fun|noutputs > 1 -%}[{% endif -%}
{%- if not fun.rtp|void -%}LVALUE{% endif -%}
{%- if not fun.rtp|void and fun|noutputs > 1 -%},{% endif -%}
{# ------------- Outputs ------------- -#}
{%- for arg in fun.req|outputs + fun.opt|outputs -%}
{{arg.name}}
{%- if arg.I -%}_out{%- endif -%}
{%- if not loop.last %}, {% endif %}
{% endfor %}
{%- if fun|noutputs > 1 -%}]{% endif -%}
{%- if fun|noutputs %} = {% endif -%}
cv.{{fun.name}}(
{#- ------------ Inputs -------------- -#}
{%- for arg in fun.req|inputs + fun.opt|inputs -%}
{{arg.name}}
{%- if arg.O -%}_in{%- endif -%}
{%- if not loop.last %}, {% endif -%}
{% endfor -%}
);
{%- endmacro %}
/*
* composeVariant
* compose a variant call for the ArgumentParser
*/
{% macro composeVariant(fun) %}
addVariant("{{ fun.name }}", {{ fun.req|inputs|length }}, {{ fun.opt|inputs|length }}
{%- if fun.opt|inputs|length %}, {% endif -%}
{%- for arg in fun.opt|inputs -%}
"{{arg.name}}"
{%- if not loop.last %}, {% endif -%}
{% endfor -%}
)
{%- endmacro %}
/*
* composeWithExceptionHandler
* compose a function call wrapped in exception traps
* This macro takes an input a Method object and composes a function
* call through the compose() macro, then wraps the return in traps
* for cv::Exceptions, std::exceptions, and all generic exceptions
* and returns a useful error message to the Matlab interpreter
*/
{%- macro composeWithExceptionHandler(fun) -%}
// call the opencv function
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
try {
{{ compose(fun) }}
} catch(cv::Exception& e) {
error(std::string("cv::exception caught: ").append(e.what()).c_str());
} catch(std::exception& e) {
error(std::string("std::exception caught: ").append(e.what()).c_str());
} catch(...) {
error("Uncaught exception occurred in {{fun.name}}");
}
{%- endmacro %}
/*
* handleInputs
* unpack input arguments from the Bridge
* Given an input Bridge object, this unpacks the object from the Bridge and
* casts them into the correct type
*/
{%- macro handleInputs(fun) %}
{% if fun|ninputs or (fun|noutputs and not fun.constructor) %}
// unpack the arguments
{# ----------- Inputs ------------- #}
{% for arg in fun.req|inputs %}
{{arg.tp}} {{arg.name}} = inputs[{{ loop.index0 }}].to{{arg.tp|toUpperCamelCase}}();
{% endfor %}
{% for opt in fun.opt|inputs %}
{{opt.tp}} {{opt.name}} = inputs[{{loop.index0 + fun.req|inputs|length}}].empty() ? {% if opt.ref == '*' -%} {{opt.tp}}() {%- else -%} {{opt.default}} {%- endif %} : inputs[{{loop.index0 + fun.req|inputs|length}}].to{{opt.tp|toUpperCamelCase}}();
{% endfor %}
{# ----------- Outputs ------------ #}
{% for arg in fun.req|only|outputs %}
{{arg.tp}} {{arg.name}};
{% endfor %}
{% for opt in fun.opt|only|outputs %}
{{opt.tp}} {{opt.name}};
{% endfor %}
{% if not fun.rtp|void and not fun.constructor %}
{{fun.rtp}} retval;
{% endif %}
{% endif %}
{%- endmacro %}
/*
* handleOutputs
* pack outputs into the bridge
* Given a set of outputs, this methods assigns them into the bridge for
* return to the calling method
*/
{%- macro handleOutputs(fun) %}
{% if fun|noutputs %}
// assign the outputs into the bridge
{% if not fun.rtp|void and not fun.constructor %}
outputs[0] = retval;
{% endif %}
{% for arg in fun.req|outputs %}
outputs[{{loop.index0 + fun.rtp|void|not}}] = {{arg.name}};
{% endfor %}
{% for opt in fun.opt|outputs %}
outputs[{{loop.index0 + fun.rtp|void|not + fun.req|outputs|length}}] = {{opt.name}};
{% endfor %}
{% endif %}
{%- endmacro %}
<commit_msg>Matlab bindings: fixed the functional template to perform an explicit cast to the type of an input option that is expected. This avoids issues with ternary operator not having the same type in rvalue and lvalue, such as in the case below:<commit_after>/*
* compose
* compose a function call
* This macro takes as input a Method object and composes
* a function call by inspecting the types and argument names
*/
{% macro compose(fun) %}
{# ----------- Return type ------------- #}
{%- if not fun.rtp|void and not fun.constructor -%} retval = {% endif -%}
{%- if fun.constructor -%}{{fun.clss}} obj = {% endif -%}
{%- if fun.clss and not fun.constructor -%}inst.{%- else -%} cv:: {%- endif -%}
{{fun.name}}(
{#- ----------- Required ------------- -#}
{%- for arg in fun.req -%}
{%- if arg.ref == '*' -%}&{%- endif -%}
{{arg.name}}
{%- if not loop.last %}, {% endif %}
{% endfor %}
{#- ----------- Optional ------------- -#}
{% if fun.req and fun.opt %}, {% endif %}
{%- for opt in fun.opt -%}
{%- if opt.ref == '*' -%}&{%- endif -%}
{{opt.name}}
{%- if not loop.last -%}, {% endif %}
{%- endfor -%}
);
{%- endmacro %}
/*
* composeMatlab
* compose a Matlab function call
* This macro takes as input a Method object and composes
* a Matlab function call by inspecting the types and argument names
*/
{% macro composeMatlab(fun) %}
{# ----------- Return type ------------- #}
{%- if fun|noutputs > 1 -%}[{% endif -%}
{%- if not fun.rtp|void -%}LVALUE{% endif -%}
{%- if not fun.rtp|void and fun|noutputs > 1 -%},{% endif -%}
{# ------------- Outputs ------------- -#}
{%- for arg in fun.req|outputs + fun.opt|outputs -%}
{{arg.name}}
{%- if arg.I -%}_out{%- endif -%}
{%- if not loop.last %}, {% endif %}
{% endfor %}
{%- if fun|noutputs > 1 -%}]{% endif -%}
{%- if fun|noutputs %} = {% endif -%}
cv.{{fun.name}}(
{#- ------------ Inputs -------------- -#}
{%- for arg in fun.req|inputs + fun.opt|inputs -%}
{{arg.name}}
{%- if arg.O -%}_in{%- endif -%}
{%- if not loop.last %}, {% endif -%}
{% endfor -%}
);
{%- endmacro %}
/*
* composeVariant
* compose a variant call for the ArgumentParser
*/
{% macro composeVariant(fun) %}
addVariant("{{ fun.name }}", {{ fun.req|inputs|length }}, {{ fun.opt|inputs|length }}
{%- if fun.opt|inputs|length %}, {% endif -%}
{%- for arg in fun.opt|inputs -%}
"{{arg.name}}"
{%- if not loop.last %}, {% endif -%}
{% endfor -%}
)
{%- endmacro %}
/*
* composeWithExceptionHandler
* compose a function call wrapped in exception traps
* This macro takes an input a Method object and composes a function
* call through the compose() macro, then wraps the return in traps
* for cv::Exceptions, std::exceptions, and all generic exceptions
* and returns a useful error message to the Matlab interpreter
*/
{%- macro composeWithExceptionHandler(fun) -%}
// call the opencv function
// [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn);
try {
{{ compose(fun) }}
} catch(cv::Exception& e) {
error(std::string("cv::exception caught: ").append(e.what()).c_str());
} catch(std::exception& e) {
error(std::string("std::exception caught: ").append(e.what()).c_str());
} catch(...) {
error("Uncaught exception occurred in {{fun.name}}");
}
{%- endmacro %}
/*
* handleInputs
* unpack input arguments from the Bridge
* Given an input Bridge object, this unpacks the object from the Bridge and
* casts them into the correct type
*/
{%- macro handleInputs(fun) %}
{% if fun|ninputs or (fun|noutputs and not fun.constructor) %}
// unpack the arguments
{# ----------- Inputs ------------- #}
{% for arg in fun.req|inputs %}
{{arg.tp}} {{arg.name}} = inputs[{{ loop.index0 }}].to{{arg.tp|toUpperCamelCase}}();
{% endfor %}
{% for opt in fun.opt|inputs %}
{{opt.tp}} {{opt.name}} = inputs[{{loop.index0 + fun.req|inputs|length}}].empty() ? ({{opt.tp}}) {% if opt.ref == '*' -%} {{opt.tp}}() {%- else -%} {{opt.default}} {%- endif %} : inputs[{{loop.index0 + fun.req|inputs|length}}].to{{opt.tp|toUpperCamelCase}}();
{% endfor %}
{# ----------- Outputs ------------ #}
{% for arg in fun.req|only|outputs %}
{{arg.tp}} {{arg.name}};
{% endfor %}
{% for opt in fun.opt|only|outputs %}
{{opt.tp}} {{opt.name}};
{% endfor %}
{% if not fun.rtp|void and not fun.constructor %}
{{fun.rtp}} retval;
{% endif %}
{% endif %}
{%- endmacro %}
/*
* handleOutputs
* pack outputs into the bridge
* Given a set of outputs, this methods assigns them into the bridge for
* return to the calling method
*/
{%- macro handleOutputs(fun) %}
{% if fun|noutputs %}
// assign the outputs into the bridge
{% if not fun.rtp|void and not fun.constructor %}
outputs[0] = retval;
{% endif %}
{% for arg in fun.req|outputs %}
outputs[{{loop.index0 + fun.rtp|void|not}}] = {{arg.name}};
{% endfor %}
{% for opt in fun.opt|outputs %}
outputs[{{loop.index0 + fun.rtp|void|not + fun.req|outputs|length}}] = {{opt.name}};
{% endfor %}
{% endif %}
{%- endmacro %}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "gflags/gflags.h"
#include "opencv2/opencv.hpp"
#include "modules/perception/inference/inference.h"
#include "modules/perception/inference/inference_factory.h"
#include "modules/perception/inference/tensorrt/batch_stream.h"
#include "modules/perception/inference/tensorrt/entropy_calibrator.h"
#include "modules/perception/inference/tensorrt/rt_net.h"
#include "modules/perception/inference/utils/util.h"
DEFINE_bool(int8, false, "use int8");
DEFINE_string(output_blob, "loc_pred", "name of output blob");
DEFINE_string(names_file, "./yolo/blob_names.txt", "path of output blob");
DEFINE_string(test_list, "image_list.txt", "path of image list");
DEFINE_string(image_root, "./images/", "path of image dir");
DEFINE_string(image_ext, ".jpg", "path of image ext");
DEFINE_string(res_dir, "./result.dat", "path of result");
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
const std::string proto_file = "./yolo/caffe.pt";
const std::string weight_file = "./yolo/caffe.caffemodel";
const std::string model_root = "./yolo";
apollo::perception::inference::Inference *rt_net;
std::vector<std::string> outputs{"loc_pred", "obj_pred", "cls_pred",
"ori_pred", "dim_pred", "lof_pred",
"lor_pred", "conv4_3"};
std::vector<std::string> inputs{"data"};
apollo::perception::inference::load_data<std::string>(FLAGS_names_file,
&outputs);
std::shared_ptr<nvinfer1::Int8EntropyCalibrator> calibrator = nullptr;
if (FLAGS_int8) {
apollo::perception::inference::BatchStream stream(2, 100, "./batches/");
calibrator.reset(
new nvinfer1::Int8EntropyCalibrator(stream, 0, true, "./"));
rt_net = new apollo::perception::inference::RTNet(
proto_file, weight_file, outputs, inputs, calibrator.get());
} else {
rt_net = apollo::perception::inference::CreateInferenceByName(
"RTNet", proto_file, weight_file, outputs, inputs);
}
const int height = 576;
const int width = 1440;
const int offset_y = 312;
std::vector<int> shape = {1, height, width, 3};
std::map<std::string, std::vector<int>> shape_map{{"data", shape}};
rt_net->Init(shape_map);
// auto input_gpu = rt_net->get_blob("data")->mutable_gpu_data();
std::vector<std::string> image_lists;
apollo::perception::inference::load_data<std::string>(FLAGS_test_list,
&image_lists);
std::vector<float> output_data_vec;
for (auto image_file : image_lists) {
cv::Mat img = cv::imread(FLAGS_image_root + image_file + FLAGS_image_ext);
cv::Rect roi(0, offset_y, img.cols, img.rows - offset_y);
cv::Mat img_roi = img(roi);
img_roi.copyTo(img);
cv::resize(img, img, cv::Size(width, height));
auto input = rt_net->get_blob("data")->mutable_cpu_data();
const int count = 3 * width * height;
for (int i = 0; i < count; i++) {
input[i] = img.data[i];
}
cudaDeviceSynchronize();
rt_net->Infer();
cudaDeviceSynchronize();
for (auto output_name : outputs) {
std::vector<int> shape;
auto blob = rt_net->get_blob(output_name);
const int size = blob->count();
std::vector<float> tmp_vec(blob->cpu_data(), blob->cpu_data() + size);
output_data_vec.insert(output_data_vec.end(), tmp_vec.begin(),
tmp_vec.end());
}
}
apollo::perception::inference::write_result(FLAGS_res_dir, output_data_vec);
delete rt_net;
return 0;
}
<commit_msg>Perception: let count outside the loop<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "gflags/gflags.h"
#include "opencv2/opencv.hpp"
#include "modules/perception/inference/inference.h"
#include "modules/perception/inference/inference_factory.h"
#include "modules/perception/inference/tensorrt/batch_stream.h"
#include "modules/perception/inference/tensorrt/entropy_calibrator.h"
#include "modules/perception/inference/tensorrt/rt_net.h"
#include "modules/perception/inference/utils/util.h"
DEFINE_bool(int8, false, "use int8");
DEFINE_string(output_blob, "loc_pred", "name of output blob");
DEFINE_string(names_file, "./yolo/blob_names.txt", "path of output blob");
DEFINE_string(test_list, "image_list.txt", "path of image list");
DEFINE_string(image_root, "./images/", "path of image dir");
DEFINE_string(image_ext, ".jpg", "path of image ext");
DEFINE_string(res_dir, "./result.dat", "path of result");
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
const std::string proto_file = "./yolo/caffe.pt";
const std::string weight_file = "./yolo/caffe.caffemodel";
const std::string model_root = "./yolo";
apollo::perception::inference::Inference *rt_net;
std::vector<std::string> outputs{"loc_pred", "obj_pred", "cls_pred",
"ori_pred", "dim_pred", "lof_pred",
"lor_pred", "conv4_3"};
std::vector<std::string> inputs{"data"};
apollo::perception::inference::load_data<std::string>(FLAGS_names_file,
&outputs);
std::shared_ptr<nvinfer1::Int8EntropyCalibrator> calibrator = nullptr;
if (FLAGS_int8) {
apollo::perception::inference::BatchStream stream(2, 100, "./batches/");
calibrator.reset(
new nvinfer1::Int8EntropyCalibrator(stream, 0, true, "./"));
rt_net = new apollo::perception::inference::RTNet(
proto_file, weight_file, outputs, inputs, calibrator.get());
} else {
rt_net = apollo::perception::inference::CreateInferenceByName(
"RTNet", proto_file, weight_file, outputs, inputs);
}
const int height = 576;
const int width = 1440;
const int offset_y = 312;
std::vector<int> shape = {1, height, width, 3};
std::map<std::string, std::vector<int>> shape_map{{"data", shape}};
rt_net->Init(shape_map);
// auto input_gpu = rt_net->get_blob("data")->mutable_gpu_data();
std::vector<std::string> image_lists;
apollo::perception::inference::load_data<std::string>(FLAGS_test_list,
&image_lists);
const int count = 3 * width * height;
std::vector<float> output_data_vec;
for (auto &image_file : image_lists) {
cv::Mat img = cv::imread(FLAGS_image_root + image_file + FLAGS_image_ext);
cv::Rect roi(0, offset_y, img.cols, img.rows - offset_y);
cv::Mat img_roi = img(roi);
img_roi.copyTo(img);
cv::resize(img, img, cv::Size(width, height));
auto input = rt_net->get_blob("data")->mutable_cpu_data();
for (int i = 0; i < count; ++i) {
input[i] = img.data[i];
}
cudaDeviceSynchronize();
rt_net->Infer();
cudaDeviceSynchronize();
for (auto output_name : outputs) {
std::vector<int> shape;
auto blob = rt_net->get_blob(output_name);
const int size = blob->count();
std::vector<float> tmp_vec(blob->cpu_data(), blob->cpu_data() + size);
output_data_vec.insert(output_data_vec.end(), tmp_vec.begin(),
tmp_vec.end());
}
}
apollo::perception::inference::write_result(FLAGS_res_dir, output_data_vec);
delete rt_net;
return 0;
}
<|endoftext|>
|
<commit_before>/*** twsgen.cpp -- twsxml converter and job generator
*
* Copyright (C) 2011 Ruediger Meier
*
* Author: Ruediger Meier <sweet_f_a@gmx.de>
*
* This file is part of twstools.
*
* 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. Neither the name of the author nor the names of any contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***/
#include "tws_xml.h"
#include "tws_meta.h"
#include "debug.h"
#include "config.h"
#include <popt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libxml/tree.h>
enum { POPT_HELP, POPT_VERSION, POPT_USAGE };
static poptContext opt_ctx;
static const char *filep = NULL;
static int skipdefp = 0;
static int histjobp = 0;
static const char *endDateTimep = "";
static const char *durationStrp = NULL;
static const char *barSizeSettingp = "1 hour";
static const char *whatToShowp = "TRADES";
static int useRTHp = 0;
static int utcp = 0;
static const char *includeExpiredp = "auto";
static int to_csvp = 0;
static int no_convp = 0;
static char** wts_list = NULL;
static char* wts_split = NULL;
enum expiry_mode{ EXP_AUTO, EXP_ALWAYS, EXP_NEVER, EXP_KEEP };
static int exp_mode = -1;
static int formatDate()
{
if( utcp ) {
return 2;
}
return 1;
}
#define VERSION_MSG \
PACKAGE_NAME " " PACKAGE_VERSION "\n\
Copyright (C) 2010-2011 Ruediger Meier <sweet_f_a@gmx.de>\n\
License: BSD 3-Clause\n"
static void displayArgs( poptContext con, poptCallbackReason /*foo*/,
poptOption *key, const char */*arg*/, void */*data*/ )
{
switch( key->val ) {
case POPT_HELP:
poptPrintHelp(con, stdout, 0);
break;
case POPT_VERSION:
fprintf(stdout, VERSION_MSG);
break;
case POPT_USAGE:
poptPrintUsage(con, stdout, 0);
break;
default:
assert(false);
}
exit(0);
}
static struct poptOption flow_opts[] = {
{"verbose-xml", 'x', POPT_ARG_NONE, &skipdefp, 0,
"Never skip xml default values.", NULL},
{"histjob", 'H', POPT_ARG_NONE, &histjobp, 0,
"generate hist job", NULL},
{"endDateTime", 'e', POPT_ARG_STRING, &endDateTimep, 0,
"Query end date time, default is \"\" which means now.", "DATETIME"},
{"durationStr", 'd', POPT_ARG_STRING, &durationStrp, 0,
"Query duration, default is maximum dependent on bar size.", NULL},
{"barSizeSetting", 'b', POPT_ARG_STRING, &barSizeSettingp, 0,
"Size of the bars, default is \"1 hour\".", NULL},
{"whatToShow", 'w', POPT_ARG_STRING, &whatToShowp, 0,
"List of data types, valid types are: TRADES, BID, ASK, etc., "
"default: TRADES", "LIST"},
{"useRTH", '\0', POPT_ARG_NONE, &useRTHp, 0,
"Return only data within regular trading hours (useRTH=1).", NULL},
{"utc", '\0', POPT_ARG_NONE, &utcp, 0,
"Dates are returned as seconds since unix epoch (formatDate=2).", NULL},
{"includeExpired", '\0', POPT_ARG_STRING, &includeExpiredp, 0,
"How to set includeExpired, valid args: auto, always, never, keep. "
"Default is auto (dependent on secType).", NULL},
{"to-csv", 'C', POPT_ARG_NONE, &to_csvp, 0,
"Just convert xml to csv.", NULL},
{"no-conv", '\0', POPT_ARG_NONE, &no_convp, 0,
"For testing, output xml again.", NULL},
POPT_TABLEEND
};
static struct poptOption help_opts[] = {
{NULL, '\0', POPT_ARG_CALLBACK, (void*)displayArgs, 0, NULL, NULL},
{"help", '\0', POPT_ARG_NONE, NULL, POPT_HELP,
"Show this help message.", NULL},
{"version", '\0', POPT_ARG_NONE, NULL, POPT_VERSION,
"Print version string and exit.", NULL},
{"usage", '\0', POPT_ARG_NONE, NULL, POPT_USAGE,
"Display brief usage message." , NULL},
POPT_TABLEEND
};
static const struct poptOption twsDL_opts[] = {
{NULL, '\0', POPT_ARG_INCLUDE_TABLE, flow_opts, 0,
"Program advice:", NULL},
{NULL, '\0', POPT_ARG_INCLUDE_TABLE, help_opts, 0,
"Help options:", NULL},
POPT_TABLEEND
};
void clear_popt()
{
poptFreeContext(opt_ctx);
}
void twsgen_parse_cl(size_t argc, const char *argv[])
{
opt_ctx = poptGetContext(NULL, argc, argv, twsDL_opts, 0);
atexit(clear_popt);
poptSetOtherOptionHelp( opt_ctx, "[OPTION]... FILE");
int rc;
while( (rc = poptGetNextOpt(opt_ctx)) > 0 ) {
// handle options when we have returning ones
assert(false);
}
if( rc != -1 ) {
fprintf( stderr, "error: %s '%s'\n",
poptStrerror(rc), poptBadOption(opt_ctx, 0) );
exit(2);
}
const char** rest = poptGetArgs(opt_ctx);
if( rest != NULL && *rest != NULL ) {
filep = *rest;
rest++;
if( *rest != NULL ) {
fprintf( stderr, "error: bad usage\n" );
exit(2);
}
} else {
fprintf( stderr, "error: bad usage\n" );
exit(2);
}
}
const char* max_durationStr( const char* barSizeSetting )
{
/* valid bars: (1|5|15|30) secs, 1 min, (2|3|5|15|30) mins, 1 hour, 4 hours
seems to be not supported anymore: 1 day, 1 week, 1 month, 3 months, 1 year
valid durations: integer{SPACE}unit (S|D|W|M|Y) */
// TODO
if( strcmp( barSizeSetting, "1 secs")==0 ) {
return "2000 S";
} else if( strcasecmp( barSizeSetting, "5 secs")==0 ) {
return "10000 S";
} else if( strcasecmp( barSizeSetting, "15 secs")==0 ) {
return "30000 S";
} else if( strcasecmp( barSizeSetting, "30 secs")==0 ) {
return "86400 S"; // seems to get more that "1 D"
} else if( strcasecmp( barSizeSetting, "1 min")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "2 mins")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "3 mins")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "5 mins")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "15 mins")==0 ) {
return "20 D";
} else if( strcasecmp( barSizeSetting, "30 mins")==0 ) {
return "34 D";
} else if( strcasecmp( barSizeSetting, "1 hour")==0 ) {
return "34 D";
} else if( strcasecmp( barSizeSetting, "4 hours")==0 ) {
return "34 D";
} else if( strcasecmp( barSizeSetting, "1 day")==0 ) {
/* Is "1 Y" always better than "52 W" or "12 M"? Note that longer
requests will be rejected from local TWS itself! */
return "1 Y";
} else {
fprintf( stderr, "error, could not guess durationStr from unknown "
"--barSizeSetting '%s', use a known one or overide with "
"--durationStr\n", barSizeSettingp );
exit(2);
}
}
void set_includeExpired()
{
if( strcmp( includeExpiredp, "auto")==0 ) {
exp_mode = EXP_AUTO;
} else if( strcmp( includeExpiredp, "always")==0 ) {
exp_mode = EXP_ALWAYS;
} else if( strcmp( includeExpiredp, "never")==0 ) {
exp_mode = EXP_NEVER;
} else if( strcmp( includeExpiredp, "keep")==0 ) {
exp_mode = EXP_KEEP;
} else {
fprintf( stderr, "error, unknow argument '%s'\n", includeExpiredp );
exit(2);
}
}
bool get_inc_exp( const char* secType )
{
switch( exp_mode ) {
case EXP_AUTO:
/* seems that includeExpired works for FUT only, however we set it for
all secTypes where TWS doesn't return errors */
if( strcasecmp(secType, "OPT")==0 || strcasecmp(secType, "FUT")==0 ||
strcasecmp(secType, "FOP")==0 || strcasecmp(secType, "WAR")==0 ) {
return true;
}
return false;
case EXP_ALWAYS:
return true;
case EXP_NEVER:
return false;
default:
assert(false);
return false;
}
}
void split_whatToShow()
{
size_t len = strlen(whatToShowp) + 1;
wts_list = (char**) malloc( (len/2 + 1) * sizeof(char*) );
wts_split = (char*) malloc( len * sizeof(char) );
strcpy( wts_split, whatToShowp );
char **wts = wts_list;
char *token = strtok( wts_split, ", \t" );
*wts = token;
wts++;
while( token != NULL ) {
token = strtok( NULL, ", \t" );
*wts = token;
wts++;
}
assert( *(wts - 1) == NULL );
assert( (wts - wts_list) <= (len/2 + 1) );
}
bool gen_hist_job()
{
TwsXml file;
if( ! file.openFile(filep) ) {
return false;
}
xmlNodePtr xn;
int count_docs = 0;
/* NOTE We are dumping single HistRequests but we should build and dump
a HistTodo object */
while( (xn = file.nextXmlNode()) != NULL ) {
count_docs++;
PacketContractDetails *pcd = PacketContractDetails::fromXml( xn );
int myProp_reqMaxContractsPerSpec = -1;
for( size_t i = 0; i < pcd->constList().size(); i++ ) {
const IB::ContractDetails &cd = pcd->constList()[i];
IB::Contract c = cd.summary;
if( exp_mode != EXP_KEEP ) {
c.includeExpired = get_inc_exp(c.secType.c_str());
}
if( myProp_reqMaxContractsPerSpec > 0 && (size_t)myProp_reqMaxContractsPerSpec <= i ) {
break;
}
for( char **wts = wts_list; *wts != NULL; wts++ ) {
HistRequest hR;
hR.initialize( c, endDateTimep, durationStrp, barSizeSettingp,
*wts, useRTHp, formatDate() );
PacketHistData phd;
phd.record( 0, hR );
phd.dumpXml();
}
}
delete pcd;
}
fprintf( stderr, "notice, %d xml docs parsed from file '%s'\n",
count_docs, filep );
return true;
}
bool gen_csv()
{
TwsXml file;
if( ! file.openFile(filep) ) {
return false;
}
xmlNodePtr xn;
int count_docs = 0;
while( (xn = file.nextXmlNode()) != NULL ) {
count_docs++;
PacketHistData *phd = PacketHistData::fromXml( xn );
if( !no_convp ) {
phd->dump( true /* printFormatDates */);
} else {
phd->dumpXml();
}
delete phd;
}
fprintf( stderr, "notice, %d xml docs parsed from file '%s'\n",
count_docs, filep );
return true;
}
int main(int argc, const char *argv[])
{
twsgen_parse_cl(argc, argv);
TwsXml::setSkipDefaults( !skipdefp );
if( !durationStrp ) {
durationStrp = max_durationStr( barSizeSettingp );
}
split_whatToShow();
set_includeExpired();
if( histjobp ) {
if( !gen_hist_job() ) {
return 1;
}
} else if( to_csvp ) {
if( !gen_csv() ) {
return 1;
}
} else {
fprintf( stderr, "error, nothing to do, use -H or -C.\n" );
return 2;
}
return 0;
}
<commit_msg>build fix, include missing time.h<commit_after>/*** twsgen.cpp -- twsxml converter and job generator
*
* Copyright (C) 2011 Ruediger Meier
*
* Author: Ruediger Meier <sweet_f_a@gmx.de>
*
* This file is part of twstools.
*
* 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. Neither the name of the author nor the names of any contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***/
#include "tws_xml.h"
#include "tws_meta.h"
#include "debug.h"
#include "config.h"
#include <popt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <libxml/tree.h>
enum { POPT_HELP, POPT_VERSION, POPT_USAGE };
static poptContext opt_ctx;
static const char *filep = NULL;
static int skipdefp = 0;
static int histjobp = 0;
static const char *endDateTimep = "";
static const char *durationStrp = NULL;
static const char *barSizeSettingp = "1 hour";
static const char *whatToShowp = "TRADES";
static int useRTHp = 0;
static int utcp = 0;
static const char *includeExpiredp = "auto";
static int to_csvp = 0;
static int no_convp = 0;
static char** wts_list = NULL;
static char* wts_split = NULL;
enum expiry_mode{ EXP_AUTO, EXP_ALWAYS, EXP_NEVER, EXP_KEEP };
static int exp_mode = -1;
static int formatDate()
{
if( utcp ) {
return 2;
}
return 1;
}
#define VERSION_MSG \
PACKAGE_NAME " " PACKAGE_VERSION "\n\
Copyright (C) 2010-2011 Ruediger Meier <sweet_f_a@gmx.de>\n\
License: BSD 3-Clause\n"
static void displayArgs( poptContext con, poptCallbackReason /*foo*/,
poptOption *key, const char */*arg*/, void */*data*/ )
{
switch( key->val ) {
case POPT_HELP:
poptPrintHelp(con, stdout, 0);
break;
case POPT_VERSION:
fprintf(stdout, VERSION_MSG);
break;
case POPT_USAGE:
poptPrintUsage(con, stdout, 0);
break;
default:
assert(false);
}
exit(0);
}
static struct poptOption flow_opts[] = {
{"verbose-xml", 'x', POPT_ARG_NONE, &skipdefp, 0,
"Never skip xml default values.", NULL},
{"histjob", 'H', POPT_ARG_NONE, &histjobp, 0,
"generate hist job", NULL},
{"endDateTime", 'e', POPT_ARG_STRING, &endDateTimep, 0,
"Query end date time, default is \"\" which means now.", "DATETIME"},
{"durationStr", 'd', POPT_ARG_STRING, &durationStrp, 0,
"Query duration, default is maximum dependent on bar size.", NULL},
{"barSizeSetting", 'b', POPT_ARG_STRING, &barSizeSettingp, 0,
"Size of the bars, default is \"1 hour\".", NULL},
{"whatToShow", 'w', POPT_ARG_STRING, &whatToShowp, 0,
"List of data types, valid types are: TRADES, BID, ASK, etc., "
"default: TRADES", "LIST"},
{"useRTH", '\0', POPT_ARG_NONE, &useRTHp, 0,
"Return only data within regular trading hours (useRTH=1).", NULL},
{"utc", '\0', POPT_ARG_NONE, &utcp, 0,
"Dates are returned as seconds since unix epoch (formatDate=2).", NULL},
{"includeExpired", '\0', POPT_ARG_STRING, &includeExpiredp, 0,
"How to set includeExpired, valid args: auto, always, never, keep. "
"Default is auto (dependent on secType).", NULL},
{"to-csv", 'C', POPT_ARG_NONE, &to_csvp, 0,
"Just convert xml to csv.", NULL},
{"no-conv", '\0', POPT_ARG_NONE, &no_convp, 0,
"For testing, output xml again.", NULL},
POPT_TABLEEND
};
static struct poptOption help_opts[] = {
{NULL, '\0', POPT_ARG_CALLBACK, (void*)displayArgs, 0, NULL, NULL},
{"help", '\0', POPT_ARG_NONE, NULL, POPT_HELP,
"Show this help message.", NULL},
{"version", '\0', POPT_ARG_NONE, NULL, POPT_VERSION,
"Print version string and exit.", NULL},
{"usage", '\0', POPT_ARG_NONE, NULL, POPT_USAGE,
"Display brief usage message." , NULL},
POPT_TABLEEND
};
static const struct poptOption twsDL_opts[] = {
{NULL, '\0', POPT_ARG_INCLUDE_TABLE, flow_opts, 0,
"Program advice:", NULL},
{NULL, '\0', POPT_ARG_INCLUDE_TABLE, help_opts, 0,
"Help options:", NULL},
POPT_TABLEEND
};
void clear_popt()
{
poptFreeContext(opt_ctx);
}
void twsgen_parse_cl(size_t argc, const char *argv[])
{
opt_ctx = poptGetContext(NULL, argc, argv, twsDL_opts, 0);
atexit(clear_popt);
poptSetOtherOptionHelp( opt_ctx, "[OPTION]... FILE");
int rc;
while( (rc = poptGetNextOpt(opt_ctx)) > 0 ) {
// handle options when we have returning ones
assert(false);
}
if( rc != -1 ) {
fprintf( stderr, "error: %s '%s'\n",
poptStrerror(rc), poptBadOption(opt_ctx, 0) );
exit(2);
}
const char** rest = poptGetArgs(opt_ctx);
if( rest != NULL && *rest != NULL ) {
filep = *rest;
rest++;
if( *rest != NULL ) {
fprintf( stderr, "error: bad usage\n" );
exit(2);
}
} else {
fprintf( stderr, "error: bad usage\n" );
exit(2);
}
}
const char* max_durationStr( const char* barSizeSetting )
{
/* valid bars: (1|5|15|30) secs, 1 min, (2|3|5|15|30) mins, 1 hour, 4 hours
seems to be not supported anymore: 1 day, 1 week, 1 month, 3 months, 1 year
valid durations: integer{SPACE}unit (S|D|W|M|Y) */
// TODO
if( strcmp( barSizeSetting, "1 secs")==0 ) {
return "2000 S";
} else if( strcasecmp( barSizeSetting, "5 secs")==0 ) {
return "10000 S";
} else if( strcasecmp( barSizeSetting, "15 secs")==0 ) {
return "30000 S";
} else if( strcasecmp( barSizeSetting, "30 secs")==0 ) {
return "86400 S"; // seems to get more that "1 D"
} else if( strcasecmp( barSizeSetting, "1 min")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "2 mins")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "3 mins")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "5 mins")==0 ) {
return "6 D";
} else if( strcasecmp( barSizeSetting, "15 mins")==0 ) {
return "20 D";
} else if( strcasecmp( barSizeSetting, "30 mins")==0 ) {
return "34 D";
} else if( strcasecmp( barSizeSetting, "1 hour")==0 ) {
return "34 D";
} else if( strcasecmp( barSizeSetting, "4 hours")==0 ) {
return "34 D";
} else if( strcasecmp( barSizeSetting, "1 day")==0 ) {
/* Is "1 Y" always better than "52 W" or "12 M"? Note that longer
requests will be rejected from local TWS itself! */
return "1 Y";
} else {
fprintf( stderr, "error, could not guess durationStr from unknown "
"--barSizeSetting '%s', use a known one or overide with "
"--durationStr\n", barSizeSettingp );
exit(2);
}
}
void set_includeExpired()
{
if( strcmp( includeExpiredp, "auto")==0 ) {
exp_mode = EXP_AUTO;
} else if( strcmp( includeExpiredp, "always")==0 ) {
exp_mode = EXP_ALWAYS;
} else if( strcmp( includeExpiredp, "never")==0 ) {
exp_mode = EXP_NEVER;
} else if( strcmp( includeExpiredp, "keep")==0 ) {
exp_mode = EXP_KEEP;
} else {
fprintf( stderr, "error, unknow argument '%s'\n", includeExpiredp );
exit(2);
}
}
bool get_inc_exp( const char* secType )
{
switch( exp_mode ) {
case EXP_AUTO:
/* seems that includeExpired works for FUT only, however we set it for
all secTypes where TWS doesn't return errors */
if( strcasecmp(secType, "OPT")==0 || strcasecmp(secType, "FUT")==0 ||
strcasecmp(secType, "FOP")==0 || strcasecmp(secType, "WAR")==0 ) {
return true;
}
return false;
case EXP_ALWAYS:
return true;
case EXP_NEVER:
return false;
default:
assert(false);
return false;
}
}
void split_whatToShow()
{
size_t len = strlen(whatToShowp) + 1;
wts_list = (char**) malloc( (len/2 + 1) * sizeof(char*) );
wts_split = (char*) malloc( len * sizeof(char) );
strcpy( wts_split, whatToShowp );
char **wts = wts_list;
char *token = strtok( wts_split, ", \t" );
*wts = token;
wts++;
while( token != NULL ) {
token = strtok( NULL, ", \t" );
*wts = token;
wts++;
}
assert( *(wts - 1) == NULL );
assert( (wts - wts_list) <= (len/2 + 1) );
}
bool gen_hist_job()
{
TwsXml file;
if( ! file.openFile(filep) ) {
return false;
}
xmlNodePtr xn;
int count_docs = 0;
/* NOTE We are dumping single HistRequests but we should build and dump
a HistTodo object */
while( (xn = file.nextXmlNode()) != NULL ) {
count_docs++;
PacketContractDetails *pcd = PacketContractDetails::fromXml( xn );
int myProp_reqMaxContractsPerSpec = -1;
for( size_t i = 0; i < pcd->constList().size(); i++ ) {
const IB::ContractDetails &cd = pcd->constList()[i];
IB::Contract c = cd.summary;
if( exp_mode != EXP_KEEP ) {
c.includeExpired = get_inc_exp(c.secType.c_str());
}
if( myProp_reqMaxContractsPerSpec > 0 && (size_t)myProp_reqMaxContractsPerSpec <= i ) {
break;
}
for( char **wts = wts_list; *wts != NULL; wts++ ) {
HistRequest hR;
hR.initialize( c, endDateTimep, durationStrp, barSizeSettingp,
*wts, useRTHp, formatDate() );
PacketHistData phd;
phd.record( 0, hR );
phd.dumpXml();
}
}
delete pcd;
}
fprintf( stderr, "notice, %d xml docs parsed from file '%s'\n",
count_docs, filep );
return true;
}
bool gen_csv()
{
TwsXml file;
if( ! file.openFile(filep) ) {
return false;
}
xmlNodePtr xn;
int count_docs = 0;
while( (xn = file.nextXmlNode()) != NULL ) {
count_docs++;
PacketHistData *phd = PacketHistData::fromXml( xn );
if( !no_convp ) {
phd->dump( true /* printFormatDates */);
} else {
phd->dumpXml();
}
delete phd;
}
fprintf( stderr, "notice, %d xml docs parsed from file '%s'\n",
count_docs, filep );
return true;
}
int main(int argc, const char *argv[])
{
twsgen_parse_cl(argc, argv);
TwsXml::setSkipDefaults( !skipdefp );
if( !durationStrp ) {
durationStrp = max_durationStr( barSizeSettingp );
}
split_whatToShow();
set_includeExpired();
if( histjobp ) {
if( !gen_hist_job() ) {
return 1;
}
} else if( to_csvp ) {
if( !gen_csv() ) {
return 1;
}
} else {
fprintf( stderr, "error, nothing to do, use -H or -C.\n" );
return 2;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <neat-socketapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
static const char* properties = "{\
\"transport\": [\
{\
\"value\": \"TCP\",\
\"precedence\": 1\
}\
]\
}";\
int main(int argc, char** argv)
{
int sd = nsa_socket(AF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, properties);
if(sd < 0) {
perror("nsa_socket() failed");
exit(1);
}
printf("sd=%d\n", sd);
sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(8888);
if(nsa_bind(sd, (sockaddr*)&local, sizeof(local)) < 0) {
perror("nsa_bind() failed");
exit(1);
}
if(nsa_listen(sd, 10) < 0) {
perror("nsa_listen() failed");
exit(1);
}
puts("### LISTENING ... ###");
int newSD = nsa_accept(sd, NULL, NULL);
if(newSD >= 0) {
puts("### ACCEPTED ###");
if(nsa_write(newSD, "TEST\n", 5) < 0) {
perror("nsa_write() failed");
}
char buffer[1024];
ssize_t r = nsa_read(newSD, (char*)&buffer, sizeof(buffer));
if(r > 0) {
printf("r=%d\n", r);
if(nsa_write(newSD, buffer, r) < 0) {
perror("nsa_write() failed");
}
}
nsa_close(newSD);
}
else {
perror("nsa_accept() failed");
}
nsa_close(sd);
nsa_cleanup();
return 0;
}
<commit_msg>A fix.<commit_after>#include <neat-socketapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
static const char* properties = "{\
\"transport\": [\
{\
\"value\": \"TCP\",\
\"precedence\": 1\
}\
]\
}";\
int main(int argc, char** argv)
{
int sd = nsa_socket(AF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, properties);
if(sd < 0) {
perror("nsa_socket() failed");
exit(1);
}
printf("sd=%d\n", sd);
sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(8888);
if(nsa_bind(sd, (sockaddr*)&local, sizeof(local)) < 0) {
perror("nsa_bind() failed");
exit(1);
}
if(nsa_listen(sd, 10) < 0) {
perror("nsa_listen() failed");
exit(1);
}
puts("### LISTENING ... ###");
int newSD = nsa_accept(sd, NULL, NULL);
if(newSD >= 0) {
puts("### ACCEPTED ###");
if(nsa_write(newSD, "TEST\n", 5) < 0) {
perror("nsa_write() failed");
}
char buffer[1024];
ssize_t r = nsa_read(newSD, (char*)&buffer, sizeof(buffer));
if(r > 0) {
printf("r=%d\n", (int)r);
if(nsa_write(newSD, buffer, r) < 0) {
perror("nsa_write() failed");
}
}
nsa_close(newSD);
}
else {
perror("nsa_accept() failed");
}
nsa_close(sd);
nsa_cleanup();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
bool send_peer(peer_connection const& p)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!p.is_local()) return false;
// don't send out peers that we haven't successfully connected to
if (p.is_connecting()) return false;
return true;
}
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(55) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
entry pex;
std::string& pla = pex["added"].string();
std::string& pld = pex["dropped"].string();
std::string& plf = pex["added.f"].string();
std::string& pla6 = pex["added6"].string();
std::string& pld6 = pex["dropped6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> pld6_out(pld6);
std::back_insert_iterator<std::string> plf6_out(plf6);
std::set<tcp::endpoint> dropped;
m_old_peers.swap(dropped);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
tcp::endpoint const& remote = peer->remote();
m_old_peers.insert(remote);
std::set<tcp::endpoint>::iterator di = dropped.find(remote);
if (di == dropped.end())
{
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
else
{
// this was in the previous message
// so, it wasn't dropped
dropped.erase(di);
}
}
for (std::set<tcp::endpoint>::const_iterator i = dropped.begin()
, end(dropped.end()); i != end; ++i)
{
if (i->address().is_v4())
detail::write_endpoint(*i, pld_out);
else
detail::write_endpoint(*i, pld6_out);
}
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::set<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(55)
, m_message_index(0)
, m_first_time(true)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
m_message_index = 0;
entry const* messages = h.find_key("m");
if (!messages || messages->type() != entry::dictionary_t) return false;
entry const* index = messages->find_key(extension_name);
if (!index || index->type() != entry::int_t) return false;
m_message_index = int(index->integer());
return true;
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
throw protocol_error("uT peer exchange message larger than 500 kB");
if (body.left() < length) return true;
entry pex_msg = bdecode(body.begin, body.end);
entry const* p = pex_msg.find_key("added");
entry const* pf = pex_msg.find_key("added.f");
if (p != 0 && pf != 0 && p->type() == entry::string_t && pf->type() == entry::string_t)
{
std::string const& peers = p->string();
std::string const& peer_flags = pf->string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
char const* fin = peer_flags.c_str();
if (int(peer_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
entry const* p6 = pex_msg.find_key("added6");
entry const* p6f = pex_msg.find_key("added6.f");
if (p6 && p6f && p6->type() == entry::string_t && p6f->type() == entry::string_t)
{
std::string const& peers6 = p6->string();
std::string const& peer6_flags = p6f->string();
int num_peers = peers6.length() / 18;
char const* in = peers6.c_str();
char const* fin = peer6_flags.c_str();
if (int(peer6_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
if (m_first_time)
{
send_ut_peer_list();
m_first_time = false;
}
else
{
send_ut_peer_diff();
}
m_1_minute = 0;
}
private:
void send_ut_peer_diff()
{
std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
void send_ut_peer_list()
{
entry pex;
// leave the dropped string empty
pex["dropped"].string();
std::string& pla = pex["added"].string();
std::string& plf = pex["added.f"].string();
pex["dropped6"].string();
std::string& pla6 = pex["added6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> plf6_out(plf6);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
tcp::endpoint const& remote = peer->remote();
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
std::vector<char> pex_msg;
bencode(std::back_inserter(pex_msg), pex);
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
// this is initialized to true, and set to
// false after the first pex message has been sent.
// it is used to know if a diff message or a full
// message should be sent.
bool m_first_time;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc);
if (!c) return boost::shared_ptr<peer_plugin>();
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<commit_msg>ut_pex exception fix<commit_after>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
bool send_peer(peer_connection const& p)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!p.is_local()) return false;
// don't send out peers that we haven't successfully connected to
if (p.is_connecting()) return false;
return true;
}
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(55) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
entry pex;
std::string& pla = pex["added"].string();
std::string& pld = pex["dropped"].string();
std::string& plf = pex["added.f"].string();
std::string& pla6 = pex["added6"].string();
std::string& pld6 = pex["dropped6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> pld6_out(pld6);
std::back_insert_iterator<std::string> plf6_out(plf6);
std::set<tcp::endpoint> dropped;
m_old_peers.swap(dropped);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
tcp::endpoint const& remote = peer->remote();
m_old_peers.insert(remote);
std::set<tcp::endpoint>::iterator di = dropped.find(remote);
if (di == dropped.end())
{
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
else
{
// this was in the previous message
// so, it wasn't dropped
dropped.erase(di);
}
}
for (std::set<tcp::endpoint>::const_iterator i = dropped.begin()
, end(dropped.end()); i != end; ++i)
{
if (i->address().is_v4())
detail::write_endpoint(*i, pld_out);
else
detail::write_endpoint(*i, pld6_out);
}
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::set<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(55)
, m_message_index(0)
, m_first_time(true)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
m_message_index = 0;
entry const* messages = h.find_key("m");
if (!messages || messages->type() != entry::dictionary_t) return false;
entry const* index = messages->find_key(extension_name);
if (!index || index->type() != entry::int_t) return false;
m_message_index = int(index->integer());
return true;
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
{
m_pc.disconnect("peer exchange message larger than 500 kB");
return true;
}
if (body.left() < length) return true;
entry pex_msg = bdecode(body.begin, body.end);
entry const* p = pex_msg.find_key("added");
entry const* pf = pex_msg.find_key("added.f");
if (p != 0 && pf != 0 && p->type() == entry::string_t && pf->type() == entry::string_t)
{
std::string const& peers = p->string();
std::string const& peer_flags = pf->string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
char const* fin = peer_flags.c_str();
if (int(peer_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
entry const* p6 = pex_msg.find_key("added6");
entry const* p6f = pex_msg.find_key("added6.f");
if (p6 && p6f && p6->type() == entry::string_t && p6f->type() == entry::string_t)
{
std::string const& peers6 = p6->string();
std::string const& peer6_flags = p6f->string();
int num_peers = peers6.length() / 18;
char const* in = peers6.c_str();
char const* fin = peer6_flags.c_str();
if (int(peer6_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
if (m_first_time)
{
send_ut_peer_list();
m_first_time = false;
}
else
{
send_ut_peer_diff();
}
m_1_minute = 0;
}
private:
void send_ut_peer_diff()
{
std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
void send_ut_peer_list()
{
entry pex;
// leave the dropped string empty
pex["dropped"].string();
std::string& pla = pex["added"].string();
std::string& plf = pex["added.f"].string();
pex["dropped6"].string();
std::string& pla6 = pex["added6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> plf6_out(plf6);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
tcp::endpoint const& remote = peer->remote();
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
std::vector<char> pex_msg;
bencode(std::back_inserter(pex_msg), pex);
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
// this is initialized to true, and set to
// false after the first pex message has been sent.
// it is used to know if a diff message or a full
// message should be sent.
bool m_first_time;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc);
if (!c) return boost::shared_ptr<peer_plugin>();
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<|endoftext|>
|
<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
private:
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all species using this shader.
void render();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
private:
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader.
void switch_to_new_shader(model::Shader *new_shader_pointer);
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
void *vertex_UV_pointer; // pointer to the vertex & UV species (not yet in use!).
// The rest fields are created in the constructor.
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
model::Shader *shader_pointer; // pointer to the shader.
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint speciesID_from_shader; // species ID, returned by `model::Shader->get_speciesID()`.
GLuint speciesID_from_texture; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_texture_file_format;
const char *char_texture_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<commit_msg>Muokattu kommentteja.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
private:
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all species using this shader.
void render();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint textureID; // texture ID, returned by `World::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
private:
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader.
void switch_to_new_shader(model::Shader *new_shader_pointer);
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
void *vertex_UV_pointer; // pointer to the vertex & UV species (not yet in use!).
// The rest fields are created in the constructor.
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
model::Shader *shader_pointer; // pointer to the shader.
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint speciesID_from_shader; // species ID, returned by `model::Shader->get_speciesID()`.
GLuint speciesID_from_texture; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_texture_file_format;
const char *char_texture_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<|endoftext|>
|
<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
friend class Shader;
friend class Species;
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
private:
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
void compute_matrices_from_inputs();
void* world_species_pointer; // pointer to world species (used in collision detection).
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
};
class Shader
{
friend class World;
friend class Texture;
friend class Species;
friend class Object;
public:
// constructor.
Shader(ShaderStruct shader_struct);
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
// destructor.
~Shader();
private:
// this method renders all textures using this shader.
void render();
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::World *world_pointer; // pointer to the world.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
void bind_to_world();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
friend class Shader;
friend class Species;
friend class Object;
public:
// constructor.
Texture(TextureStruct texture_struct);
// this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
void switch_to_new_shader(model::Shader *new_shader_pointer);
// destructor.
~Texture();
private:
// this method renders all species using this texture.
void render();
// this method sets a species pointer.
void set_species_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_species_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::Shader *shader_pointer; // pointer to the shader.
void bind_to_shader();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `Shader::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
friend class Node;
public:
// constructor.
Graph();
// destructor.
~Graph();
private:
// this method sets a node pointer.
void set_node_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_node_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
private:
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
bool is_world; // worlds currently do not rotate nor translate.
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
model::Texture *texture_pointer; // pointer to the texture.
private:
void bind_to_texture();
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Font
{
public:
// constructor.
Font(FontStruct font_struct);
// destructor.
~Font();
// this method renders all objects of this species.
void render();
// this method sets a glyph pointer.
void set_glyph_pointer(GLuint objectID, void* object_pointer);
// this method gets a glyph pointer.
void* get_glyph_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_glyphID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
model::Texture *texture_pointer; // pointer to the texture.
private:
void bind_to_texture();
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Glyph
{
public:
// constructor.
Glyph(GlyphStruct glyph_struct);
// destructor.
~Glyph();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
model::Font *font_pointer; // pointer to the font.
private:
void bind_to_font();
GLuint glyphID; // glyph ID, returned by `model::Font->get_glyphID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
private:
void bind_to_species();
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // coordinate vector.
glm::vec3 original_scale_vector; // original scale vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<commit_msg>`class Species`: Muokattu koodirivien järjestystä.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
friend class Shader;
friend class Species;
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
private:
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
void compute_matrices_from_inputs();
void* world_species_pointer; // pointer to world species (used in collision detection).
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
};
class Shader
{
friend class World;
friend class Texture;
friend class Species;
friend class Object;
public:
// constructor.
Shader(ShaderStruct shader_struct);
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
// destructor.
~Shader();
private:
// this method renders all textures using this shader.
void render();
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::World *world_pointer; // pointer to the world.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
void bind_to_world();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
friend class Shader;
friend class Species;
friend class Object;
public:
// constructor.
Texture(TextureStruct texture_struct);
// this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
void switch_to_new_shader(model::Shader *new_shader_pointer);
// destructor.
~Texture();
private:
// this method renders all species using this texture.
void render();
// this method sets a species pointer.
void set_species_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_species_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::Shader *shader_pointer; // pointer to the shader.
void bind_to_shader();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `Shader::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
friend class Node;
public:
// constructor.
Graph();
// destructor.
~Graph();
private:
// this method sets a node pointer.
void set_node_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_node_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
private:
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
bool is_world; // worlds currently do not rotate nor translate.
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
model::Texture *texture_pointer; // pointer to the texture.
private:
void bind_to_texture();
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Font
{
public:
// constructor.
Font(FontStruct font_struct);
// destructor.
~Font();
// this method renders all objects of this species.
void render();
// this method sets a glyph pointer.
void set_glyph_pointer(GLuint objectID, void* object_pointer);
// this method gets a glyph pointer.
void* get_glyph_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_glyphID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
model::Texture *texture_pointer; // pointer to the texture.
private:
void bind_to_texture();
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Glyph
{
public:
// constructor.
Glyph(GlyphStruct glyph_struct);
// destructor.
~Glyph();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
model::Font *font_pointer; // pointer to the font.
private:
void bind_to_font();
GLuint glyphID; // glyph ID, returned by `model::Font->get_glyphID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
private:
void bind_to_species();
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // coordinate vector.
glm::vec3 original_scale_vector; // original scale vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************/
/* */
/* X r d S y s P t h r e a d . c c */
/* */
/* (c) 2004 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved. See XrdInfo.cc for complete License Terms */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC03-76-SFO0515 with the Department of Energy */
/******************************************************************************/
// $Id$
const char *XrdSysPthreadCVSID = "$Id$";
#include <errno.h>
#include <pthread.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/time.h>
#else
#include <Winsock2.h>
#include <time.h>
#include "XrdSys/XrdWin32.hh"
#endif
#include <sys/types.h>
#include "XrdSys/XrdSysPthread.hh"
/******************************************************************************/
/* L o c a l S t r u c t s */
/******************************************************************************/
struct XrdSysThreadArgs
{
pthread_key_t numKey;
XrdSysError *eDest;
const char *tDesc;
void *(*proc)(void *);
void *arg;
XrdSysThreadArgs(pthread_key_t nk, XrdSysError *ed, const char *td,
void *(*p)(void *), void *a)
{numKey=nk; eDest=ed; tDesc=td, proc=p; arg=a;}
~XrdSysThreadArgs() {}
};
/******************************************************************************/
/* G l o b a l D a t a */
/******************************************************************************/
pthread_key_t XrdSysThread::threadNumkey;
XrdSysError *XrdSysThread::eDest = 0;
size_t XrdSysThread::stackSize = 0;
int XrdSysThread::initDone = 0;
/******************************************************************************/
/* T h r e a d I n t e r f a c e P r o g r a m s */
/******************************************************************************/
extern "C"
{
void *XrdSysThread_Xeq(void *myargs)
{
XrdSysThreadArgs *ap = (XrdSysThreadArgs *)myargs;
unsigned long myNum;
void *retc;
#if defined(__linux__)
myNum = static_cast<unsigned int>(getpid());
#elif defined(__solaris__)
myNum = static_cast<unsigned int>(pthread_self());
#elif defined(__macos__)
myNum = static_cast<unsigned int>(pthread_mach_thread_np(pthread_self()));
#else
static XrdSysMutex numMutex;
static unsigned long threadNum = 1;
numMutex.Lock(); threadNum++; myNum = threadNum; numMutex.UnLock();
#endif
pthread_setspecific(ap->numKey, reinterpret_cast<const void *>(myNum));
if (ap->eDest && ap->tDesc)
ap->eDest->Emsg("Xeq", ap->tDesc, "thread started");
retc = ap->proc(ap->arg);
delete ap;
return retc;
}
}
/******************************************************************************/
/* X r d S y s C o n d V a r */
/******************************************************************************/
/******************************************************************************/
/* W a i t */
/******************************************************************************/
int XrdSysCondVar::Wait()
{
int retc;
// Wait for the condition
//
if (relMutex) Lock();
retc = pthread_cond_wait(&cvar, &cmut);
if (relMutex) UnLock();
return retc;
}
/******************************************************************************/
int XrdSysCondVar::Wait(int sec)
{
struct timespec tval;
int retc;
// Get the mutex before calculating the time
//
if (relMutex) Lock();
// Simply adjust the time in seconds
//
tval.tv_sec = time(0) + sec;
tval.tv_nsec = 0;
// Wait for the condition or timeout
//
do {retc = pthread_cond_timedwait(&cvar, &cmut, &tval);}
while (retc && (retc != ETIMEDOUT));
if (relMutex) UnLock();
return retc == ETIMEDOUT;
}
/******************************************************************************/
/* W a i t M S */
/******************************************************************************/
int XrdSysCondVar::WaitMS(int msec)
{
int sec, retc, usec;
struct timeval tnow;
struct timespec tval;
// Adjust millseconds
//
if (msec < 1000) sec = 0;
else {sec = msec / 1000; msec = msec % 1000;}
usec = msec * 1000;
// Get the mutex before getting the time
//
if (relMutex) Lock();
// Get current time of day
//
gettimeofday(&tnow, 0);
// Add the second and microseconds
//
tval.tv_sec = tnow.tv_sec + sec;
tval.tv_nsec = tnow.tv_usec + usec;
if (tval.tv_nsec > 1000000)
{tval.tv_sec += tval.tv_nsec / 1000000;
tval.tv_nsec = tval.tv_nsec % 1000000;
}
tval.tv_nsec *= 1000;
// Now wait for the condition or timeout
//
do {retc = pthread_cond_timedwait(&cvar, &cmut, &tval);}
while (retc && (retc != ETIMEDOUT));
if (relMutex) UnLock();
return retc == ETIMEDOUT;
}
/******************************************************************************/
/* X r d S y s S e m a p h o r e */
/******************************************************************************/
/******************************************************************************/
/* C o n d W a i t */
/******************************************************************************/
#ifdef __macos__
int XrdSysSemaphore::CondWait()
{
int rc;
// Get the semaphore only we can get it without waiting
//
semVar.Lock();
if ((rc = (semVal > 0) && !semWait)) semVal--;
semVar.UnLock();
return rc;
}
/******************************************************************************/
/* P o s t */
/******************************************************************************/
void XrdSysSemaphore::Post()
{
// Add one to the semaphore counter. If we the value is > 0 and there is a
// thread waiting for the sempagore, signal it to get the semaphore.
//
semVar.Lock();
semVal++;
if (semVal && semWait) semVar.Signal();
semVar.UnLock();
}
/******************************************************************************/
/* W a i t */
/******************************************************************************/
void XrdSysSemaphore::Wait()
{
// Wait until the sempahore value is positive. This will not be starvation
// free is the OS implements an unfair mutex;
//
semVar.Lock();
if (semVal < 1 || semWait)
while(semVal < 1)
{semWait++;
semVar.Wait();
semWait--;
}
// Decrement the semaphore value and return
//
semVal--;
semVar.UnLock();
}
#endif
/******************************************************************************/
/* T h r e a d M e t h o d s */
/******************************************************************************/
/******************************************************************************/
/* d o I n i t */
/******************************************************************************/
void XrdSysThread::doInit()
{
static XrdSysMutex initMutex;
initMutex.Lock();
if (!initDone)
{pthread_key_create(&threadNumkey, 0);
pthread_setspecific(threadNumkey, (const void *)1);
initDone = 1;
}
initMutex.UnLock();
}
/******************************************************************************/
/* R u n */
/******************************************************************************/
int XrdSysThread::Run(pthread_t *tid, void *(*proc)(void *), void *arg,
int opts, const char *tDesc)
{
pthread_attr_t tattr;
XrdSysThreadArgs *myargs;
if (!initDone) doInit();
myargs = new XrdSysThreadArgs(threadNumkey, eDest, tDesc, proc, arg);
pthread_attr_init(&tattr);
if ( opts & XRDSYSTHREAD_BIND)
pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM);
if (!(opts & XRDSYSTHREAD_HOLD))
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
if (stackSize)
pthread_attr_setstacksize(&tattr, stackSize);
return pthread_create(tid, &tattr, XrdSysThread_Xeq,
static_cast<void *>(myargs));
}
/******************************************************************************/
/* W a i t */
/******************************************************************************/
int XrdSysThread::Wait(pthread_t tid)
{
int retc, *tstat;
if ((retc = pthread_join(tid, reinterpret_cast<void **>(&tstat)))) return retc;
return *tstat;
}
/******************************************************************************/
/* X r d S y s R e c M u t e x */
/******************************************************************************/
XrdSysRecMutex::XrdSysRecMutex() {
int rc;
pthread_mutexattr_t attr;
rc = pthread_mutexattr_init(&attr);
if (!rc) {
rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (!rc)
pthread_mutex_init(&cs, &attr);
}
pthread_mutexattr_destroy(&attr);
}
<commit_msg><commit_after>/******************************************************************************/
/* */
/* X r d S y s P t h r e a d . c c */
/* */
/* (c) 2004 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved. See XrdInfo.cc for complete License Terms */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC03-76-SFO0515 with the Department of Energy */
/******************************************************************************/
// $Id$
const char *XrdSysPthreadCVSID = "$Id$";
#include <errno.h>
#include <pthread.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/time.h>
#else
#undef ETIMEDOUT // Make sure that the definition from Winsock2.h is used ...
#include <Winsock2.h>
#include <time.h>
#include "XrdSys/XrdWin32.hh"
#endif
#include <sys/types.h>
#include "XrdSys/XrdSysPthread.hh"
/******************************************************************************/
/* L o c a l S t r u c t s */
/******************************************************************************/
struct XrdSysThreadArgs
{
pthread_key_t numKey;
XrdSysError *eDest;
const char *tDesc;
void *(*proc)(void *);
void *arg;
XrdSysThreadArgs(pthread_key_t nk, XrdSysError *ed, const char *td,
void *(*p)(void *), void *a)
{numKey=nk; eDest=ed; tDesc=td, proc=p; arg=a;}
~XrdSysThreadArgs() {}
};
/******************************************************************************/
/* G l o b a l D a t a */
/******************************************************************************/
pthread_key_t XrdSysThread::threadNumkey;
XrdSysError *XrdSysThread::eDest = 0;
size_t XrdSysThread::stackSize = 0;
int XrdSysThread::initDone = 0;
/******************************************************************************/
/* T h r e a d I n t e r f a c e P r o g r a m s */
/******************************************************************************/
extern "C"
{
void *XrdSysThread_Xeq(void *myargs)
{
XrdSysThreadArgs *ap = (XrdSysThreadArgs *)myargs;
unsigned long myNum;
void *retc;
#if defined(__linux__)
myNum = static_cast<unsigned int>(getpid());
#elif defined(__solaris__)
myNum = static_cast<unsigned int>(pthread_self());
#elif defined(__macos__)
myNum = static_cast<unsigned int>(pthread_mach_thread_np(pthread_self()));
#else
static XrdSysMutex numMutex;
static unsigned long threadNum = 1;
numMutex.Lock(); threadNum++; myNum = threadNum; numMutex.UnLock();
#endif
pthread_setspecific(ap->numKey, reinterpret_cast<const void *>(myNum));
if (ap->eDest && ap->tDesc)
ap->eDest->Emsg("Xeq", ap->tDesc, "thread started");
retc = ap->proc(ap->arg);
delete ap;
return retc;
}
}
/******************************************************************************/
/* X r d S y s C o n d V a r */
/******************************************************************************/
/******************************************************************************/
/* W a i t */
/******************************************************************************/
int XrdSysCondVar::Wait()
{
int retc;
// Wait for the condition
//
if (relMutex) Lock();
retc = pthread_cond_wait(&cvar, &cmut);
if (relMutex) UnLock();
return retc;
}
/******************************************************************************/
int XrdSysCondVar::Wait(int sec)
{
struct timespec tval;
int retc;
// Get the mutex before calculating the time
//
if (relMutex) Lock();
// Simply adjust the time in seconds
//
tval.tv_sec = time(0) + sec;
tval.tv_nsec = 0;
// Wait for the condition or timeout
//
do {retc = pthread_cond_timedwait(&cvar, &cmut, &tval);}
while (retc && (retc != ETIMEDOUT));
if (relMutex) UnLock();
return retc == ETIMEDOUT;
}
/******************************************************************************/
/* W a i t M S */
/******************************************************************************/
int XrdSysCondVar::WaitMS(int msec)
{
int sec, retc, usec;
struct timeval tnow;
struct timespec tval;
// Adjust millseconds
//
if (msec < 1000) sec = 0;
else {sec = msec / 1000; msec = msec % 1000;}
usec = msec * 1000;
// Get the mutex before getting the time
//
if (relMutex) Lock();
// Get current time of day
//
gettimeofday(&tnow, 0);
// Add the second and microseconds
//
tval.tv_sec = tnow.tv_sec + sec;
tval.tv_nsec = tnow.tv_usec + usec;
if (tval.tv_nsec > 1000000)
{tval.tv_sec += tval.tv_nsec / 1000000;
tval.tv_nsec = tval.tv_nsec % 1000000;
}
tval.tv_nsec *= 1000;
// Now wait for the condition or timeout
//
do {retc = pthread_cond_timedwait(&cvar, &cmut, &tval);}
while (retc && (retc != ETIMEDOUT));
if (relMutex) UnLock();
return retc == ETIMEDOUT;
}
/******************************************************************************/
/* X r d S y s S e m a p h o r e */
/******************************************************************************/
/******************************************************************************/
/* C o n d W a i t */
/******************************************************************************/
#ifdef __macos__
int XrdSysSemaphore::CondWait()
{
int rc;
// Get the semaphore only we can get it without waiting
//
semVar.Lock();
if ((rc = (semVal > 0) && !semWait)) semVal--;
semVar.UnLock();
return rc;
}
/******************************************************************************/
/* P o s t */
/******************************************************************************/
void XrdSysSemaphore::Post()
{
// Add one to the semaphore counter. If we the value is > 0 and there is a
// thread waiting for the sempagore, signal it to get the semaphore.
//
semVar.Lock();
semVal++;
if (semVal && semWait) semVar.Signal();
semVar.UnLock();
}
/******************************************************************************/
/* W a i t */
/******************************************************************************/
void XrdSysSemaphore::Wait()
{
// Wait until the sempahore value is positive. This will not be starvation
// free is the OS implements an unfair mutex;
//
semVar.Lock();
if (semVal < 1 || semWait)
while(semVal < 1)
{semWait++;
semVar.Wait();
semWait--;
}
// Decrement the semaphore value and return
//
semVal--;
semVar.UnLock();
}
#endif
/******************************************************************************/
/* T h r e a d M e t h o d s */
/******************************************************************************/
/******************************************************************************/
/* d o I n i t */
/******************************************************************************/
void XrdSysThread::doInit()
{
static XrdSysMutex initMutex;
initMutex.Lock();
if (!initDone)
{pthread_key_create(&threadNumkey, 0);
pthread_setspecific(threadNumkey, (const void *)1);
initDone = 1;
}
initMutex.UnLock();
}
/******************************************************************************/
/* R u n */
/******************************************************************************/
int XrdSysThread::Run(pthread_t *tid, void *(*proc)(void *), void *arg,
int opts, const char *tDesc)
{
pthread_attr_t tattr;
XrdSysThreadArgs *myargs;
if (!initDone) doInit();
myargs = new XrdSysThreadArgs(threadNumkey, eDest, tDesc, proc, arg);
pthread_attr_init(&tattr);
if ( opts & XRDSYSTHREAD_BIND)
pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM);
if (!(opts & XRDSYSTHREAD_HOLD))
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
if (stackSize)
pthread_attr_setstacksize(&tattr, stackSize);
return pthread_create(tid, &tattr, XrdSysThread_Xeq,
static_cast<void *>(myargs));
}
/******************************************************************************/
/* W a i t */
/******************************************************************************/
int XrdSysThread::Wait(pthread_t tid)
{
int retc, *tstat;
if ((retc = pthread_join(tid, reinterpret_cast<void **>(&tstat)))) return retc;
return *tstat;
}
/******************************************************************************/
/* X r d S y s R e c M u t e x */
/******************************************************************************/
XrdSysRecMutex::XrdSysRecMutex() {
int rc;
pthread_mutexattr_t attr;
rc = pthread_mutexattr_init(&attr);
if (!rc) {
rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (!rc)
pthread_mutex_init(&cs, &attr);
}
pthread_mutexattr_destroy(&attr);
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/fs.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include "rop.h"
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
std::vector<std::string> extensions = {"cia"};
bool exit = false;
bool showNetworkPrompts = true;
u64 freeSpace = 0;
MediaType destination = SD;
Mode mode = INSTALL_CIA;
int prevProgress = -1;
std::string installInfo = "";
bool onProgress(u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << installInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
}
void networkInstall() {
while(platformIsRunning()) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts.";
});
if(file.fd == NULL) {
break;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, &onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
}
fclose(file.fd);
}
}
void installROP() {
u32 selected = 0;
bool dirty = true;
while(platformIsRunning()) {
inputPoll();
if(inputIsPressed(BUTTON_B)) {
break;
}
if(inputIsPressed(BUTTON_A)) {
std::stringstream stream;
stream << "Install the selected ROP?" << "\n";
stream << ropNames[selected];
if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
u16 userSettingsOffset = 0;
bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);
std::stringstream resultMsg;
resultMsg << "ROP installation ";
if(result) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError());
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
dirty = true;
}
if(inputIsPressed(BUTTON_LEFT)) {
if(selected == 0) {
selected = ROP_COUNT - 1;
} else {
selected--;
}
dirty = true;
}
if(inputIsPressed(BUTTON_RIGHT)) {
if(selected >= ROP_COUNT - 1) {
selected = 0;
} else {
selected++;
}
dirty = true;
}
if(dirty) {
std::stringstream stream;
stream << "Select a ROP to install." << "\n";
stream << "< " << ropNames[selected] << " >" << "\n";
stream << "Press A to install, B to cancel.";
uiDisplayMessage(TOP_SCREEN, stream.str());
}
}
}
bool installCIA(MediaType destination, const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream batchInstallStream;
batchInstallStream << name << "\n";
installInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
if(ret != APP_SUCCESS && platformHasError()) {
Error error = platformGetError();
if(error.module == MODULE_NN_AM && error.description == DESCRIPTION_ALREADY_EXISTS) {
std::stringstream overwriteMsg;
overwriteMsg << "Title already installed, overwrite?" << "\n";
overwriteMsg << name;
if(uiPrompt(TOP_SCREEN, overwriteMsg.str(), true)) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult deleteRet = appDelete(appGetCiaInfo(path, destination));
if(deleteRet != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(deleteRet);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
} else {
platformSetError(error);
}
} else {
platformSetError(error);
}
}
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteCIA(const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << name;
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << strerror(errno);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool launchTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool onLoop() {
bool launcher = platformHasLauncher();
if(launcher && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
networkInstall();
}
if(inputIsPressed(BUTTON_SELECT)) {
installROP();
}
std::stringstream stream;
stream << "Battery: ";
if(platformIsBatteryCharging()) {
stream << "Charging";
} else {
for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
stream << "|";
}
}
stream << ", WiFi: ";
if(!platformIsWifiConnected()) {
stream << "Disconnected";
} else {
for(u32 i = 0; i < platformGetWifiLevel(); i++) {
stream << "|";
}
}
stream << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "SELECT - Install MSET ROP";
if(launcher) {
stream << "\n" << "START - Exit to launcher";
}
std::string str = stream.str();
const std::string title = "FBI v1.4.7";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);
return breakLoop;
}
int main(int argc, char **argv) {
if(!platformInit(argc)) {
return 0;
}
freeSpace = fsGetFreeSpace(destination);
while(platformIsRunning()) {
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");
std::string fileTarget;
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string name = (*it).name;
if(!fsIsDirectory(name) && fsHasExtensions(name, extensions)) {
if(mode == INSTALL_CIA) {
if(!installCIA(destination, path, name)) {
failed = true;
break;
}
} else {
if(deleteCIA(path, name)) {
updateList = true;
} else {
failed = true;
break;
}
}
}
}
if(!failed) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool success = false;
if(mode == INSTALL_CIA) {
success = installCIA(destination, path, fsGetFileName(path));
} else {
success = deleteCIA(path, fsGetFileName(path));
}
if(success) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
App appTarget;
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
if(deleteTitle(app)) {
uiPrompt(TOP_SCREEN, "Delete succeeded!", false);
}
updateList = true;
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
if(launchTitle(app)) {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<commit_msg>Bump version.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/fs.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include "rop.h"
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
std::vector<std::string> extensions = {"cia"};
bool exit = false;
bool showNetworkPrompts = true;
u64 freeSpace = 0;
MediaType destination = SD;
Mode mode = INSTALL_CIA;
int prevProgress = -1;
std::string installInfo = "";
bool onProgress(u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << installInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
}
void networkInstall() {
while(platformIsRunning()) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts.";
});
if(file.fd == NULL) {
break;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, &onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
}
fclose(file.fd);
}
}
void installROP() {
u32 selected = 0;
bool dirty = true;
while(platformIsRunning()) {
inputPoll();
if(inputIsPressed(BUTTON_B)) {
break;
}
if(inputIsPressed(BUTTON_A)) {
std::stringstream stream;
stream << "Install the selected ROP?" << "\n";
stream << ropNames[selected];
if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
u16 userSettingsOffset = 0;
bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);
std::stringstream resultMsg;
resultMsg << "ROP installation ";
if(result) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError());
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
dirty = true;
}
if(inputIsPressed(BUTTON_LEFT)) {
if(selected == 0) {
selected = ROP_COUNT - 1;
} else {
selected--;
}
dirty = true;
}
if(inputIsPressed(BUTTON_RIGHT)) {
if(selected >= ROP_COUNT - 1) {
selected = 0;
} else {
selected++;
}
dirty = true;
}
if(dirty) {
std::stringstream stream;
stream << "Select a ROP to install." << "\n";
stream << "< " << ropNames[selected] << " >" << "\n";
stream << "Press A to install, B to cancel.";
uiDisplayMessage(TOP_SCREEN, stream.str());
}
}
}
bool installCIA(MediaType destination, const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream batchInstallStream;
batchInstallStream << name << "\n";
installInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
if(ret != APP_SUCCESS && platformHasError()) {
Error error = platformGetError();
if(error.module == MODULE_NN_AM && error.description == DESCRIPTION_ALREADY_EXISTS) {
std::stringstream overwriteMsg;
overwriteMsg << "Title already installed, overwrite?" << "\n";
overwriteMsg << name;
if(uiPrompt(TOP_SCREEN, overwriteMsg.str(), true)) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult deleteRet = appDelete(appGetCiaInfo(path, destination));
if(deleteRet != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(deleteRet);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
} else {
platformSetError(error);
}
} else {
platformSetError(error);
}
}
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteCIA(const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << name;
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << strerror(errno);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool launchTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool onLoop() {
bool launcher = platformHasLauncher();
if(launcher && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
networkInstall();
}
if(inputIsPressed(BUTTON_SELECT)) {
installROP();
}
std::stringstream stream;
stream << "Battery: ";
if(platformIsBatteryCharging()) {
stream << "Charging";
} else {
for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
stream << "|";
}
}
stream << ", WiFi: ";
if(!platformIsWifiConnected()) {
stream << "Disconnected";
} else {
for(u32 i = 0; i < platformGetWifiLevel(); i++) {
stream << "|";
}
}
stream << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "SELECT - Install MSET ROP";
if(launcher) {
stream << "\n" << "START - Exit to launcher";
}
std::string str = stream.str();
const std::string title = "FBI v1.4.8";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);
return breakLoop;
}
int main(int argc, char **argv) {
if(!platformInit(argc)) {
return 0;
}
freeSpace = fsGetFreeSpace(destination);
while(platformIsRunning()) {
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");
std::string fileTarget;
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string name = (*it).name;
if(!fsIsDirectory(name) && fsHasExtensions(name, extensions)) {
if(mode == INSTALL_CIA) {
if(!installCIA(destination, path, name)) {
failed = true;
break;
}
} else {
if(deleteCIA(path, name)) {
updateList = true;
} else {
failed = true;
break;
}
}
}
}
if(!failed) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool success = false;
if(mode == INSTALL_CIA) {
success = installCIA(destination, path, fsGetFileName(path));
} else {
success = deleteCIA(path, fsGetFileName(path));
}
if(success) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
App appTarget;
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
if(deleteTitle(app)) {
uiPrompt(TOP_SCREEN, "Delete succeeded!", false);
}
updateList = true;
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
if(launchTitle(app)) {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "game.hpp"
#include <SDL2/SDL.h>
#include <thread>
#include <chrono>
#include <atomic>
#ifdef _OPENMP
#include <omp.h>
#endif
// TODO: reorder header includes (std first)
// TODO: fix formatting
using namespace std::chrono;
milliseconds last_frame_time;
Scal last_frame_game_time;
milliseconds last_report_time;
std::atomic<Scal> next_game_time_target;
std::unique_ptr<game> G;
GLdouble width, height; /* window width and height */
std::atomic<bool> flag_display;
std::atomic<bool> quit;
using std::cout;
using std::endl;
int frame_number;
void init()
{
width = 800.0; /* initial window width and height, */
height = 800.0; /* within which we draw. */
last_frame_game_time = 0.;
}
/* Callback functions for GLUT */
/* Draw the window - this is where all the GL actions are */
void display(void)
{
if(flag_display) return;
flag_display=true;
const Scal fps=30.0;
milliseconds current_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
milliseconds time_past_from_last_frame = current_time-last_frame_time;
//if(time_past_from_last_frame<milliseconds(100)) return;
milliseconds frame_duration(int(1000.0/fps));
milliseconds time_residual=frame_duration-time_past_from_last_frame;
//cout<<"sleep for "<<time_residual.count()<<endl;
//std::this_thread::sleep_for(time_residual);
//std::this_thread::sleep_for(frame_duration);
auto new_frame_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
auto new_frame_game_time = G->PS->GetTime();
const Scal frame_real_duration_s =
(new_frame_time - last_frame_time).count() / 1000.;
if ((new_frame_time - last_report_time).count() > 1000.) {
std::cout
<< "fps: " << 1. / frame_real_duration_s
<< ", game rate="
<< (new_frame_game_time -
last_frame_game_time) / frame_real_duration_s
<< ", particles="
<< G->PS->GetNumParticles()
<< ", max_per_cell="
<< G->PS->GetNumPerCell()
<< ", t="
<< G->PS->GetTime()
<< ", steps="
<< G->PS->GetNumSteps()
<< std::endl;
last_report_time = new_frame_time;
//G->PS->Blocks.print_status();
}
const Scal game_rate_target = 10.;
//const Scal game_rate_target = 1.;
next_game_time_target = new_frame_game_time + game_rate_target / fps;
last_frame_time = new_frame_time;
last_frame_game_time = new_frame_game_time;
//cout<<"Frame "<<frame_number++<<endl;
/* clear the screen to white */
glClear(GL_COLOR_BUFFER_BIT);
{
std::lock_guard<std::mutex> lg(G->PS->m_buffer_);
G->R->DrawAll();
G->PS->SetRendererReadyForNext(true);
}
glFlush();
//glutSwapBuffers();
flag_display=false;
}
void cycle()
{
//omp_set_dynamic(0);
//omp_set_nested(0);
//omp_set_num_threads(std::thread::hardware_concurrency());
#ifdef _OPENMP
omp_set_num_threads(2);
#endif
#pragma omp parallel
{
#pragma omp master
std::cout
<< "Computation started, "
#ifdef _OPENMP
<< "OpenMP with " << omp_get_num_threads() << " threads"
#else
<< "single-threaded"
#endif
<< std::endl;
}
while (!quit) {
G->PS->step(next_game_time_target, quit);
}
std::cout << "Computation finished" << std::endl;
}
// TODO: detect motionless regions
vect GetDomainMousePosition(int x, int y) {
vect c;
vect A(-1.,-1.), B(-1 + 2. * width / 800, -1. + 2. * height / 800);
c.x = A.x + (B.x - A.x) * (x / width);
c.y = B.y + (A.y - B.y) * (y / height);
return c;
}
vect GetDomainMousePosition() {
int x, y;
SDL_GetMouseState(&x, &y);
return GetDomainMousePosition(x, y);
}
int main() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_Log("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
init();
SDL_Window* window = SDL_CreateWindow(
"ptoy",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
);
if (window == NULL) {
SDL_Log("Unable to create window: %s\n", SDL_GetError());
return 1;
}
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
auto gray = 0.5;
glClearColor(gray, gray, gray, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
G = std::unique_ptr<game>(new game(width, height));
std::thread computation_thread(cycle);
G->PS->SetForce(vect(0., 0.), false);
//Main loop flag
quit = false;
//Event handler
SDL_Event e;
enum class MouseState {None, Force, Bonds};
MouseState mouse_state = MouseState::Force;
//While application is running
while (!quit) {
while (SDL_PollEvent( &e ) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN) {
switch( e.key.keysym.sym ) {
case 'q':
quit = true;
break;
case 'n':
mouse_state = MouseState::None;
std::cout << "Mouse switched to None mode" << std::endl;
break;
case 'f':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to Force mode" << std::endl;
G->PS->SetForceAttractive(false);
break;
case 'a':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to ForceAttractive mode" << std::endl;
G->PS->SetForceAttractive(true);
break;
case 'b':
mouse_state = MouseState::Bonds;
std::cout << "Mouse switched to Bonds mode" << std::endl;
break;
case 'g':
G->PS->InvertGravity();
std::cout
<< (G->PS->GetGravity() ? "Gravity on" : "Gravity off")
<< std::endl;
break;
}
} else if (e.type == SDL_MOUSEMOTION) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition());
break;
case MouseState::Bonds:
G->PS->BondsMove(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONDOWN) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition(), true);
break;
case MouseState::Bonds:
G->PS->BondsStart(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONUP) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(false);
break;
case MouseState::Bonds:
G->PS->BondsStop(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_WINDOWEVENT) {
switch (e.window.event) {
case SDL_WINDOWEVENT_RESIZED:
width = e.window.data1;
height = e.window.data2;
glViewport(0, 0, width, height);
G->SetWindowSize(width, height);
break;
}
}
}
display();
SDL_GL_SwapWindow(window);
SDL_Delay(30);
}
// Finalize
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
computation_thread.join();
return 0;
}
<commit_msg>Add pause key<commit_after>#include <iostream>
#include "game.hpp"
#include <SDL2/SDL.h>
#include <thread>
#include <chrono>
#include <atomic>
#ifdef _OPENMP
#include <omp.h>
#endif
// TODO: reorder header includes (std first)
// TODO: fix formatting
using namespace std::chrono;
milliseconds last_frame_time;
Scal last_frame_game_time;
milliseconds last_report_time;
std::atomic<Scal> next_game_time_target;
std::unique_ptr<game> G;
GLdouble width, height; /* window width and height */
std::atomic<bool> flag_display;
std::atomic<bool> quit;
std::atomic<bool> pause;
using std::cout;
using std::endl;
int frame_number;
void init()
{
width = 800.0; /* initial window width and height, */
height = 800.0; /* within which we draw. */
last_frame_game_time = 0.;
pause = false;
}
/* Callback functions for GLUT */
/* Draw the window - this is where all the GL actions are */
void display(void)
{
if(flag_display) return;
flag_display=true;
const Scal fps=30.0;
milliseconds current_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
milliseconds time_past_from_last_frame = current_time-last_frame_time;
//if(time_past_from_last_frame<milliseconds(100)) return;
milliseconds frame_duration(int(1000.0/fps));
milliseconds time_residual=frame_duration-time_past_from_last_frame;
//cout<<"sleep for "<<time_residual.count()<<endl;
//std::this_thread::sleep_for(time_residual);
//std::this_thread::sleep_for(frame_duration);
auto new_frame_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
auto new_frame_game_time = G->PS->GetTime();
const Scal frame_real_duration_s =
(new_frame_time - last_frame_time).count() / 1000.;
if ((new_frame_time - last_report_time).count() > 1000.) {
std::cout
<< "fps: " << 1. / frame_real_duration_s
<< ", game rate="
<< (new_frame_game_time -
last_frame_game_time) / frame_real_duration_s
<< ", particles="
<< G->PS->GetNumParticles()
<< ", max_per_cell="
<< G->PS->GetNumPerCell()
<< ", t="
<< G->PS->GetTime()
<< ", steps="
<< G->PS->GetNumSteps()
<< std::endl;
last_report_time = new_frame_time;
//G->PS->Blocks.print_status();
}
const Scal game_rate_target = 10.;
//const Scal game_rate_target = 1.;
if (!pause) {
next_game_time_target = new_frame_game_time + game_rate_target / fps;
}
last_frame_time = new_frame_time;
last_frame_game_time = new_frame_game_time;
//cout<<"Frame "<<frame_number++<<endl;
/* clear the screen to white */
glClear(GL_COLOR_BUFFER_BIT);
{
std::lock_guard<std::mutex> lg(G->PS->m_buffer_);
G->R->DrawAll();
G->PS->SetRendererReadyForNext(true);
}
glFlush();
//glutSwapBuffers();
flag_display=false;
}
void cycle()
{
//omp_set_dynamic(0);
//omp_set_nested(0);
//omp_set_num_threads(std::thread::hardware_concurrency());
#ifdef _OPENMP
omp_set_num_threads(2);
#endif
#pragma omp parallel
{
#pragma omp master
std::cout
<< "Computation started, "
#ifdef _OPENMP
<< "OpenMP with " << omp_get_num_threads() << " threads"
#else
<< "single-threaded"
#endif
<< std::endl;
}
while (!quit) {
G->PS->step(next_game_time_target, pause);
if (pause) {
std::this_thread::sleep_for(milliseconds(100));
}
}
std::cout << "Computation finished" << std::endl;
}
// TODO: detect motionless regions
vect GetDomainMousePosition(int x, int y) {
vect c;
vect A(-1.,-1.), B(-1 + 2. * width / 800, -1. + 2. * height / 800);
c.x = A.x + (B.x - A.x) * (x / width);
c.y = B.y + (A.y - B.y) * (y / height);
return c;
}
vect GetDomainMousePosition() {
int x, y;
SDL_GetMouseState(&x, &y);
return GetDomainMousePosition(x, y);
}
int main() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_Log("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
init();
SDL_Window* window = SDL_CreateWindow(
"ptoy",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
);
if (window == NULL) {
SDL_Log("Unable to create window: %s\n", SDL_GetError());
return 1;
}
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
auto gray = 0.5;
glClearColor(gray, gray, gray, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
G = std::unique_ptr<game>(new game(width, height));
std::thread computation_thread(cycle);
G->PS->SetForce(vect(0., 0.), false);
//Main loop flag
quit = false;
//Event handler
SDL_Event e;
enum class MouseState {None, Force, Bonds};
MouseState mouse_state = MouseState::Force;
//While application is running
while (!quit) {
while (SDL_PollEvent( &e ) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN) {
switch( e.key.keysym.sym ) {
case 'q':
quit = true;
break;
case 'n':
mouse_state = MouseState::None;
std::cout << "Mouse switched to None mode" << std::endl;
break;
case 'f':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to Force mode" << std::endl;
G->PS->SetForceAttractive(false);
break;
case 'a':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to ForceAttractive mode" << std::endl;
G->PS->SetForceAttractive(true);
break;
case 'b':
mouse_state = MouseState::Bonds;
std::cout << "Mouse switched to Bonds mode" << std::endl;
break;
case 'g':
G->PS->InvertGravity();
std::cout
<< (G->PS->GetGravity() ? "Gravity on" : "Gravity off")
<< std::endl;
break;
case 'p':
case ' ':
pause = !pause;
break;
}
} else if (e.type == SDL_MOUSEMOTION) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition());
break;
case MouseState::Bonds:
G->PS->BondsMove(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONDOWN) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition(), true);
break;
case MouseState::Bonds:
G->PS->BondsStart(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONUP) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(false);
break;
case MouseState::Bonds:
G->PS->BondsStop(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_WINDOWEVENT) {
switch (e.window.event) {
case SDL_WINDOWEVENT_RESIZED:
width = e.window.data1;
height = e.window.data2;
glViewport(0, 0, width, height);
G->SetWindowSize(width, height);
break;
}
}
}
display();
SDL_GL_SwapWindow(window);
SDL_Delay(30);
}
// Finalize
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
computation_thread.join();
return 0;
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <stdexcept>
#include <opencv2/core/core.hpp>
#include "utils.h"
namespace icpl {
std::vector<std::vector<float>> build_histograms(const cv::Mat &src) {
int channels = src.channels();
int rows = src.rows;
int cols = src.cols;
if (src.step[1] / channels != sizeof(uchar)) {
throw std::logic_error("build_histogram: src image should have "
"uchar type!");
}
std::vector<std::vector<float>> histogram(channels);
for (int i = 0; i < channels; i++) {
histogram[i].resize(256);
}
if (src.isContinuous()) {
cols = rows * cols;
rows = 1;
}
//#pragma omp parallel for if(rows > 1)
for (int i = 0; i < rows; i++) {
const uchar* cur_line = src.ptr(i);
//#pragma omp parallel for if(rows == 1)
for (int j = 0; j < cols; j++) {
for (int ch = 0; ch < channels; ch++) {
const uchar cur_color = cur_line[(j - 1) * channels + ch];
histogram[ch][cur_color]++;
}
}
}
//#pragma omp parallel for
for (int i = 0; i < channels; i++) {
for (int j = 0; j < 256; j++) {
histogram[i][j] = histogram[i][j] / (rows * cols);
}
}
return histogram;
}
void draw_histogram(const std::vector<float> &histogram,
const cv::Scalar &color, cv::Mat &histogram_image) {
if (histogram_image.empty()) {
throw std::logic_error("draw_histogram: image is empty!");
}
const int histSize = histogram.size();
const int hist_w = histogram_image.cols;
const int hist_h = histogram_image.rows;
const int bin_w = cvRound((double) hist_w / histSize);
for(int i = 1; i < histSize; i++) {
cv::line(histogram_image, cv::Point(bin_w*(i-1),
hist_h - cvRound(hist_h * histogram[i-1])) ,
cv::Point(bin_w*(i), hist_h - cvRound(hist_h * histogram[i])),
color, 2, 8, 0);
}
}
} // namespace icpl
<commit_msg>Include all needed<commit_after>#include <vector>
#include <stdexcept>
#include <opencv2/opencv.hpp>
#include "utils.h"
namespace icpl {
std::vector<std::vector<float>> build_histograms(const cv::Mat &src) {
int channels = src.channels();
int rows = src.rows;
int cols = src.cols;
if (src.step[1] / channels != sizeof(uchar)) {
throw std::logic_error("build_histogram: src image should have "
"uchar type!");
}
std::vector<std::vector<float>> histogram(channels);
for (int i = 0; i < channels; i++) {
histogram[i].resize(256);
}
if (src.isContinuous()) {
cols = rows * cols;
rows = 1;
}
//#pragma omp parallel for if(rows > 1)
for (int i = 0; i < rows; i++) {
const uchar* cur_line = src.ptr(i);
//#pragma omp parallel for if(rows == 1)
for (int j = 0; j < cols; j++) {
for (int ch = 0; ch < channels; ch++) {
const uchar cur_color = cur_line[(j - 1) * channels + ch];
histogram[ch][cur_color]++;
}
}
}
//#pragma omp parallel for
for (int i = 0; i < channels; i++) {
for (int j = 0; j < 256; j++) {
histogram[i][j] = histogram[i][j] / (rows * cols);
}
}
return histogram;
}
void draw_histogram(const std::vector<float> &histogram,
const cv::Scalar &color, cv::Mat &histogram_image) {
if (histogram_image.empty()) {
throw std::logic_error("draw_histogram: image is empty!");
}
const int histSize = histogram.size();
const int hist_w = histogram_image.cols;
const int hist_h = histogram_image.rows;
const int bin_w = cvRound((double) hist_w / histSize);
for(int i = 1; i < histSize; i++) {
cv::line(histogram_image, cv::Point(bin_w*(i-1),
hist_h - cvRound(hist_h * histogram[i-1])) ,
cv::Point(bin_w*(i), hist_h - cvRound(hist_h * histogram[i])),
color, 2, 8, 0);
}
}
} // namespace icpl
<|endoftext|>
|
<commit_before>// スプライン補間
#ifndef SPLINE_H
#define SPLINE_H
#include <vector>
#include <map>
#include <algorithm>
/******** クラス一覧 ********/
template<class T> class spline;
typedef spline<double> Spline;
/******** クラスI/F ********/
template<class T> class spline{
public:
spline (void);
spline (const std::map<T,T>& x2y);
void set(const std::map<T,T>& x2y); // 制御点指定
std::map<T,T> get(void) const; // 制御点取得
T operator()(T x, int deg=3) const; // 補間値計算
private:
std::vector<T> xx,yy,aa,bb,cc,dd; // 制御点, スプライン係数
void init_abcd(void); // スプライン係数の計算
};
/******** インライン実装 ********/
template<class T> spline<T>::spline(void){}
template<class T> spline<T>::spline(const std::map<T,T>& x2y){ set(x2y); }
template<class T> void spline<T>::set(const std::map<T,T>& x2y){
xx=yy=aa=bb=cc=dd=std::vector<T>();
for(typename std::map<T,T>::const_iterator p=x2y.begin(); p!=x2y.end(); p++){
xx.push_back(p->first);
yy.push_back(p->second);
}
if(x2y.size()>=3) init_abcd();
}
template<class T> std::map<T,T> spline<T>::get(void) const{
std::map<T,T> x2y;
for(int i=0; i<xx.size(); i++) x2y[xx[i]]=yy[i];
return x2y;
}
// 補間値計算
template<class T> T spline<T>::operator()(T x, int deg) const{
int n=xx.size();
int k=std::upper_bound(xx.begin(),xx.end(),x)-xx.begin()-1; // x∈[xx[k],xx[k+1])
if(n<3) return (n==0 ? 0 : n==1 ? yy[0] : yy[0]+(yy[1]-yy[0])*(x-xx[0])/(xx[1]-xx[0])); // 不足
k=(k<0 ? 0 : n-2<k ? n-2 : k); // 範囲外
x-=xx[k];
if(deg<=0) return (xx[k]+x<xx[k+1]-x ? yy[k] : yy[k+1]); // 0次(最近傍)
if(deg<=1) return yy[k]+(yy[k+1]-yy[k])*x/(xx[k+1]-xx[k]); // 1次(線形)
return ((aa[k]*x+bb[k])*x+cc[k])*x+dd[k]; // スプライン
}
// スプライン係数の計算
// 制御点 (x0,y0)...(xn,yn) を補間する区分多項式 Sk(x)=ak(x-xk)^3+bk(x-xk)^2+ck(x-xk)+dk (k=0..n-1)の係数
template<class T> void spline<T>::init_abcd(void){
int n=xx.size()-1; // 区間数 = 点数-1
std::vector<T> vv(n+1),pp(n),qq(n),rr(n);
// 後述の(3)"を解いてb[1]..b[n-1]を得る
for(int j=1; j<n; j++){
pp[j] = 2 * (xx[j+1] - xx[j-1]); // 係数行列Aの対角成分
qq[j] = xx[j+1]-xx[j]; // Aの下側副対角成分
rr[j] = xx[j]-xx[j-1]; // Aの上川副対角成分
vv[j] = 3 * ((yy[j+1]-yy[j])/(xx[j+1]-xx[j]) - (yy[j]-yy[j-1])/(xx[j]-xx[j-1])); // 初期値=(3)"右辺
}
for(int j=1; j<n-1; j++){ T s=qq[j]/pp[j]; vv[j+1]-=s*vv[j]; qq[j]=0; pp[j+1]-=s*rr[j+1]; } // Aの下側をsweep
for(int j=n-1; j>1; j--){ T s=rr[j]/pp[j]; vv[j-1]-=s*vv[j]; rr[j]=0; } // Aの上側をsweep
for(int j=1; j<n ; j++){ vv[j]/=pp[j]; pp[j]=1; } // Aの対角を正規化
vv[0]=vv[n]=0; // (5)'
// (1)"(2)"(4)"でabdを得る
aa=bb=cc=dd=std::vector<T>(n);
for(int k=0; k<n; k++){
T b0=vv[k], b1=vv[k+1], h=xx[k+1]-xx[k], g=yy[k+1]-yy[k];
aa[k] = (b1-b0)/(3*h);
bb[k] = b0;
cc[k] = g/h-(b1+2*b0)*h/3;
dd[k] = yy[k];
}
}
// 係数ak,bk,ck,dkの算出要領は下記。
//
// 制御点を通る(以下x[k+1]-x[k]をh[k]と略記):
// (1) S[k](0) =y[k] for k=0..n-1
// (2) S[k](h[k])=y[k+1] for k=〃
// 制御点で滑らか:
// (3) S[k]'(h[k])=S[k+1]'(0) for k=0..n-2
// (4) S[k]"(h[k])=S[k+1]"(0) for k=〃
// 両端点で上下に凸でない:
// (5) S[0]"(0)=S[n-1]"(h[n-1])=0
//
// 展開すると (以下○[k]を○,○[k+1]を○'などと略記)
// (1)' d = y for k=0..n-1
// (2)' ah^3 + bh^2 + ch + d = y' for k=〃
// (3)' 3 ah^2 + 2bh + c = c' for k=0..n-2
// (4)' 6 ah + 2b = 2b' for k=〃
// (5)' b0=bn=0 (bn:=S[n-1]"(h[n-1])は便宜的に導入)
//
// bについて解くと (以下x'-xをh,y'-yをgなどと略記)
// (1)" d = y for k=0..n-1
// (4)" a = (b'-b)/3h for k=0..n-1 (bn=0としてk=n-1でもOK)
// (2)" c = g/h - (b'+2b)h/3 for k=0..n-1
// (3)" bh + 2b'(h'+h) + b"h' = 3{g'/h' - g/h} for k=0..n-2
//
// (3)"は3重対角行列を係数とする未知数b[1]..b[n-1] の連立一次方程式であり容易に解ける。
// 残りのa,c,dは(4)"(2)"(1)"で求まる。
#endif //SPLINE_H
<commit_msg>Refactored Spline class<commit_after>// スプライン補間
#ifndef SPLINE_H
#define SPLINE_H
#include <vector>
#include <map>
#include <algorithm>
/******** クラス一覧 ********/
template<class T> class spline;
typedef spline<double> Spline;
/******** クラスI/F ********/
template<class T> class spline{
public:
spline (void);
spline (const std::map<T,T>& x2y);
void set(const std::map<T,T>& x2y); // 制御点指定
void get( std::map<T,T>& x2y) const; // 制御点取得
T operator()(T x, int deg=3) const; // 補間値計算(次数deg=0,1,3)
private:
std::vector<T> xx,yy,aa,bb,cc,dd; // 制御点, スプライン係数
void init_abcd(void); // スプライン係数の計算
};
/******** インライン実装 ********/
template<class T> spline<T>::spline(void){}
template<class T> spline<T>::spline(const std::map<T,T>& x2y){ set(x2y); }
template<class T> void spline<T>::set(const std::map<T,T>& x2y){
xx=yy=aa=bb=cc=dd=std::vector<T>();
for(typename std::map<T,T>::const_iterator p=x2y.begin(); p!=x2y.end(); p++){
xx.push_back(p->first);
yy.push_back(p->second);
}
if(x2y.size()>=3) init_abcd();
}
template<class T> void spline<T>::get(std::map<T,T>& x2y) const{
x2y=std::map<T,T>();
for(int i=0; i<xx.size(); i++) x2y[xx[i]]=yy[i];
}
// 補間値計算(次数deg=0,1,3)
template<class T> T spline<T>::operator()(T x, int deg) const{
int n=xx.size();
if(n<=1) return (n==1 ? yy[0] : 0);
if(n==2) deg=std::min(deg,1);
int k=std::upper_bound(xx.begin(),xx.end(),x)-xx.begin()-1; // x∈[xx[k],xx[k+1])
k=std::max(std::min(k,n-2),0); // 範囲外は端で計算
x-=xx[k];
if(deg<1) return (x*2<xx[k+1]-xx[k] ? yy[k] : yy[k+1]); // 0次(最近傍)
if(deg<3) return yy[k]+(yy[k+1]-yy[k])*x/(xx[k+1]-xx[k]); // 1次(線形)
return ((aa[k]*x+bb[k])*x+cc[k])*x+dd[k]; // スプライン
}
// スプライン係数の計算
// 制御点 (x0,y0)...(xn,yn) を補間する区分多項式 Sk(x)=ak(x-xk)^3+bk(x-xk)^2+ck(x-xk)+dk (k=0..n-1)の係数
template<class T> void spline<T>::init_abcd(void){
int n=xx.size()-1; // 区間数 = 点数-1
std::vector<T> vv(n+1),pp(n),qq(n),rr(n);
// 後述の(3)"を解いてb[1]..b[n-1]を得る
for(int j=1; j<n; j++){
T h0=xx[j]-xx[j-1], h1=xx[j+1]-xx[j], g0=yy[j]-yy[j-1], g1=yy[j+1]-yy[j];
pp[j] = 2*(h1+h0); // 係数行列Aの対角成分 A(j,j)
qq[j] = h1; // 下側の副対角成分 A(j+1,j)
rr[j] = h0; // 上側の副対角成分 A(j-1,j)
vv[j] = 3*(g1/h1-g0/h0); // 初期値=(3)"の右辺
}
for(int j=1; j<n-1; j++){ T s=qq[j]/pp[j]; vv[j+1]-=s*vv[j]; qq[j]=0; pp[j+1]-=s*rr[j+1]; } // Aの下側をsweep
for(int j=n-1; j>1; j--){ T s=rr[j]/pp[j]; vv[j-1]-=s*vv[j]; rr[j]=0; } // Aの上側をsweep
for(int j=1; j<n ; j++){ vv[j]/=pp[j]; pp[j]=1; } // Aの対角を正規化
vv[0]=vv[n]=0; // (5)'
// (1)"(2)"(4)"でabdを得る
aa=bb=cc=dd=std::vector<T>(n);
for(int k=0; k<n; k++){
T b0=vv[k], b1=vv[k+1], h=xx[k+1]-xx[k], g=yy[k+1]-yy[k], y0=yy[k];
aa[k] = (b1-b0)/(3*h);
bb[k] = b0;
cc[k] = g/h-(b1+2*b0)*h/3;
dd[k] = y0;
}
}
// 係数ak,bk,ck,dkの算出要領は下記。
//
// 制御点を通る(以下x[k+1]-x[k]をh[k]と略記):
// (1) S[k](0) =y[k] for k=0..n-1
// (2) S[k](h[k])=y[k+1] for k=〃
// 制御点で滑らか:
// (3) S[k]'(h[k])=S[k+1]'(0) for k=0..n-2
// (4) S[k]"(h[k])=S[k+1]"(0) for k=〃
// 両端点で上下に凸でない("natural" splineの場合):
// (5) S[0]"(0)=S[n-1]"(h[n-1])=0
//
// 展開すると(以下○[k]を○,○[k+1]を○'などと略記):
// (1)' d = y for k=0..n-1
// (2)' ah^3 + bh^2 + ch + d = y' for k=〃
// (3)' 3 ah^2 + 2bh + c = c' for k=0..n-2
// (4)' 6 ah + 2b = 2b' for k=〃
// (5)' b0=bn=0 (bn:=S[n-1]"(h[n-1])は便宜的に追加導入)
//
// bについて解くと(以下x'-xをh,y'-yをgなどと略記):
// (1)" d = y for k=0..n-1
// (4)" a = (b'-b)/3h for k=0..n-1 (bn=0としてk=n-1でもOK)
// (2)" c = g/h - (b'+2b)h/3 for k=0..n-1
// (3)" bh + 2b'(h'+h) + b"h' = 3{g'/h' - g/h} for k=0..n-2
//
// (3)"は3重対角行列を係数とする未知数b[1]..b[n-1] の連立一次方程式であり容易に解ける。
// 残りのa,c,dは(4)"(2)"(1)"で求まる。
//
// ちなみに"clamped" spline(b0,bnでなくc0,cnがgiven)の場合は、
// (2)'(3)'をa,bについて解くと(4)'がc[1]..c[n-1]の3重対角方程式になり解ける。
// "natural"より"clamped"のほうが明示的に形状の知識を使った計算になる。
#endif //SPLINE_H
<|endoftext|>
|
<commit_before>/** @file palettetoolbox.cpp
* @brief Класс палитры элементов
* */
#include <QtGui>
#include "palettetoolbox.h"
#include "realrepoinfo.h"
PaletteToolbox::DraggableElement::DraggableElement(int classid, QWidget *parent/*0*/)
: QWidget(parent)
{
RealRepoInfo info;
m_id = classid;
m_text = info.objectDesc(classid);
m_icon = info.objectIcon(classid);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins ( 4,4,4,4 );
QLabel *icon = new QLabel(this);
icon->setFixedSize(16,16);
icon->setPixmap(m_icon.pixmap(16,16));
layout->addWidget(icon);
QLabel *text = new QLabel(this);
text->setText(m_text);
layout->addWidget(text);
setLayout(layout);
}
PaletteToolbox::PaletteToolbox(QWidget *parent)
: QTabWidget(parent)
{
RealRepoInfo info;
setTabPosition(QTabWidget::West);
setTabShape(QTabWidget::Triangular);
// setAcceptDrops(true);
QStringList categories = info.getObjectCategories();
mTabs.resize(categories.size());
mTabNames.resize(categories.size());
mShownTabs.resize(categories.size());
QSettings settings("Tercom", "QReal");
for (int i = 0; i < categories.size(); i++) {
QScrollArea *scroller = new QScrollArea(this);
QWidget *tab = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(tab);
layout->setSpacing(0);
layout->setContentsMargins ( 0,0,0,0 );
foreach(int classid, info.getObjects(i)) {
DraggableElement *element = new DraggableElement(classid, this);
layout->addWidget(element);
}
tab->setLayout(layout);
scroller->setWidget(tab);
Q_ASSERT(!categories[i].isEmpty());
mTabs[i] = scroller;
mTabNames[i] = categories[i];
mShownTabs[i] = settings.contains(categories[i]);
addTab(scroller, categories[i]);
}
checkFirstLaunch();
setEditors(mShownTabs);
}
PaletteToolbox::~PaletteToolbox()
{
QSettings settings("Tercom", "QReal");
for (int i = 0; i < mTabNames.count(); ++i)
if (mShownTabs[i])
settings.setValue(mTabNames[i], "Show");
else
settings.remove(mTabNames[i]);
}
void PaletteToolbox::checkFirstLaunch()
{
foreach (bool const val, mShownTabs)
if (val)
return;
for (int i = 0; i < mShownTabs.count(); ++i)
mShownTabs[i] = true;
}
void PaletteToolbox::setEditors(QVector<bool> const &editors)
{
Q_ASSERT(editors.count() == mTabs.count());
setUpdatesEnabled(false);
for (int i = 0; i < editors.size(); ++i)
{
if (editors[i] && indexOf(mTabs[i]) == -1)
addTab(mTabs[i], mTabNames[i]);
if (!editors[i] && indexOf(mTabs[i]) != -1)
removeTab(indexOf(mTabs[i]));
mShownTabs[i] = editors[i];
}
setUpdatesEnabled(true);
}
QVector<bool> PaletteToolbox::getSelectedTabs() const
{
return mShownTabs;
}
void PaletteToolbox::dragEnterEvent(QDragEnterEvent * /*event*/)
{
}
void PaletteToolbox::dropEvent(QDropEvent * /*event*/)
{
}
void PaletteToolbox::mousePressEvent(QMouseEvent *event)
{
QWidget *atMouse = childAt(event->pos());
if ( ! atMouse || atMouse == this )
return;
DraggableElement *child = dynamic_cast<DraggableElement *>(atMouse->parent());
if (!child)
child = dynamic_cast<DraggableElement *>(atMouse);
if (!child)
return;
QByteArray itemData;
QDataStream stream(&itemData, QIODevice::WriteOnly);
stream << -1; // uuid
stream << child->id(); // type
stream << QString("(anon element)");
stream << QPointF(0,0);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-real-uml-data", itemData);
// mimeData->setText(child->text());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
QPixmap p = child->icon().pixmap(96,96);
if ( ! p.isNull() )
drag->setPixmap(child->icon().pixmap(96,96));
if (drag->start(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction)
child->close();
else
child->show();
}
<commit_msg>Новые редакторы видимы по умолчанию. Часть фикса к #86.<commit_after>/** @file palettetoolbox.cpp
* @brief Класс палитры элементов
* */
#include <QtGui>
#include "palettetoolbox.h"
#include "realrepoinfo.h"
PaletteToolbox::DraggableElement::DraggableElement(int classid, QWidget *parent/*0*/)
: QWidget(parent)
{
RealRepoInfo info;
m_id = classid;
m_text = info.objectDesc(classid);
m_icon = info.objectIcon(classid);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins ( 4,4,4,4 );
QLabel *icon = new QLabel(this);
icon->setFixedSize(16,16);
icon->setPixmap(m_icon.pixmap(16,16));
layout->addWidget(icon);
QLabel *text = new QLabel(this);
text->setText(m_text);
layout->addWidget(text);
setLayout(layout);
}
PaletteToolbox::PaletteToolbox(QWidget *parent)
: QTabWidget(parent)
{
RealRepoInfo info;
setTabPosition(QTabWidget::West);
setTabShape(QTabWidget::Triangular);
// setAcceptDrops(true);
QStringList categories = info.getObjectCategories();
mTabs.resize(categories.size());
mTabNames.resize(categories.size());
mShownTabs.resize(categories.size());
QSettings settings("Tercom", "QReal");
for (int i = 0; i < categories.size(); i++) {
QScrollArea *scroller = new QScrollArea(this);
QWidget *tab = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(tab);
layout->setSpacing(0);
layout->setContentsMargins ( 0,0,0,0 );
foreach(int classid, info.getObjects(i)) {
DraggableElement *element = new DraggableElement(classid, this);
layout->addWidget(element);
}
tab->setLayout(layout);
scroller->setWidget(tab);
Q_ASSERT(!categories[i].isEmpty());
mTabs[i] = scroller;
mTabNames[i] = categories[i];
mShownTabs[i] = !settings.contains(categories[i])
|| settings.value(categories[i]).toString() == "Show";
addTab(scroller, categories[i]);
}
setEditors(mShownTabs);
}
PaletteToolbox::~PaletteToolbox()
{
QSettings settings("Tercom", "QReal");
for (int i = 0; i < mTabNames.count(); ++i)
if (mShownTabs[i])
settings.setValue(mTabNames[i], "Show");
else
settings.setValue(mTabNames[i], "Hide");
}
void PaletteToolbox::setEditors(QVector<bool> const &editors)
{
Q_ASSERT(editors.count() == mTabs.count());
setUpdatesEnabled(false);
for (int i = 0; i < editors.size(); ++i)
{
if (editors[i] && indexOf(mTabs[i]) == -1)
addTab(mTabs[i], mTabNames[i]);
if (!editors[i] && indexOf(mTabs[i]) != -1)
removeTab(indexOf(mTabs[i]));
mShownTabs[i] = editors[i];
}
setUpdatesEnabled(true);
}
QVector<bool> PaletteToolbox::getSelectedTabs() const
{
return mShownTabs;
}
void PaletteToolbox::dragEnterEvent(QDragEnterEvent * /*event*/)
{
}
void PaletteToolbox::dropEvent(QDropEvent * /*event*/)
{
}
void PaletteToolbox::mousePressEvent(QMouseEvent *event)
{
QWidget *atMouse = childAt(event->pos());
if ( ! atMouse || atMouse == this )
return;
DraggableElement *child = dynamic_cast<DraggableElement *>(atMouse->parent());
if (!child)
child = dynamic_cast<DraggableElement *>(atMouse);
if (!child)
return;
QByteArray itemData;
QDataStream stream(&itemData, QIODevice::WriteOnly);
stream << -1; // uuid
stream << child->id(); // type
stream << QString("(anon element)");
stream << QPointF(0,0);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-real-uml-data", itemData);
// mimeData->setText(child->text());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
QPixmap p = child->icon().pixmap(96,96);
if ( ! p.isNull() )
drag->setPixmap(child->icon().pixmap(96,96));
if (drag->start(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction)
child->close();
else
child->show();
}
<|endoftext|>
|
<commit_before>/*! \file
*
* \brief Various string helper functions (header)
* \author Benjamin Pritchard (ben@bennyp.org)
*/
#ifndef BPMODULE_GUARD_UTIL__STRINGUTIL_HPP_
#define BPMODULE_GUARD_UTIL__STRINGUTIL_HPP_
#include <string>
namespace bpmodule {
namespace util {
/*! \brief Joins each element of a container of strings
*
* \tparam A container type (vector, set) of strings
* \param [in] container A container of strings to join
* \param [in] j What to put in between each string
* \return A string with each element of \p container joined with \p j in between
*/
template<typename T>
std::string Join(const T & container, const std::string & j)
{
if(container.size() == 0)
return std::string();
std::string str = container.begin();
for(const auto it = container.begin() + 1,
it != container.end(),
++it)
{
str.append(j);
str.append(*it);
}
return str;
}
/*! \brief Transform a string to lower case
*
* \param [inout] str String to convert to lowercase
*/
void ToLower(std::string & str);
/*! \brief Transform a string to lower case, copying to a new string
*
* \param [in] str String to convert to lowercase
* \return The string converted to lowercase
*/
std::string ToLowerCopy(std::string str);
/*! \brief Trim a string (beginning)
*
* \param [in] s String to trim
*/
void LeftTrim(std::string & s);
/*! \brief Trim a string (ending)
*
* \param [in] s String to trim
*/
void RightTrim(std::string & s);
/*! \brief Trim a string (beginning and ending)
*
* \param [in] s String to trim
*/
void Trim(std::string & s);
/*! \brief Trim a string (beginning)
*
* \param [in] s String to trim
* \return Copy of s with leading whitespace removed
*/
std::string LeftTrim_Copy(std::string s);
/*! \brief Trim a string _Copy(ending)
*
* \param [in] s String to trim
* \return Copy of s with trailing whitespace removed
*/
std::string RightTrim_Copy(std::string s);
/*! \brief Trim a string _Copy(beginning and ending)
*
* \param [in] s String to trim
* \return Copy of s with leading and trailing whitespace removed
*/
std::string Trim_Copy(std::string s);
/*! \brief Comparison of a case-insensitive string
*
* Useful for containers (maps) where the key is
* case insensitive
*/
struct CaseInsensitiveCompare
{
bool operator()(std::string lhs, std::string rhs) const;
};
/*! \brief Comparison of a case-insensitive string, trimming leading and trailing whitespace
*
* Useful for containers (maps) where the key is
* case insensitive
*/
struct CaseInsensitiveTrimCompare
{
bool operator()(std::string lhs, std::string rhs) const;
};
/*! \brief Create a line of characters
*
* Repeats a character a number of times. A newline is included.
*
* \param [in] c The character to use
* \param [in] n The number of times to repeat the character
*/
std::string Line(char c, int n = 80);
} // close namespace util
} // close namespace bpmodule
#endif
<commit_msg>Fix errors in last commit<commit_after>/*! \file
*
* \brief Various string helper functions (header)
* \author Benjamin Pritchard (ben@bennyp.org)
*/
#ifndef BPMODULE_GUARD_UTIL__STRINGUTIL_HPP_
#define BPMODULE_GUARD_UTIL__STRINGUTIL_HPP_
#include <string>
namespace bpmodule {
namespace util {
/*! \brief Joins each element of a container of strings
*
* \tparam A container type (vector, set) of strings
* \param [in] container A container of strings to join
* \param [in] j What to put in between each string
* \return A string with each element of \p container joined with \p j in between
*/
template<typename T>
std::string Join(const T & container, const std::string & j)
{
if(container.size() == 0)
return std::string();
auto it = container.begin();
std::string str = *it;
std::advance(it, 1);
for(; it != container.end(); ++it)
{
str.append(j);
str.append(*it);
}
return str;
}
/*! \brief Transform a string to lower case
*
* \param [inout] str String to convert to lowercase
*/
void ToLower(std::string & str);
/*! \brief Transform a string to lower case, copying to a new string
*
* \param [in] str String to convert to lowercase
* \return The string converted to lowercase
*/
std::string ToLowerCopy(std::string str);
/*! \brief Trim a string (beginning)
*
* \param [in] s String to trim
*/
void LeftTrim(std::string & s);
/*! \brief Trim a string (ending)
*
* \param [in] s String to trim
*/
void RightTrim(std::string & s);
/*! \brief Trim a string (beginning and ending)
*
* \param [in] s String to trim
*/
void Trim(std::string & s);
/*! \brief Trim a string (beginning)
*
* \param [in] s String to trim
* \return Copy of s with leading whitespace removed
*/
std::string LeftTrim_Copy(std::string s);
/*! \brief Trim a string _Copy(ending)
*
* \param [in] s String to trim
* \return Copy of s with trailing whitespace removed
*/
std::string RightTrim_Copy(std::string s);
/*! \brief Trim a string _Copy(beginning and ending)
*
* \param [in] s String to trim
* \return Copy of s with leading and trailing whitespace removed
*/
std::string Trim_Copy(std::string s);
/*! \brief Comparison of a case-insensitive string
*
* Useful for containers (maps) where the key is
* case insensitive
*/
struct CaseInsensitiveCompare
{
bool operator()(std::string lhs, std::string rhs) const;
};
/*! \brief Comparison of a case-insensitive string, trimming leading and trailing whitespace
*
* Useful for containers (maps) where the key is
* case insensitive
*/
struct CaseInsensitiveTrimCompare
{
bool operator()(std::string lhs, std::string rhs) const;
};
/*! \brief Create a line of characters
*
* Repeats a character a number of times. A newline is included.
*
* \param [in] c The character to use
* \param [in] n The number of times to repeat the character
*/
std::string Line(char c, int n = 80);
} // close namespace util
} // close namespace bpmodule
#endif
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: CEGUIFreeImageImageCodec.cpp
created: Sun Jun 18th 2006
author: Andrzej Krzysztof Haczewski (aka guyver6)
purpose: This codec provide FreeImage based image loading
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/Exceptions.h"
#include "CEGUI/ImageCodecModules/FreeImage/ImageCodec.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Size.h"
#include <FreeImage.h>
namespace
{
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message)
{
CEGUI::Logger::getSingleton().logEvent(
CEGUI::String("FreeImage error (") + FreeImage_GetFormatFromFIF(fif) + "): " + message, CEGUI::Errors);
}
}
// Start of CEGUI namespace section
namespace CEGUI
{
FreeImageImageCodec::FreeImageImageCodec()
: ImageCodec("FreeImageCodec - FreeImage based image codec")
{
FreeImage_Initialise(true);
FreeImage_SetOutputMessage(&FreeImageErrorHandler);
// Getting extensions
for (int i = 0; i < FreeImage_GetFIFCount(); ++i)
{
String exts(FreeImage_GetFIFExtensionList((FREE_IMAGE_FORMAT)i));
// Replace commas with spaces
for (size_t i = 0; i < exts.length(); ++i)
if (exts[i] == ',')
exts[i] = ' ';
// Add space after existing extensions
if (!d_supportedFormat.empty())
d_supportedFormat += ' ';
d_supportedFormat += exts;
}
}
FreeImageImageCodec::~FreeImageImageCodec()
{
FreeImage_DeInitialise();
}
Texture* FreeImageImageCodec::load(const RawDataContainer& data, Texture* result)
{
int len = (int)data.getSize();
FIMEMORY *mem = 0;
FIBITMAP *img = 0;
Texture *retval = 0;
CEGUI_TRY
{
mem = FreeImage_OpenMemory((BYTE*)data.getDataPtr(), len);
if (mem == 0)
CEGUI_THROW(MemoryException("Unable to open memory stream, FreeImage_OpenMemory failed"));
FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, len);
if (fif == FIF_UNKNOWN) // it may be that it's TARGA or MNG
{
fif = FIF_TARGA;
img = FreeImage_LoadFromMemory(fif, mem, 0);
if (img == 0)
{
fif = FIF_MNG;
img = FreeImage_LoadFromMemory(fif, mem, 0);
}
}
else
img = FreeImage_LoadFromMemory(fif, mem, 0);
if (img == 0)
CEGUI_THROW(GenericException("Unable to load image, FreeImage_LoadFromMemory failed"));
FIBITMAP *newImg = FreeImage_ConvertTo32Bits(img);
if (newImg == 0)
CEGUI_THROW(GenericException("Unable to convert image, FreeImage_ConvertTo32Bits failed"));
FreeImage_Unload(img);
img = newImg;
newImg = 0;
// FreeImage pixel format for little-endian architecture (which CEGUI
// supports) is like BGRA. We need to convert that to RGBA.
//
// It is now:
// RED_MASK 0x00FF0000
// GREEN_MASK 0x0000FF00
// BLUE_MASK 0x000000FF
// ALPHA_MASK 0xFF000000
//
// It should be:
// RED_MASK 0x000000FF
// GREEN_MASK 0x0000FF00
// BLUE_MASK 0x00FF0000
// ALPHA_MASK 0xFF000000
uint pitch = FreeImage_GetPitch(img);
uint height = FreeImage_GetHeight(img);
uint width = FreeImage_GetWidth(img);
uint8 *rawBuf = new uint8[width * height << 2];
// convert the bitmap to raw bits (top-left pixel first)
FreeImage_ConvertToRawBits(rawBuf, img, pitch, 32,
FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, true);
// We need to convert pixel format a little
// NB: little endian only - I think(!)
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
for (uint i = 0; i < height; ++i)
{
for (uint j = 0; j < width; ++j)
{
uint p = *(((uint*)(rawBuf + i * pitch)) + j);
uint r = (p >> 16) & 0x000000FF;
uint b = (p << 16) & 0x00FF0000;
p &= 0xFF00FF00;
p |= r | b;
// write the adjusted pixel back
*(((uint*)(rawBuf + i * pitch)) + j) = p;
}
}
#endif
FreeImage_Unload(img);
img = 0;
result->loadFromMemory(rawBuf, Sizef(width, height), Texture::PF_RGBA);
delete [] rawBuf;
retval = result;
}
CEGUI_CATCH(Exception&)
{
}
if (img != 0) FreeImage_Unload(img);
if (mem != 0) FreeImage_CloseMemory(mem);
return retval;
}
} // End of CEGUI namespace section
<commit_msg>Explicitly const_cast and then static_cast in FreeImage image codec, avoids a warning and makes our intentions clear<commit_after>/***********************************************************************
filename: CEGUIFreeImageImageCodec.cpp
created: Sun Jun 18th 2006
author: Andrzej Krzysztof Haczewski (aka guyver6)
purpose: This codec provide FreeImage based image loading
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/Exceptions.h"
#include "CEGUI/ImageCodecModules/FreeImage/ImageCodec.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Size.h"
#include <FreeImage.h>
namespace
{
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message)
{
CEGUI::Logger::getSingleton().logEvent(
CEGUI::String("FreeImage error (") + FreeImage_GetFormatFromFIF(fif) + "): " + message, CEGUI::Errors);
}
}
// Start of CEGUI namespace section
namespace CEGUI
{
FreeImageImageCodec::FreeImageImageCodec()
: ImageCodec("FreeImageCodec - FreeImage based image codec")
{
FreeImage_Initialise(true);
FreeImage_SetOutputMessage(&FreeImageErrorHandler);
// Getting extensions
for (int i = 0; i < FreeImage_GetFIFCount(); ++i)
{
String exts(FreeImage_GetFIFExtensionList((FREE_IMAGE_FORMAT)i));
// Replace commas with spaces
for (size_t i = 0; i < exts.length(); ++i)
if (exts[i] == ',')
exts[i] = ' ';
// Add space after existing extensions
if (!d_supportedFormat.empty())
d_supportedFormat += ' ';
d_supportedFormat += exts;
}
}
FreeImageImageCodec::~FreeImageImageCodec()
{
FreeImage_DeInitialise();
}
Texture* FreeImageImageCodec::load(const RawDataContainer& data, Texture* result)
{
int len = (int)data.getSize();
FIMEMORY *mem = 0;
FIBITMAP *img = 0;
Texture *retval = 0;
CEGUI_TRY
{
mem = FreeImage_OpenMemory(static_cast<BYTE*>(const_cast<uint8*>(data.getDataPtr())), len);
if (mem == 0)
CEGUI_THROW(MemoryException("Unable to open memory stream, FreeImage_OpenMemory failed"));
FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, len);
if (fif == FIF_UNKNOWN) // it may be that it's TARGA or MNG
{
fif = FIF_TARGA;
img = FreeImage_LoadFromMemory(fif, mem, 0);
if (img == 0)
{
fif = FIF_MNG;
img = FreeImage_LoadFromMemory(fif, mem, 0);
}
}
else
img = FreeImage_LoadFromMemory(fif, mem, 0);
if (img == 0)
CEGUI_THROW(GenericException("Unable to load image, FreeImage_LoadFromMemory failed"));
FIBITMAP *newImg = FreeImage_ConvertTo32Bits(img);
if (newImg == 0)
CEGUI_THROW(GenericException("Unable to convert image, FreeImage_ConvertTo32Bits failed"));
FreeImage_Unload(img);
img = newImg;
newImg = 0;
// FreeImage pixel format for little-endian architecture (which CEGUI
// supports) is like BGRA. We need to convert that to RGBA.
//
// It is now:
// RED_MASK 0x00FF0000
// GREEN_MASK 0x0000FF00
// BLUE_MASK 0x000000FF
// ALPHA_MASK 0xFF000000
//
// It should be:
// RED_MASK 0x000000FF
// GREEN_MASK 0x0000FF00
// BLUE_MASK 0x00FF0000
// ALPHA_MASK 0xFF000000
uint pitch = FreeImage_GetPitch(img);
uint height = FreeImage_GetHeight(img);
uint width = FreeImage_GetWidth(img);
uint8 *rawBuf = new uint8[width * height << 2];
// convert the bitmap to raw bits (top-left pixel first)
FreeImage_ConvertToRawBits(rawBuf, img, pitch, 32,
FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, true);
// We need to convert pixel format a little
// NB: little endian only - I think(!)
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
for (uint i = 0; i < height; ++i)
{
for (uint j = 0; j < width; ++j)
{
uint p = *(((uint*)(rawBuf + i * pitch)) + j);
uint r = (p >> 16) & 0x000000FF;
uint b = (p << 16) & 0x00FF0000;
p &= 0xFF00FF00;
p |= r | b;
// write the adjusted pixel back
*(((uint*)(rawBuf + i * pitch)) + j) = p;
}
}
#endif
FreeImage_Unload(img);
img = 0;
result->loadFromMemory(rawBuf, Sizef(width, height), Texture::PF_RGBA);
delete [] rawBuf;
retval = result;
}
CEGUI_CATCH(Exception&)
{
}
if (img != 0) FreeImage_Unload(img);
if (mem != 0) FreeImage_CloseMemory(mem);
return retval;
}
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>/**
* This code is auto-generated; unless you know what you're doing, do not modify!
**/
#include <v8.h>
#include <node.h>
#include <string>
#include "../include/wrapper.h"
#include "node_buffer.h"
using namespace v8;
using namespace node;
Wrapper::Wrapper(void *raw) {
this->raw = raw;
}
void Wrapper::Initialize(Handle<v8::Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewSymbol("Wrapper"));
NODE_SET_PROTOTYPE_METHOD(tpl, "toBuffer", ToBuffer);
constructor_template = Persistent<Function>::New(tpl->GetFunction());
target->Set(String::NewSymbol("Wrapper"), constructor_template);
}
Handle<Value> Wrapper::New(const Arguments& args) {
HandleScope scope;
if (args.Length() == 0 || !args[0]->IsExternal()) {
return ThrowException(Exception::Error(String::New("void * is required.")));
}
Wrapper* object = new Wrapper(External::Unwrap(args[0]));
object->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value> Wrapper::New(void *raw) {
HandleScope scope;
Handle<Value> argv[1] = { External::New((void *)raw) };
return scope.Close(Wrapper::constructor_template->NewInstance(1, argv));
}
void *Wrapper::GetValue() {
return this->raw;
}
Handle<Value> Wrapper::ToBuffer(const Arguments& args) {
HandleScope scope;
if(args.Length() == 0 || !args[0]->IsNumber()) {
return ThrowException(Exception::Error(String::New("Number is required.")));
}
int len = args[0]->ToNumber()->Value();
Buffer *slowBuffer = Buffer::New(
const_cast<char *>(std::string((const char *)const_cast<void *>(ObjectWrap::Unwrap<Wrapper>(args.This())->GetValue())).c_str()),
len);
Local<Function> bufferConstructor = Local<Function>::Cast(
Context::GetCurrent()->Global()->Get(String::New("Buffer")));
Handle<Value> constructorArgs[3] = { slowBuffer->handle_, Integer::New(len), Integer::New(0) };
Local<Object> fastBuffer = bufferConstructor->NewInstance(3, constructorArgs);
return scope.Close(fastBuffer);
}
Persistent<Function> Wrapper::constructor_template;
<commit_msg>Fix issue https://github.com/nodegit/nodegit/issues/83<commit_after>/**
* This code is auto-generated; unless you know what you're doing, do not modify!
**/
#include <v8.h>
#include <node.h>
#include <string>
#include "../include/wrapper.h"
#include "node_buffer.h"
using namespace v8;
using namespace node;
Wrapper::Wrapper(void *raw) {
this->raw = raw;
}
void Wrapper::Initialize(Handle<v8::Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewSymbol("Wrapper"));
NODE_SET_PROTOTYPE_METHOD(tpl, "toBuffer", ToBuffer);
constructor_template = Persistent<Function>::New(tpl->GetFunction());
target->Set(String::NewSymbol("Wrapper"), constructor_template);
}
Handle<Value> Wrapper::New(const Arguments& args) {
HandleScope scope;
if (args.Length() == 0 || !args[0]->IsExternal()) {
return ThrowException(Exception::Error(String::New("void * is required.")));
}
Wrapper* object = new Wrapper(External::Unwrap(args[0]));
object->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value> Wrapper::New(void *raw) {
HandleScope scope;
Handle<Value> argv[1] = { External::New((void *)raw) };
return scope.Close(Wrapper::constructor_template->NewInstance(1, argv));
}
void *Wrapper::GetValue() {
return this->raw;
}
Handle<Value> Wrapper::ToBuffer(const Arguments& args) {
HandleScope scope;
if(args.Length() == 0 || !args[0]->IsNumber()) {
return ThrowException(Exception::Error(String::New("Number is required.")));
}
int len = args[0]->ToNumber()->Value();
Local<Function> bufferConstructor = Local<Function>::Cast(
Context::GetCurrent()->Global()->Get(String::New("Buffer")));
Handle<Value> constructorArgs[1] = { Integer::New(len) };
Local<Object> nodeBuffer = bufferConstructor->NewInstance(1, constructorArgs);
memcpy(node::Buffer::Data(nodeBuffer), ObjectWrap::Unwrap<Wrapper>(args.This())->GetValue(), len);
return scope.Close(nodeBuffer);
}
Persistent<Function> Wrapper::constructor_template;
<|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 "chrome/browser/automation/automation_profile_impl.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/test/automation/automation_messages.h"
namespace {
// A special Request context for automation. Substitute a few things
// like cookie store, proxy settings etc to handle them differently
// for automation.
class AutomationURLRequestContext : public ChromeURLRequestContext {
public:
AutomationURLRequestContext(ChromeURLRequestContext* original_context,
net::CookieStore* automation_cookie_store)
: ChromeURLRequestContext(original_context),
// We must hold a reference to |original_context|, since many
// of the dependencies that ChromeURLRequestContext(original_context)
// copied are scoped to |original_context|.
original_context_(original_context) {
cookie_store_ = automation_cookie_store;
}
private:
virtual ~AutomationURLRequestContext() {
// Clear out members before calling base class dtor since we don't
// own any of them.
// Clear URLRequestContext members.
host_resolver_ = NULL;
proxy_service_ = NULL;
http_transaction_factory_ = NULL;
ftp_transaction_factory_ = NULL;
cookie_store_ = NULL;
strict_transport_security_state_ = NULL;
// Clear ChromeURLRequestContext members.
blacklist_ = NULL;
}
scoped_refptr<ChromeURLRequestContext> original_context_;
DISALLOW_COPY_AND_ASSIGN(AutomationURLRequestContext);
};
// CookieStore specialization to have automation specific
// behavior for cookies.
class AutomationCookieStore : public net::CookieStore {
public:
AutomationCookieStore(AutomationProfileImpl* profile,
net::CookieStore* original_cookie_store,
IPC::Message::Sender* automation_client)
: profile_(profile),
original_cookie_store_(original_cookie_store),
automation_client_(automation_client) {
}
// CookieStore implementation.
virtual bool SetCookie(const GURL& url, const std::string& cookie_line) {
bool cookie_set = original_cookie_store_->SetCookie(url, cookie_line);
if (cookie_set) {
// TODO(eroman): Should NOT be accessing the profile from here, as this
// is running on the IO thread.
automation_client_->Send(new AutomationMsg_SetCookieAsync(0,
profile_->tab_handle(), url, cookie_line));
}
return cookie_set;
}
virtual bool SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithOptions(url, cookie_line,
options);
}
virtual bool SetCookieWithCreationTime(const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time) {
return original_cookie_store_->SetCookieWithCreationTime(url, cookie_line,
creation_time);
}
virtual bool SetCookieWithCreationTimeWithOptions(
const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithCreationTimeWithOptions(url,
cookie_line, creation_time, options);
}
virtual void SetCookies(const GURL& url,
const std::vector<std::string>& cookies) {
original_cookie_store_->SetCookies(url, cookies);
}
virtual void SetCookiesWithOptions(const GURL& url,
const std::vector<std::string>& cookies,
const net::CookieOptions& options) {
original_cookie_store_->SetCookiesWithOptions(url, cookies, options);
}
virtual std::string GetCookies(const GURL& url) {
return original_cookie_store_->GetCookies(url);
}
virtual std::string GetCookiesWithOptions(const GURL& url,
const net::CookieOptions& options) {
return original_cookie_store_->GetCookiesWithOptions(url, options);
}
protected:
AutomationProfileImpl* profile_;
net::CookieStore* original_cookie_store_;
IPC::Message::Sender* automation_client_;
private:
DISALLOW_COPY_AND_ASSIGN(AutomationCookieStore);
};
class Factory : public ChromeURLRequestContextFactory {
public:
Factory(ChromeURLRequestContextGetter* original_context_getter,
AutomationProfileImpl* profile,
IPC::Message::Sender* automation_client)
: ChromeURLRequestContextFactory(profile),
original_context_getter_(original_context_getter),
profile_(profile),
automation_client_(automation_client) {
}
virtual ChromeURLRequestContext* Create() {
ChromeURLRequestContext* original_context =
original_context_getter_->GetIOContext();
// Create an automation cookie store.
scoped_refptr<net::CookieStore> automation_cookie_store =
new AutomationCookieStore(profile_,
original_context->cookie_store(),
automation_client_);
return new AutomationURLRequestContext(original_context,
automation_cookie_store);
}
private:
scoped_refptr<ChromeURLRequestContextGetter> original_context_getter_;
AutomationProfileImpl* profile_;
IPC::Message::Sender* automation_client_;
};
// TODO(eroman): This duplicates CleanupRequestContext() from profile.cc.
void CleanupRequestContext(ChromeURLRequestContextGetter* context) {
context->CleanupOnUIThread();
// Clean up request context on IO thread.
ChromeThread::ReleaseSoon(ChromeThread::IO, FROM_HERE, context);
}
} // namespace
AutomationProfileImpl::~AutomationProfileImpl() {
CleanupRequestContext(alternate_request_context_);
}
void AutomationProfileImpl::Initialize(Profile* original_profile,
IPC::Message::Sender* automation_client) {
DCHECK(original_profile);
original_profile_ = original_profile;
ChromeURLRequestContextGetter* original_context =
static_cast<ChromeURLRequestContextGetter*>(
original_profile_->GetRequestContext());
alternate_request_context_ = new ChromeURLRequestContextGetter(
NULL, // Don't register an observer on PrefService.
new Factory(original_context, this, automation_client));
alternate_request_context_->AddRef(); // Balananced in the destructor.
}
<commit_msg>Ensure AutomationMsg_SetCookieAsync is sent on IO thread. If SetCookie is invoked via automation and load_requests_via_automation is true, the IPC will be sent back from the UI thread. BUG=27568<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 "chrome/browser/automation/automation_profile_impl.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/test/automation/automation_messages.h"
namespace {
// A special Request context for automation. Substitute a few things
// like cookie store, proxy settings etc to handle them differently
// for automation.
class AutomationURLRequestContext : public ChromeURLRequestContext {
public:
AutomationURLRequestContext(ChromeURLRequestContext* original_context,
net::CookieStore* automation_cookie_store)
: ChromeURLRequestContext(original_context),
// We must hold a reference to |original_context|, since many
// of the dependencies that ChromeURLRequestContext(original_context)
// copied are scoped to |original_context|.
original_context_(original_context) {
cookie_store_ = automation_cookie_store;
}
private:
virtual ~AutomationURLRequestContext() {
// Clear out members before calling base class dtor since we don't
// own any of them.
// Clear URLRequestContext members.
host_resolver_ = NULL;
proxy_service_ = NULL;
http_transaction_factory_ = NULL;
ftp_transaction_factory_ = NULL;
cookie_store_ = NULL;
strict_transport_security_state_ = NULL;
// Clear ChromeURLRequestContext members.
blacklist_ = NULL;
}
scoped_refptr<ChromeURLRequestContext> original_context_;
DISALLOW_COPY_AND_ASSIGN(AutomationURLRequestContext);
};
// CookieStore specialization to have automation specific
// behavior for cookies.
class AutomationCookieStore : public net::CookieStore {
public:
AutomationCookieStore(AutomationProfileImpl* profile,
net::CookieStore* original_cookie_store,
IPC::Message::Sender* automation_client)
: profile_(profile),
original_cookie_store_(original_cookie_store),
automation_client_(automation_client) {
}
// CookieStore implementation.
virtual bool SetCookie(const GURL& url, const std::string& cookie_line) {
bool cookie_set = original_cookie_store_->SetCookie(url, cookie_line);
if (cookie_set) {
// TODO(eroman): Should NOT be accessing the profile from here, as this
// is running on the IO thread.
SendIPCMessageOnIOThread(new AutomationMsg_SetCookieAsync(0,
profile_->tab_handle(), url, cookie_line));
}
return cookie_set;
}
virtual bool SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithOptions(url, cookie_line,
options);
}
virtual bool SetCookieWithCreationTime(const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time) {
return original_cookie_store_->SetCookieWithCreationTime(url, cookie_line,
creation_time);
}
virtual bool SetCookieWithCreationTimeWithOptions(
const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithCreationTimeWithOptions(url,
cookie_line, creation_time, options);
}
virtual void SetCookies(const GURL& url,
const std::vector<std::string>& cookies) {
original_cookie_store_->SetCookies(url, cookies);
}
virtual void SetCookiesWithOptions(const GURL& url,
const std::vector<std::string>& cookies,
const net::CookieOptions& options) {
original_cookie_store_->SetCookiesWithOptions(url, cookies, options);
}
virtual std::string GetCookies(const GURL& url) {
return original_cookie_store_->GetCookies(url);
}
virtual std::string GetCookiesWithOptions(const GURL& url,
const net::CookieOptions& options) {
return original_cookie_store_->GetCookiesWithOptions(url, options);
}
protected:
void SendIPCMessageOnIOThread(IPC::Message* m) {
if (ChromeThread::CurrentlyOn(ChromeThread::IO)) {
automation_client_->Send(m);
} else {
Task* task = NewRunnableMethod(this,
&AutomationCookieStore::SendIPCMessageOnIOThread, m);
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE, task);
}
}
AutomationProfileImpl* profile_;
net::CookieStore* original_cookie_store_;
IPC::Message::Sender* automation_client_;
private:
DISALLOW_COPY_AND_ASSIGN(AutomationCookieStore);
};
class Factory : public ChromeURLRequestContextFactory {
public:
Factory(ChromeURLRequestContextGetter* original_context_getter,
AutomationProfileImpl* profile,
IPC::Message::Sender* automation_client)
: ChromeURLRequestContextFactory(profile),
original_context_getter_(original_context_getter),
profile_(profile),
automation_client_(automation_client) {
}
virtual ChromeURLRequestContext* Create() {
ChromeURLRequestContext* original_context =
original_context_getter_->GetIOContext();
// Create an automation cookie store.
scoped_refptr<net::CookieStore> automation_cookie_store =
new AutomationCookieStore(profile_,
original_context->cookie_store(),
automation_client_);
return new AutomationURLRequestContext(original_context,
automation_cookie_store);
}
private:
scoped_refptr<ChromeURLRequestContextGetter> original_context_getter_;
AutomationProfileImpl* profile_;
IPC::Message::Sender* automation_client_;
};
// TODO(eroman): This duplicates CleanupRequestContext() from profile.cc.
void CleanupRequestContext(ChromeURLRequestContextGetter* context) {
context->CleanupOnUIThread();
// Clean up request context on IO thread.
ChromeThread::ReleaseSoon(ChromeThread::IO, FROM_HERE, context);
}
} // namespace
AutomationProfileImpl::~AutomationProfileImpl() {
CleanupRequestContext(alternate_request_context_);
}
void AutomationProfileImpl::Initialize(Profile* original_profile,
IPC::Message::Sender* automation_client) {
DCHECK(original_profile);
original_profile_ = original_profile;
ChromeURLRequestContextGetter* original_context =
static_cast<ChromeURLRequestContextGetter*>(
original_profile_->GetRequestContext());
alternate_request_context_ = new ChromeURLRequestContextGetter(
NULL, // Don't register an observer on PrefService.
new Factory(original_context, this, automation_client));
alternate_request_context_->AddRef(); // Balananced in the destructor.
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/options/wimax_config_view.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/onc_constants.h"
#include "chrome/browser/chromeos/enrollment_dialog_view.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
namespace chromeos {
WimaxConfigView::WimaxConfigView(NetworkConfigView* parent, WimaxNetwork* wimax)
: ChildNetworkConfigView(parent, wimax),
identity_label_(NULL),
identity_textfield_(NULL),
save_credentials_checkbox_(NULL),
share_network_checkbox_(NULL),
shared_network_label_(NULL),
passphrase_label_(NULL),
passphrase_textfield_(NULL),
passphrase_visible_button_(NULL),
error_label_(NULL) {
Init(wimax);
}
WimaxConfigView::~WimaxConfigView() {
}
views::View* WimaxConfigView::GetInitiallyFocusedView() {
if (identity_textfield_ && identity_textfield_->enabled())
return identity_textfield_;
if (passphrase_textfield_ && passphrase_textfield_->enabled())
return passphrase_textfield_;
return NULL;
}
bool WimaxConfigView::CanLogin() {
// TODO(benchan): Update this with the correct minimum length (don't just
// check if empty).
// If the network requires a passphrase, make sure it is the right length.
return passphrase_textfield_ && !passphrase_textfield_->text().empty();
}
void WimaxConfigView::UpdateDialogButtons() {
parent_->GetDialogClientView()->UpdateDialogButtons();
}
void WimaxConfigView::UpdateErrorLabel() {
std::string error_msg;
if (!service_path_.empty()) {
NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary();
const WimaxNetwork* wimax = cros->FindWimaxNetworkByPath(service_path_);
if (wimax && wimax->failed()) {
bool passphrase_empty = wimax->eap_passphrase().empty();
switch (wimax->error()) {
case ERROR_BAD_PASSPHRASE:
if (!passphrase_empty) {
error_msg = l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_PASSPHRASE);
}
break;
case ERROR_BAD_WEPKEY:
if (!passphrase_empty) {
error_msg = l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_WEPKEY);
}
break;
default:
error_msg = wimax->GetErrorString();
break;
}
}
}
if (!error_msg.empty()) {
error_label_->SetText(UTF8ToUTF16(error_msg));
error_label_->SetVisible(true);
} else {
error_label_->SetVisible(false);
}
}
void WimaxConfigView::ContentsChanged(views::Textfield* sender,
const string16& new_contents) {
UpdateDialogButtons();
}
bool WimaxConfigView::HandleKeyEvent(views::Textfield* sender,
const views::KeyEvent& key_event) {
if (sender == passphrase_textfield_ &&
key_event.key_code() == ui::VKEY_RETURN) {
parent_->GetDialogClientView()->AcceptWindow();
}
return false;
}
void WimaxConfigView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == passphrase_visible_button_) {
if (passphrase_textfield_) {
passphrase_textfield_->SetObscured(!passphrase_textfield_->IsObscured());
passphrase_visible_button_->SetToggled(
!passphrase_textfield_->IsObscured());
}
} else {
NOTREACHED();
}
}
bool WimaxConfigView::Login() {
NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary();
WimaxNetwork* wimax = cros->FindWimaxNetworkByPath(service_path_);
if (!wimax) {
// Flimflam no longer knows about this wimax network (edge case).
// TODO(stevenjb): Add a notification (chromium-os13225).
LOG(WARNING) << "Wimax network: " << service_path_ << " no longer exists.";
return true;
}
wimax->SetEAPIdentity(GetEapIdentity());
wimax->SetEAPPassphrase(GetEapPassphrase());
wimax->SetSaveCredentials(GetSaveCredentials());
bool share_default = (wimax->profile_type() != PROFILE_USER);
bool share = GetShareNetwork(share_default);
wimax->SetEnrollmentDelegate(
CreateEnrollmentDelegate(GetWidget()->GetNativeWindow(),
wimax->name(),
ProfileManager::GetLastUsedProfile()));
cros->ConnectToWimaxNetwork(wimax, share);
// Connection failures are responsible for updating the UI, including
// reopening dialogs.
return true; // dialog will be closed
}
std::string WimaxConfigView::GetEapIdentity() const {
DCHECK(identity_textfield_);
return UTF16ToUTF8(identity_textfield_->text());
}
std::string WimaxConfigView::GetEapPassphrase() const {
return passphrase_textfield_ ? UTF16ToUTF8(passphrase_textfield_->text()) :
std::string();
}
bool WimaxConfigView::GetSaveCredentials() const {
return save_credentials_checkbox_ ? save_credentials_checkbox_->checked() :
false;
}
bool WimaxConfigView::GetShareNetwork(bool share_default) const {
return share_network_checkbox_ ? share_network_checkbox_->checked() :
share_default;
}
void WimaxConfigView::Cancel() {
}
void WimaxConfigView::Init(WimaxNetwork* wimax) {
DCHECK(wimax);
WifiConfigView::ParseWiFiEAPUIProperty(
&save_credentials_ui_data_, wimax, onc::eap::kSaveCredentials);
WifiConfigView::ParseWiFiEAPUIProperty(
&identity_ui_data_, wimax, onc::eap::kIdentity);
WifiConfigView::ParseWiFiUIProperty(
&passphrase_ui_data_, wimax, onc::wifi::kPassphrase);
views::GridLayout* layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(layout);
const int column_view_set_id = 0;
views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id);
const int kPasswordVisibleWidth = 20;
// Label
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, views::kRelatedControlSmallHorizontalSpacing);
// Textfield, combobox.
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0,
ChildNetworkConfigView::kInputFieldMinWidth);
column_set->AddPaddingColumn(0, views::kRelatedControlSmallHorizontalSpacing);
// Password visible button / policy indicator.
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, kPasswordVisibleWidth);
// Title
layout->StartRow(0, column_view_set_id);
views::Label* title = new views::Label(l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_JOIN_WIMAX_NETWORKS));
title->SetFont(title->font().DeriveFont(1, gfx::Font::BOLD));
layout->AddView(title, 5, 1);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
// Netowrk name
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_TAB_NETWORK)));
views::Label* label = new views::Label(UTF8ToUTF16(wimax->name()));
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
layout->AddView(label);
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Identity
layout->StartRow(0, column_view_set_id);
identity_label_ = new views::Label(l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_IDENTITY));
layout->AddView(identity_label_);
identity_textfield_ = new views::Textfield(
views::Textfield::STYLE_DEFAULT);
identity_textfield_->SetController(this);
const std::string& eap_identity = wimax->eap_identity();
identity_textfield_->SetText(UTF8ToUTF16(eap_identity));
identity_textfield_->SetEnabled(identity_ui_data_.editable());
layout->AddView(identity_textfield_);
layout->AddView(new ControlledSettingIndicatorView(identity_ui_data_));
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Passphrase input
layout->StartRow(0, column_view_set_id);
int label_text_id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE;
passphrase_label_ = new views::Label(
l10n_util::GetStringUTF16(label_text_id));
layout->AddView(passphrase_label_);
passphrase_textfield_ = new views::Textfield(
views::Textfield::STYLE_OBSCURED);
passphrase_textfield_->SetController(this);
passphrase_label_->SetEnabled(true);
passphrase_textfield_->SetEnabled(passphrase_ui_data_.editable());
passphrase_textfield_->SetAccessibleName(l10n_util::GetStringUTF16(
label_text_id));
layout->AddView(passphrase_textfield_);
if (passphrase_ui_data_.managed()) {
layout->AddView(new ControlledSettingIndicatorView(passphrase_ui_data_));
} else {
// Password visible button.
passphrase_visible_button_ = new views::ToggleImageButton(this);
passphrase_visible_button_->SetTooltipText(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE_SHOW));
passphrase_visible_button_->SetToggledTooltipText(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE_HIDE));
passphrase_visible_button_->SetImage(
views::ImageButton::BS_NORMAL,
ResourceBundle::GetSharedInstance().
GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_OFF));
passphrase_visible_button_->SetImage(
views::ImageButton::BS_HOT,
ResourceBundle::GetSharedInstance().
GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_HOVER));
passphrase_visible_button_->SetToggledImage(
views::ImageButton::BS_NORMAL,
ResourceBundle::GetSharedInstance().
GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_ON));
passphrase_visible_button_->SetImageAlignment(
views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE);
layout->AddView(passphrase_visible_button_);
}
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Checkboxes.
if (UserManager::Get()->IsUserLoggedIn()) {
// Save credentials
layout->StartRow(0, column_view_set_id);
save_credentials_checkbox_ = new views::Checkbox(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SAVE_CREDENTIALS));
save_credentials_checkbox_->SetEnabled(
save_credentials_ui_data_.editable());
save_credentials_checkbox_->SetChecked(wimax->save_credentials());
layout->SkipColumns(1);
layout->AddView(save_credentials_checkbox_);
layout->AddView(
new ControlledSettingIndicatorView(save_credentials_ui_data_));
// Share network
if (wimax->profile_type() == PROFILE_NONE && wimax->passphrase_required()) {
layout->StartRow(0, column_view_set_id);
share_network_checkbox_ = new views::Checkbox(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SHARE_NETWORK));
share_network_checkbox_->SetEnabled(true);
share_network_checkbox_->SetChecked(false); // Default to unshared.
layout->SkipColumns(1);
layout->AddView(share_network_checkbox_);
}
}
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Create an error label.
layout->StartRow(0, column_view_set_id);
layout->SkipColumns(1);
error_label_ = new views::Label();
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_->SetEnabledColor(SK_ColorRED);
layout->AddView(error_label_);
UpdateErrorLabel();
}
void WimaxConfigView::InitFocus() {
views::View* view_to_focus = GetInitiallyFocusedView();
if (view_to_focus)
view_to_focus->RequestFocus();
}
} // namespace chromeos
<commit_msg>Allow connection attempt to WiMax with no credentials in OOBE screen<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/options/wimax_config_view.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/onc_constants.h"
#include "chrome/browser/chromeos/enrollment_dialog_view.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
namespace chromeos {
WimaxConfigView::WimaxConfigView(NetworkConfigView* parent, WimaxNetwork* wimax)
: ChildNetworkConfigView(parent, wimax),
identity_label_(NULL),
identity_textfield_(NULL),
save_credentials_checkbox_(NULL),
share_network_checkbox_(NULL),
shared_network_label_(NULL),
passphrase_label_(NULL),
passphrase_textfield_(NULL),
passphrase_visible_button_(NULL),
error_label_(NULL) {
Init(wimax);
}
WimaxConfigView::~WimaxConfigView() {
}
views::View* WimaxConfigView::GetInitiallyFocusedView() {
if (identity_textfield_ && identity_textfield_->enabled())
return identity_textfield_;
if (passphrase_textfield_ && passphrase_textfield_->enabled())
return passphrase_textfield_;
return NULL;
}
bool WimaxConfigView::CanLogin() {
// In OOBE it may be valid to log in with no credentials (crbug.com/137776).
if (!chromeos::WizardController::IsOobeCompleted())
return true;
// TODO(benchan): Update this with the correct minimum length (don't just
// check if empty).
// If the network requires a passphrase, make sure it is the right length.
return passphrase_textfield_ && !passphrase_textfield_->text().empty();
}
void WimaxConfigView::UpdateDialogButtons() {
parent_->GetDialogClientView()->UpdateDialogButtons();
}
void WimaxConfigView::UpdateErrorLabel() {
std::string error_msg;
if (!service_path_.empty()) {
NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary();
const WimaxNetwork* wimax = cros->FindWimaxNetworkByPath(service_path_);
if (wimax && wimax->failed()) {
bool passphrase_empty = wimax->eap_passphrase().empty();
switch (wimax->error()) {
case ERROR_BAD_PASSPHRASE:
if (!passphrase_empty) {
error_msg = l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_PASSPHRASE);
}
break;
case ERROR_BAD_WEPKEY:
if (!passphrase_empty) {
error_msg = l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_WEPKEY);
}
break;
default:
error_msg = wimax->GetErrorString();
break;
}
}
}
if (!error_msg.empty()) {
error_label_->SetText(UTF8ToUTF16(error_msg));
error_label_->SetVisible(true);
} else {
error_label_->SetVisible(false);
}
}
void WimaxConfigView::ContentsChanged(views::Textfield* sender,
const string16& new_contents) {
UpdateDialogButtons();
}
bool WimaxConfigView::HandleKeyEvent(views::Textfield* sender,
const views::KeyEvent& key_event) {
if (sender == passphrase_textfield_ &&
key_event.key_code() == ui::VKEY_RETURN) {
parent_->GetDialogClientView()->AcceptWindow();
}
return false;
}
void WimaxConfigView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == passphrase_visible_button_) {
if (passphrase_textfield_) {
passphrase_textfield_->SetObscured(!passphrase_textfield_->IsObscured());
passphrase_visible_button_->SetToggled(
!passphrase_textfield_->IsObscured());
}
} else {
NOTREACHED();
}
}
bool WimaxConfigView::Login() {
NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary();
WimaxNetwork* wimax = cros->FindWimaxNetworkByPath(service_path_);
if (!wimax) {
// Flimflam no longer knows about this wimax network (edge case).
// TODO(stevenjb): Add a notification (chromium-os13225).
LOG(WARNING) << "Wimax network: " << service_path_ << " no longer exists.";
return true;
}
wimax->SetEAPIdentity(GetEapIdentity());
wimax->SetEAPPassphrase(GetEapPassphrase());
wimax->SetSaveCredentials(GetSaveCredentials());
bool share_default = (wimax->profile_type() != PROFILE_USER);
bool share = GetShareNetwork(share_default);
wimax->SetEnrollmentDelegate(
CreateEnrollmentDelegate(GetWidget()->GetNativeWindow(),
wimax->name(),
ProfileManager::GetLastUsedProfile()));
cros->ConnectToWimaxNetwork(wimax, share);
// Connection failures are responsible for updating the UI, including
// reopening dialogs.
return true; // dialog will be closed
}
std::string WimaxConfigView::GetEapIdentity() const {
DCHECK(identity_textfield_);
return UTF16ToUTF8(identity_textfield_->text());
}
std::string WimaxConfigView::GetEapPassphrase() const {
return passphrase_textfield_ ? UTF16ToUTF8(passphrase_textfield_->text()) :
std::string();
}
bool WimaxConfigView::GetSaveCredentials() const {
return save_credentials_checkbox_ ? save_credentials_checkbox_->checked() :
false;
}
bool WimaxConfigView::GetShareNetwork(bool share_default) const {
return share_network_checkbox_ ? share_network_checkbox_->checked() :
share_default;
}
void WimaxConfigView::Cancel() {
}
void WimaxConfigView::Init(WimaxNetwork* wimax) {
DCHECK(wimax);
WifiConfigView::ParseWiFiEAPUIProperty(
&save_credentials_ui_data_, wimax, onc::eap::kSaveCredentials);
WifiConfigView::ParseWiFiEAPUIProperty(
&identity_ui_data_, wimax, onc::eap::kIdentity);
WifiConfigView::ParseWiFiUIProperty(
&passphrase_ui_data_, wimax, onc::wifi::kPassphrase);
views::GridLayout* layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(layout);
const int column_view_set_id = 0;
views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id);
const int kPasswordVisibleWidth = 20;
// Label
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, views::kRelatedControlSmallHorizontalSpacing);
// Textfield, combobox.
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0,
ChildNetworkConfigView::kInputFieldMinWidth);
column_set->AddPaddingColumn(0, views::kRelatedControlSmallHorizontalSpacing);
// Password visible button / policy indicator.
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, kPasswordVisibleWidth);
// Title
layout->StartRow(0, column_view_set_id);
views::Label* title = new views::Label(l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_JOIN_WIMAX_NETWORKS));
title->SetFont(title->font().DeriveFont(1, gfx::Font::BOLD));
layout->AddView(title, 5, 1);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
// Netowrk name
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_TAB_NETWORK)));
views::Label* label = new views::Label(UTF8ToUTF16(wimax->name()));
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
layout->AddView(label);
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Identity
layout->StartRow(0, column_view_set_id);
identity_label_ = new views::Label(l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_IDENTITY));
layout->AddView(identity_label_);
identity_textfield_ = new views::Textfield(
views::Textfield::STYLE_DEFAULT);
identity_textfield_->SetController(this);
const std::string& eap_identity = wimax->eap_identity();
identity_textfield_->SetText(UTF8ToUTF16(eap_identity));
identity_textfield_->SetEnabled(identity_ui_data_.editable());
layout->AddView(identity_textfield_);
layout->AddView(new ControlledSettingIndicatorView(identity_ui_data_));
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Passphrase input
layout->StartRow(0, column_view_set_id);
int label_text_id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE;
passphrase_label_ = new views::Label(
l10n_util::GetStringUTF16(label_text_id));
layout->AddView(passphrase_label_);
passphrase_textfield_ = new views::Textfield(
views::Textfield::STYLE_OBSCURED);
passphrase_textfield_->SetController(this);
passphrase_label_->SetEnabled(true);
passphrase_textfield_->SetEnabled(passphrase_ui_data_.editable());
passphrase_textfield_->SetAccessibleName(l10n_util::GetStringUTF16(
label_text_id));
layout->AddView(passphrase_textfield_);
if (passphrase_ui_data_.managed()) {
layout->AddView(new ControlledSettingIndicatorView(passphrase_ui_data_));
} else {
// Password visible button.
passphrase_visible_button_ = new views::ToggleImageButton(this);
passphrase_visible_button_->SetTooltipText(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE_SHOW));
passphrase_visible_button_->SetToggledTooltipText(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE_HIDE));
passphrase_visible_button_->SetImage(
views::ImageButton::BS_NORMAL,
ResourceBundle::GetSharedInstance().
GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_OFF));
passphrase_visible_button_->SetImage(
views::ImageButton::BS_HOT,
ResourceBundle::GetSharedInstance().
GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_HOVER));
passphrase_visible_button_->SetToggledImage(
views::ImageButton::BS_NORMAL,
ResourceBundle::GetSharedInstance().
GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_ON));
passphrase_visible_button_->SetImageAlignment(
views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE);
layout->AddView(passphrase_visible_button_);
}
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Checkboxes.
if (UserManager::Get()->IsUserLoggedIn()) {
// Save credentials
layout->StartRow(0, column_view_set_id);
save_credentials_checkbox_ = new views::Checkbox(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SAVE_CREDENTIALS));
save_credentials_checkbox_->SetEnabled(
save_credentials_ui_data_.editable());
save_credentials_checkbox_->SetChecked(wimax->save_credentials());
layout->SkipColumns(1);
layout->AddView(save_credentials_checkbox_);
layout->AddView(
new ControlledSettingIndicatorView(save_credentials_ui_data_));
// Share network
if (wimax->profile_type() == PROFILE_NONE && wimax->passphrase_required()) {
layout->StartRow(0, column_view_set_id);
share_network_checkbox_ = new views::Checkbox(
l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SHARE_NETWORK));
share_network_checkbox_->SetEnabled(true);
share_network_checkbox_->SetChecked(false); // Default to unshared.
layout->SkipColumns(1);
layout->AddView(share_network_checkbox_);
}
}
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
// Create an error label.
layout->StartRow(0, column_view_set_id);
layout->SkipColumns(1);
error_label_ = new views::Label();
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_->SetEnabledColor(SK_ColorRED);
layout->AddView(error_label_);
UpdateErrorLabel();
}
void WimaxConfigView::InitFocus() {
views::View* view_to_focus = GetInitiallyFocusedView();
if (view_to_focus)
view_to_focus->RequestFocus();
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "xapiand.h"
#include "utils.h"
#include "manager.h"
#include "tclap/CmdLine.h"
#include "tclap/ZshCompletionOutput.h"
#include <thread>
#include <clocale>
#include <stdlib.h>
#include <unistd.h>
#include <sys/param.h> // for MAXPATHLEN
#include <fcntl.h>
using namespace TCLAP;
std::shared_ptr<XapiandManager> manager;
static void sig_shutdown_handler(int sig) {
if (manager) {
manager->sig_shutdown_handler(sig);
}
}
void setup_signal_handlers(void) {
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
struct sigaction act;
/* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
* Otherwise, sa_handler is used. */
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = sig_shutdown_handler;
sigaction(SIGTERM, &act, nullptr);
sigaction(SIGINT, &act, nullptr);
}
// int num_servers, const char *cluster_name_, const char *node_name_, const char *discovery_group, int discovery_port, const char *raft_group, int raft_port, int http_port, int binary_port, size_t dbpool_size
void run(const opts_t &opts) {
set_thread_name("===");
setup_signal_handlers();
ev::default_loop default_loop;
manager = Worker::create<XapiandManager>(&default_loop, opts);
LOG_DEBUG(nullptr, "Call run, Num of share: %d\n", manager.use_count());
manager->run(opts);
}
// This exemplifies how the output class can be overridden to provide
// user defined output.
class CmdOutput : public StdOutput
{
public:
virtual void failure(CmdLineInterface& _cmd, ArgException& e) {
std::string progName = _cmd.getProgramName();
std::cerr << "Error: " << e.argId() << std::endl;
spacePrint(std::cerr, e.error(), 75, 3, 0);
std::cerr << std::endl;
if (_cmd.hasHelpAndVersion()) {
std::cerr << "Usage: " << std::endl;
_shortUsage( _cmd, std::cerr );
std::cerr << std::endl << "For complete usage and help type: "
<< std::endl << " " << progName << " "
<< Arg::nameStartString() << "help"
<< std::endl << std::endl;
} else {
usage(_cmd);
}
throw ExitException(1);
}
virtual void usage(CmdLineInterface& _cmd) {
spacePrint(std::cout, PACKAGE_STRING, 75, 0, 0);
spacePrint(std::cout, "[" PACKAGE_BUGREPORT "]", 75, 0, 0);
std::cout << std::endl;
std::cout << "Usage: " << std::endl;
_shortUsage(_cmd, std::cout);
std::cout << std::endl << "Where: " << std::endl;
_longUsage(_cmd, std::cout);
}
virtual void version(CmdLineInterface& _cmd) {
std::string xversion = _cmd.getVersion();
std::cout << xversion << std::endl;
}
};
void parseOptions(int argc, char** argv, opts_t &opts)
{
const unsigned int nthreads = std::thread::hardware_concurrency() * 2;
try {
CmdLine cmd("", ' ', PACKAGE_STRING);
// ZshCompletionOutput zshoutput;
// cmd.setOutput(&zshoutput);
CmdOutput output;
cmd.setOutput(&output);
MultiSwitchArg verbosity("v", "verbose", "Increase verbosity.", cmd);
SwitchArg daemonize("d", "daemon", "daemonize (run in background).", cmd);
#ifdef XAPIAN_HAS_GLASS_BACKEND
SwitchArg chert("", "chert", "Use chert databases.", cmd, false);
#endif
ValueArg<std::string> database("D", "database", "Node database.", false, ".", "path", cmd);
ValueArg<std::string> cluster_name("", "cluster", "Cluster name to join.", false, XAPIAND_CLUSTER_NAME, "cluster", cmd);
ValueArg<std::string> node_name("n", "name", "Node name.", false, "", "node", cmd);
ValueArg<unsigned int> http_port("", "http", "HTTP REST API port", false, XAPIAND_HTTP_SERVERPORT, "port", cmd);
ValueArg<unsigned int> binary_port("", "xapian", "Xapian binary protocol port", false, XAPIAND_BINARY_SERVERPORT, "port", cmd);
ValueArg<unsigned int> discovery_port("", "discovery", "Discovery UDP port", false, XAPIAND_DISCOVERY_SERVERPORT, "port", cmd);
ValueArg<std::string> discovery_group("", "dgroup", "Discovery UDP group", false, XAPIAND_DISCOVERY_GROUP, "group", cmd);
ValueArg<unsigned int> raft_port("", "raft", "Raft UDP port", false, XAPIAND_RAFT_SERVERPORT, "port", cmd);
ValueArg<std::string> raft_group("", "rgroup", "Raft UDP group", false, XAPIAND_RAFT_GROUP, "group", cmd);
ValueArg<std::string> pidfile("p", "pid", "Write PID to <pidfile>.", false, "xapiand.pid", "pidfile", cmd);
ValueArg<std::string> uid("u", "uid", "User ID.", false, "xapiand", "uid", cmd);
ValueArg<std::string> gid("g", "gid", "Group ID.", false, "xapiand", "uid", cmd);
ValueArg<size_t> num_servers("", "workers", "Number of worker servers.", false, nthreads, "threads", cmd);
ValueArg<size_t> dbpool_size("", "dbpool", "Maximum number of database endpoints in database pool.", false, DBPOOL_SIZE, "size", cmd);
ValueArg<size_t> num_replicators("", "replicators", "Number of replicators.", false, NUM_REPLICATORS, "replicators", cmd);
cmd.parse(argc, argv);
opts.verbosity = verbosity.getValue();
opts.daemonize = daemonize.getValue();
#ifdef XAPIAN_HAS_GLASS_BACKEND
opts.chert = chert.getValue();
#else
opts.chert = true;
#endif
opts.database = database.getValue();
opts.cluster_name = cluster_name.getValue();
opts.node_name = node_name.getValue();
opts.http_port = http_port.getValue();
opts.binary_port = binary_port.getValue();
opts.discovery_port = discovery_port.getValue();
opts.discovery_group = discovery_group.getValue();
opts.raft_port = raft_port.getValue();
opts.raft_group = raft_group.getValue();
opts.pidfile = pidfile.getValue();
opts.uid = uid.getValue();
opts.gid = gid.getValue();
opts.num_servers = num_servers.getValue();
opts.dbpool_size = dbpool_size.getValue();
opts.num_replicators = num_replicators.getValue();
opts.threadpool_size = THEADPOOL_SIZE;
opts.endpoints_list_size = ENDPOINT_LIST_SIZE;
} catch (const ArgException &e) { // catch any exceptions
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
}
void daemonize(void) {
int fd;
if (fork() != 0) exit(0); /* parent exits */
setsid(); /* create a new session */
/* Every output goes to /dev/null */
if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO) close(fd);
}
}
int main(int argc, char **argv)
{
opts_t opts;
parseOptions(argc, argv, opts);
std::setlocale(LC_CTYPE, "");
LOG_INFO(nullptr,
"\n\n" WHITE
" __ __ _ _\n"
" \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n"
" \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n"
" / \\ (_| | |_) | | (_| | | | | (_| |\n"
" /_/\\_\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n"
" |_| " BRIGHT_GREEN "v%s\n" GREEN
" [%s]\n"
" Using Xapian v%s\n\n", PACKAGE_VERSION, PACKAGE_BUGREPORT, XAPIAN_VERSION);
LOG_INFO(nullptr, "Running on process ID: %d\n", getpid());
#ifdef XAPIAN_HAS_GLASS_BACKEND
if (!opts.chert) {
// Prefer glass database
if (setenv("XAPIAN_PREFER_GLASS", "1", false) != 0) {
opts.chert = true;
}
}
#endif
if (opts.chert) {
LOG_INFO(nullptr, "By default using Chert databases.\n");
} else {
LOG_INFO(nullptr, "By default using Glass databases.\n");
}
// Enable changesets
if (setenv("XAPIAN_MAX_CHANGESETS", "200", false) == 0) {
LOG_INFO(nullptr, "Database changesets set to 200.\n");
}
// Flush threshold increased
int flush_threshold = 10000; // Default is 10000 (if no set)
const char *p = getenv("XAPIAN_FLUSH_THRESHOLD");
if (p) flush_threshold = atoi(p);
if (flush_threshold < 100000 && setenv("XAPIAN_FLUSH_THRESHOLD", "100000", false) == 0) {
LOG_INFO(nullptr, "Increased flush threshold to 100000 (it was originally set to %d).\n", flush_threshold);
}
assert(!chdir(opts.database.c_str()));
char buffer[MAXPATHLEN];
LOG_INFO(nullptr, "Changed current working directory to %s\n", getcwd(buffer, sizeof(buffer)));
init_time = std::chrono::system_clock::now();
time_t epoch = std::chrono::system_clock::to_time_t(init_time);
struct tm *timeinfo = localtime(&epoch);
timeinfo->tm_hour = 0;
timeinfo->tm_min = 0;
timeinfo->tm_sec = 0;
auto diff_t = epoch - mktime(timeinfo);
b_time.minute = diff_t / SLOT_TIME_SECOND;
b_time.second = diff_t % SLOT_TIME_SECOND;
if (opts.daemonize) {
daemonize();
}
run(opts);
LOG_INFO(nullptr, "Done with all work!\n");
return 0;
}
<commit_msg>Print daemonized pid and banner<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "xapiand.h"
#include "utils.h"
#include "manager.h"
#include "tclap/CmdLine.h"
#include "tclap/ZshCompletionOutput.h"
#include <thread>
#include <clocale>
#include <stdlib.h>
#include <unistd.h>
#include <sys/param.h> // for MAXPATHLEN
#include <fcntl.h>
using namespace TCLAP;
std::shared_ptr<XapiandManager> manager;
static void sig_shutdown_handler(int sig) {
if (manager) {
manager->sig_shutdown_handler(sig);
}
}
void setup_signal_handlers(void) {
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
struct sigaction act;
/* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
* Otherwise, sa_handler is used. */
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = sig_shutdown_handler;
sigaction(SIGTERM, &act, nullptr);
sigaction(SIGINT, &act, nullptr);
}
// int num_servers, const char *cluster_name_, const char *node_name_, const char *discovery_group, int discovery_port, const char *raft_group, int raft_port, int http_port, int binary_port, size_t dbpool_size
void run(const opts_t &opts) {
setup_signal_handlers();
ev::default_loop default_loop;
manager = Worker::create<XapiandManager>(&default_loop, opts);
LOG_DEBUG(nullptr, "Call run, Num of share: %d\n", manager.use_count());
manager->run(opts);
}
// This exemplifies how the output class can be overridden to provide
// user defined output.
class CmdOutput : public StdOutput
{
public:
virtual void failure(CmdLineInterface& _cmd, ArgException& e) {
std::string progName = _cmd.getProgramName();
std::cerr << "Error: " << e.argId() << std::endl;
spacePrint(std::cerr, e.error(), 75, 3, 0);
std::cerr << std::endl;
if (_cmd.hasHelpAndVersion()) {
std::cerr << "Usage: " << std::endl;
_shortUsage( _cmd, std::cerr );
std::cerr << std::endl << "For complete usage and help type: "
<< std::endl << " " << progName << " "
<< Arg::nameStartString() << "help"
<< std::endl << std::endl;
} else {
usage(_cmd);
}
throw ExitException(1);
}
virtual void usage(CmdLineInterface& _cmd) {
spacePrint(std::cout, PACKAGE_STRING, 75, 0, 0);
spacePrint(std::cout, "[" PACKAGE_BUGREPORT "]", 75, 0, 0);
std::cout << std::endl;
std::cout << "Usage: " << std::endl;
_shortUsage(_cmd, std::cout);
std::cout << std::endl << "Where: " << std::endl;
_longUsage(_cmd, std::cout);
}
virtual void version(CmdLineInterface& _cmd) {
std::string xversion = _cmd.getVersion();
std::cout << xversion << std::endl;
}
};
void parseOptions(int argc, char** argv, opts_t &opts)
{
const unsigned int nthreads = std::thread::hardware_concurrency() * 2;
try {
CmdLine cmd("", ' ', PACKAGE_STRING);
// ZshCompletionOutput zshoutput;
// cmd.setOutput(&zshoutput);
CmdOutput output;
cmd.setOutput(&output);
MultiSwitchArg verbosity("v", "verbose", "Increase verbosity.", cmd);
SwitchArg daemonize("d", "daemon", "daemonize (run in background).", cmd);
#ifdef XAPIAN_HAS_GLASS_BACKEND
SwitchArg chert("", "chert", "Use chert databases.", cmd, false);
#endif
ValueArg<std::string> database("D", "database", "Node database.", false, ".", "path", cmd);
ValueArg<std::string> cluster_name("", "cluster", "Cluster name to join.", false, XAPIAND_CLUSTER_NAME, "cluster", cmd);
ValueArg<std::string> node_name("n", "name", "Node name.", false, "", "node", cmd);
ValueArg<unsigned int> http_port("", "http", "HTTP REST API port", false, XAPIAND_HTTP_SERVERPORT, "port", cmd);
ValueArg<unsigned int> binary_port("", "xapian", "Xapian binary protocol port", false, XAPIAND_BINARY_SERVERPORT, "port", cmd);
ValueArg<unsigned int> discovery_port("", "discovery", "Discovery UDP port", false, XAPIAND_DISCOVERY_SERVERPORT, "port", cmd);
ValueArg<std::string> discovery_group("", "dgroup", "Discovery UDP group", false, XAPIAND_DISCOVERY_GROUP, "group", cmd);
ValueArg<unsigned int> raft_port("", "raft", "Raft UDP port", false, XAPIAND_RAFT_SERVERPORT, "port", cmd);
ValueArg<std::string> raft_group("", "rgroup", "Raft UDP group", false, XAPIAND_RAFT_GROUP, "group", cmd);
ValueArg<std::string> pidfile("p", "pid", "Write PID to <pidfile>.", false, "xapiand.pid", "pidfile", cmd);
ValueArg<std::string> uid("u", "uid", "User ID.", false, "xapiand", "uid", cmd);
ValueArg<std::string> gid("g", "gid", "Group ID.", false, "xapiand", "uid", cmd);
ValueArg<size_t> num_servers("", "workers", "Number of worker servers.", false, nthreads, "threads", cmd);
ValueArg<size_t> dbpool_size("", "dbpool", "Maximum number of database endpoints in database pool.", false, DBPOOL_SIZE, "size", cmd);
ValueArg<size_t> num_replicators("", "replicators", "Number of replicators.", false, NUM_REPLICATORS, "replicators", cmd);
cmd.parse(argc, argv);
opts.verbosity = verbosity.getValue();
opts.daemonize = daemonize.getValue();
#ifdef XAPIAN_HAS_GLASS_BACKEND
opts.chert = chert.getValue();
#else
opts.chert = true;
#endif
opts.database = database.getValue();
opts.cluster_name = cluster_name.getValue();
opts.node_name = node_name.getValue();
opts.http_port = http_port.getValue();
opts.binary_port = binary_port.getValue();
opts.discovery_port = discovery_port.getValue();
opts.discovery_group = discovery_group.getValue();
opts.raft_port = raft_port.getValue();
opts.raft_group = raft_group.getValue();
opts.pidfile = pidfile.getValue();
opts.uid = uid.getValue();
opts.gid = gid.getValue();
opts.num_servers = num_servers.getValue();
opts.dbpool_size = dbpool_size.getValue();
opts.num_replicators = num_replicators.getValue();
opts.threadpool_size = THEADPOOL_SIZE;
opts.endpoints_list_size = ENDPOINT_LIST_SIZE;
} catch (const ArgException &e) { // catch any exceptions
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
}
void daemonize(void) {
int fd;
pid_t pid = fork();
if (pid != 0) {
LOG_INFO(nullptr, "Done with all work here. Daemon on process ID [%d] taking over!\n", pid);
exit(0); /* parent exits */
}
setsid(); /* create a new session */
/* Every output goes to /dev/null */
if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO) close(fd);
}
}
void banner() {
set_thread_name("==");
LOG_INFO(nullptr,
"\n\n" WHITE
" __ __ _ _\n"
" \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n"
" \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n"
" / \\ (_| | |_) | | (_| | | | | (_| |\n"
" /_/\\_\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n"
" |_| " BRIGHT_GREEN "v%s\n" GREEN
" [%s]\n"
" Using Xapian v%s\n\n", PACKAGE_VERSION, PACKAGE_BUGREPORT, XAPIAN_VERSION);
}
int main(int argc, char **argv)
{
opts_t opts;
parseOptions(argc, argv, opts);
std::setlocale(LC_CTYPE, "");
banner();
if (opts.daemonize) {
daemonize();
banner();
}
LOG_INFO(nullptr, "Running on process ID [%d]\n", getpid());
#ifdef XAPIAN_HAS_GLASS_BACKEND
if (!opts.chert) {
// Prefer glass database
if (setenv("XAPIAN_PREFER_GLASS", "1", false) != 0) {
opts.chert = true;
}
}
#endif
if (opts.chert) {
LOG_INFO(nullptr, "By default using Chert databases.\n");
} else {
LOG_INFO(nullptr, "By default using Glass databases.\n");
}
// Enable changesets
if (setenv("XAPIAN_MAX_CHANGESETS", "200", false) == 0) {
LOG_INFO(nullptr, "Database changesets set to 200.\n");
}
// Flush threshold increased
int flush_threshold = 10000; // Default is 10000 (if no set)
const char *p = getenv("XAPIAN_FLUSH_THRESHOLD");
if (p) flush_threshold = atoi(p);
if (flush_threshold < 100000 && setenv("XAPIAN_FLUSH_THRESHOLD", "100000", false) == 0) {
LOG_INFO(nullptr, "Increased flush threshold to 100000 (it was originally set to %d).\n", flush_threshold);
}
assert(!chdir(opts.database.c_str()));
char buffer[MAXPATHLEN];
LOG_INFO(nullptr, "Changed current working directory to %s\n", getcwd(buffer, sizeof(buffer)));
init_time = std::chrono::system_clock::now();
time_t epoch = std::chrono::system_clock::to_time_t(init_time);
struct tm *timeinfo = localtime(&epoch);
timeinfo->tm_hour = 0;
timeinfo->tm_min = 0;
timeinfo->tm_sec = 0;
auto diff_t = epoch - mktime(timeinfo);
b_time.minute = diff_t / SLOT_TIME_SECOND;
b_time.second = diff_t % SLOT_TIME_SECOND;
run(opts);
LOG_INFO(nullptr, "Done with all work!\n");
return 0;
}
<|endoftext|>
|
<commit_before>//
// TapeUEF.cpp
// Clock Signal
//
// Created by Thomas Harte on 18/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "TapeUEF.hpp"
#include <string.h>
#include <math.h>
static float gzgetfloat(gzFile file)
{
uint8_t bytes[4];
bytes[0] = (uint8_t)gzgetc(file);
bytes[1] = (uint8_t)gzgetc(file);
bytes[2] = (uint8_t)gzgetc(file);
bytes[3] = (uint8_t)gzgetc(file);
/* assume a four byte array named Float exists, where Float[0]
was the first byte read from the UEF, Float[1] the second, etc */
/* decode mantissa */
int mantissa;
mantissa = bytes[0] | (bytes[1] << 8) | ((bytes[2]&0x7f)|0x80) << 16;
float result = (float)mantissa;
result = (float)ldexp(result, -23);
/* decode exponent */
int exponent;
exponent = ((bytes[2]&0x80) >> 7) | (bytes[3]&0x7f) << 1;
exponent -= 127;
result = (float)ldexp(result, exponent);
/* flip sign if necessary */
if(bytes[3]&0x80)
result = -result;
return result;
}
Storage::UEF::UEF(const char *file_name) :
_chunk_id(0), _chunk_length(0), _chunk_position(0),
_time_base(1200)
{
_file = gzopen(file_name, "rb");
char identifier[10];
int bytes_read = gzread(_file, identifier, 10);
if(bytes_read < 10 || strcmp(identifier, "UEF File!"))
{
throw ErrorNotUEF;
}
int minor, major;
minor = gzgetc(_file);
major = gzgetc(_file);
if(major > 0 || minor > 10 || major < 0 || minor < 0)
{
throw ErrorNotUEF;
}
_start_of_next_chunk = gztell(_file);
find_next_tape_chunk();
}
Storage::UEF::~UEF()
{
gzclose(_file);
}
void Storage::UEF::reset()
{
gzseek(_file, 12, SEEK_SET);
}
Storage::Tape::Pulse Storage::UEF::get_next_pulse()
{
Pulse next_pulse;
if(!_bit_position && chunk_is_finished())
{
find_next_tape_chunk();
}
switch(_chunk_id)
{
case 0x0100: case 0x0102:
{
// In the ordinary ("1200 baud") data encoding format,
// a zero bit is encoded as one complete cycle at the base frequency.
// A one bit is two complete cycles at twice the base frequency.
if(!_bit_position)
{
_current_bit = get_next_bit();
}
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = _current_bit ? 1 : 2;
next_pulse.length.clock_rate = _time_base * 4;
_bit_position = (_bit_position+1)&(_current_bit ? 3 : 1);
} break;
case 0x0114:
case 0x0110:
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = 1;
next_pulse.length.clock_rate = _time_base * 4;
_bit_position ^= 1;
if(!_bit_position) _chunk_position++;
break;
case 0x0112:
case 0x0116:
next_pulse.type = Pulse::Zero;
next_pulse.length = _chunk_duration;
_chunk_position++;
break;
}
return next_pulse;
}
void Storage::UEF::find_next_tape_chunk()
{
int reset_count = 0;
_chunk_position = 0;
_bit_position = 0;
while(1)
{
gzseek(_file, _start_of_next_chunk, SEEK_SET);
// read chunk ID
_chunk_id = (uint16_t)gzgetc(_file);
_chunk_id |= (uint16_t)(gzgetc(_file) << 8);
_chunk_length = (uint32_t)(gzgetc(_file) << 0);
_chunk_length |= (uint32_t)(gzgetc(_file) << 8);
_chunk_length |= (uint32_t)(gzgetc(_file) << 16);
_chunk_length |= (uint32_t)(gzgetc(_file) << 24);
_start_of_next_chunk = gztell(_file) + _chunk_length;
if(gzeof(_file))
{
reset_count++;
if(reset_count == 2) break;
reset();
continue;
}
printf("Deal with %04x?\n", _chunk_id);
switch(_chunk_id)
{
case 0x0100: case 0x0102: // implicit and explicit bit patterns
return;
case 0x0112: // integer gap
_chunk_duration.length = (uint16_t)gzgetc(_file);
_chunk_duration.length |= (uint16_t)(gzgetc(_file) << 8);
_chunk_duration.clock_rate = _time_base;
return;
case 0x0116: // floating point gap
{
float length = gzgetfloat(_file);
_chunk_duration.length = (unsigned int)(length * 4000000);
_chunk_duration.clock_rate = 4000000;
}
return;
case 0x0110: // carrier tone
_chunk_duration.length = (uint16_t)gzgetc(_file);
_chunk_duration.length |= (uint16_t)(gzgetc(_file) << 8);
gzseek(_file, _chunk_length - 2, SEEK_CUR);
return;
// case 0x0111: // carrier tone with dummy byte
// TODO: read lengths
// return;
case 0x0114: // security cycles
// read number of cycles
_chunk_duration.length = (uint32_t)gzgetc(_file);
_chunk_duration.length |= (uint32_t)gzgetc(_file) << 8;
_chunk_duration.length |= (uint32_t)gzgetc(_file) << 16;
// Ps and Ws
_first_is_pulse = gzgetc(_file) == 'P';
_last_is_pulse = gzgetc(_file) == 'P';
if(_first_is_pulse)
_bit_position ^= 1;
// TODO: last is pulse
break;
case 0x113: // change of base rate
{
// TODO: something smarter than just converting this to an int
float new_time_base = gzgetfloat(_file);
_time_base = (unsigned int)roundf(new_time_base);
}
break;
default:
gzseek(_file, _chunk_length, SEEK_CUR);
break;
}
}
}
bool Storage::UEF::chunk_is_finished()
{
switch(_chunk_id)
{
case 0x0100: return (_chunk_position / 10) == _chunk_length;
case 0x0102: return (_chunk_position / 8) == _chunk_length;
case 0x0114:
case 0x0110: return _chunk_position == _chunk_duration.length;
case 0x0112:
case 0x0116: return _chunk_position ? true : false;
default: return true;
}
}
bool Storage::UEF::get_next_bit()
{
switch(_chunk_id)
{
case 0x0100:
{
uint32_t bit_position = _chunk_position%10;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
if(bit_position == 0) return false;
if(bit_position == 9) return true;
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0114:
case 0x0102:
{
uint32_t bit_position = _chunk_position%8;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0110:
_chunk_position++;
return true;
default: return true;
}
}
<commit_msg>Made an attempt to fix my 0114 implementation.<commit_after>//
// TapeUEF.cpp
// Clock Signal
//
// Created by Thomas Harte on 18/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "TapeUEF.hpp"
#include <string.h>
#include <math.h>
static float gzgetfloat(gzFile file)
{
uint8_t bytes[4];
bytes[0] = (uint8_t)gzgetc(file);
bytes[1] = (uint8_t)gzgetc(file);
bytes[2] = (uint8_t)gzgetc(file);
bytes[3] = (uint8_t)gzgetc(file);
/* assume a four byte array named Float exists, where Float[0]
was the first byte read from the UEF, Float[1] the second, etc */
/* decode mantissa */
int mantissa;
mantissa = bytes[0] | (bytes[1] << 8) | ((bytes[2]&0x7f)|0x80) << 16;
float result = (float)mantissa;
result = (float)ldexp(result, -23);
/* decode exponent */
int exponent;
exponent = ((bytes[2]&0x80) >> 7) | (bytes[3]&0x7f) << 1;
exponent -= 127;
result = (float)ldexp(result, exponent);
/* flip sign if necessary */
if(bytes[3]&0x80)
result = -result;
return result;
}
Storage::UEF::UEF(const char *file_name) :
_chunk_id(0), _chunk_length(0), _chunk_position(0),
_time_base(1200)
{
_file = gzopen(file_name, "rb");
char identifier[10];
int bytes_read = gzread(_file, identifier, 10);
if(bytes_read < 10 || strcmp(identifier, "UEF File!"))
{
throw ErrorNotUEF;
}
int minor, major;
minor = gzgetc(_file);
major = gzgetc(_file);
if(major > 0 || minor > 10 || major < 0 || minor < 0)
{
throw ErrorNotUEF;
}
_start_of_next_chunk = gztell(_file);
find_next_tape_chunk();
}
Storage::UEF::~UEF()
{
gzclose(_file);
}
void Storage::UEF::reset()
{
gzseek(_file, 12, SEEK_SET);
}
Storage::Tape::Pulse Storage::UEF::get_next_pulse()
{
Pulse next_pulse;
if(!_bit_position && chunk_is_finished())
{
find_next_tape_chunk();
}
switch(_chunk_id)
{
case 0x0100: case 0x0102:
// In the ordinary ("1200 baud") data encoding format,
// a zero bit is encoded as one complete cycle at the base frequency.
// A one bit is two complete cycles at twice the base frequency.
if(!_bit_position)
{
_current_bit = get_next_bit();
}
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = _current_bit ? 1 : 2;
next_pulse.length.clock_rate = _time_base * 4;
_bit_position = (_bit_position+1)&(_current_bit ? 3 : 1);
break;
case 0x0110:
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = 1;
next_pulse.length.clock_rate = _time_base * 4;
_bit_position ^= 1;
if(!_bit_position) _chunk_position++;
break;
case 0x0114:
if(!_bit_position)
{
_current_bit = get_next_bit();
if(_first_is_pulse && !_chunk_position)
{
_bit_position++;
}
}
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = _current_bit ? 1 : 2;
next_pulse.length.clock_rate = _time_base * 4;
_bit_position ^= 1;
if((_chunk_id == 0x0114) && (_chunk_position == _chunk_duration.length-1) && _last_is_pulse)
{
_chunk_position++;
}
break;
case 0x0112:
case 0x0116:
next_pulse.type = Pulse::Zero;
next_pulse.length = _chunk_duration;
_chunk_position++;
break;
}
return next_pulse;
}
void Storage::UEF::find_next_tape_chunk()
{
int reset_count = 0;
_chunk_position = 0;
_bit_position = 0;
while(1)
{
gzseek(_file, _start_of_next_chunk, SEEK_SET);
// read chunk ID
_chunk_id = (uint16_t)gzgetc(_file);
_chunk_id |= (uint16_t)(gzgetc(_file) << 8);
_chunk_length = (uint32_t)(gzgetc(_file) << 0);
_chunk_length |= (uint32_t)(gzgetc(_file) << 8);
_chunk_length |= (uint32_t)(gzgetc(_file) << 16);
_chunk_length |= (uint32_t)(gzgetc(_file) << 24);
_start_of_next_chunk = gztell(_file) + _chunk_length;
if(gzeof(_file))
{
reset_count++;
if(reset_count == 2) break;
reset();
continue;
}
switch(_chunk_id)
{
case 0x0100: case 0x0102: // implicit and explicit bit patterns
return;
case 0x0112: // integer gap
_chunk_duration.length = (uint16_t)gzgetc(_file);
_chunk_duration.length |= (uint16_t)(gzgetc(_file) << 8);
_chunk_duration.clock_rate = _time_base;
return;
case 0x0116: // floating point gap
{
float length = gzgetfloat(_file);
_chunk_duration.length = (unsigned int)(length * 4000000);
_chunk_duration.clock_rate = 4000000;
}
return;
case 0x0110: // carrier tone
_chunk_duration.length = (uint16_t)gzgetc(_file);
_chunk_duration.length |= (uint16_t)(gzgetc(_file) << 8);
gzseek(_file, _chunk_length - 2, SEEK_CUR);
return;
// case 0x0111: // carrier tone with dummy byte
// TODO: read lengths
// return;
case 0x0114: // security cycles
{
// read number of cycles
_chunk_duration.length = (uint32_t)gzgetc(_file);
_chunk_duration.length |= (uint32_t)gzgetc(_file) << 8;
_chunk_duration.length |= (uint32_t)gzgetc(_file) << 16;
// Ps and Ws
_first_is_pulse = gzgetc(_file) == 'P';
_last_is_pulse = gzgetc(_file) == 'P';
}
break;
case 0x113: // change of base rate
{
// TODO: something smarter than just converting this to an int
float new_time_base = gzgetfloat(_file);
_time_base = (unsigned int)roundf(new_time_base);
}
break;
default:
gzseek(_file, _chunk_length, SEEK_CUR);
break;
}
}
}
bool Storage::UEF::chunk_is_finished()
{
switch(_chunk_id)
{
case 0x0100: return (_chunk_position / 10) == _chunk_length;
case 0x0102: return (_chunk_position / 8) == _chunk_length;
case 0x0114:
case 0x0110: return _chunk_position == _chunk_duration.length;
case 0x0112:
case 0x0116: return _chunk_position ? true : false;
default: return true;
}
}
bool Storage::UEF::get_next_bit()
{
switch(_chunk_id)
{
case 0x0100:
{
uint32_t bit_position = _chunk_position%10;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
if(bit_position == 0) return false;
if(bit_position == 9) return true;
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
// TODO: 0x0104, 0x0111
case 0x0114:
case 0x0102:
{
uint32_t bit_position = _chunk_position%8;
_chunk_position++;
if(!bit_position && _chunk_position < _chunk_duration.length)
{
_current_byte = (uint8_t)gzgetc(_file);
}
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0110:
_chunk_position++;
return true;
default: return true;
}
}
<|endoftext|>
|
<commit_before>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
typedef ssize_t (*ReadSignature)(int, void*, size_t);
thread_local ReadSignature realRead = NULL;
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::vector<std::string> history;
thread_local auto historyCurrentPos = history.end(); // FIXME: this is wrong, but I only need the iterator type
static void readHistory() {
if (history.size()) return;
std::string historyFileName(getenv("HOME"));
historyFileName += "/.bash_history";
std::ifstream historyFile(historyFileName);
std::string line;
while (std::getline(historyFile, line))
history.push_back(line); // TODO: maybe reverse order?
}
static void newlineHandler() {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
}
static void backspaceHandler() {
if (lineBufferPos != lineBuffer.begin())
*(--lineBufferPos) = 0;
}
std::string findCompletion(const std::string &pattern) {
for (auto it = history.end() - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyCurrentPos = it;
return *it;
}
}
historyCurrentPos = history.end() - 1;
return pattern;
}
// TODO: merge this with the above function
std::string findNextCompletion(const std::string &pattern) {
for (auto it = historyCurrentPos; it >= history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyCurrentPos = it;
return *it;
}
}
historyCurrentPos = history.end() - 1;
return pattern;
}
void printCompletion() {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(pattern);
cursor_forward(1);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + 1);
fflush(stdout);
}
void regularCharHandler(char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion();
}
void tabHandler() {
printCompletion();
}
static unsigned char yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
readHistory();
switch (c) {
case 0x09: // tab
tabHandler();
break;
case 0x0d: // newline
newlineHandler();
break;
case 0x17: // ctrl+w
newlineHandler(); // TODO: this has to clear lineBuffer
break;
case 0x7f: // backspace
backspaceHandler();
break;
default: // regular char or other special chars
if (c < 0x20)
newlineHandler();
else
regularCharHandler(c);
break;
}
return 0;
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0 && isatty(fileno(stdin))) {
unsigned char c = yebash(*reinterpret_cast<unsigned char *>(buf));
if (c) *reinterpret_cast<unsigned char *>(buf) = c;
}
return returnValue;
}
<commit_msg>WIP: browsing history by Ctrl-F<commit_after>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
typedef ssize_t (*ReadSignature)(int, void*, size_t);
thread_local ReadSignature realRead = NULL;
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::vector<std::string> history;
thread_local std::vector<std::string>::iterator historyPos;
static void readHistory() {
if (history.size()) return;
std::string historyFileName(getenv("HOME"));
historyFileName += "/.bash_history";
std::ifstream historyFile(historyFileName);
std::string line;
while (std::getline(historyFile, line))
history.push_back(line); // TODO: maybe reverse order?
}
static void newlineHandler() {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
}
static void backspaceHandler() {
if (lineBufferPos != lineBuffer.begin())
*(--lineBufferPos) = 0;
}
std::string findCompletion(std::vector<std::string>::iterator start, const std::string &pattern) {
for (auto it = start - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.end();
return pattern;
}
void printCompletion(std::vector<std::string>::iterator startIterator) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
cursor_forward(1);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + 1);
fflush(stdout);
}
void regularCharHandler(char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.end());
}
void tabHandler() {
printCompletion(historyPos);
}
static unsigned char yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
readHistory();
switch (c) {
case 0x06: // ctrl+f
// FIXME: SEGFAULT
tabHandler();
break;
case 0x0d: // newline
newlineHandler();
break;
case 0x17: // ctrl+w
newlineHandler(); // TODO: this has to clear lineBuffer
break;
case 0x7f: // backspace
backspaceHandler();
break;
default: // regular char or other special chars
if (c < 0x20)
newlineHandler();
else
regularCharHandler(c);
break;
}
return 0;
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0 && isatty(fileno(stdin))) {
unsigned char c = yebash(*reinterpret_cast<unsigned char *>(buf));
if (c) *reinterpret_cast<unsigned char *>(buf) = c;
}
return returnValue;
}
<|endoftext|>
|
<commit_before>#include <Rcpp.h>
#include <chrono>
#include <string>
#include <unordered_map>
#include "zmq.hpp"
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
extern Rcpp::Function R_serialize;
extern Rcpp::Function R_unserialize;
int pending_interrupt();
class ZeroMQ {
public:
ZeroMQ(int threads=1) { ctx = new zmq::context_t(threads); }
~ZeroMQ() {
for (auto kv : sockets)
delete sockets[kv.first];
delete ctx;
}
std::string listen(Rcpp::CharacterVector addrs, std::string socket_type="ZMQ_REP",
std::string sid="default") {
auto sock = new zmq::socket_t(*ctx, str2socket(socket_type));
int i;
for (i=0; i<addrs.length(); i++) {
auto addr = Rcpp::as<std::string>(addrs[i]);
try {
sock->bind(addr);
} catch(zmq::error_t const &e) {
if (errno != EADDRINUSE)
Rf_error(e.what());
}
sockets.emplace(sid, sock);
char option_value[1024];
size_t option_value_len = sizeof(option_value);
sock->getsockopt(ZMQ_LAST_ENDPOINT, option_value, &option_value_len);
return std::string(option_value);
}
Rf_error("Could not bind port after ", i, " tries");
}
void connect(std::string address, std::string socket_type="ZMQ_REQ", std::string sid="default") {
auto sock = new zmq::socket_t(*ctx, str2socket(socket_type));
sock->connect(address);
sockets.emplace(sid, sock);
}
void disconnect(std::string sid="default") {
if (sockets[sid]) {
delete sockets[sid];
sockets.erase(sid);
}
}
void send(SEXP data, std::string sid="default", bool dont_wait=false, bool send_more=false) {
check_socket(sid);
auto flags = zmq::send_flags::none;
if (dont_wait)
flags = flags | zmq::send_flags::dontwait;
if (send_more)
flags = flags | zmq::send_flags::sndmore;
if (TYPEOF(data) != RAWSXP)
data = R_serialize(data, R_NilValue);
zmq::message_t message(Rf_xlength(data));
memcpy(message.data(), RAW(data), Rf_xlength(data));
sockets[sid]->send(message, flags);
}
SEXP receive(std::string sid="default", bool dont_wait=false, bool unserialize=true) {
check_socket(sid);
auto message = rcv_msg(sid, dont_wait);
SEXP ans = Rf_allocVector(RAWSXP, message.size());
memcpy(RAW(ans), message.data(), message.size());
if (unserialize)
return R_unserialize(ans);
else
return ans;
}
Rcpp::IntegerVector poll(Rcpp::CharacterVector sids, int timeout=-1) {
auto nsock = sids.length();
auto pitems = std::vector<zmq::pollitem_t>(nsock);
for (int i = 0; i < nsock; i++) {
auto socket_id = Rcpp::as<std::string>(sids[i]);
check_socket(socket_id);
pitems[i].socket = *sockets[socket_id];
pitems[i].events = ZMQ_POLLIN; // | ZMQ_POLLOUT; // ssh_proxy XREP/XREQ has 2200
}
int rc = -1;
auto start = Time::now();
do {
try {
rc = zmq::poll(pitems, timeout);
} catch(zmq::error_t const &e) {
if (errno != EINTR || pending_interrupt())
Rf_error(e.what());
if (timeout != -1) {
ms dt = std::chrono::duration_cast<ms>(Time::now() - start);
timeout = timeout - dt.count();
if (timeout <= 0)
break;
}
}
} while(rc < 0);
auto result = Rcpp::IntegerVector(nsock);
for (int i = 0; i < nsock; i++)
result[i] = pitems[i].revents;
return result;
}
private:
zmq::context_t *ctx;
std::unordered_map<std::string, zmq::socket_t*> sockets;
int str2socket(std::string str) {
if (str == "ZMQ_REP") {
return ZMQ_REP;
} else if (str == "ZMQ_REQ") {
return ZMQ_REQ;
} else if (str == "ZMQ_XREP") {
return ZMQ_XREP;
} else if (str == "ZMQ_XREQ") {
return ZMQ_XREQ;
} else {
Rcpp::exception(("Invalid socket type: " + str).c_str());
}
return -1;
}
void check_socket(std::string socket_id) {
if (sockets.find(socket_id) == sockets.end())
Rf_error("Trying to access non-existing socket: ", socket_id.c_str());
}
zmq::message_t rcv_msg(std::string sid="default", bool dont_wait=false) {
auto flags = zmq::recv_flags::none;
if (dont_wait)
flags = flags | zmq::recv_flags::dontwait;
zmq::message_t message;
sockets[sid]->recv(message, flags);
return message;
}
};
RCPP_MODULE(zmq) {
using namespace Rcpp;
class_<ZeroMQ>("ZeroMQ_raw")
.constructor() // .constructor<int>() SIGABRT
.method("listen", &ZeroMQ::listen)
.method("connect", &ZeroMQ::connect)
.method("disconnect", &ZeroMQ::disconnect)
.method("send", &ZeroMQ::send)
.method("receive", &ZeroMQ::receive)
.method("poll", &ZeroMQ::poll)
;
}
<commit_msg>Remove manual resource management<commit_after>#include <Rcpp.h>
#include <chrono>
#include <string>
#include <unordered_map>
#include "zmq.hpp"
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
extern Rcpp::Function R_serialize;
extern Rcpp::Function R_unserialize;
int pending_interrupt();
class ZeroMQ {
public:
ZeroMQ(int threads=1) : ctx(threads), sockets() {}
std::string listen(Rcpp::CharacterVector addrs, std::string socket_type="ZMQ_REP",
std::string sid="default") {
auto sock = zmq::socket_t(ctx, str2socket(socket_type));
int i;
for (i=0; i<addrs.length(); i++) {
auto addr = Rcpp::as<std::string>(addrs[i]);
try {
sock.bind(addr);
} catch(zmq::error_t const &e) {
if (errno != EADDRINUSE)
Rf_error(e.what());
}
char option_value[1024];
size_t option_value_len = sizeof(option_value);
sock.getsockopt(ZMQ_LAST_ENDPOINT, option_value, &option_value_len);
sockets.emplace(sid, std::move(sock));
return std::string(option_value);
}
Rf_error("Could not bind port after ", i, " tries");
}
void connect(std::string address, std::string socket_type="ZMQ_REQ", std::string sid="default") {
auto sock = zmq::socket_t(ctx, str2socket(socket_type));
sock.connect(address);
sockets.emplace(sid, std::move(sock));
}
void disconnect(std::string sid="default") {
sockets.erase(sid);
}
void send(SEXP data, std::string sid="default", bool dont_wait=false, bool send_more=false) {
check_socket(sid);
auto flags = zmq::send_flags::none;
if (dont_wait)
flags = flags | zmq::send_flags::dontwait;
if (send_more)
flags = flags | zmq::send_flags::sndmore;
if (TYPEOF(data) != RAWSXP)
data = R_serialize(data, R_NilValue);
zmq::message_t message(Rf_xlength(data));
memcpy(message.data(), RAW(data), Rf_xlength(data));
sockets[sid].send(message, flags);
}
SEXP receive(std::string sid="default", bool dont_wait=false, bool unserialize=true) {
check_socket(sid);
auto message = rcv_msg(sid, dont_wait);
SEXP ans = Rf_allocVector(RAWSXP, message.size());
memcpy(RAW(ans), message.data(), message.size());
if (unserialize)
return R_unserialize(ans);
else
return ans;
}
Rcpp::IntegerVector poll(Rcpp::CharacterVector sids, int timeout=-1) {
auto nsock = sids.length();
auto pitems = std::vector<zmq::pollitem_t>(nsock);
for (int i = 0; i < nsock; i++) {
auto socket_id = Rcpp::as<std::string>(sids[i]);
check_socket(socket_id);
pitems[i].socket = sockets[socket_id];
pitems[i].events = ZMQ_POLLIN; // | ZMQ_POLLOUT; // ssh_proxy XREP/XREQ has 2200
}
int rc = -1;
auto start = Time::now();
do {
try {
rc = zmq::poll(pitems, timeout);
} catch(zmq::error_t const &e) {
if (errno != EINTR || pending_interrupt())
Rf_error(e.what());
if (timeout != -1) {
ms dt = std::chrono::duration_cast<ms>(Time::now() - start);
timeout = timeout - dt.count();
if (timeout <= 0)
break;
}
}
} while(rc < 0);
auto result = Rcpp::IntegerVector(nsock);
for (int i = 0; i < nsock; i++)
result[i] = pitems[i].revents;
return result;
}
private:
zmq::context_t ctx;
std::unordered_map<std::string, zmq::socket_t> sockets;
int str2socket(std::string str) {
if (str == "ZMQ_REP") {
return ZMQ_REP;
} else if (str == "ZMQ_REQ") {
return ZMQ_REQ;
} else if (str == "ZMQ_XREP") {
return ZMQ_XREP;
} else if (str == "ZMQ_XREQ") {
return ZMQ_XREQ;
} else {
Rcpp::exception(("Invalid socket type: " + str).c_str());
}
return -1;
}
void check_socket(std::string socket_id) {
if (sockets.find(socket_id) == sockets.end())
Rf_error("Trying to access non-existing socket: ", socket_id.c_str());
}
zmq::message_t rcv_msg(std::string sid="default", bool dont_wait=false) {
auto flags = zmq::recv_flags::none;
if (dont_wait)
flags = flags | zmq::recv_flags::dontwait;
zmq::message_t message;
sockets[sid].recv(message, flags);
return message;
}
};
RCPP_MODULE(zmq) {
using namespace Rcpp;
class_<ZeroMQ>("ZeroMQ_raw")
.constructor() // .constructor<int>() SIGABRT
.method("listen", &ZeroMQ::listen)
.method("connect", &ZeroMQ::connect)
.method("disconnect", &ZeroMQ::disconnect)
.method("send", &ZeroMQ::send)
.method("receive", &ZeroMQ::receive)
.method("poll", &ZeroMQ::poll)
;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INGEN_ATOM_HPP
#define INGEN_ATOM_HPP
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "ingen/ingen.h"
#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/urid/urid.h"
namespace Ingen {
/**
A generic typed data container.
An Atom holds a value with some type and size, both specified by a uint32_t.
Values with size less than sizeof(void*) are stored inline: no dynamic
allocation occurs so Atoms may be created in hard real-time threads.
Otherwise, if the size is larger than sizeof(void*), the value will be
dynamically allocated in a separate chunk of memory.
In either case, the data is stored in a binary compatible format to LV2_Atom
(i.e., if the value is dynamically allocated, the header is repeated there).
*/
class INGEN_API Atom {
public:
Atom() { _atom.size = 0; _atom.type = 0; _body.ptr = nullptr; }
~Atom() { dealloc(); }
/** Construct a raw atom.
*
* Typically this is not used directly, use Forge methods to make atoms.
*/
Atom(uint32_t size, LV2_URID type, const void* body) {
_atom.size = size;
_atom.type = type;
_body.ptr = nullptr;
if (is_reference()) {
_body.ptr = (LV2_Atom*)malloc(sizeof(LV2_Atom) + size);
memcpy(_body.ptr, &_atom, sizeof(LV2_Atom));
}
if (body) {
memcpy(get_body(), body, size);
}
}
Atom(const Atom& copy)
: _atom(copy._atom)
{
if (is_reference()) {
_body.ptr = (LV2_Atom*)malloc(sizeof(LV2_Atom) + _atom.size);
memcpy(_body.ptr, copy._body.ptr, sizeof(LV2_Atom) + _atom.size);
} else {
_body.val = copy._body.val;
}
}
Atom& operator=(const Atom& other) {
if (&other == this) {
return *this;
}
dealloc();
_atom = other._atom;
if (is_reference()) {
_body.ptr = (LV2_Atom*)malloc(sizeof(LV2_Atom) + _atom.size);
memcpy(_body.ptr, other._body.ptr, sizeof(LV2_Atom) + _atom.size);
} else {
_body.val = other._body.val;
}
return *this;
}
inline bool operator==(const Atom& other) const {
if (_atom.type != other._atom.type ||
_atom.size != other._atom.size) {
return false;
}
return is_reference()
? !memcmp(_body.ptr, other._body.ptr, sizeof(LV2_Atom) + _atom.size)
: _body.val == other._body.val;
}
inline bool operator!=(const Atom& other) const {
return !operator==(other);
}
inline bool operator<(const Atom& other) const {
if (_atom.type == other._atom.type) {
const uint32_t min_size = std::min(_atom.size, other._atom.size);
const int cmp = is_reference()
? memcmp(_body.ptr, other._body.ptr, min_size)
: memcmp(&_body.val, &other._body.val, min_size);
return cmp < 0 || (cmp == 0 && _atom.size < other._atom.size);
}
return type() < other.type();
}
/** Like assignment, but only works for value atoms (not references).
* Always real-time safe.
* @return true iff set succeeded.
*/
inline bool set_rt(const Atom& other) {
if (is_reference()) {
return false;
} else {
_atom = other._atom;
_body.val = other._body.val;
return true;
}
}
inline uint32_t size() const { return _atom.size; }
inline LV2_URID type() const { return _atom.type; }
inline bool is_valid() const { return _atom.type; }
inline const void* get_body() const {
return is_reference() ? (void*)(_body.ptr + 1) : &_body.val;
}
inline void* get_body() {
return is_reference() ? (void*)(_body.ptr + 1) : &_body.val;
}
template <typename T> const T& get() const {
assert(size() == sizeof(T));
return *static_cast<const T*>(get_body());
}
template <typename T> const T* ptr() const {
return static_cast<const T*>(get_body());
}
const LV2_Atom* atom() const {
return is_reference() ? _body.ptr : &_atom;
}
private:
/** Free dynamically allocated value, if applicable. */
inline void dealloc() {
if (is_reference()) {
free(_body.ptr);
}
}
/** Return true iff this value is dynamically allocated. */
inline bool is_reference() const {
return _atom.size > sizeof(_body.val);
}
LV2_Atom _atom;
union {
intptr_t val;
LV2_Atom* ptr;
} _body;
};
} // namespace Ingen
#endif // INGEN_ATOM_HPP
<commit_msg>Avoid static construction exception warning<commit_after>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INGEN_ATOM_HPP
#define INGEN_ATOM_HPP
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "ingen/ingen.h"
#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/urid/urid.h"
namespace Ingen {
/**
A generic typed data container.
An Atom holds a value with some type and size, both specified by a uint32_t.
Values with size less than sizeof(void*) are stored inline: no dynamic
allocation occurs so Atoms may be created in hard real-time threads.
Otherwise, if the size is larger than sizeof(void*), the value will be
dynamically allocated in a separate chunk of memory.
In either case, the data is stored in a binary compatible format to LV2_Atom
(i.e., if the value is dynamically allocated, the header is repeated there).
*/
class INGEN_API Atom {
public:
Atom() noexcept { _atom.size = 0; _atom.type = 0; _body.ptr = nullptr; }
~Atom() { dealloc(); }
/** Construct a raw atom.
*
* Typically this is not used directly, use Forge methods to make atoms.
*/
Atom(uint32_t size, LV2_URID type, const void* body) {
_atom.size = size;
_atom.type = type;
_body.ptr = nullptr;
if (is_reference()) {
_body.ptr = (LV2_Atom*)malloc(sizeof(LV2_Atom) + size);
memcpy(_body.ptr, &_atom, sizeof(LV2_Atom));
}
if (body) {
memcpy(get_body(), body, size);
}
}
Atom(const Atom& copy)
: _atom(copy._atom)
{
if (is_reference()) {
_body.ptr = (LV2_Atom*)malloc(sizeof(LV2_Atom) + _atom.size);
memcpy(_body.ptr, copy._body.ptr, sizeof(LV2_Atom) + _atom.size);
} else {
_body.val = copy._body.val;
}
}
Atom& operator=(const Atom& other) {
if (&other == this) {
return *this;
}
dealloc();
_atom = other._atom;
if (is_reference()) {
_body.ptr = (LV2_Atom*)malloc(sizeof(LV2_Atom) + _atom.size);
memcpy(_body.ptr, other._body.ptr, sizeof(LV2_Atom) + _atom.size);
} else {
_body.val = other._body.val;
}
return *this;
}
inline bool operator==(const Atom& other) const {
if (_atom.type != other._atom.type ||
_atom.size != other._atom.size) {
return false;
}
return is_reference()
? !memcmp(_body.ptr, other._body.ptr, sizeof(LV2_Atom) + _atom.size)
: _body.val == other._body.val;
}
inline bool operator!=(const Atom& other) const {
return !operator==(other);
}
inline bool operator<(const Atom& other) const {
if (_atom.type == other._atom.type) {
const uint32_t min_size = std::min(_atom.size, other._atom.size);
const int cmp = is_reference()
? memcmp(_body.ptr, other._body.ptr, min_size)
: memcmp(&_body.val, &other._body.val, min_size);
return cmp < 0 || (cmp == 0 && _atom.size < other._atom.size);
}
return type() < other.type();
}
/** Like assignment, but only works for value atoms (not references).
* Always real-time safe.
* @return true iff set succeeded.
*/
inline bool set_rt(const Atom& other) {
if (is_reference()) {
return false;
} else {
_atom = other._atom;
_body.val = other._body.val;
return true;
}
}
inline uint32_t size() const { return _atom.size; }
inline LV2_URID type() const { return _atom.type; }
inline bool is_valid() const { return _atom.type; }
inline const void* get_body() const {
return is_reference() ? (void*)(_body.ptr + 1) : &_body.val;
}
inline void* get_body() {
return is_reference() ? (void*)(_body.ptr + 1) : &_body.val;
}
template <typename T> const T& get() const {
assert(size() == sizeof(T));
return *static_cast<const T*>(get_body());
}
template <typename T> const T* ptr() const {
return static_cast<const T*>(get_body());
}
const LV2_Atom* atom() const {
return is_reference() ? _body.ptr : &_atom;
}
private:
/** Free dynamically allocated value, if applicable. */
inline void dealloc() {
if (is_reference()) {
free(_body.ptr);
}
}
/** Return true iff this value is dynamically allocated. */
inline bool is_reference() const {
return _atom.size > sizeof(_body.val);
}
LV2_Atom _atom;
union {
intptr_t val;
LV2_Atom* ptr;
} _body;
};
} // namespace Ingen
#endif // INGEN_ATOM_HPP
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/parsed_interior_qoi.h"
// GRINS
#include "grins/multiphysics_sys.h"
#include "grins/assembly_context.h"
// libMesh
#include "libmesh/getpot.h"
#include "libmesh/fem_system.h"
#include "libmesh/quadrature.h"
#include "libmesh/fe_base.h"
#include "libmesh/parsed_fem_function.h"
namespace GRINS
{
ParsedInteriorQoI::ParsedInteriorQoI( const std::string& qoi_name )
: QoIBase(qoi_name) {}
ParsedInteriorQoI::ParsedInteriorQoI( const ParsedInteriorQoI& original )
: QoIBase(original.name())
{
this->qoi_functional = original.qoi_functional->clone();
}
ParsedInteriorQoI::~ParsedInteriorQoI() {}
QoIBase* ParsedInteriorQoI::clone() const
{
return new ParsedInteriorQoI( *this );
}
void ParsedInteriorQoI::init( const GetPot& input, const MultiphysicsSystem& system )
{
std::string qoi_functional_string =
input("QoI/ParsedInterior/qoi_functional", std::string("0"));
if (qoi_functional_string == "0")
libmesh_error_msg("Error! Zero ParsedInteriorQoI specified!" <<
std::endl);
this->qoi_functional.reset
(new libMesh::ParsedFEMFunction<libMesh::Number>
(system, qoi_functional_string));
}
void ParsedInteriorQoI::init_context( AssemblyContext& context )
{
libMesh::FEBase* element_fe;
context.get_element_fe<libMesh::Real>(0, element_fe);
element_fe->get_JxW();
element_fe->get_xyz();
qoi_functional->init_context(context);
}
void ParsedInteriorQoI::element_qoi( AssemblyContext& context,
const unsigned int qoi_index )
{
libMesh::FEBase* element_fe;
context.get_element_fe<libMesh::Real>(0, element_fe);
const std::vector<libMesh::Real> &JxW = element_fe->get_JxW();
const std::vector<libMesh::Point>& x_qp = element_fe->get_xyz();
unsigned int n_qpoints = context.get_element_qrule().n_points();
/*! \todo Need to generalize this to the multiple QoI case */
libMesh::Number& qoi = context.get_qois()[qoi_index];
for( unsigned int qp = 0; qp != n_qpoints; qp++ )
{
const libMesh::Number func_val =
(*qoi_functional)(context, x_qp[qp], context.get_time());
qoi += func_val;
}
}
void ParsedInteriorQoI::element_qoi_derivative( AssemblyContext& context,
const unsigned int qoi_index )
{
libMesh::FEBase* element_fe;
context.get_element_fe<libMesh::Real>(0, element_fe);
const std::vector<libMesh::Real> &JxW = element_fe->get_JxW();
const std::vector<libMesh::Point>& x_qp = element_fe->get_xyz();
// Local DOF count and quadrature point count
const unsigned int n_u_dofs = context.get_dof_indices().size();
unsigned int n_qpoints = context.get_element_qrule().n_points();
// Local solution vector - non-const version for finite
// differenting purposes
libMesh::DenseVector<libMesh::Number>& elem_solution =
const_cast<libMesh::DenseVector<libMesh::Number>&>
(context.get_elem_solution());
/*! \todo Need to generalize this to the multiple QoI case */
libMesh::DenseVector<libMesh::Number> &Qu =
context.get_qoi_derivatives()[qoi_index];
for( unsigned int qp = 0; qp != n_qpoints; qp++ )
{
// Central finite differencing to approximate derivatives.
// FIXME - we should hook the FParserAD stuff into
// ParsedFEMFunction
for( unsigned int i = 0; i != n_u_dofs; ++i )
{
libMesh::Number ¤t_solution = elem_solution(i);
const libMesh::Number original_solution = current_solution;
current_solution = original_solution + libMesh::TOLERANCE;
const libMesh::Number plus_val =
(*qoi_functional)(context, x_qp[qp], context.get_time());
current_solution = original_solution - libMesh::TOLERANCE;
const libMesh::Number minus_val =
(*qoi_functional)(context, x_qp[qp], context.get_time());
Qu(i) += (plus_val - minus_val) * (0.5 / libMesh::TOLERANCE);
// Don't forget to restore the correct solution...
current_solution = original_solution;
}
}
}
} //namespace GRINS
<commit_msg>ParsedInteriorQoI bugfix<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/parsed_interior_qoi.h"
// GRINS
#include "grins/multiphysics_sys.h"
#include "grins/assembly_context.h"
// libMesh
#include "libmesh/getpot.h"
#include "libmesh/fem_system.h"
#include "libmesh/quadrature.h"
#include "libmesh/fe_base.h"
#include "libmesh/parsed_fem_function.h"
namespace GRINS
{
ParsedInteriorQoI::ParsedInteriorQoI( const std::string& qoi_name )
: QoIBase(qoi_name) {}
ParsedInteriorQoI::ParsedInteriorQoI( const ParsedInteriorQoI& original )
: QoIBase(original.name())
{
if (original.qoi_functional.get())
this->qoi_functional = original.qoi_functional->clone();
}
ParsedInteriorQoI::~ParsedInteriorQoI() {}
QoIBase* ParsedInteriorQoI::clone() const
{
return new ParsedInteriorQoI( *this );
}
void ParsedInteriorQoI::init( const GetPot& input, const MultiphysicsSystem& system )
{
std::string qoi_functional_string =
input("QoI/ParsedInterior/qoi_functional", std::string("0"));
if (qoi_functional_string == "0")
libmesh_error_msg("Error! Zero ParsedInteriorQoI specified!" <<
std::endl);
this->qoi_functional.reset
(new libMesh::ParsedFEMFunction<libMesh::Number>
(system, qoi_functional_string));
}
void ParsedInteriorQoI::init_context( AssemblyContext& context )
{
libMesh::FEBase* element_fe;
context.get_element_fe<libMesh::Real>(0, element_fe);
element_fe->get_JxW();
element_fe->get_xyz();
qoi_functional->init_context(context);
}
void ParsedInteriorQoI::element_qoi( AssemblyContext& context,
const unsigned int qoi_index )
{
libMesh::FEBase* element_fe;
context.get_element_fe<libMesh::Real>(0, element_fe);
const std::vector<libMesh::Real> &JxW = element_fe->get_JxW();
const std::vector<libMesh::Point>& x_qp = element_fe->get_xyz();
unsigned int n_qpoints = context.get_element_qrule().n_points();
/*! \todo Need to generalize this to the multiple QoI case */
libMesh::Number& qoi = context.get_qois()[qoi_index];
for( unsigned int qp = 0; qp != n_qpoints; qp++ )
{
const libMesh::Number func_val =
(*qoi_functional)(context, x_qp[qp], context.get_time());
qoi += func_val;
}
}
void ParsedInteriorQoI::element_qoi_derivative( AssemblyContext& context,
const unsigned int qoi_index )
{
libMesh::FEBase* element_fe;
context.get_element_fe<libMesh::Real>(0, element_fe);
const std::vector<libMesh::Real> &JxW = element_fe->get_JxW();
const std::vector<libMesh::Point>& x_qp = element_fe->get_xyz();
// Local DOF count and quadrature point count
const unsigned int n_u_dofs = context.get_dof_indices().size();
unsigned int n_qpoints = context.get_element_qrule().n_points();
// Local solution vector - non-const version for finite
// differenting purposes
libMesh::DenseVector<libMesh::Number>& elem_solution =
const_cast<libMesh::DenseVector<libMesh::Number>&>
(context.get_elem_solution());
/*! \todo Need to generalize this to the multiple QoI case */
libMesh::DenseVector<libMesh::Number> &Qu =
context.get_qoi_derivatives()[qoi_index];
for( unsigned int qp = 0; qp != n_qpoints; qp++ )
{
// Central finite differencing to approximate derivatives.
// FIXME - we should hook the FParserAD stuff into
// ParsedFEMFunction
for( unsigned int i = 0; i != n_u_dofs; ++i )
{
libMesh::Number ¤t_solution = elem_solution(i);
const libMesh::Number original_solution = current_solution;
current_solution = original_solution + libMesh::TOLERANCE;
const libMesh::Number plus_val =
(*qoi_functional)(context, x_qp[qp], context.get_time());
current_solution = original_solution - libMesh::TOLERANCE;
const libMesh::Number minus_val =
(*qoi_functional)(context, x_qp[qp], context.get_time());
Qu(i) += (plus_val - minus_val) * (0.5 / libMesh::TOLERANCE);
// Don't forget to restore the correct solution...
current_solution = original_solution;
}
}
}
} //namespace GRINS
<|endoftext|>
|
<commit_before>// Qt includes
#include <QtGui>
#include <QApplication>
// Local includes
#include "FluoroPredViz.h"
// VTK includes
#include <QVTKOpenGLWidget.h>
int main(int argc, char** argv)
{
QSurfaceFormat::setDefaultFormat(QVTKOpenGLWidget::defaultFormat());
QApplication a(argc, argv);
FluoroPredViz* w = new FluoroPredViz();
if (w->GetSuccessInit())
{
w->show();
}
else
{
return 0;
}
return a.exec();
}<commit_msg>Removing missed patch change<commit_after>// Qt includes
#include <QtGui>
#include <QApplication>
// Local includes
#include "FluoroPredViz.h"
int main(int argc, char** argv)
{
QApplication a(argc, argv);
FluoroPredViz* w = new FluoroPredViz();
if (w->GetSuccessInit())
{
w->show();
}
else
{
return 0;
}
return a.exec();
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
// Because of the -Wundef flag we have to do this
#define __LIBELF_INTERNAL__ 0
#define __LIBELF64_LINUX 1
#define __LIBELF_NEED_LINK_H 0
#include <libelf/libelf.h>
#include <libelf/gelf.h>
#include "base/loader/elf_object.hh"
#include "mem/functional_mem/functional_memory.hh"
#include "base/loader/symtab.hh"
#include "base/trace.hh" // for DPRINTF
using namespace std;
ObjectFile *
ElfObject::tryFile(const string &fname, int fd, size_t len, uint8_t *data)
{
Elf *elf;
GElf_Ehdr ehdr;
// check that header matches library version
assert(elf_version(EV_CURRENT) != EV_NONE);
// get a pointer to elf structure
elf = elf_memory((char*)data,len);
// will only fail if fd is invalid
assert(elf != NULL);
// Check that we actually have a elf file
if (gelf_getehdr(elf, &ehdr) ==0) {
DPRINTFR(Loader, "Not ELF\n");
elf_end(elf);
return NULL;
}
else {
if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
panic("32 bit ELF Binary, Not Supported");
if (ehdr.e_machine != EM_ALPHA)
panic("Non Alpha Binary, Not Supported");
elf_end(elf);
return new ElfObject(fname, fd, len, data,
ObjectFile::Alpha, ObjectFile::Linux);
}
}
ElfObject::ElfObject(const string &_filename, int _fd,
size_t _len, uint8_t *_data,
Arch _arch, OpSys _opSys)
: ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
{
Elf *elf;
GElf_Ehdr ehdr;
// check that header matches library version
assert(elf_version(EV_CURRENT) != EV_NONE);
// get a pointer to elf structure
elf = elf_memory((char*)fileData,len);
// will only fail if fd is invalid
assert(elf != NULL);
// Check that we actually have a elf file
if (gelf_getehdr(elf, &ehdr) ==0) {
panic("Not ELF, shouldn't be here");
}
entry = ehdr.e_entry;
// initialize segment sizes to 0 in case they're not present
text.size = data.size = bss.size = 0;
for (int i = 0; i < ehdr.e_phnum; ++i) {
GElf_Phdr phdr;
if (gelf_getphdr(elf, i, &phdr) == 0) {
panic("gelf_getphdr failed for section %d", i);
}
// for now we don't care about non-loadable segments
if (!(phdr.p_type & PT_LOAD))
continue;
// the headers don't explicitly distinguish text from data,
// but empirically the text segment comes first.
if (text.size == 0) { // haven't seen text segment yet
text.baseAddr = phdr.p_vaddr;
text.size = phdr.p_filesz;
// remember where the data is for loadSections()
fileTextBits = fileData + phdr.p_offset;
// if there's any padding at the end that's not in the
// file, call it the bss. This happens in the "text"
// segment if there's only one loadable segment (as for
// kernel images).
bss.size = phdr.p_memsz - phdr.p_filesz;
bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
}
else if (data.size == 0) { // have text, this must be data
data.baseAddr = phdr.p_vaddr;
data.size = phdr.p_filesz;
// remember where the data is for loadSections()
fileDataBits = fileData + phdr.p_offset;
// if there's any padding at the end that's not in the
// file, call it the bss. Warn if this happens for both
// the text & data segments (should only have one bss).
if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
warn("Two implied bss segments in file!\n");
}
bss.size = phdr.p_memsz - phdr.p_filesz;
bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
}
}
// should have found at least one loadable segment
assert(text.size != 0);
DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
text.baseAddr, text.size, data.baseAddr, data.size,
bss.baseAddr, bss.size);
elf_end(elf);
// We will actually read the sections when we need to load them
}
bool
ElfObject::loadSections(FunctionalMemory *mem, bool loadPhys)
{
Addr textAddr = text.baseAddr;
Addr dataAddr = data.baseAddr;
if (loadPhys) {
textAddr &= (ULL(1) << 40) - 1;
dataAddr &= (ULL(1) << 40) - 1;
}
// Since we don't really have an MMU and all memory is
// zero-filled, there's no need to set up the BSS segment.
if (text.size != 0)
mem->prot_write(textAddr, fileTextBits, text.size);
if (data.size != 0)
mem->prot_write(dataAddr, fileDataBits, data.size);
return true;
}
bool
ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
{
Elf *elf;
int secidx = 1; // there is a 0 but it is nothing, go figure
Elf_Scn *section;
GElf_Shdr shdr;
Elf_Data *data;
int count, ii;
bool found = false;
GElf_Sym sym;
if (!symtab)
return false;
// check that header matches library version
assert(elf_version(EV_CURRENT) != EV_NONE);
// get a pointer to elf structure
elf = elf_memory((char*)fileData,len);
assert(elf != NULL);
// Get the first section
section = elf_getscn(elf, secidx);
// While there are no more sections
while (section != NULL) {
gelf_getshdr(section, &shdr);
if (shdr.sh_type == SHT_SYMTAB) {
found = true;
data = elf_getdata(section, NULL);
count = shdr.sh_size / shdr.sh_entsize;
DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
// loop through all the symbols, only loading global ones
for (ii = 0; ii < count; ++ii) {
gelf_getsym(data, ii, &sym);
if (GELF_ST_BIND(sym.st_info) & binding) {
symtab->insert(sym.st_value,
elf_strptr(elf, shdr.sh_link, sym.st_name));
}
}
}
++secidx;
section = elf_getscn(elf, secidx);
}
elf_end(elf);
return found;
}
bool
ElfObject::loadGlobalSymbols(SymbolTable *symtab)
{
return loadSomeSymbols(symtab, STB_GLOBAL);
}
bool
ElfObject::loadLocalSymbols(SymbolTable *symtab)
{
return loadSomeSymbols(symtab, STB_LOCAL);
}
<commit_msg>Set LIBELF_LINUX to 0 to build on zax. Builds but did not test... however the only thing this affects in libelf is the header, so I don't expect any functional problems.<commit_after>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
// Because of the -Wundef flag we have to do this
#define __LIBELF_INTERNAL__ 0
// counterintuitive, but the flag below causes libelf to define
// 64-bit elf types that apparently didn't exist in some older
// versions of Linux. They seem to be there in 2.4.x, so don't
// set this now (it causes things to break on 64-bit platforms).
#define __LIBELF64_LINUX 0
#define __LIBELF_NEED_LINK_H 0
#include <libelf/libelf.h>
#include <libelf/gelf.h>
#include "base/loader/elf_object.hh"
#include "mem/functional_mem/functional_memory.hh"
#include "base/loader/symtab.hh"
#include "base/trace.hh" // for DPRINTF
using namespace std;
ObjectFile *
ElfObject::tryFile(const string &fname, int fd, size_t len, uint8_t *data)
{
Elf *elf;
GElf_Ehdr ehdr;
// check that header matches library version
assert(elf_version(EV_CURRENT) != EV_NONE);
// get a pointer to elf structure
elf = elf_memory((char*)data,len);
// will only fail if fd is invalid
assert(elf != NULL);
// Check that we actually have a elf file
if (gelf_getehdr(elf, &ehdr) ==0) {
DPRINTFR(Loader, "Not ELF\n");
elf_end(elf);
return NULL;
}
else {
if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
panic("32 bit ELF Binary, Not Supported");
if (ehdr.e_machine != EM_ALPHA)
panic("Non Alpha Binary, Not Supported");
elf_end(elf);
return new ElfObject(fname, fd, len, data,
ObjectFile::Alpha, ObjectFile::Linux);
}
}
ElfObject::ElfObject(const string &_filename, int _fd,
size_t _len, uint8_t *_data,
Arch _arch, OpSys _opSys)
: ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
{
Elf *elf;
GElf_Ehdr ehdr;
// check that header matches library version
assert(elf_version(EV_CURRENT) != EV_NONE);
// get a pointer to elf structure
elf = elf_memory((char*)fileData,len);
// will only fail if fd is invalid
assert(elf != NULL);
// Check that we actually have a elf file
if (gelf_getehdr(elf, &ehdr) ==0) {
panic("Not ELF, shouldn't be here");
}
entry = ehdr.e_entry;
// initialize segment sizes to 0 in case they're not present
text.size = data.size = bss.size = 0;
for (int i = 0; i < ehdr.e_phnum; ++i) {
GElf_Phdr phdr;
if (gelf_getphdr(elf, i, &phdr) == 0) {
panic("gelf_getphdr failed for section %d", i);
}
// for now we don't care about non-loadable segments
if (!(phdr.p_type & PT_LOAD))
continue;
// the headers don't explicitly distinguish text from data,
// but empirically the text segment comes first.
if (text.size == 0) { // haven't seen text segment yet
text.baseAddr = phdr.p_vaddr;
text.size = phdr.p_filesz;
// remember where the data is for loadSections()
fileTextBits = fileData + phdr.p_offset;
// if there's any padding at the end that's not in the
// file, call it the bss. This happens in the "text"
// segment if there's only one loadable segment (as for
// kernel images).
bss.size = phdr.p_memsz - phdr.p_filesz;
bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
}
else if (data.size == 0) { // have text, this must be data
data.baseAddr = phdr.p_vaddr;
data.size = phdr.p_filesz;
// remember where the data is for loadSections()
fileDataBits = fileData + phdr.p_offset;
// if there's any padding at the end that's not in the
// file, call it the bss. Warn if this happens for both
// the text & data segments (should only have one bss).
if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
warn("Two implied bss segments in file!\n");
}
bss.size = phdr.p_memsz - phdr.p_filesz;
bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
}
}
// should have found at least one loadable segment
assert(text.size != 0);
DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
text.baseAddr, text.size, data.baseAddr, data.size,
bss.baseAddr, bss.size);
elf_end(elf);
// We will actually read the sections when we need to load them
}
bool
ElfObject::loadSections(FunctionalMemory *mem, bool loadPhys)
{
Addr textAddr = text.baseAddr;
Addr dataAddr = data.baseAddr;
if (loadPhys) {
textAddr &= (ULL(1) << 40) - 1;
dataAddr &= (ULL(1) << 40) - 1;
}
// Since we don't really have an MMU and all memory is
// zero-filled, there's no need to set up the BSS segment.
if (text.size != 0)
mem->prot_write(textAddr, fileTextBits, text.size);
if (data.size != 0)
mem->prot_write(dataAddr, fileDataBits, data.size);
return true;
}
bool
ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
{
Elf *elf;
int secidx = 1; // there is a 0 but it is nothing, go figure
Elf_Scn *section;
GElf_Shdr shdr;
Elf_Data *data;
int count, ii;
bool found = false;
GElf_Sym sym;
if (!symtab)
return false;
// check that header matches library version
assert(elf_version(EV_CURRENT) != EV_NONE);
// get a pointer to elf structure
elf = elf_memory((char*)fileData,len);
assert(elf != NULL);
// Get the first section
section = elf_getscn(elf, secidx);
// While there are no more sections
while (section != NULL) {
gelf_getshdr(section, &shdr);
if (shdr.sh_type == SHT_SYMTAB) {
found = true;
data = elf_getdata(section, NULL);
count = shdr.sh_size / shdr.sh_entsize;
DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
// loop through all the symbols, only loading global ones
for (ii = 0; ii < count; ++ii) {
gelf_getsym(data, ii, &sym);
if (GELF_ST_BIND(sym.st_info) & binding) {
symtab->insert(sym.st_value,
elf_strptr(elf, shdr.sh_link, sym.st_name));
}
}
}
++secidx;
section = elf_getscn(elf, secidx);
}
elf_end(elf);
return found;
}
bool
ElfObject::loadGlobalSymbols(SymbolTable *symtab)
{
return loadSomeSymbols(symtab, STB_GLOBAL);
}
bool
ElfObject::loadLocalSymbols(SymbolTable *symtab)
{
return loadSomeSymbols(symtab, STB_LOCAL);
}
<|endoftext|>
|
<commit_before><commit_msg>Rename rts to rendertargets<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2006-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.
// Tests for Watchdog class.
#include "base/platform_thread.h"
#include "base/spin_wait.h"
#include "base/time.h"
#include "base/watchdog.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
namespace {
//------------------------------------------------------------------------------
// Provide a derived class to facilitate testing.
class WatchdogCounter : public Watchdog {
public:
WatchdogCounter(const TimeDelta& duration,
const std::string& thread_watched_name,
bool enabled)
: Watchdog(duration, thread_watched_name, enabled), alarm_counter_(0) {
}
virtual ~WatchdogCounter() {}
virtual void Alarm() {
alarm_counter_++;
Watchdog::Alarm();
}
int alarm_counter() { return alarm_counter_; }
private:
int alarm_counter_;
DISALLOW_COPY_AND_ASSIGN(WatchdogCounter);
};
class WatchdogTest : public testing::Test {
public:
void SetUp() {
Watchdog::ResetStaticData();
}
};
//------------------------------------------------------------------------------
// Actual tests
// Minimal constructor/destructor test.
TEST_F(WatchdogTest, StartupShutdownTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
}
// Test ability to call Arm and Disarm repeatedly.
TEST_F(WatchdogTest, ArmDisarmTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
watchdog1.Arm();
watchdog1.Disarm();
watchdog1.Arm();
watchdog1.Disarm();
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
watchdog2.Arm();
watchdog2.Disarm();
watchdog2.Arm();
watchdog2.Disarm();
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Enabled", true);
watchdog.Arm();
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmPriorTimeTest) {
WatchdogCounter watchdog(TimeDelta::TimeDelta(), "Enabled2", true);
// Set a time in the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(2));
// It should instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a disable alarm does nothing, even if we arm it.
TEST_F(WatchdogTest, ConstructorDisabledTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Disabled", false);
watchdog.Arm();
// Alarm should not fire, as it was disabled.
PlatformThread::Sleep(500);
EXPECT_EQ(0, watchdog.alarm_counter());
}
// Make sure Disarming will prevent firing, even after Arming.
TEST_F(WatchdogTest, DisarmTest) {
WatchdogCounter watchdog(TimeDelta::FromSeconds(5), "Enabled3", true);
watchdog.Arm();
PlatformThread::Sleep(100); // Don't sleep too long
watchdog.Disarm();
// Alarm should not fire.
PlatformThread::Sleep(5500);
EXPECT_EQ(0, watchdog.alarm_counter());
// ...but even after disarming, we can still use the alarm...
// Set a time greater than the timeout into the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(10));
// It should almost instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
} // namespace
<commit_msg>base_unittests: cut a sleep down to 1 second by being more careful about time.<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.
// Tests for Watchdog class.
#include "base/watchdog.h"
#include "base/logging.h"
#include "base/platform_thread.h"
#include "base/spin_wait.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
//------------------------------------------------------------------------------
// Provide a derived class to facilitate testing.
class WatchdogCounter : public Watchdog {
public:
WatchdogCounter(const TimeDelta& duration,
const std::string& thread_watched_name,
bool enabled)
: Watchdog(duration, thread_watched_name, enabled), alarm_counter_(0) {
}
virtual ~WatchdogCounter() {}
virtual void Alarm() {
alarm_counter_++;
Watchdog::Alarm();
}
int alarm_counter() { return alarm_counter_; }
private:
int alarm_counter_;
DISALLOW_COPY_AND_ASSIGN(WatchdogCounter);
};
class WatchdogTest : public testing::Test {
public:
void SetUp() {
Watchdog::ResetStaticData();
}
};
//------------------------------------------------------------------------------
// Actual tests
// Minimal constructor/destructor test.
TEST_F(WatchdogTest, StartupShutdownTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
}
// Test ability to call Arm and Disarm repeatedly.
TEST_F(WatchdogTest, ArmDisarmTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
watchdog1.Arm();
watchdog1.Disarm();
watchdog1.Arm();
watchdog1.Disarm();
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
watchdog2.Arm();
watchdog2.Disarm();
watchdog2.Arm();
watchdog2.Disarm();
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Enabled", true);
watchdog.Arm();
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmPriorTimeTest) {
WatchdogCounter watchdog(TimeDelta::TimeDelta(), "Enabled2", true);
// Set a time in the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(2));
// It should instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a disable alarm does nothing, even if we arm it.
TEST_F(WatchdogTest, ConstructorDisabledTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Disabled", false);
watchdog.Arm();
// Alarm should not fire, as it was disabled.
PlatformThread::Sleep(500);
EXPECT_EQ(0, watchdog.alarm_counter());
}
// Make sure Disarming will prevent firing, even after Arming.
TEST_F(WatchdogTest, DisarmTest) {
WatchdogCounter watchdog(TimeDelta::FromSeconds(1), "Enabled3", true);
TimeTicks start = TimeTicks::Now();
watchdog.Arm();
PlatformThread::Sleep(100); // Sleep a bit, but not past the alarm point.
watchdog.Disarm();
TimeTicks end = TimeTicks::Now();
if (end - start > TimeDelta::FromMilliseconds(500)) {
LOG(WARNING) << "100ms sleep took over 500ms, making the results of this "
<< "timing-sensitive test suspicious. Aborting now.";
return;
}
// Alarm should not have fired before it was disarmed.
EXPECT_EQ(0, watchdog.alarm_counter());
// Sleep past the point where it would have fired if it wasn't disarmed,
// and verify that it didn't fire.
PlatformThread::Sleep(1000);
EXPECT_EQ(0, watchdog.alarm_counter());
// ...but even after disarming, we can still use the alarm...
// Set a time greater than the timeout into the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(10));
// It should almost instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
} // namespace
<|endoftext|>
|
<commit_before><commit_msg>Emulate glNamedBufferSubData<commit_after><|endoftext|>
|
<commit_before>// Created on: 1998-03-11
// Created by: Jean-Louis Frenkel
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#include <CDF.ixx>
#include <Standard_Failure.hxx>
// Unused :
#ifdef DEB
static void CDF_CheckStatus(int LicenseStatus) {
if (LicenseStatus != 0) {
switch (LicenseStatus) {
case 1: Standard_Failure::Raise("LICENSE_unauthorized"); break;
case 2: Standard_Failure::Raise("LICENSE_wrong_data"); break;
case 3: Standard_Failure::Raise("LICENSE_max_users"); break;
case 4: Standard_Failure::Raise("LICENSE_unspecified"); break;
case 5: Standard_Failure::Raise("LICENSE_pb_init"); break;
case 6: Standard_Failure::Raise("LICENSE_unspecified"); break;
case 7: Standard_Failure::Raise("LICENSE_cantopenfile"); break;
case 8: Standard_Failure::Raise("LICENSE_connexion"); break;
case 9: Standard_Failure::Raise("LICENSE_syntaxe"); break;
default: Standard_Failure::Raise("LICENSE_unspecified"); break;
}
}
}
#endif
void static CDF_InitApplication () {
static Standard_Boolean FirstApplication = Standard_True;
if(FirstApplication) {
FirstApplication = Standard_False;
}
}
void CDF::GetLicense(const Standard_Integer ){
CDF_InitApplication();
}
Standard_Boolean CDF::IsAvailable(const Standard_Integer ) {
CDF_InitApplication();
return Standard_True;
}
<commit_msg>[intel-warning-fix][old-declarators]<commit_after>// Created on: 1998-03-11
// Created by: Jean-Louis Frenkel
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#include <CDF.ixx>
#include <Standard_Failure.hxx>
// Unused :
#ifdef DEB
static void CDF_CheckStatus(int LicenseStatus) {
if (LicenseStatus != 0) {
switch (LicenseStatus) {
case 1: Standard_Failure::Raise("LICENSE_unauthorized"); break;
case 2: Standard_Failure::Raise("LICENSE_wrong_data"); break;
case 3: Standard_Failure::Raise("LICENSE_max_users"); break;
case 4: Standard_Failure::Raise("LICENSE_unspecified"); break;
case 5: Standard_Failure::Raise("LICENSE_pb_init"); break;
case 6: Standard_Failure::Raise("LICENSE_unspecified"); break;
case 7: Standard_Failure::Raise("LICENSE_cantopenfile"); break;
case 8: Standard_Failure::Raise("LICENSE_connexion"); break;
case 9: Standard_Failure::Raise("LICENSE_syntaxe"); break;
default: Standard_Failure::Raise("LICENSE_unspecified"); break;
}
}
}
#endif
static void CDF_InitApplication () {
static Standard_Boolean FirstApplication = Standard_True;
if(FirstApplication) {
FirstApplication = Standard_False;
}
}
void CDF::GetLicense(const Standard_Integer ){
CDF_InitApplication();
}
Standard_Boolean CDF::IsAvailable(const Standard_Integer ) {
CDF_InitApplication();
return Standard_True;
}
<|endoftext|>
|
<commit_before>/***
Copyright (C) 2013 Aniket Deole <aniket.deole@gmail.com>
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License version 2.1, as published
by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include <gtkmm/box.h>
#include <gtkmm/widget.h>
#include <gtkmm/stylecontext.h>
#include <gtkmm/cssprovider.h>
#include <gtkmm/styleprovider.h>
#include "windowbody.hh"
void addCss (Gtk::Widget* widget, std::string cssClass, std::string css) {
Glib::RefPtr<Gtk::StyleContext> context;
context = widget->get_style_context ();
widget->set_name (cssClass);
Glib::RefPtr<Gtk::CssProvider> provider = Gtk::CssProvider::create ();
provider->load_from_data (css);
context->add_provider (provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
context->add_class (cssClass);
}
WindowBody::WindowBody (bool homogeneous, int spacing, Gtk::PackOptions options, int padding) {
set_orientation (Gtk::ORIENTATION_VERTICAL);
mainToolbar = new MainToolbar ();
add (*mainToolbar);
Gtk::Box* body = Gtk::manage (new Gtk::Box (Gtk::ORIENTATION_HORIZONTAL, 0));
Gtk::Paned* paneOne = Gtk::manage (new Gtk::Paned (Gtk::ORIENTATION_HORIZONTAL));
addCss (paneOne, "paneOne", ".paneOne{ -GtkPaned-handle-size: 1px;}");
lpv = new LeftPaneView (false, 0, Gtk::PACK_SHRINK,0);
paneOne->pack1 (*lpv, false, false);
Gtk::Box* rightFrameOfPaneOne = Gtk::manage (new Gtk::Box (Gtk::ORIENTATION_HORIZONTAL, 0));
Gtk::Paned* paneTwo = Gtk::manage (new Gtk::Paned (Gtk::ORIENTATION_HORIZONTAL));
nlpv = new NoteListPaneView (false, 0, Gtk::PACK_SHRINK, 0);
paneTwo->pack1 (*nlpv, false, false);
npv = new NotePaneView (false, 0, Gtk::PACK_SHRINK, 0);
paneTwo->pack2 (*npv, true, false);
rightFrameOfPaneOne->pack_start (*paneTwo, true, true, 0);
paneOne->pack2 (*rightFrameOfPaneOne, true, false);
body->pack_start (*paneOne, true, true, 0);
pack_end (*body, Gtk::PACK_EXPAND_WIDGET, 0);
show_all ();
}
WindowBody::~WindowBody () {
}
void WindowBody::setApp (Notify* a) {
app = a;
app->lpv = lpv;
app->nlpv = nlpv;
app->npv = npv;
nlpv->setApp (app);
lpv->setApp (app);
npv->setApp (app);
mainToolbar->setApp (app);
}
void WindowBody::setDatabaseManager (DatabaseManager* d) {
dbm = d;
lpv->setDatabaseManager (d);
nlpv->setDatabaseManager (d);
npv->setDatabaseManager (d);
lpv->dbInitialized = true;
}
<commit_msg>Experimental changes for ubuntu.<commit_after>/***
Copyright (C) 2013 Aniket Deole <aniket.deole@gmail.com>
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License version 2.1, as published
by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
***/
#include <gtkmm/box.h>
#include <gtkmm/widget.h>
#include <gtkmm/stylecontext.h>
#include <gtkmm/cssprovider.h>
#include <gtkmm/styleprovider.h>
#include "windowbody.hh"
void addCss (Gtk::Widget* widget, std::string cssClass, std::string css) {
Glib::RefPtr<Gtk::StyleContext> context;
context = widget->get_style_context ();
widget->set_name (cssClass);
Glib::RefPtr<Gtk::CssProvider> provider = Gtk::CssProvider::create ();
provider->load_from_data (css);
context->add_provider (provider, GTK_STYLE_PROVIDER_PRIORITY_THEME);
context->add_class (cssClass);
}
WindowBody::WindowBody (bool homogeneous, int spacing, Gtk::PackOptions options, int padding) {
set_orientation (Gtk::ORIENTATION_VERTICAL);
mainToolbar = new MainToolbar ();
add (*mainToolbar);
Gtk::Box* body = Gtk::manage (new Gtk::Box (Gtk::ORIENTATION_HORIZONTAL, 0));
Gtk::Paned* paneOne = Gtk::manage (new Gtk::Paned (Gtk::ORIENTATION_HORIZONTAL));
addCss (paneOne, "paneOne", ".paneOne{ -GtkPaned-handle-size: 1px;}");
lpv = new LeftPaneView (false, 0, Gtk::PACK_SHRINK,0);
paneOne->pack1 (*lpv, false, false);
Gtk::Box* rightFrameOfPaneOne = Gtk::manage (new Gtk::Box (Gtk::ORIENTATION_HORIZONTAL, 0));
Gtk::Paned* paneTwo = Gtk::manage (new Gtk::Paned (Gtk::ORIENTATION_HORIZONTAL));
nlpv = new NoteListPaneView (false, 0, Gtk::PACK_SHRINK, 0);
paneTwo->pack1 (*nlpv, false, false);
npv = new NotePaneView (false, 0, Gtk::PACK_SHRINK, 0);
paneTwo->pack2 (*npv, true, false);
rightFrameOfPaneOne->pack_start (*paneTwo, true, true, 0);
paneOne->pack2 (*rightFrameOfPaneOne, true, false);
body->pack_start (*paneOne, true, true, 0);
pack_end (*body, Gtk::PACK_EXPAND_WIDGET, 0);
show_all ();
}
WindowBody::~WindowBody () {
}
void WindowBody::setApp (Notify* a) {
app = a;
app->lpv = lpv;
app->nlpv = nlpv;
app->npv = npv;
nlpv->setApp (app);
lpv->setApp (app);
npv->setApp (app);
mainToolbar->setApp (app);
}
void WindowBody::setDatabaseManager (DatabaseManager* d) {
dbm = d;
lpv->setDatabaseManager (d);
nlpv->setDatabaseManager (d);
npv->setDatabaseManager (d);
lpv->dbInitialized = true;
}
<|endoftext|>
|
<commit_before>
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataSet.h"
#include "vtkCompositeDataDisplayAttributes.h"
#include "vtkCompositePolyDataMapper2.h"
#include "vtkCullerCollection.h"
#include "vtkCylinderSource.h"
#include "vtkInformation.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkNew.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTimerLog.h"
#include "vtkTrivialProducer.h"
#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>
int TestCompositePolyDataMapper2(int argc, char* argv[])
{
bool interact = false;
for (int i = 1; i < argc; ++i)
{
if (!strcmp(argv[i], "-I"))
{
interact = true;
continue;
}
if (!strcmp(argv[i], "-T") ||
!strcmp(argv[i], "-V") ||
!strcmp(argv[i], "-D"))
{
++i;
continue;
}
cerr << argv[0] << " options:" << endl;
cerr << " -N: Number of actors" << endl;
}
vtkSmartPointer<vtkRenderWindow> win =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkRenderer> ren =
vtkSmartPointer<vtkRenderer>::New();
win->AddRenderer(ren);
win->SetInteractor(iren);
int resolution = 18;
vtkNew<vtkCylinderSource> cyl;
cyl->CappingOn();
cyl->SetRadius(0.2);
cyl->SetResolution(resolution);
vtkSmartPointer<vtkCompositePolyDataMapper2> mapper =
vtkSmartPointer<vtkCompositePolyDataMapper2>::New();
vtkNew<vtkCompositeDataDisplayAttributes> cdsa;
mapper->SetCompositeDataDisplayAttributes(cdsa.GetPointer());
// build a composite dataset
vtkNew<vtkMultiBlockDataSet> data;
// int blocksPerLevel[3] = {1,64,256};
int blocksPerLevel[3] = {1,32,64};
std::vector<vtkSmartPointer<vtkMultiBlockDataSet> > blocks;
blocks.push_back(data.GetPointer());
unsigned levelStart = 0;
unsigned levelEnd = 1;
int numLevels = sizeof(blocksPerLevel) / sizeof(blocksPerLevel[0]);
int numLeaves = 0;
int numNodes = 0;
vtkStdString blockName("Rolf");
for (int level = 1; level < numLevels; ++level)
{
int nblocks=blocksPerLevel[level];
for (unsigned parent = levelStart; parent < levelEnd; ++parent)
{
blocks[parent]->SetNumberOfBlocks(nblocks);
for (int block=0; block < nblocks; ++block, ++numNodes)
{
if (level == numLevels - 1)
{
vtkNew<vtkPolyData> child;
cyl->SetCenter(block*0.25, 0.0, parent*0.5);
cyl->Update();
child->DeepCopy(cyl->GetOutput(0));
blocks[parent]->SetBlock(
block, block % 2 ? NULL : child.GetPointer());
blocks[parent]->GetMetaData(block)->Set(
vtkCompositeDataSet::NAME(), blockName.c_str());
// test not setting it on some
if (block % 11)
{
mapper->SetBlockColor(parent+numLeaves+1,
vtkMath::HSVToRGB(0.8*block/nblocks, 0.2 + 0.8*((parent - levelStart) % 8)/7.0, 1.0));
mapper->SetBlockOpacity(parent+numLeaves, (block + 3) % 7 == 0 ? 0.3 : 1.0);
mapper->SetBlockVisibility(parent+numLeaves, (block % 7) != 0);
}
++numLeaves;
}
else
{
vtkNew<vtkMultiBlockDataSet> child;
blocks[parent]->SetBlock(block, child.GetPointer());
blocks.push_back(child.GetPointer());
}
}
}
levelStart = levelEnd;
levelEnd = static_cast<unsigned>(blocks.size());
}
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
mapper->SetInputData((vtkPolyData *)(data.GetPointer()));
actor->SetMapper(mapper);
ren->AddActor(actor);
win->SetSize(400,400);
ren->RemoveCuller(ren->GetCullers()->GetLastItem());
ren->ResetCamera();
vtkSmartPointer<vtkTimerLog> timer = vtkSmartPointer<vtkTimerLog>::New();
win->Render(); // get the window up
// modify the data to force a rebuild of OpenGL structs
// after rendering set one cylinder to white
mapper->SetBlockColor(1011,1.0,1.0,1.0);
mapper->SetBlockOpacity(1011,1.0);
mapper->SetBlockVisibility(1011,1.0);
timer->StartTimer();
win->Render();
timer->StopTimer();
cout << "First frame time: " << timer->GetElapsedTime() << "\n";
timer->StartTimer();
int numFrames = 2;
for (int i = 0; i <= numFrames; i++)
{
ren->GetActiveCamera()->Elevation(40.0/numFrames);
ren->GetActiveCamera()->Zoom(pow(2.0,1.0/numFrames));
ren->GetActiveCamera()->Roll(20.0/numFrames);
win->Render();
}
timer->StopTimer();
double t = timer->GetElapsedTime();
cout << "Avg Frame time: " << t/numFrames << " Frame Rate: " << numFrames / t << "\n";
int retVal = vtkRegressionTestImage( win.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<commit_msg>Fix compiler warning and increase test threshold<commit_after>
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataSet.h"
#include "vtkCompositeDataDisplayAttributes.h"
#include "vtkCompositePolyDataMapper2.h"
#include "vtkCullerCollection.h"
#include "vtkCylinderSource.h"
#include "vtkInformation.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkNew.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTimerLog.h"
#include "vtkTrivialProducer.h"
#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>
int TestCompositePolyDataMapper2(int argc, char* argv[])
{
vtkSmartPointer<vtkRenderWindow> win =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkRenderer> ren =
vtkSmartPointer<vtkRenderer>::New();
win->AddRenderer(ren);
win->SetInteractor(iren);
int resolution = 18;
vtkNew<vtkCylinderSource> cyl;
cyl->CappingOn();
cyl->SetRadius(0.2);
cyl->SetResolution(resolution);
vtkSmartPointer<vtkCompositePolyDataMapper2> mapper =
vtkSmartPointer<vtkCompositePolyDataMapper2>::New();
vtkNew<vtkCompositeDataDisplayAttributes> cdsa;
mapper->SetCompositeDataDisplayAttributes(cdsa.GetPointer());
// build a composite dataset
vtkNew<vtkMultiBlockDataSet> data;
// int blocksPerLevel[3] = {1,64,256};
int blocksPerLevel[3] = {1,32,64};
std::vector<vtkSmartPointer<vtkMultiBlockDataSet> > blocks;
blocks.push_back(data.GetPointer());
unsigned levelStart = 0;
unsigned levelEnd = 1;
int numLevels = sizeof(blocksPerLevel) / sizeof(blocksPerLevel[0]);
int numLeaves = 0;
int numNodes = 0;
vtkStdString blockName("Rolf");
for (int level = 1; level < numLevels; ++level)
{
int nblocks=blocksPerLevel[level];
for (unsigned parent = levelStart; parent < levelEnd; ++parent)
{
blocks[parent]->SetNumberOfBlocks(nblocks);
for (int block=0; block < nblocks; ++block, ++numNodes)
{
if (level == numLevels - 1)
{
vtkNew<vtkPolyData> child;
cyl->SetCenter(block*0.25, 0.0, parent*0.5);
cyl->Update();
child->DeepCopy(cyl->GetOutput(0));
blocks[parent]->SetBlock(
block, block % 2 ? NULL : child.GetPointer());
blocks[parent]->GetMetaData(block)->Set(
vtkCompositeDataSet::NAME(), blockName.c_str());
// test not setting it on some
if (block % 11)
{
mapper->SetBlockColor(parent+numLeaves+1,
vtkMath::HSVToRGB(0.8*block/nblocks, 0.2 + 0.8*((parent - levelStart) % 8)/7.0, 1.0));
mapper->SetBlockOpacity(parent+numLeaves, (block + 3) % 7 == 0 ? 0.3 : 1.0);
mapper->SetBlockVisibility(parent+numLeaves, (block % 7) != 0);
}
++numLeaves;
}
else
{
vtkNew<vtkMultiBlockDataSet> child;
blocks[parent]->SetBlock(block, child.GetPointer());
blocks.push_back(child.GetPointer());
}
}
}
levelStart = levelEnd;
levelEnd = static_cast<unsigned>(blocks.size());
}
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
mapper->SetInputData((vtkPolyData *)(data.GetPointer()));
actor->SetMapper(mapper);
ren->AddActor(actor);
win->SetSize(400,400);
ren->RemoveCuller(ren->GetCullers()->GetLastItem());
ren->ResetCamera();
vtkSmartPointer<vtkTimerLog> timer = vtkSmartPointer<vtkTimerLog>::New();
win->Render(); // get the window up
// modify the data to force a rebuild of OpenGL structs
// after rendering set one cylinder to white
mapper->SetBlockColor(1011,1.0,1.0,1.0);
mapper->SetBlockOpacity(1011,1.0);
mapper->SetBlockVisibility(1011,1.0);
timer->StartTimer();
win->Render();
timer->StopTimer();
cout << "First frame time: " << timer->GetElapsedTime() << "\n";
timer->StartTimer();
int numFrames = 2;
for (int i = 0; i <= numFrames; i++)
{
ren->GetActiveCamera()->Elevation(40.0/numFrames);
ren->GetActiveCamera()->Zoom(pow(2.0,1.0/numFrames));
ren->GetActiveCamera()->Roll(20.0/numFrames);
win->Render();
}
timer->StopTimer();
double t = timer->GetElapsedTime();
cout << "Avg Frame time: " << t/numFrames << " Frame Rate: " << numFrames / t << "\n";
int retVal = vtkRegressionTestImageThreshold( win.GetPointer(),15);
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------
#include <stdio.h>
#include <math.h>
#include <sstream>
#include <string>
#include <fstream>
#include <random>
#include <particle_simulator.hpp>
//------------------------------------------------------------------------
const PS::F64 CUTOFF_LENGTH = 3.0;
//------------------------------------------------------------------------
class ForceLJ {
public:
PS::F64vec force;
PS::F64 potential;
void clear() {
force = 0.0;
potential = 0.0;
}
};
//------------------------------------------------------------------------
class FPLJ {
public:
PS::S32 id;
PS::F64vec p;
PS::F64vec q;
PS::F64vec force;
PS::F64 potential;
PS::F64vec getPos() const {
return q;
}
void setPos(PS::F64vec nq) {
q = nq;
}
void copyFromForce(const ForceLJ & f) {
force = f.force;
potential = f.potential;
}
};
//------------------------------------------------------------------------
class EPLJ {
public:
PS::S32 id;
PS::F64vec q;
PS::F64vec getPos() const {
return q;
}
void setPos(const PS::F64vec & nq) {
q = nq;
}
PS::F64 getRSearch() const {
return CUTOFF_LENGTH;
}
void copyFromFP(const FPLJ & fp) {
id = fp.id;
q = fp.q;
}
};
//------------------------------------------------------------------------
class CalcForceLJ {
public:
void operator() (const EPLJ * epi, const PS::S32 ni,
const EPLJ * epj, const PS::S32 nj,
ForceLJ *force) {
const PS::F64 CL2 = CUTOFF_LENGTH*CUTOFF_LENGTH;
const PS::F64 CL6 = CL2*CL2*CL2;
const PS::F64 CL12 = CL6*CL6;
const PS::F64 C0 = - 4.0 * (1.0/CL12 - 1.0/CL6);
for (PS::S32 i = 0; i < ni; i++) {
force[i].force = 0.0;
force[i].potential = 0.0;
for (PS::S32 j = 0; j < nj; j++) {
if(epi[i].id == epj[j].id) continue;
PS::F64vec dq = epj[j].q - epi[i].q;
PS::F64 r2 = dq * dq;
PS::F64 r6 = r2*r2*r2;
PS::F64 r12 = r6 * r6;
if (r2 > CL2) continue;
PS::F64 df = (24.0 * r6 - 48.0) / (r6 * r6 * r2);
force[i].force += dq * df;
force[i].potential += (4.0 * (1.0 / r12 - 1.0 / r6) + C0)*0.5;
}
}
}
};
//------------------------------------------------------------------------
template<class Tpsys>
PS::F64
energy(const Tpsys &system){
PS::F64 e = 0.0;
const PS::S32 n = system.getNumberOfParticleLocal();
for(PS::S32 i = 0; i < n; i++) {
FPLJ a = system[i];
e += (a.p*a.p)*0.5;
e += a.potential;
}
return e;
}
//------------------------------------------------------------------------
template<class Tpsys>
void
drift(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].q += system[i].p * dt;
}
}
//------------------------------------------------------------------------
template<class Tpsys>
void
kick(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].p += system[i].force * dt;
}
}
//------------------------------------------------------------------------
int
main(int argc, char **argv) {
PS::Initialize(argc, argv);
PS::ParticleSystem<FPLJ> lj_system;
lj_system.initialize();
const PS::F64 L = 10;
PS::DomainInfo dinfo;
dinfo.initialize();
dinfo.setBoundaryCondition(PS::BOUNDARY_CONDITION_PERIODIC_XYZ);
dinfo.setPosRootDomain(PS::F64vec(0, 0, 0), PS::F64vec(L, L, L));
const int N = 2;
lj_system.setNumberOfParticleLocal(N);
lj_system[0].id = 0;
lj_system[0].p = PS::F64vec(1.0, 0.0, 0.0);
lj_system[0].q = PS::F64vec(2.5, 5.0, 5.0);
lj_system[1].id = 1;
lj_system[1].p = PS::F64vec(-1.0, 0.0, 0.0);
lj_system[1].q = PS::F64vec(7.5, 5.0, 5.0);
PS::TreeForForceShort<ForceLJ, EPLJ, EPLJ>::Gather tree_lj;
tree_lj.initialize(N);
const PS::F64 dt = 0.01;
PS::F64 s_time = 0.0;
const int LOOP = 1000;
for(int i=0;i<LOOP;i++){
drift(lj_system, dt*0.5);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
kick(lj_system, dt);
drift(lj_system, dt*0.5);
std::cout << s_time << " ";
std::cout << lj_system[0].q.x << " ";
std::cout << lj_system[1].q.x << " ";
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
std::cout << energy(lj_system) << " ";
std::cout << std::endl;
lj_system.adjustPositionIntoRootDomain(dinfo);
s_time += dt;
}
PS::Finalize();
}
//------------------------------------------------------------------------
<commit_msg>debug on bounrary condition<commit_after>//------------------------------------------------------------------------
#include <stdio.h>
#include <math.h>
#include <sstream>
#include <string>
#include <fstream>
#include <random>
#include <particle_simulator.hpp>
//------------------------------------------------------------------------
const PS::F64 CUTOFF_LENGTH = 3.0;
//------------------------------------------------------------------------
class ForceLJ {
public:
PS::F64vec force;
PS::F64 potential;
void clear() {
force = 0.0;
potential = 0.0;
}
};
//------------------------------------------------------------------------
class FPLJ {
public:
PS::S32 id;
PS::F64vec p;
PS::F64vec q;
PS::F64vec force;
PS::F64 potential;
PS::F64vec getPos() const {
return q;
}
void setPos(PS::F64vec nq) {
q = nq;
}
void copyFromForce(const ForceLJ & f) {
force = f.force;
potential = f.potential;
}
};
//------------------------------------------------------------------------
class EPLJ {
public:
PS::S32 id;
PS::F64vec q;
PS::F64vec getPos() const {
return q;
}
void setPos(const PS::F64vec & nq) {
q = nq;
}
PS::F64 getRSearch() const {
return CUTOFF_LENGTH;
}
void copyFromFP(const FPLJ & fp) {
id = fp.id;
q = fp.q;
}
};
//------------------------------------------------------------------------
class CalcForceLJ {
public:
void operator() (const EPLJ * epi, const PS::S32 ni,
const EPLJ * epj, const PS::S32 nj,
ForceLJ *force) {
const PS::F64 CL2 = CUTOFF_LENGTH*CUTOFF_LENGTH;
const PS::F64 CL6 = CL2*CL2*CL2;
const PS::F64 CL12 = CL6*CL6;
const PS::F64 C0 = - 4.0 * (1.0/CL12 - 1.0/CL6);
for (PS::S32 i = 0; i < ni; i++) {
force[i].force = 0.0;
force[i].potential = 0.0;
for (PS::S32 j = 0; j < nj; j++) {
if(epi[i].id == epj[j].id) continue;
PS::F64vec dq = epj[j].q - epi[i].q;
PS::F64 r2 = dq * dq;
PS::F64 r6 = r2*r2*r2;
PS::F64 r12 = r6 * r6;
if (r2 > CL2) continue;
PS::F64 df = (24.0 * r6 - 48.0) / (r6 * r6 * r2);
force[i].force += dq * df;
force[i].potential += (4.0 * (1.0 / r12 - 1.0 / r6) + C0)*0.5;
}
}
}
};
//------------------------------------------------------------------------
template<class Tpsys>
PS::F64
energy(const Tpsys &system){
PS::F64 e = 0.0;
const PS::S32 n = system.getNumberOfParticleLocal();
for(PS::S32 i = 0; i < n; i++) {
FPLJ a = system[i];
e += (a.p*a.p)*0.5;
e += a.potential;
}
return e;
}
//------------------------------------------------------------------------
template<class Tpsys>
void
drift(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].q += system[i].p * dt;
}
}
//------------------------------------------------------------------------
template<class Tpsys>
void
kick(Tpsys & system, const PS::F64 dt) {
const PS::S32 n = system.getNumberOfParticleLocal();
for (PS::S32 i = 0; i < n; i++) {
system[i].p += system[i].force * dt;
}
}
//------------------------------------------------------------------------
int
main(int argc, char **argv) {
PS::Initialize(argc, argv);
PS::ParticleSystem<FPLJ> lj_system;
lj_system.initialize();
const PS::F64 L = 10;
PS::DomainInfo dinfo;
dinfo.initialize();
dinfo.setBoundaryCondition(PS::BOUNDARY_CONDITION_PERIODIC_XYZ);
dinfo.setPosRootDomain(PS::F64vec(0, 0, 0), PS::F64vec(L, L, L));
const int N = 2;
lj_system.setNumberOfParticleLocal(N);
lj_system[0].id = 0;
lj_system[0].p = PS::F64vec(1.0, 0.0, 0.0);
lj_system[0].q = PS::F64vec(2.5, 5.0, 5.0);
lj_system[1].id = 1;
lj_system[1].p = PS::F64vec(-1.0, 0.0, 0.0);
lj_system[1].q = PS::F64vec(7.5, 5.0, 5.0);
PS::TreeForForceShort<ForceLJ, EPLJ, EPLJ>::Gather tree_lj;
tree_lj.initialize(N);
const PS::F64 dt = 0.01;
PS::F64 s_time = 0.0;
const int LOOP = 1000;
dinfo.decomposeDomainAll(lj_system);
for(int i=0;i<LOOP;i++){
/* 1st order
drift(lj_system, dt);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
kick(lj_system, dt);
*/
// 2nd order
drift(lj_system, dt*0.5);
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
kick(lj_system, dt);
drift(lj_system, dt*0.5);
std::cout << s_time << " ";
std::cout << lj_system[0].q.x << " ";
std::cout << lj_system[1].q.x << " ";
tree_lj.calcForceAllAndWriteBack(CalcForceLJ(), lj_system, dinfo);
std::cout << energy(lj_system) << " ";
std::cout << std::endl;
lj_system.adjustPositionIntoRootDomain(dinfo);
s_time += dt;
}
PS::Finalize();
}
//------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include "musicnetworktestthread.h"
#include "musicobject.h"
#include <QProcess>
#ifdef Q_OS_WIN
# ifdef Q_CC_MINGW
# include <winsock2.h>
# endif
# include <windows.h>
# include <cstdio>
# include <iphlpapi.h>
#elif defined Q_OS_UNIX
# include <ifaddrs.h>
# include <arpa/inet.h>
#endif
MusicNetworkTestThread::MusicNetworkTestThread(QObject *parent)
: QThread(parent)
{
m_run = false;
m_process = nullptr;
#ifdef Q_OS_UNIX
setAvailableNewtworkNames(QStringList("eth0"));
#endif
}
MusicNetworkTestThread::~MusicNetworkTestThread()
{
if(m_process)
{
m_process->kill();
}
delete m_process;
stopAndQuitThread();
}
void MusicNetworkTestThread::stopAndQuitThread()
{
if(isRunning())
{
m_run = false;
wait();
}
quit();
}
void MusicNetworkTestThread::setAvailableNewtworkNames(const QStringList &names)
{
m_names = names;
#ifdef Q_OS_UNIX
if(m_names.isEmpty())
{
return;
}
delete m_process;
m_process = new QProcess(this);
m_process->setProcessChannelMode(QProcess::MergedChannels);
connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(outputRecieved()));
QStringList arguments;
arguments << m_names.first() << "1";
m_process->start(MAKE_NETS_AL, arguments);
#endif
}
QStringList MusicNetworkTestThread::getAvailableNewtworkNames() const
{
return m_names;
}
QStringList MusicNetworkTestThread::getNewtworkNames() const
{
QStringList names;
#ifdef Q_OS_WIN
PMIB_IFTABLE m_pTable = nullptr;
DWORD m_dwAdapters = 0;
ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
if(uRetCode == ERROR_NOT_SUPPORTED)
{
return names;
}
if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
{
m_pTable = (PMIB_IFTABLE)new BYTE[65535];
}
GetIfTable(m_pTable, &m_dwAdapters, TRUE);
for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
{
MIB_IFROW Row = m_pTable->table[i];
std::string s(MReinterpret_cast(char const*, Row.bDescr));
QString qs = QString::fromStdString(s);
if((Row.dwType == 71 || Row.dwType == 6) && !names.contains(qs))
{
names << QString::fromStdString(s);
}
}
delete[] m_pTable;
#elif defined Q_OS_UNIX
struct ifaddrs *ifa = nullptr, *ifList;
if (getifaddrs(&ifList) < 0)
{
return QStringList();
}
for (ifa = ifList; ifa != nullptr; ifa = ifa->ifa_next)
{
if(ifa->ifa_addr->sa_family == AF_INET)
{
names << QString(ifa->ifa_name);
}
}
freeifaddrs(ifList);
#endif
return names;
}
void MusicNetworkTestThread::outputRecieved()
{
while(m_process->canReadLine())
{
QByteArray datas = m_process->readLine();
QStringList lists = QString(datas).split("|");
ulong upload = 0, download = 0;
if(lists.count() == 3)
{
download= lists[1].trimmed().toULong();
upload = lists[2].trimmed().toULong();
}
emit networkData(upload, download);
}
}
void MusicNetworkTestThread::start()
{
m_run = true;
QThread::start();
}
void MusicNetworkTestThread::run()
{
#ifdef Q_OS_WIN
PMIB_IFTABLE m_pTable = nullptr;
DWORD m_dwAdapters = 0;
ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
if(uRetCode == ERROR_NOT_SUPPORTED)
{
return;
}
if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
{
m_pTable = (PMIB_IFTABLE)new BYTE[65535];
}
DWORD dwLastIn = 0;
DWORD dwLastOut = 0;
DWORD dwBandIn = 0;
DWORD dwBandOut = 0;
while(m_run)
{
GetIfTable(m_pTable, &m_dwAdapters, TRUE);
DWORD dwInOctets = 0;
DWORD dwOutOctets = 0;
for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
{
MIB_IFROW Row = m_pTable->table[i];
std::string s(MReinterpret_cast(char const*, Row.bDescr));
if(Row.dwType == 71 && m_names.contains(QString::fromStdString(s)))
{
dwInOctets += Row.dwInOctets;
dwOutOctets += Row.dwOutOctets;
}
}
dwBandIn = dwInOctets - dwLastIn;
dwBandOut = dwOutOctets - dwLastOut;
if(dwLastIn <= 0)
{
dwBandIn = 0;
}
if (dwLastOut <= 0)
{
dwBandOut = 0;
}
dwLastIn = dwInOctets;
dwLastOut = dwOutOctets;
emit networkData(dwBandOut, dwBandIn);
sleep(1);
}
delete[] m_pTable;
#endif
}
<commit_msg>fix get all network interface name[210514]<commit_after>#include "musicnetworktestthread.h"
#include "musicobject.h"
#include <QProcess>
#ifdef Q_OS_WIN
# ifdef Q_CC_MINGW
# include <winsock2.h>
# endif
# include <windows.h>
# include <cstdio>
# include <iphlpapi.h>
#elif defined Q_OS_UNIX
# include <ifaddrs.h>
# include <arpa/inet.h>
#endif
MusicNetworkTestThread::MusicNetworkTestThread(QObject *parent)
: QThread(parent)
{
m_run = false;
m_process = nullptr;
#ifdef Q_OS_UNIX
setAvailableNewtworkNames(QStringList("eth0"));
#endif
}
MusicNetworkTestThread::~MusicNetworkTestThread()
{
if(m_process)
{
m_process->kill();
}
delete m_process;
stopAndQuitThread();
}
void MusicNetworkTestThread::stopAndQuitThread()
{
if(isRunning())
{
m_run = false;
wait();
}
quit();
}
void MusicNetworkTestThread::setAvailableNewtworkNames(const QStringList &names)
{
m_names = names;
#ifdef Q_OS_UNIX
if(m_names.isEmpty())
{
return;
}
delete m_process;
m_process = new QProcess(this);
m_process->setProcessChannelMode(QProcess::MergedChannels);
connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(outputRecieved()));
QStringList arguments;
arguments << m_names.first() << "1";
m_process->start(MAKE_NETS_AL, arguments);
#endif
}
QStringList MusicNetworkTestThread::getAvailableNewtworkNames() const
{
return m_names;
}
QStringList MusicNetworkTestThread::getNewtworkNames() const
{
QStringList names;
#ifdef Q_OS_WIN
PMIB_IFTABLE m_pTable = nullptr;
DWORD m_dwAdapters = 0;
ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
if(uRetCode == ERROR_NOT_SUPPORTED)
{
return names;
}
if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
{
m_pTable = (PMIB_IFTABLE)new BYTE[65535];
}
GetIfTable(m_pTable, &m_dwAdapters, TRUE);
for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
{
MIB_IFROW Row = m_pTable->table[i];
std::string s(MReinterpret_cast(char const*, Row.bDescr));
QString qs = QString::fromStdString(s);
if((Row.dwType == 71 || Row.dwType == 6) && !names.contains(qs))
{
names << qs;
}
}
delete[] m_pTable;
#elif defined Q_OS_UNIX
struct ifaddrs *ifa = nullptr, *ifList;
if (getifaddrs(&ifList) < 0)
{
return QStringList();
}
for (ifa = ifList; ifa != nullptr; ifa = ifa->ifa_next)
{
if(ifa->ifa_addr->sa_family == AF_INET)
{
names << QString(ifa->ifa_name);
}
}
freeifaddrs(ifList);
#endif
return names;
}
void MusicNetworkTestThread::outputRecieved()
{
while(m_process->canReadLine())
{
QByteArray datas = m_process->readLine();
QStringList lists = QString(datas).split("|");
ulong upload = 0, download = 0;
if(lists.count() == 3)
{
download= lists[1].trimmed().toULong();
upload = lists[2].trimmed().toULong();
}
emit networkData(upload, download);
}
}
void MusicNetworkTestThread::start()
{
m_run = true;
QThread::start();
}
void MusicNetworkTestThread::run()
{
#ifdef Q_OS_WIN
PMIB_IFTABLE m_pTable = nullptr;
DWORD m_dwAdapters = 0;
ULONG uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
if(uRetCode == ERROR_NOT_SUPPORTED)
{
return;
}
if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
{
m_pTable = (PMIB_IFTABLE)new BYTE[65535];
}
DWORD dwLastIn = 0;
DWORD dwLastOut = 0;
DWORD dwBandIn = 0;
DWORD dwBandOut = 0;
while(m_run)
{
GetIfTable(m_pTable, &m_dwAdapters, TRUE);
DWORD dwInOctets = 0;
DWORD dwOutOctets = 0;
for(UINT i = 0; i < m_pTable->dwNumEntries; i++)
{
MIB_IFROW Row = m_pTable->table[i];
std::string s(MReinterpret_cast(char const*, Row.bDescr));
if(Row.dwType == 71 && m_names.contains(QString::fromStdString(s)))
{
dwInOctets += Row.dwInOctets;
dwOutOctets += Row.dwOutOctets;
}
}
dwBandIn = dwInOctets - dwLastIn;
dwBandOut = dwOutOctets - dwLastOut;
if(dwLastIn <= 0)
{
dwBandIn = 0;
}
if (dwLastOut <= 0)
{
dwBandOut = 0;
}
dwLastIn = dwInOctets;
dwLastOut = dwOutOctets;
emit networkData(dwBandOut, dwBandIn);
sleep(1);
}
delete[] m_pTable;
#endif
}
<|endoftext|>
|
<commit_before>#include "Channel.hpp"
#include "Message.hpp"
#include "Network.hpp"
#include "PawnDispatcher.hpp"
#include "CLog.hpp"
#include "Guild.hpp"
#include "utils.hpp"
#include "fmt/format.h"
#undef SendMessage // Windows at its finest
Channel::Channel(ChannelId_t pawn_id, json &data, GuildId_t guild_id) :
m_PawnId(pawn_id)
{
std::underlying_type<Type>::type type;
if (!utils::TryGetJsonValue(data, type, "type")
|| !utils::TryGetJsonValue(data, m_Id, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"type\" and \"id\" in \"{}\"", data.dump());
return;
}
m_Type = static_cast<Type>(type);
if (guild_id != 0)
{
m_GuildId = guild_id;
}
else
{
std::string guild_id;
if (utils::TryGetJsonValue(data, guild_id, "guild_id"))
{
Guild_t const &guild = GuildManager::Get()->FindGuildById(guild_id);
m_GuildId = guild->GetPawnId();
guild->AddChannel(pawn_id);
}
else
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"guild_id\" in \"{}\"", data.dump());
}
}
utils::TryGetJsonValue(data, m_Name, "name");
utils::TryGetJsonValue(data, m_Topic, "topic");
utils::TryGetJsonValue(data, m_Position, "position");
utils::TryGetJsonValue(data, m_IsNsfw, "nsfw");
}
void Channel::SendMessage(std::string &&msg)
{
json data = {
{ "content", std::move(msg) }
};
std::string json_str;
if(!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Post(fmt::format("/channels/{:s}/messages", GetId()), json_str);
}
void Channel::SetChannelName(std::string const &name)
{
json data = {
{ "name", name }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelTopic(std::string const &topic)
{
json data = {
{ "topic", topic }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelPosition(int const position)
{
json data = {
{ "position", position }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelNsfw(bool const is_nsfw)
{
json data = {
{ "nsfw", is_nsfw }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelParentCategory(Channel_t const &parent)
{
if (parent->GetType() != Type::GUILD_CATEGORY)
return;
json data = {
{ "parent_id", parent->GetId() }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::DeleteChannel()
{
Network::Get()->Http().Delete(fmt::format("/channels/{:s}", GetId()));
}
void ChannelManager::Initialize()
{
assert(m_Initialized != m_InitValue);
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_CREATE, [](json &data)
{
PawnDispatcher::Get()->Dispatch([data]() mutable
{
auto const channel_id = ChannelManager::Get()->AddChannel(data);
if (channel_id == INVALID_CHANNEL_ID)
return;
// forward DCC_OnChannelCreate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelCreate", channel_id);
});
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_UPDATE, [](json &data)
{
ChannelManager::Get()->UpdateChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_DELETE, [](json &data)
{
ChannelManager::Get()->DeleteChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data)
{
static const char *PRIVATE_CHANNEL_KEY = "private_channels";
if (utils::IsValidJson(data, PRIVATE_CHANNEL_KEY, json::value_t::array))
{
for (json &c : data.at(PRIVATE_CHANNEL_KEY))
AddChannel(c);
}
else
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"{}\" in \"{}\"", PRIVATE_CHANNEL_KEY, data.dump());
}
m_Initialized++;
});
}
bool ChannelManager::IsInitialized()
{
return m_Initialized == m_InitValue;
}
ChannelId_t ChannelManager::AddChannel(json &data, GuildId_t guild_id/* = 0*/)
{
std::underlying_type<Channel::Type>::type type_u;
if (!utils::TryGetJsonValue(data, type_u, "type"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"type\" in \"{}\"", data.dump());
return INVALID_CHANNEL_ID;
}
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return INVALID_CHANNEL_ID;
}
Channel_t const &channel = FindChannelById(sfid);
if (channel)
return INVALID_CHANNEL_ID; // channel already exists
ChannelId_t id = 1;
while (m_Channels.find(id) != m_Channels.end())
++id;
if (!m_Channels.emplace(id, Channel_t(new Channel(id, data, guild_id))).second)
{
CLog::Get()->Log(LogLevel::ERROR,
"can't create channel: duplicate key '{}'", id);
return INVALID_CHANNEL_ID;
}
CLog::Get()->Log(LogLevel::INFO, "successfully created channel with id '{}'", id);
return id;
}
void ChannelManager::UpdateChannel(json &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
CLog::Get()->Log(LogLevel::ERROR,
"can't update channel: channel id \"{}\" not cached", sfid);
return;
}
std::string name, topic;
int position;
bool is_nsfw;
bool
update_name = utils::TryGetJsonValue(data, name, "name"),
update_topic = utils::TryGetJsonValue(data, topic, "topic"),
update_position = utils::TryGetJsonValue(data, position, "position"),
update_nsfw = utils::TryGetJsonValue(data, is_nsfw, "nsfw");
PawnDispatcher::Get()->Dispatch([=, &channel]()
{
if (update_name && !name.empty())
channel->m_Name = name;
if (update_topic && !topic.empty())
channel->m_Topic = topic;
if (update_position)
channel->m_Position = position;
if (update_nsfw)
channel->m_IsNsfw = is_nsfw;
// forward DCC_OnChannelUpdate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelUpdate", channel->GetPawnId());
});
}
void ChannelManager::DeleteChannel(json &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
CLog::Get()->Log(LogLevel::ERROR,
"can't delete channel: channel id \"{}\" not cached", sfid);
return;
}
PawnDispatcher::Get()->Dispatch([this, &channel]()
{
// forward DCC_OnChannelDelete(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelDelete", channel->GetPawnId());
Guild_t const &guild = GuildManager::Get()->FindGuild(channel->GetGuildId());
if (guild)
guild->RemoveChannel(channel->GetPawnId());
m_Channels.erase(channel->GetPawnId());
});
}
Channel_t const &ChannelManager::FindChannel(ChannelId_t id)
{
static Channel_t invalid_channel;
auto it = m_Channels.find(id);
if (it == m_Channels.end())
return invalid_channel;
return it->second;
}
Channel_t const &ChannelManager::FindChannelByName(std::string const &name)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetName().compare(name) == 0)
return channel;
}
return invalid_channel;
}
Channel_t const &ChannelManager::FindChannelById(Snowflake_t const &sfid)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetId().compare(sfid) == 0)
return channel;
}
return invalid_channel;
}
<commit_msg>return channel id if it already exists<commit_after>#include "Channel.hpp"
#include "Message.hpp"
#include "Network.hpp"
#include "PawnDispatcher.hpp"
#include "CLog.hpp"
#include "Guild.hpp"
#include "utils.hpp"
#include "fmt/format.h"
#undef SendMessage // Windows at its finest
Channel::Channel(ChannelId_t pawn_id, json &data, GuildId_t guild_id) :
m_PawnId(pawn_id)
{
std::underlying_type<Type>::type type;
if (!utils::TryGetJsonValue(data, type, "type")
|| !utils::TryGetJsonValue(data, m_Id, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"type\" and \"id\" in \"{}\"", data.dump());
return;
}
m_Type = static_cast<Type>(type);
if (guild_id != 0)
{
m_GuildId = guild_id;
}
else
{
std::string guild_id;
if (utils::TryGetJsonValue(data, guild_id, "guild_id"))
{
Guild_t const &guild = GuildManager::Get()->FindGuildById(guild_id);
m_GuildId = guild->GetPawnId();
guild->AddChannel(pawn_id);
}
else
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"guild_id\" in \"{}\"", data.dump());
}
}
utils::TryGetJsonValue(data, m_Name, "name");
utils::TryGetJsonValue(data, m_Topic, "topic");
utils::TryGetJsonValue(data, m_Position, "position");
utils::TryGetJsonValue(data, m_IsNsfw, "nsfw");
}
void Channel::SendMessage(std::string &&msg)
{
json data = {
{ "content", std::move(msg) }
};
std::string json_str;
if(!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Post(fmt::format("/channels/{:s}/messages", GetId()), json_str);
}
void Channel::SetChannelName(std::string const &name)
{
json data = {
{ "name", name }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelTopic(std::string const &topic)
{
json data = {
{ "topic", topic }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelPosition(int const position)
{
json data = {
{ "position", position }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelNsfw(bool const is_nsfw)
{
json data = {
{ "nsfw", is_nsfw }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::SetChannelParentCategory(Channel_t const &parent)
{
if (parent->GetType() != Type::GUILD_CATEGORY)
return;
json data = {
{ "parent_id", parent->GetId() }
};
std::string json_str;
if (!utils::TryDumpJson(data, json_str))
CLog::Get()->Log(LogLevel::ERROR, "can't serialize JSON: {}", json_str);
Network::Get()->Http().Patch(fmt::format("/channels/{:s}", GetId()), json_str);
}
void Channel::DeleteChannel()
{
Network::Get()->Http().Delete(fmt::format("/channels/{:s}", GetId()));
}
void ChannelManager::Initialize()
{
assert(m_Initialized != m_InitValue);
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_CREATE, [](json &data)
{
PawnDispatcher::Get()->Dispatch([data]() mutable
{
auto const channel_id = ChannelManager::Get()->AddChannel(data);
if (channel_id == INVALID_CHANNEL_ID)
return;
// forward DCC_OnChannelCreate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelCreate", channel_id);
});
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_UPDATE, [](json &data)
{
ChannelManager::Get()->UpdateChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::CHANNEL_DELETE, [](json &data)
{
ChannelManager::Get()->DeleteChannel(data);
});
Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data)
{
static const char *PRIVATE_CHANNEL_KEY = "private_channels";
if (utils::IsValidJson(data, PRIVATE_CHANNEL_KEY, json::value_t::array))
{
for (json &c : data.at(PRIVATE_CHANNEL_KEY))
AddChannel(c);
}
else
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"{}\" in \"{}\"", PRIVATE_CHANNEL_KEY, data.dump());
}
m_Initialized++;
});
}
bool ChannelManager::IsInitialized()
{
return m_Initialized == m_InitValue;
}
ChannelId_t ChannelManager::AddChannel(json &data, GuildId_t guild_id/* = 0*/)
{
std::underlying_type<Channel::Type>::type type_u;
if (!utils::TryGetJsonValue(data, type_u, "type"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"type\" in \"{}\"", data.dump());
return INVALID_CHANNEL_ID;
}
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return INVALID_CHANNEL_ID;
}
Channel_t const &channel = FindChannelById(sfid);
if (channel)
return channel->GetPawnId(); // channel already exists
ChannelId_t id = 1;
while (m_Channels.find(id) != m_Channels.end())
++id;
if (!m_Channels.emplace(id, Channel_t(new Channel(id, data, guild_id))).second)
{
CLog::Get()->Log(LogLevel::ERROR,
"can't create channel: duplicate key '{}'", id);
return INVALID_CHANNEL_ID;
}
CLog::Get()->Log(LogLevel::INFO, "successfully added channel with id '{}'", id);
return id;
}
void ChannelManager::UpdateChannel(json &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
CLog::Get()->Log(LogLevel::ERROR,
"can't update channel: channel id \"{}\" not cached", sfid);
return;
}
std::string name, topic;
int position;
bool is_nsfw;
bool
update_name = utils::TryGetJsonValue(data, name, "name"),
update_topic = utils::TryGetJsonValue(data, topic, "topic"),
update_position = utils::TryGetJsonValue(data, position, "position"),
update_nsfw = utils::TryGetJsonValue(data, is_nsfw, "nsfw");
PawnDispatcher::Get()->Dispatch([=, &channel]()
{
if (update_name && !name.empty())
channel->m_Name = name;
if (update_topic && !topic.empty())
channel->m_Topic = topic;
if (update_position)
channel->m_Position = position;
if (update_nsfw)
channel->m_IsNsfw = is_nsfw;
// forward DCC_OnChannelUpdate(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelUpdate", channel->GetPawnId());
});
}
void ChannelManager::DeleteChannel(json &data)
{
Snowflake_t sfid;
if (!utils::TryGetJsonValue(data, sfid, "id"))
{
CLog::Get()->Log(LogLevel::ERROR,
"invalid JSON: expected \"id\" in \"{}\"", data.dump());
return;
}
Channel_t const &channel = FindChannelById(sfid);
if (!channel)
{
CLog::Get()->Log(LogLevel::ERROR,
"can't delete channel: channel id \"{}\" not cached", sfid);
return;
}
PawnDispatcher::Get()->Dispatch([this, &channel]()
{
// forward DCC_OnChannelDelete(DCC_Channel:channel);
pawn_cb::Error error;
pawn_cb::Callback::CallFirst(error, "DCC_OnChannelDelete", channel->GetPawnId());
Guild_t const &guild = GuildManager::Get()->FindGuild(channel->GetGuildId());
if (guild)
guild->RemoveChannel(channel->GetPawnId());
m_Channels.erase(channel->GetPawnId());
});
}
Channel_t const &ChannelManager::FindChannel(ChannelId_t id)
{
static Channel_t invalid_channel;
auto it = m_Channels.find(id);
if (it == m_Channels.end())
return invalid_channel;
return it->second;
}
Channel_t const &ChannelManager::FindChannelByName(std::string const &name)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetName().compare(name) == 0)
return channel;
}
return invalid_channel;
}
Channel_t const &ChannelManager::FindChannelById(Snowflake_t const &sfid)
{
static Channel_t invalid_channel;
for (auto const &c : m_Channels)
{
Channel_t const &channel = c.second;
if (channel->GetId().compare(sfid) == 0)
return channel;
}
return invalid_channel;
}
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ws_uplink.hpp"
#include "common.hpp"
#include <memdisk>
#ifndef RAPIDJSON_HAS_STDSTRING
#define RAPIDJSON_HAS_STDSTRING 1
#endif
#ifndef RAPIDJSON_THROWPARSEEXCEPTION
#define RAPIDJSON_THROWPARSEEXCEPTION 1
#endif
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <os>
#include <util/sha1.hpp>
namespace uplink {
const std::string WS_uplink::UPLINK_CFG_FILE{"config.json"};
void* UPDATE_LOC = (void*) 0x3200000; // at 50mb
WS_uplink::WS_uplink(net::Inet<net::IP4>& inet)
: id_{inet.link_addr().to_string()},
parser_({this, &WS_uplink::handle_transport})
{
Expects(inet.ip_addr() != 0 && "Network interface not configured");
read_config();
start(inet);
/*parser_.on_header = [](const auto& hdr) {
MYINFO("Header: Code: %u Len: %u", static_cast<uint8_t>(hdr.code), hdr.length);
};*/
}
void WS_uplink::start(net::Inet<net::IP4>& inet) {
MYINFO("Starting WS uplink on %s with ID: %s",
inet.ifname().c_str(), id_.c_str());
Expects(not config_.url.empty());
if(liu::LiveUpdate::is_resumable(UPDATE_LOC))
{
MYINFO("Found resumable state, try restoring...");
auto success = liu::LiveUpdate::resume(UPDATE_LOC, {this, &WS_uplink::restore});
CHECK(success, "Success");
}
client_ = std::make_unique<http::Client>(inet.tcp(),
http::Client::Request_handler{this, &WS_uplink::inject_token});
auth();
}
void WS_uplink::store(liu::Storage& store, const liu::buffer_t*)
{
liu::Storage::uid id = 0;
// BINARY HASH
store.add_string(id++, binary_hash_);
}
void WS_uplink::restore(liu::Restore& store)
{
// BINARY HASH
binary_hash_ = store.as_string(); store.go_next();
}
std::string WS_uplink::auth_data() const
{
return "{ \"id\": \"" + id_ + "\", \"key\": \"" + config_.token + "\"}";
}
void WS_uplink::auth()
{
std::string url{"http://"};
url.append(config_.url).append("/auth");
//static const std::string auth_data{"{ \"id\": \"testor\", \"key\": \"kappa123\"}"};
MYINFO("Sending auth request to %s", url.c_str());
client_->post(http::URI{url},
{ {"Content-Type", "application/json"} },
auth_data(),
{this, &WS_uplink::handle_auth_response});
}
void WS_uplink::handle_auth_response(http::Error err, http::Response_ptr res, http::Connection&)
{
if(err)
{
MYINFO("Auth failed - %s", err.to_string().c_str());
return;
}
if(res->status_code() != http::OK)
{
MYINFO("Auth failed - %s", res->to_string().c_str());
return;
}
MYINFO("Auth success (token received)");
token_ = res->body().to_string();
dock();
}
void WS_uplink::dock()
{
Expects(not token_.empty() and client_ != nullptr);
std::string url{"ws://"};
url.append(config_.url).append("/dock");
MYINFO("Dock attempt to %s", url.c_str());
net::WebSocket::connect(*client_, http::URI{url}, {this, &WS_uplink::establish_ws});
}
void WS_uplink::establish_ws(net::WebSocket_ptr ws)
{
if(ws == nullptr) {
MYINFO("Failed to establish websocket");
return;
}
ws_ = std::move(ws);
ws_->on_read = {this, &WS_uplink::parse_transport};
ws_->on_error = [](const auto& reason) {
MYINFO("(WS err) %s", reason.c_str());
};
MYINFO("Websocket established");
send_ident();
}
void WS_uplink::parse_transport(net::WebSocket::Message_ptr msg)
{
if(msg != nullptr) {
parser_.parse(msg->data(), msg->size());
}
else {
MYINFO("Malformed WS message, try to re-establish");
send_error("WebSocket error");
ws_->close();
ws_ = nullptr;
dock();
}
}
void WS_uplink::handle_transport(Transport_ptr t)
{
if(UNLIKELY(t == nullptr))
{
MYINFO("Something went terribly wrong...");
return;
}
MYINFO("New transport (%lu bytes)", t->size());
switch(t->code())
{
case Transport_code::UPDATE:
{
INFO2("Update received - commencing update...");
update({t->begin(), t->end()});
return;
}
default:
{
INFO2("Bad transport");
}
}
}
void WS_uplink::update(const std::vector<char>& buffer)
{
static SHA1 checksum;
checksum.update(buffer);
binary_hash_ = checksum.as_hex();
// send a reponse with the to tell we received the update
auto trans = Transport{Header{Transport_code::UPDATE, static_cast<uint32_t>(binary_hash_.size())}};
trans.load_cargo(binary_hash_.data(), binary_hash_.size());
ws_->write(trans.data().data(), trans.data().size());
ws_->close();
// do the update
Timers::oneshot(std::chrono::milliseconds(200), [this, buffer] (auto) {
liu::LiveUpdate::begin(UPDATE_LOC, buffer, {this, &WS_uplink::store});
});
}
void WS_uplink::read_config()
{
MYINFO("Reading uplink config from %s", UPLINK_CFG_FILE.c_str());
auto& disk = fs::memdisk();
if (not disk.fs_ready())
{
disk.init_fs([] (auto err, auto&) {
Expects(not err && "Error occured when mounting FS.");
});
}
auto cfg = disk.fs().stat(UPLINK_CFG_FILE); // name hardcoded for now
Expects(cfg.is_file() && "File not found.");
Expects(cfg.size() && "File is empty.");
auto content = cfg.read();
parse_config(content);
}
void WS_uplink::parse_config(const std::string& json)
{
using namespace rapidjson;
Document doc;
doc.Parse(json.data());
Expects(doc.IsObject() && "Malformed config");
Expects(doc.HasMember("uplink") && "Missing member \"uplink\"");
auto& cfg = doc["uplink"];
Expects(cfg.HasMember("url") && cfg.HasMember("token") && "Missing url or/and token");
config_.url = cfg["url"].GetString();
config_.token = cfg["token"].GetString();
}
void WS_uplink::send_ident()
{
MYINFO("Sending ident");
using namespace rapidjson;
StringBuffer buf;
Writer<StringBuffer> writer{buf};
writer.StartObject();
writer.Key("version");
writer.String(OS::version());
writer.Key("arch");
writer.String(OS::arch());
writer.Key("service");
writer.String(Service::name());
if(not binary_hash_.empty())
{
writer.Key("binary");
writer.String(binary_hash_);
}
writer.EndObject();
std::string str = buf.GetString();
auto transport = Transport{Header{Transport_code::IDENT, static_cast<uint32_t>(str.size())}};
transport.load_cargo(str.data(), str.size());
ws_->write(transport.data().data(), transport.data().size());
}
void WS_uplink::send_error(const std::string& err)
{
auto transport = Transport{Header{Transport_code::IDENT, static_cast<uint32_t>(err.size())}};
transport.load_cargo(err.data(), err.size());
ws_->write(transport.data().data(), transport.data().size());
}
}
<commit_msg>ws_uplink: serialize PCI devices with ident<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ws_uplink.hpp"
#include "common.hpp"
#include <memdisk>
#ifndef RAPIDJSON_HAS_STDSTRING
#define RAPIDJSON_HAS_STDSTRING 1
#endif
#ifndef RAPIDJSON_THROWPARSEEXCEPTION
#define RAPIDJSON_THROWPARSEEXCEPTION 1
#endif
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <os>
#include <util/sha1.hpp>
#include <kernel/pci_manager.hpp>
#include <hw/pci_device.hpp>
namespace uplink {
const std::string WS_uplink::UPLINK_CFG_FILE{"config.json"};
void* UPDATE_LOC = (void*) 0x3200000; // at 50mb
WS_uplink::WS_uplink(net::Inet<net::IP4>& inet)
: id_{inet.link_addr().to_string()},
parser_({this, &WS_uplink::handle_transport})
{
Expects(inet.ip_addr() != 0 && "Network interface not configured");
read_config();
start(inet);
/*parser_.on_header = [](const auto& hdr) {
MYINFO("Header: Code: %u Len: %u", static_cast<uint8_t>(hdr.code), hdr.length);
};*/
}
void WS_uplink::start(net::Inet<net::IP4>& inet) {
MYINFO("Starting WS uplink on %s with ID: %s",
inet.ifname().c_str(), id_.c_str());
Expects(not config_.url.empty());
if(liu::LiveUpdate::is_resumable(UPDATE_LOC))
{
MYINFO("Found resumable state, try restoring...");
auto success = liu::LiveUpdate::resume(UPDATE_LOC, {this, &WS_uplink::restore});
CHECK(success, "Success");
}
client_ = std::make_unique<http::Client>(inet.tcp(),
http::Client::Request_handler{this, &WS_uplink::inject_token});
auth();
}
void WS_uplink::store(liu::Storage& store, const liu::buffer_t*)
{
liu::Storage::uid id = 0;
// BINARY HASH
store.add_string(id++, binary_hash_);
}
void WS_uplink::restore(liu::Restore& store)
{
// BINARY HASH
binary_hash_ = store.as_string(); store.go_next();
}
std::string WS_uplink::auth_data() const
{
return "{ \"id\": \"" + id_ + "\", \"key\": \"" + config_.token + "\"}";
}
void WS_uplink::auth()
{
std::string url{"http://"};
url.append(config_.url).append("/auth");
//static const std::string auth_data{"{ \"id\": \"testor\", \"key\": \"kappa123\"}"};
MYINFO("Sending auth request to %s", url.c_str());
client_->post(http::URI{url},
{ {"Content-Type", "application/json"} },
auth_data(),
{this, &WS_uplink::handle_auth_response});
}
void WS_uplink::handle_auth_response(http::Error err, http::Response_ptr res, http::Connection&)
{
if(err)
{
MYINFO("Auth failed - %s", err.to_string().c_str());
return;
}
if(res->status_code() != http::OK)
{
MYINFO("Auth failed - %s", res->to_string().c_str());
return;
}
MYINFO("Auth success (token received)");
token_ = res->body().to_string();
dock();
}
void WS_uplink::dock()
{
Expects(not token_.empty() and client_ != nullptr);
std::string url{"ws://"};
url.append(config_.url).append("/dock");
MYINFO("Dock attempt to %s", url.c_str());
net::WebSocket::connect(*client_, http::URI{url}, {this, &WS_uplink::establish_ws});
}
void WS_uplink::establish_ws(net::WebSocket_ptr ws)
{
if(ws == nullptr) {
MYINFO("Failed to establish websocket");
return;
}
ws_ = std::move(ws);
ws_->on_read = {this, &WS_uplink::parse_transport};
ws_->on_error = [](const auto& reason) {
MYINFO("(WS err) %s", reason.c_str());
};
MYINFO("Websocket established");
send_ident();
}
void WS_uplink::parse_transport(net::WebSocket::Message_ptr msg)
{
if(msg != nullptr) {
parser_.parse(msg->data(), msg->size());
}
else {
MYINFO("Malformed WS message, try to re-establish");
send_error("WebSocket error");
ws_->close();
ws_ = nullptr;
dock();
}
}
void WS_uplink::handle_transport(Transport_ptr t)
{
if(UNLIKELY(t == nullptr))
{
MYINFO("Something went terribly wrong...");
return;
}
MYINFO("New transport (%lu bytes)", t->size());
switch(t->code())
{
case Transport_code::UPDATE:
{
INFO2("Update received - commencing update...");
update({t->begin(), t->end()});
return;
}
default:
{
INFO2("Bad transport");
}
}
}
void WS_uplink::update(const std::vector<char>& buffer)
{
static SHA1 checksum;
checksum.update(buffer);
binary_hash_ = checksum.as_hex();
// send a reponse with the to tell we received the update
auto trans = Transport{Header{Transport_code::UPDATE, static_cast<uint32_t>(binary_hash_.size())}};
trans.load_cargo(binary_hash_.data(), binary_hash_.size());
ws_->write(trans.data().data(), trans.data().size());
ws_->close();
// do the update
Timers::oneshot(std::chrono::milliseconds(200), [this, buffer] (auto) {
liu::LiveUpdate::begin(UPDATE_LOC, buffer, {this, &WS_uplink::store});
});
}
void WS_uplink::read_config()
{
MYINFO("Reading uplink config from %s", UPLINK_CFG_FILE.c_str());
auto& disk = fs::memdisk();
if (not disk.fs_ready())
{
disk.init_fs([] (auto err, auto&) {
Expects(not err && "Error occured when mounting FS.");
});
}
auto cfg = disk.fs().stat(UPLINK_CFG_FILE); // name hardcoded for now
Expects(cfg.is_file() && "File not found.");
Expects(cfg.size() && "File is empty.");
auto content = cfg.read();
parse_config(content);
}
void WS_uplink::parse_config(const std::string& json)
{
using namespace rapidjson;
Document doc;
doc.Parse(json.data());
Expects(doc.IsObject() && "Malformed config");
Expects(doc.HasMember("uplink") && "Missing member \"uplink\"");
auto& cfg = doc["uplink"];
Expects(cfg.HasMember("url") && cfg.HasMember("token") && "Missing url or/and token");
config_.url = cfg["url"].GetString();
config_.token = cfg["token"].GetString();
}
void WS_uplink::send_ident()
{
MYINFO("Sending ident");
using namespace rapidjson;
StringBuffer buf;
Writer<StringBuffer> writer{buf};
writer.StartObject();
writer.Key("version");
writer.String(OS::version());
writer.Key("service");
writer.String(Service::name());
if(not binary_hash_.empty())
{
writer.Key("binary");
writer.String(binary_hash_);
}
writer.Key("arch");
writer.String(OS::arch());
auto devices = PCI_manager::devices();
writer.Key("devices");
writer.StartArray();
for (auto* dev : devices) {
writer.String(dev->to_string());
}
writer.EndArray();
writer.EndObject();
std::string str = buf.GetString();
MYINFO("%s", str.c_str());
auto transport = Transport{Header{Transport_code::IDENT, static_cast<uint32_t>(str.size())}};
transport.load_cargo(str.data(), str.size());
ws_->write(transport.data().data(), transport.data().size());
}
void WS_uplink::send_error(const std::string& err)
{
auto transport = Transport{Header{Transport_code::IDENT, static_cast<uint32_t>(err.size())}};
transport.load_cargo(err.data(), err.size());
ws_->write(transport.data().data(), transport.data().size());
}
}
<|endoftext|>
|
<commit_before><commit_msg>Add check that the first 2 Loop subgraph inputs have an shape (could be explicit or inferred) as we need to know the rank the subgraph expects. Other inputs to the subgraph are more opaque so we can just pass them through. (#6891)<commit_after><|endoftext|>
|
<commit_before>//=============================================================================
// ■ map.cpp
//-----------------------------------------------------------------------------
// 地图类
//=============================================================================
#include "tiled_map.hpp"
#include "glm/gtc/noise.hpp"
namespace VM76 {
DataMap::DataMap(int w, int h, int l) {
constStone = {1, 0};
map = (TileData*) malloc(sizeof(TileData) * w * h * l);
width = w; length = l; height = h;
if (!read_map()) generate_V1();
}
void DataMap::generate_flat() {
for (int x = 0; x < width; x++)
for (int z = 0; z < length; z++)
for (int y = 0; y < height; y++) {
TileData t = map[calcIndex(x,y,z)];
t.tid = (y == 0) ? Grass : Air;
}
}
bool DataMap::read_map() {
log("Reading map");
VBinaryFileReader* fr = new VBinaryFileReader("map.dat");
if (!fr->f) return false;
int map_version = fr->read_i32();
if (fr->read_u8() == 'V' && fr->read_u8() == 'M'
&& fr->read_u8() == '7' && fr->read_u8() == '6') {
log("Map version : %d", map_version);
for (int x = 0; x < width * length * height; x++) {
if (x % (width * length * height / 7) == 0)
log("Map %d%% loaded", 100 * x / (width * length * height));
map[x].tid = fr->read_u8();
map[x].data_flag = fr->read_u8();
}
return true;
} else {
log("Invalid map.dat");
return false;
}
}
void DataMap::save_map() {
VBinaryFileWriter* fw = new VBinaryFileWriter("map.dat");
// 版本号
fw->write_i32(100);
// 文件头标识
fw->write_u8('V');
fw->write_u8('M');
fw->write_u8('7');
fw->write_u8('6');
for (int x = 0; x < width * length * height; x++) {
fw->write_u8(map[x].tid);
fw->write_u8(map[x].data_flag);
}
delete fw;
log("Map saved");
}
void DataMap::generate_V1() {
log("Start generating maps, %d x %d x %d", width, length, height);
for (int i = 0; i < width; i++) {
if (i % (width / 12) == 0)
log("Generated %d%% (%d / %d)",
(int) (100.0 / width * i),
i * length * height, width * length * height
);
for (int j = 0; j < length; j++) {
glm::vec2 coord = glm::vec2(i, j) * 0.006f;
const glm::mat2 rotate = glm::mat2(1.4, 1.1, -1.2, 1.4);
glm::vec2 dir = glm::vec2(1.0, 0.1);
float n = glm::sin(glm::perlin(coord * dir)) * 0.5f; coord *= 1.2f;dir = dir * rotate; coord += dir * 0.3f;
dir += glm::vec2(n * 0.8, 0.0);
n += glm::perlin(coord * dir) * 0.45f; dir = dir * rotate;
dir += glm::vec2(n * 0.6, 0.0);
n += glm::perlin(coord * dir) * 0.35f; dir = dir * rotate;
dir += glm::vec2(n * 0.4, 0.0);
n += glm::perlin(coord * dir) * 0.25f; dir = dir * rotate;
dir += glm::vec2(n * 0.2, 0.0);
coord *= 3.01f; dir = dir * rotate; coord += dir * 0.6f;
n += glm::perlin(coord) * 0.125f;
n = n + 0.5f;
n = glm::clamp(n * 0.7f + 0.2f, 1.0f / (float) TERRIAN_MAX_HEIGHT, 1.0f);
int h = n * TERRIAN_MAX_HEIGHT;
int ho = h;
h = glm::clamp(0, h, height);
for (int y = 0; y < h; y++) {
map[calcIndex(i,y,j)].tid = (y == ho - 1) ? Grass : Stone;
}
for (int y = h; y < height; y++) {
map[calcIndex(i,y,j)].tid = Air;
}
}
}
log("Generated 100%%, Complete");
}
Map::Map(int w, int h, int l, int csize) {
log("Init map with size %d, %d, %d in chunk size %d", w, l, h, csize);
CHUNK_SIZE = csize;
width = w; length = l; height = h;
bw = CHUNK_SIZE * w; bl = CHUNK_SIZE * l; bh = CHUNK_SIZE * h;
chunks = new TiledMap*[w * l * h];
map = new DataMap(bw, bh, bl);
for (int x = 0; x < length; x++) {
log("Baking Chunks: %d%% (%d / %d)",
(int) (100.0 / length * x),
x * width * height, width * length * height
);
for (int z = 0; z < width; z++)
for (int y = 0; y < height; y++) {
int ind = calcChunkIndex(x,y,z);
chunks[ind] = new TiledMap(
CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE,
glm::vec3(CHUNK_SIZE * x, CHUNK_SIZE * y, CHUNK_SIZE * z),
map
);
chunks[ind]->bake_tiles();
}
}
log("Baking Chunks: 100%%, map initialized");
log("Preparing render command buffer");
update_render_buffer();
}
void Map::update_render_buffer() {
XE(delete, cmd_buffer);
int max_count = width * length * height;
size_t size = 0x10 + (max_count + 1) * sizeof(GDrawable*);
ASM76::Instruct* cmd_buf = (ASM76::Instruct*) malloc(size);
memset(cmd_buf, 0x0, size);
cmd_buf[0] = {ASM76::INTX, CLEnum_GDrawable_batchOnce, 0x10};
cmd_buf[1] = {ASM76::HALT, 0, 0};
int real_count = 0;
GDrawable** list = (GDrawable**) (((uint8_t*) cmd_buf) + 0x10);
for (int i = 0; i < max_count; i++) {
GDrawable* obj = chunks[i]->getBatch();
if (!obj) {
list[real_count] = obj;
real_count++;
}
}
size = 0x10 + (real_count + 1) * sizeof(GDrawable*);
cmd_buf = (ASM76::Instruct*) realloc(cmd_buf, size);
cmd_buffer = new CmdList({{.size = size, .instruct = cmd_buf}});
}
void Map::place_block(glm::vec3 dir, int tid) {
int cx = (int) dir.x / CHUNK_SIZE;
int cy = (int) dir.y / CHUNK_SIZE;
int cz = (int) dir.z / CHUNK_SIZE;
map->map[map->calcIndex(dir)].tid = tid;
chunks[calcChunkIndex(cx,cy,cz)]->bake_tiles();
update_render_buffer();
}
void Map::render() {
cmd_buffer->call();
}
Map::~Map() {
for (int x = 0; x < width * length * height; x++) {
VMDE_Dispose(delete, chunks[x]);
}
XE(delete[], chunks);
log("Saving map");
map->save_map();
XE(delete, cmd_buffer);
}
}
<commit_msg>fix command buffer bugs<commit_after>//=============================================================================
// ■ map.cpp
//-----------------------------------------------------------------------------
// 地图类
//=============================================================================
#include "tiled_map.hpp"
#include "glm/gtc/noise.hpp"
namespace VM76 {
DataMap::DataMap(int w, int h, int l) {
constStone = {1, 0};
map = (TileData*) malloc(sizeof(TileData) * w * h * l);
width = w; length = l; height = h;
if (!read_map()) generate_V1();
}
void DataMap::generate_flat() {
for (int x = 0; x < width; x++)
for (int z = 0; z < length; z++)
for (int y = 0; y < height; y++) {
TileData t = map[calcIndex(x,y,z)];
t.tid = (y == 0) ? Grass : Air;
}
}
bool DataMap::read_map() {
log("Reading map");
VBinaryFileReader* fr = new VBinaryFileReader("map.dat");
if (!fr->f) return false;
int map_version = fr->read_i32();
if (fr->read_u8() == 'V' && fr->read_u8() == 'M'
&& fr->read_u8() == '7' && fr->read_u8() == '6') {
log("Map version : %d", map_version);
for (int x = 0; x < width * length * height; x++) {
if (x % (width * length * height / 7) == 0)
log("Map %d%% loaded", 100 * x / (width * length * height));
map[x].tid = fr->read_u8();
map[x].data_flag = fr->read_u8();
}
return true;
} else {
log("Invalid map.dat");
return false;
}
}
void DataMap::save_map() {
VBinaryFileWriter* fw = new VBinaryFileWriter("map.dat");
// 版本号
fw->write_i32(100);
// 文件头标识
fw->write_u8('V');
fw->write_u8('M');
fw->write_u8('7');
fw->write_u8('6');
for (int x = 0; x < width * length * height; x++) {
fw->write_u8(map[x].tid);
fw->write_u8(map[x].data_flag);
}
delete fw;
log("Map saved");
}
void DataMap::generate_V1() {
log("Start generating maps, %d x %d x %d", width, length, height);
for (int i = 0; i < width; i++) {
if (i % (width / 12) == 0)
log("Generated %d%% (%d / %d)",
(int) (100.0 / width * i),
i * length * height, width * length * height
);
for (int j = 0; j < length; j++) {
glm::vec2 coord = glm::vec2(i, j) * 0.006f;
const glm::mat2 rotate = glm::mat2(1.4, 1.1, -1.2, 1.4);
glm::vec2 dir = glm::vec2(1.0, 0.1);
float n = glm::sin(glm::perlin(coord * dir)) * 0.5f; coord *= 1.2f;dir = dir * rotate; coord += dir * 0.3f;
dir += glm::vec2(n * 0.8, 0.0);
n += glm::perlin(coord * dir) * 0.45f; dir = dir * rotate;
dir += glm::vec2(n * 0.6, 0.0);
n += glm::perlin(coord * dir) * 0.35f; dir = dir * rotate;
dir += glm::vec2(n * 0.4, 0.0);
n += glm::perlin(coord * dir) * 0.25f; dir = dir * rotate;
dir += glm::vec2(n * 0.2, 0.0);
coord *= 3.01f; dir = dir * rotate; coord += dir * 0.6f;
n += glm::perlin(coord) * 0.125f;
n = n + 0.5f;
n = glm::clamp(n * 0.7f + 0.2f, 1.0f / (float) TERRIAN_MAX_HEIGHT, 1.0f);
int h = n * TERRIAN_MAX_HEIGHT;
int ho = h;
h = glm::clamp(0, h, height);
for (int y = 0; y < h; y++) {
map[calcIndex(i,y,j)].tid = (y == ho - 1) ? Grass : Stone;
}
for (int y = h; y < height; y++) {
map[calcIndex(i,y,j)].tid = Air;
}
}
}
log("Generated 100%%, Complete");
}
Map::Map(int w, int h, int l, int csize) {
log("Init map with size %d, %d, %d in chunk size %d", w, l, h, csize);
CHUNK_SIZE = csize;
width = w; length = l; height = h;
bw = CHUNK_SIZE * w; bl = CHUNK_SIZE * l; bh = CHUNK_SIZE * h;
chunks = new TiledMap*[w * l * h];
map = new DataMap(bw, bh, bl);
for (int x = 0; x < length; x++) {
log("Baking Chunks: %d%% (%d / %d)",
(int) (100.0 / length * x),
x * width * height, width * length * height
);
for (int z = 0; z < width; z++)
for (int y = 0; y < height; y++) {
int ind = calcChunkIndex(x,y,z);
chunks[ind] = new TiledMap(
CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE,
glm::vec3(CHUNK_SIZE * x, CHUNK_SIZE * y, CHUNK_SIZE * z),
map
);
chunks[ind]->bake_tiles();
}
}
log("Baking Chunks: 100%%, map initialized");
log("Preparing render command buffer");
cmd_buffer = NULL;
update_render_buffer();
}
void Map::update_render_buffer() {
if (cmd_buffer) XE(delete, cmd_buffer);
int max_count = width * length * height;
size_t size = 0x10 + (max_count + 1) * sizeof(GDrawable*);
ASM76::Instruct* cmd_buf = (ASM76::Instruct*) malloc(size);
memset(cmd_buf, 0x0, size);
cmd_buf[0] = {ASM76::INTX, CLEnum_GDrawable_batchOnce, 0x10};
cmd_buf[1] = {ASM76::HALT, 0, 0};
int real_count = 0;
GDrawable** list = (GDrawable**) (((uint8_t*) cmd_buf) + 0x10);
for (int i = 0; i < max_count; i++) {
GDrawable* obj = chunks[i]->getBatch();
if (obj) {
list[real_count] = obj;
real_count++;
}
}
size = 0x10 + (real_count + 1) * sizeof(GDrawable*);
cmd_buf = (ASM76::Instruct*) realloc(cmd_buf, size);
cmd_buffer = new CmdList({{.size = size, .instruct = cmd_buf}});
}
void Map::place_block(glm::vec3 dir, int tid) {
int cx = (int) dir.x / CHUNK_SIZE;
int cy = (int) dir.y / CHUNK_SIZE;
int cz = (int) dir.z / CHUNK_SIZE;
map->map[map->calcIndex(dir)].tid = tid;
chunks[calcChunkIndex(cx,cy,cz)]->bake_tiles();
update_render_buffer();
}
void Map::render() {
cmd_buffer->call();
}
Map::~Map() {
for (int x = 0; x < width * length * height; x++) {
VMDE_Dispose(delete, chunks[x]);
}
XE(delete[], chunks);
log("Saving map");
map->save_map();
XE(delete, cmd_buffer);
}
}
<|endoftext|>
|
<commit_before>#include <boost/intrusive_ptr.hpp>
#include <boost/program_options.hpp>
#include <curl/curl.h>
#include <iostream>
#include <iomanip>
#include "auth_plus.h"
#include "ostree_object.h"
#include "ostree_ref.h"
#include "ostree_repo.h"
#include "treehub_server.h"
#include "request_pool.h"
namespace po = boost::program_options;
using std::cout;
using std::string;
using std::list;
const int kCurlTimeoutms = 10000;
const int kMaxCurlRequests = 30;
const string kBaseUrl =
"https://treehub-staging.gw.prod01.advancedtelematic.com/api/v1/";
const string kPassword = "quochai1ech5oot5gaeJaifooqu6Saew";
const string kAuthPlusUrl = "";
int present_already = 0;
int uploaded = 0;
int errors = 0;
void queried_ev(RequestPool &p, OSTreeObject::ptr h) {
switch (h->is_on_server()) {
case OBJECT_MISSING:
h->populate_children();
if (h->children_ready())
p.add_upload(h);
else
h->query_children(p);
break;
case OBJECT_PRESENT:
present_already++;
h->notify_parents(p);
break;
default:
std::cerr << "Surprise state:" << h->is_on_server() << "\n";
p.abort();
errors++;
break;
}
}
void uploaded_ev(RequestPool &p, OSTreeObject::ptr h) {
if (h->is_on_server() == OBJECT_PRESENT) {
uploaded++;
h->notify_parents(p);
} else {
std::cerr << "Surprise state:" << h->is_on_server() << "\n";
p.abort();
errors++;
}
}
int main(int argc, char **argv) {
cout << "Garage push\n";
string repo_path;
string ref;
TreehubServer push_target;
string auth_plus_server;
string client_id;
string client_secret;
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("help", "produce a help message")
("repo,C", po::value<string>(&repo_path)->required(), "location of ostree repo")
("ref,r", po::value<string>(&ref)->required(), "ref to push")
("user,u", po::value<string>(&push_target.username)->required(), "Username")
("password", po::value<string>(&push_target.password) ->default_value(kPassword), "Password")
("url", po::value<string>(&push_target.root_url)->default_value(kBaseUrl), "Treehub URL")
("auth-server", po::value<string>(&auth_plus_server), "Auth+ Server")
("client-id", po::value<string>(&client_id), "Client ID")
("client-secret", po::value<string>(&client_secret), "Client Secret")
("dry-run,n", "Dry Run: Check arguments and authenticate but don't upload");
// clang-format on
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
cout << desc << "\n";
return EXIT_SUCCESS;
}
po::notify(vm);
} catch (const po::error &o) {
cout << o.what() << "\n";
cout << desc << "\n";
return EXIT_FAILURE;
}
OSTreeRepo repo(repo_path);
if (!repo.LooksValid()) {
cout << "The OSTree repo dir " << repo_path
<< " does not appear to contain a valid OSTree repository\n";
return EXIT_FAILURE;
}
OSTreeRef ostree_ref(repo, ref);
if (!ostree_ref.IsValid()) {
cout << "Ref " << ref << " was not found in repository " << repo_path
<< "\n";
return EXIT_FAILURE;
}
uint8_t root_sha256[32];
ostree_ref.GetHash(root_sha256);
OSTreeObject::ptr root_object = repo.GetObject(root_sha256);
if (!root_object) {
cout << "Commit pointed to by " << ref << " was not found in repository "
<< repo_path << "\n";
return EXIT_FAILURE;
}
// Authenticate with Auth+
AuthPlus auth_plus(auth_plus_server, client_id, client_secret);
if (client_id != "") {
if (auth_plus.Authenticate() != AUTHENTICATION_SUCCESS) {
std::cerr << "Authentication with Auth+ failed\n";
return EXIT_FAILURE;
} else {
cout << "Using Auth+ authentication token\n";
push_target.SetToken(auth_plus.token());
}
} else {
cout << "Skipping Authentication\n";
}
if (vm.count("dry-run")) {
cout << "Dry run. Exiting.\n";
return EXIT_SUCCESS;
}
RequestPool request_pool(push_target, kMaxCurlRequests);
// Add commit object to the queue
request_pool.add_query(root_object);
// Set callbacks
request_pool.on_query(queried_ev);
request_pool.on_upload(uploaded_ev);
// Main curl event loop.
// request_pool takes care of holding number of outstanding requests below
// kMaxCurlRequests
// Callbacks (queried_ev and uploaded_ev) add new requests to the pool and
// stop the pool on error
do {
request_pool.loop();
} while (root_object->is_on_server() != OBJECT_PRESENT &&
!request_pool.is_stopped());
cout << "Uploaded " << uploaded << " objects\n";
cout << "Already present " << present_already << " objects\n";
// Push ref
CURL *easy_handle = curl_easy_init();
curl_easy_setopt(easy_handle, CURLOPT_VERBOSE, 1L);
ostree_ref.PushRef(push_target, easy_handle);
CURLcode err = curl_easy_perform(easy_handle);
if (err) {
cout << "Error pushing root ref:" << curl_easy_strerror(err) << "\n";
errors++;
}
long rescode;
curl_easy_getinfo(easy_handle, CURLINFO_RESPONSE_CODE, &rescode);
if (rescode != 200) {
cout << "Error pushing root ref, got " << rescode << " HTTP response\n";
errors++;
}
curl_easy_cleanup(easy_handle);
if (errors) {
std::cerr << "One or more errors while pushing\n";
return EXIT_FAILURE;
} else {
return EXIT_SUCCESS;
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<commit_msg>Only push the ref if commit uploading was successful<commit_after>#include <boost/intrusive_ptr.hpp>
#include <boost/program_options.hpp>
#include <curl/curl.h>
#include <iostream>
#include <iomanip>
#include "auth_plus.h"
#include "ostree_object.h"
#include "ostree_ref.h"
#include "ostree_repo.h"
#include "treehub_server.h"
#include "request_pool.h"
namespace po = boost::program_options;
using std::cout;
using std::string;
using std::list;
const int kCurlTimeoutms = 10000;
const int kMaxCurlRequests = 30;
const string kBaseUrl =
"https://treehub-staging.gw.prod01.advancedtelematic.com/api/v1/";
const string kPassword = "quochai1ech5oot5gaeJaifooqu6Saew";
const string kAuthPlusUrl = "";
int present_already = 0;
int uploaded = 0;
int errors = 0;
void queried_ev(RequestPool &p, OSTreeObject::ptr h) {
switch (h->is_on_server()) {
case OBJECT_MISSING:
h->populate_children();
if (h->children_ready())
p.add_upload(h);
else
h->query_children(p);
break;
case OBJECT_PRESENT:
present_already++;
h->notify_parents(p);
break;
default:
std::cerr << "Surprise state:" << h->is_on_server() << "\n";
p.abort();
errors++;
break;
}
}
void uploaded_ev(RequestPool &p, OSTreeObject::ptr h) {
if (h->is_on_server() == OBJECT_PRESENT) {
uploaded++;
h->notify_parents(p);
} else {
std::cerr << "Surprise state:" << h->is_on_server() << "\n";
p.abort();
errors++;
}
}
int main(int argc, char **argv) {
cout << "Garage push\n";
string repo_path;
string ref;
TreehubServer push_target;
string auth_plus_server;
string client_id;
string client_secret;
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("help", "produce a help message")
("repo,C", po::value<string>(&repo_path)->required(), "location of ostree repo")
("ref,r", po::value<string>(&ref)->required(), "ref to push")
("user,u", po::value<string>(&push_target.username)->required(), "Username")
("password", po::value<string>(&push_target.password) ->default_value(kPassword), "Password")
("url", po::value<string>(&push_target.root_url)->default_value(kBaseUrl), "Treehub URL")
("auth-server", po::value<string>(&auth_plus_server), "Auth+ Server")
("client-id", po::value<string>(&client_id), "Client ID")
("client-secret", po::value<string>(&client_secret), "Client Secret")
("dry-run,n", "Dry Run: Check arguments and authenticate but don't upload");
// clang-format on
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
cout << desc << "\n";
return EXIT_SUCCESS;
}
po::notify(vm);
} catch (const po::error &o) {
cout << o.what() << "\n";
cout << desc << "\n";
return EXIT_FAILURE;
}
OSTreeRepo repo(repo_path);
if (!repo.LooksValid()) {
cout << "The OSTree repo dir " << repo_path
<< " does not appear to contain a valid OSTree repository\n";
return EXIT_FAILURE;
}
OSTreeRef ostree_ref(repo, ref);
if (!ostree_ref.IsValid()) {
cout << "Ref " << ref << " was not found in repository " << repo_path
<< "\n";
return EXIT_FAILURE;
}
uint8_t root_sha256[32];
ostree_ref.GetHash(root_sha256);
OSTreeObject::ptr root_object = repo.GetObject(root_sha256);
if (!root_object) {
cout << "Commit pointed to by " << ref << " was not found in repository "
<< repo_path << "\n";
return EXIT_FAILURE;
}
// Authenticate with Auth+
AuthPlus auth_plus(auth_plus_server, client_id, client_secret);
if (client_id != "") {
if (auth_plus.Authenticate() != AUTHENTICATION_SUCCESS) {
std::cerr << "Authentication with Auth+ failed\n";
return EXIT_FAILURE;
} else {
cout << "Using Auth+ authentication token\n";
push_target.SetToken(auth_plus.token());
}
} else {
cout << "Skipping Authentication\n";
}
if (vm.count("dry-run")) {
cout << "Dry run. Exiting.\n";
return EXIT_SUCCESS;
}
RequestPool request_pool(push_target, kMaxCurlRequests);
// Add commit object to the queue
request_pool.add_query(root_object);
// Set callbacks
request_pool.on_query(queried_ev);
request_pool.on_upload(uploaded_ev);
// Main curl event loop.
// request_pool takes care of holding number of outstanding requests below
// kMaxCurlRequests
// Callbacks (queried_ev and uploaded_ev) add new requests to the pool and
// stop the pool on error
do {
request_pool.loop();
} while (root_object->is_on_server() != OBJECT_PRESENT &&
!request_pool.is_stopped());
cout << "Uploaded " << uploaded << " objects\n";
cout << "Already present " << present_already << " objects\n";
// Push ref
if (root_object->is_on_server() == OBJECT_PRESENT) {
CURL *easy_handle = curl_easy_init();
curl_easy_setopt(easy_handle, CURLOPT_VERBOSE, 1L);
ostree_ref.PushRef(push_target, easy_handle);
CURLcode err = curl_easy_perform(easy_handle);
if (err) {
cout << "Error pushing root ref:" << curl_easy_strerror(err) << "\n";
errors++;
}
long rescode;
curl_easy_getinfo(easy_handle, CURLINFO_RESPONSE_CODE, &rescode);
if (rescode != 200) {
cout << "Error pushing root ref, got " << rescode << " HTTP response\n";
errors++;
}
curl_easy_cleanup(easy_handle);
} else {
std::cerr << "Uploading failed\n";
}
if (errors) {
std::cerr << "One or more errors while pushing\n";
return EXIT_FAILURE;
} else {
return EXIT_SUCCESS;
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<|endoftext|>
|
<commit_before>// -*- c-basic-offset: 2 -*-
/*
* This file is part of the KDE libraries
* Copyright (C) 2003 Apple Computer, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "domparser.h"
#include "domparser.lut.h"
#include "html/html_documentimpl.h"
using DOM::DocumentImpl;
////////////////////// DOMParser Object ////////////////////////
/* Source for DOMParserProtoTable.
@begin DOMParserProtoTable 1
parseFromString DOMParser::ParseFromString DontDelete|Function 2
@end
*/
namespace KJS {
DEFINE_PROTOTYPE("DOMParser",DOMParserProto)
IMPLEMENT_PROTOFUNC(DOMParserProtoFunc)
IMPLEMENT_PROTOTYPE(DOMParserProto,DOMParserProtoFunc)
DOMParserConstructorImp::DOMParserConstructorImp(ExecState *, DOM::DocumentImpl *d)
: doc(d)
{
}
bool DOMParserConstructorImp::implementsConstruct() const
{
return true;
}
ObjectImp *DOMParserConstructorImp::construct(ExecState *exec, const List &)
{
return new DOMParser(exec, doc.get());
}
const ClassInfo DOMParser::info = { "DOMParser", 0, &DOMParserTable, 0 };
/* Source for DOMParserTable
@begin DOMParserTable 0
@end
*/
DOMParser::DOMParser(ExecState *exec, DOM::DocumentImpl *d)
: doc(d)
{
setPrototype(DOMParserProto::self(exec));
}
ValueImp *DOMParserProtoFunc::callAsFunction(ExecState *exec, ObjectImp *thisObj, const List &args)
{
if (!thisObj->inherits(&DOMParser::info))
return throwError(exec, TypeError);
DOMParser *parser = static_cast<DOMParser *>(thisObj);
switch (id) {
case DOMParser::ParseFromString:
{
if (args.size() != 2) {
return Undefined();
}
QString str = args[0]->toString(exec).qstring();
QString contentType = args[1]->toString(exec).qstring().stripWhiteSpace();
if (contentType == "text/xml" || contentType == "application/xml" || contentType == "application/xhtml+xml") {
DocumentImpl *docImpl = parser->doc->implementation()->createDocument();
docImpl->open();
docImpl->write(str);
docImpl->finishParsing();
docImpl->close();
return getDOMNode(exec, docImpl);
}
}
}
return Undefined();
}
} // end namespace
<commit_msg>Fix copyright header<commit_after>// -*- c-basic-offset: 2 -*-
/*
* This file is part of the KDE libraries
* Copyright (C) 2005 Anders Carlsson (andersca@mac.com)
*
* 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 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "domparser.h"
#include "domparser.lut.h"
#include "html/html_documentimpl.h"
using DOM::DocumentImpl;
////////////////////// DOMParser Object ////////////////////////
/* Source for DOMParserProtoTable.
@begin DOMParserProtoTable 1
parseFromString DOMParser::ParseFromString DontDelete|Function 2
@end
*/
namespace KJS {
DEFINE_PROTOTYPE("DOMParser",DOMParserProto)
IMPLEMENT_PROTOFUNC(DOMParserProtoFunc)
IMPLEMENT_PROTOTYPE(DOMParserProto,DOMParserProtoFunc)
DOMParserConstructorImp::DOMParserConstructorImp(ExecState *, DOM::DocumentImpl *d)
: doc(d)
{
}
bool DOMParserConstructorImp::implementsConstruct() const
{
return true;
}
ObjectImp *DOMParserConstructorImp::construct(ExecState *exec, const List &)
{
return new DOMParser(exec, doc.get());
}
const ClassInfo DOMParser::info = { "DOMParser", 0, &DOMParserTable, 0 };
/* Source for DOMParserTable
@begin DOMParserTable 0
@end
*/
DOMParser::DOMParser(ExecState *exec, DOM::DocumentImpl *d)
: doc(d)
{
setPrototype(DOMParserProto::self(exec));
}
ValueImp *DOMParserProtoFunc::callAsFunction(ExecState *exec, ObjectImp *thisObj, const List &args)
{
if (!thisObj->inherits(&DOMParser::info))
return throwError(exec, TypeError);
DOMParser *parser = static_cast<DOMParser *>(thisObj);
switch (id) {
case DOMParser::ParseFromString:
{
if (args.size() != 2) {
return Undefined();
}
QString str = args[0]->toString(exec).qstring();
QString contentType = args[1]->toString(exec).qstring().stripWhiteSpace();
if (contentType == "text/xml" || contentType == "application/xml" || contentType == "application/xhtml+xml") {
DocumentImpl *docImpl = parser->doc->implementation()->createDocument();
docImpl->open();
docImpl->write(str);
docImpl->finishParsing();
docImpl->close();
return getDOMNode(exec, docImpl);
}
}
}
return Undefined();
}
} // end namespace
<|endoftext|>
|
<commit_before>#include "Context.h"
#include <cmath>
#include <iostream>
using namespace std;
using namespace canvas;
void
Context::resize(unsigned int _width, unsigned int _height) {
width = _width;
height = _height;
getDefaultSurface().resize(_width, _height);
}
void
Context::fillRect(double x, double y, double w, double h) {
beginPath();
moveTo(x, y);
lineTo(x + w, y);
lineTo(x + w, y + h);
lineTo(x, y + h);
closePath();
fill();
}
void
Context::strokeRect(double x, double y, double w, double h) {
beginPath();
moveTo(x, y);
lineTo(x + w, y);
lineTo(x + w, y + h);
lineTo(x, y + h);
closePath();
stroke();
}
void
Context::fillText(const std::string & text, double x, double y) {
if (hasShadow()) {
// cerr << "DRAWING SHADOW for text " << text << ", w = " << getWidth() << ", h = " << getHeight() << endl;
auto shadow = createSurface(getDefaultSurface().getWidth(), getDefaultSurface().getHeight());
Style tmp = fillStyle;
fillStyle.color = shadowColor;
shadow->fillText(*this, text, x + shadowOffsetX, y + shadowOffsetY);
shadow->gaussianBlur(shadowBlur, shadowBlur);
fillStyle = tmp;
drawImage(*shadow, 0, 0, shadow->getWidth(), shadow->getHeight());
}
getDefaultSurface().fillText(*this, text, x, y);
}
// Implementation by node-canvas (Node canvas is a Cairo backed Canvas implementation for NodeJS)
// Original implementation influenced by WebKit.
void
Context::arcTo(double x1, double y1, double x2, double y2, double radius) {
Point p0 = getCurrentPoint();
Point p1(x1, y1);
Point p2(x2, y2);
if ((p1.x == p0.x && p1.y == p0.y) || (p1.x == p2.x && p1.y == p2.y) || radius == 0.f) {
lineTo(p1.x, p1.y);
// p2?
return;
}
Point p1p0((p0.x - p1.x), (p0.y - p1.y));
Point p1p2((p2.x - p1.x), (p2.y - p1.y));
float p1p0_length = sqrt(p1p0.x * p1p0.x + p1p0.y * p1p0.y);
float p1p2_length = sqrt(p1p2.x * p1p2.x + p1p2.y * p1p2.y);
double cos_phi = (p1p0.x * p1p2.x + p1p0.y * p1p2.y) / (p1p0_length * p1p2_length);
// all points on a line logic
if (-1 == cos_phi) {
lineTo(p1.x, p1.y);
// p2?
return;
}
if (1 == cos_phi) {
// add infinite far away point
unsigned int max_length = 65535;
double factor_max = max_length / p1p0_length;
Point ep((p0.x + factor_max * p1p0.x), (p0.y + factor_max * p1p0.y));
lineTo(ep.x, ep.y);
return;
}
double tangent = radius / tan(acos(cos_phi) / 2);
double factor_p1p0 = tangent / p1p0_length;
Point t_p1p0((p1.x + factor_p1p0 * p1p0.x), (p1.y + factor_p1p0 * p1p0.y));
Point orth_p1p0(p1p0.y, -p1p0.x);
double orth_p1p0_length = sqrt(orth_p1p0.x * orth_p1p0.x + orth_p1p0.y * orth_p1p0.y);
double factor_ra = radius / orth_p1p0_length;
double cos_alpha = (orth_p1p0.x * p1p2.x + orth_p1p0.y * p1p2.y) / (orth_p1p0_length * p1p2_length);
if (cos_alpha < 0.f) {
orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
}
Point p((t_p1p0.x + factor_ra * orth_p1p0.x), (t_p1p0.y + factor_ra * orth_p1p0.y));
orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
double sa = acos(orth_p1p0.x / orth_p1p0_length);
if (orth_p1p0.y < 0.f) {
sa = 2 * M_PI - sa;
}
bool anticlockwise = false;
double factor_p1p2 = tangent / p1p2_length;
Point t_p1p2((p1.x + factor_p1p2 * p1p2.x), (p1.y + factor_p1p2 * p1p2.y));
Point orth_p1p2((t_p1p2.x - p.x),(t_p1p2.y - p.y));
double orth_p1p2_length = sqrt(orth_p1p2.x * orth_p1p2.x + orth_p1p2.y * orth_p1p2.y);
double ea = acos(orth_p1p2.x / orth_p1p2_length);
if (orth_p1p2.y < 0) ea = 2 * M_PI - ea;
if ((sa > ea) && ((sa - ea) < M_PI)) anticlockwise = true;
if ((sa < ea) && ((ea - sa) > M_PI)) anticlockwise = true;
lineTo(t_p1p0.x, t_p1p0.y);
arc(p.x, p.y, radius, sa, ea, anticlockwise); // && M_PI * 2 != radius);
}
<commit_msg>add save()/restore() to fillRect<commit_after>#include "Context.h"
#include <cmath>
#include <iostream>
using namespace std;
using namespace canvas;
void
Context::resize(unsigned int _width, unsigned int _height) {
width = _width;
height = _height;
getDefaultSurface().resize(_width, _height);
}
void
Context::fillRect(double x, double y, double w, double h) {
save();
beginPath();
moveTo(x, y);
lineTo(x + w, y);
lineTo(x + w, y + h);
lineTo(x, y + h);
closePath();
fill();
beginPath(); // tmp fix
restore();
}
void
Context::strokeRect(double x, double y, double w, double h) {
beginPath();
moveTo(x, y);
lineTo(x + w, y);
lineTo(x + w, y + h);
lineTo(x, y + h);
closePath();
stroke();
}
void
Context::fillText(const std::string & text, double x, double y) {
if (hasShadow()) {
// cerr << "DRAWING SHADOW for text " << text << ", w = " << getWidth() << ", h = " << getHeight() << endl;
auto shadow = createSurface(getDefaultSurface().getWidth(), getDefaultSurface().getHeight());
Style tmp = fillStyle;
fillStyle.color = shadowColor;
shadow->fillText(*this, text, x + shadowOffsetX, y + shadowOffsetY);
shadow->gaussianBlur(shadowBlur, shadowBlur);
fillStyle = tmp;
drawImage(*shadow, 0, 0, shadow->getWidth(), shadow->getHeight());
}
getDefaultSurface().fillText(*this, text, x, y);
}
// Implementation by node-canvas (Node canvas is a Cairo backed Canvas implementation for NodeJS)
// Original implementation influenced by WebKit.
void
Context::arcTo(double x1, double y1, double x2, double y2, double radius) {
Point p0 = getCurrentPoint();
Point p1(x1, y1);
Point p2(x2, y2);
if ((p1.x == p0.x && p1.y == p0.y) || (p1.x == p2.x && p1.y == p2.y) || radius == 0.f) {
lineTo(p1.x, p1.y);
// p2?
return;
}
Point p1p0((p0.x - p1.x), (p0.y - p1.y));
Point p1p2((p2.x - p1.x), (p2.y - p1.y));
float p1p0_length = sqrt(p1p0.x * p1p0.x + p1p0.y * p1p0.y);
float p1p2_length = sqrt(p1p2.x * p1p2.x + p1p2.y * p1p2.y);
double cos_phi = (p1p0.x * p1p2.x + p1p0.y * p1p2.y) / (p1p0_length * p1p2_length);
// all points on a line logic
if (-1 == cos_phi) {
lineTo(p1.x, p1.y);
// p2?
return;
}
if (1 == cos_phi) {
// add infinite far away point
unsigned int max_length = 65535;
double factor_max = max_length / p1p0_length;
Point ep((p0.x + factor_max * p1p0.x), (p0.y + factor_max * p1p0.y));
lineTo(ep.x, ep.y);
return;
}
double tangent = radius / tan(acos(cos_phi) / 2);
double factor_p1p0 = tangent / p1p0_length;
Point t_p1p0((p1.x + factor_p1p0 * p1p0.x), (p1.y + factor_p1p0 * p1p0.y));
Point orth_p1p0(p1p0.y, -p1p0.x);
double orth_p1p0_length = sqrt(orth_p1p0.x * orth_p1p0.x + orth_p1p0.y * orth_p1p0.y);
double factor_ra = radius / orth_p1p0_length;
double cos_alpha = (orth_p1p0.x * p1p2.x + orth_p1p0.y * p1p2.y) / (orth_p1p0_length * p1p2_length);
if (cos_alpha < 0.f) {
orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
}
Point p((t_p1p0.x + factor_ra * orth_p1p0.x), (t_p1p0.y + factor_ra * orth_p1p0.y));
orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
double sa = acos(orth_p1p0.x / orth_p1p0_length);
if (orth_p1p0.y < 0.f) {
sa = 2 * M_PI - sa;
}
bool anticlockwise = false;
double factor_p1p2 = tangent / p1p2_length;
Point t_p1p2((p1.x + factor_p1p2 * p1p2.x), (p1.y + factor_p1p2 * p1p2.y));
Point orth_p1p2((t_p1p2.x - p.x),(t_p1p2.y - p.y));
double orth_p1p2_length = sqrt(orth_p1p2.x * orth_p1p2.x + orth_p1p2.y * orth_p1p2.y);
double ea = acos(orth_p1p2.x / orth_p1p2_length);
if (orth_p1p2.y < 0) ea = 2 * M_PI - ea;
if ((sa > ea) && ((sa - ea) < M_PI)) anticlockwise = true;
if ((sa < ea) && ((ea - sa) > M_PI)) anticlockwise = true;
lineTo(t_p1p0.x, t_p1p0.y);
arc(p.x, p.y, radius, sa, ea, anticlockwise); // && M_PI * 2 != radius);
}
<|endoftext|>
|
<commit_before>#include "Phase.h"
#define LOG_OUT 1
#include <FHT.h>
bool Phase::update(float linearAcceleration) {
int newMillis = millis();
int elaspedMillis = newMillis - _lastUpdateMS;
if (elaspedMillis > _intervalMS + 10) {
Serial.print("E: phase time: "); Serial.println(elaspedMillis);
}
if (elaspedMillis < _intervalMS) {
return false;
}
_lastUpdateMS = newMillis;
// Clear interrupts when we are doing FHT.
cli();
{
computeFht(linearAcceleration, elaspedMillis);
}
sei();
//int lastMillis = millis();
//Serial.print("Phase time: "); Serial.println(lastMillis - newMillis);
return true;
}
float normalize_rads(float angle_rad) {
if (angle_rad < 0) {
angle_rad += 2 * PI;
} else if (angle_rad >= 2*PI) {
angle_rad -= 2 * PI;
}
return angle_rad;
}
void Phase::computeFht(float lastValue, int elaspedMillis) {
lastValue *= 8000;
lastValue = max(-32767, min(32767, lastValue));
for (int i = FHT_N - 2; i >= 0; i--) {
_old_fht[i+1] = _old_fht[i];
fht_input[i+1] = _old_fht[i];
}
fht_input[0] = (int) lastValue;
_old_fht[0] = (int) lastValue;
fht_window();
fht_reorder();
fht_run();
fht_mag_log();
int maxValue = 0;
int maxIndex = 0;
for (int i = 0; i < FHT_N/2; i++) {
uint8_t val = fht_log_out[i];
//int val = fht_lin_out[i];
if (val > maxValue) {
maxValue = val;
maxIndex = i;
}
}
int realPlusImg = fht_input[maxIndex];
int realMinusImg = maxIndex == 0 ? realPlusImg : fht_input[FHT_N - maxIndex];
float phase = atan2(realPlusImg - realMinusImg, realPlusImg + realMinusImg) + PI;
// Add the rate to our phase even in the case where we don't update the rate.
_phase_avg += _phaseRateAverage;
if (maxIndex == _old_max_index && maxIndex > 1) {
float phaseDiff = normalize_rads(phase - _old_phase);
//Serial.print("PhaseDiff: "); Serial.println(phaseDiff);
// Only update the rate if we are in the same fht bucket.
_phaseRateAverage = (((_phaseRateAverage * 9) + phaseDiff ) / 10);
if (phase + PI < _phase_avg) {
phase += 2*PI;
} else if (phase - PI > _phase_avg) {
phase -= 2*PI;
}
_phase_avg = (_phase_avg * 9 + phase) / 10;
_phase_avg = normalize_rads(_phase_avg);
//Serial.print("Phase : "); Serial.println(phase);
//Serial.print("Phase Avg: "); Serial.println(_phase_avg);
}
_old_phase = phase;
_old_max_index = maxIndex;
//Serial.print("bpm avg: "); Serial.println(_phaseRateAverage / (2.0 * PI) * 1000.0 / FHT_INTERVAL_MS * 60);
}
float Phase::getPhasePercentage() const {
return _phase_avg/(2*PI);
}
float Phase::getPhaseRatePercentage() const {
return _phaseRateAverage/(2*PI);
}
<commit_msg>filter out super high freq<commit_after>#include "Phase.h"
#define LOG_OUT 1
#include <FHT.h>
bool Phase::update(float linearAcceleration) {
int newMillis = millis();
int elaspedMillis = newMillis - _lastUpdateMS;
if (elaspedMillis > _intervalMS + 10) {
Serial.print("E: phase time: "); Serial.println(elaspedMillis);
}
if (elaspedMillis < _intervalMS) {
return false;
}
_lastUpdateMS = newMillis;
// Clear interrupts when we are doing FHT.
cli();
{
computeFht(linearAcceleration, elaspedMillis);
}
sei();
//int lastMillis = millis();
//Serial.print("Phase time: "); Serial.println(lastMillis - newMillis);
return true;
}
float normalize_rads(float angle_rad) {
if (angle_rad < 0) {
angle_rad += 2 * PI;
} else if (angle_rad >= 2*PI) {
angle_rad -= 2 * PI;
}
return angle_rad;
}
void Phase::computeFht(float lastValue, int elaspedMillis) {
lastValue *= 8000;
lastValue = max(-32767, min(32767, lastValue));
for (int i = FHT_N - 2; i >= 0; i--) {
_old_fht[i+1] = _old_fht[i];
fht_input[i+1] = _old_fht[i];
}
fht_input[0] = (int) lastValue;
_old_fht[0] = (int) lastValue;
fht_window();
fht_reorder();
fht_run();
fht_mag_log();
int maxValue = 0;
int maxIndex = 0;
for (int i = 0; i < FHT_N/2; i++) {
uint8_t val = fht_log_out[i];
//int val = fht_lin_out[i];
if (val > maxValue) {
maxValue = val;
maxIndex = i;
}
}
int realPlusImg = fht_input[maxIndex];
int realMinusImg = maxIndex == 0 ? realPlusImg : fht_input[FHT_N - maxIndex];
float phase = atan2(realPlusImg - realMinusImg, realPlusImg + realMinusImg) + PI;
// Add the rate to our phase even in the case where we don't update the rate.
_phase_avg += _phaseRateAverage;
if (maxIndex == _old_max_index && maxIndex > 1 && maxIndex < FHT_N/2 - 5) {
float phaseDiff = normalize_rads(phase - _old_phase);
//Serial.print("PhaseDiff: "); Serial.println(phaseDiff);
// Only update the rate if we are in the same fht bucket.
_phaseRateAverage = (((_phaseRateAverage * 9) + phaseDiff ) / 10);
if (phase + PI < _phase_avg) {
phase += 2*PI;
} else if (phase - PI > _phase_avg) {
phase -= 2*PI;
}
_phase_avg = (_phase_avg * 9 + phase) / 10;
_phase_avg = normalize_rads(_phase_avg);
//Serial.print("Phase : "); Serial.println(phase);
//Serial.print("Phase Avg: "); Serial.println(_phase_avg);
}
_old_phase = phase;
_old_max_index = maxIndex;
//Serial.print("bpm avg: "); Serial.println(_phaseRateAverage / (2.0 * PI) * 1000.0 / FHT_INTERVAL_MS * 60);
}
float Phase::getPhasePercentage() const {
return _phase_avg/(2*PI);
}
float Phase::getPhaseRatePercentage() const {
return _phaseRateAverage/(2*PI);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <graphene/chain/asset.hpp>
#include <fc/uint128.hpp>
#include <boost/rational.hpp>
namespace graphene { namespace chain {
bool operator < ( const asset& a, const asset& b )
{
return std::tie( a.asset_id, a.amount ) < std::tie( b.asset_id, b.amount);
}
bool operator <= ( const asset& a, const asset& b )
{
return std::tie( a.asset_id, a.amount ) <= std::tie( b.asset_id, b.amount);
}
bool operator < ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
auto amult = fc::uint128(b.quote.amount.value) * a.base.amount.value;
auto bmult = fc::uint128(a.quote.amount.value) * b.base.amount.value;
assert( (a.to_real() < b.to_real()) == (amult < bmult) );
return amult < bmult;
}
bool operator <= ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
auto amult = fc::uint128(b.quote.amount.value) * a.base.amount.value;
auto bmult = fc::uint128(a.quote.amount.value) * b.base.amount.value;
assert( (a.to_real() <= b.to_real()) == (amult <= bmult) );
return amult <= bmult;
}
bool operator == ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
auto amult = fc::uint128(a.quote.amount.value) * b.base.amount.value;
auto bmult = fc::uint128(b.quote.amount.value) * a.base.amount.value;
return amult == bmult;
}
bool operator != ( const price& a, const price& b )
{
return !(a==b);
}
bool operator >= ( const price& a, const price& b )
{
return !(a < b);
}
bool operator > ( const price& a, const price& b )
{
return !(a <= b);
}
asset operator * ( const asset& a, const price& b )
{
if( a.asset_id == b.base.asset_id )
{
FC_ASSERT( b.base.amount.value > 0 );
auto result = (fc::uint128(a.amount.value) * b.quote.amount.value)/b.base.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.to_uint64(), b.quote.asset_id );
}
else if( a.asset_id == b.quote.asset_id )
{
FC_ASSERT( b.quote.amount.value > 0 );
auto result = (fc::uint128(a.amount.value) * b.base.amount.value)/b.quote.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.to_uint64(), b.base.asset_id );
}
FC_ASSERT( !"invalid asset * price", "", ("asset",a)("price",b) );
}
price operator / ( const asset& base, const asset& quote )
{
FC_ASSERT( base.asset_id != quote.asset_id );
return price{base,quote};
}
price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }
price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); }
/**
* The black swan price is defined as debt/collateral, we want to perform a margin call
* before debt == collateral. Given a debt/collateral ratio of 1 USD / CORE and
* a maintenance collateral requirement of 2x we can define the call price to be
* 2 USD / CORE.
*
* This method divides the collateral by the maintenance collateral ratio to derive
* a call price for the given black swan ratio.
*
* There exists some cases where the debt and collateral values are so small that
* dividing by the collateral ratio will result in a 0 price or really poor
* rounding errors. No matter what the collateral part of the price ratio can
* never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY
*
* CR * DEBT/COLLAT or DEBT/(COLLAT/CR)
*/
price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio)
{ try {
//wdump((debt)(collateral)(collateral_ratio));
boost::rational<uint64_t> swan(debt.amount.value,collateral.amount.value);
boost::rational<uint64_t> ratio( collateral_ratio, 1000 );
auto cp = swan * ratio;
return ~(asset( cp.numerator(), debt.asset_id ) / asset( cp.denominator(), collateral.asset_id ));
/*
while( collateral.amount < 100000 && debt.amount < GRAPHENE_MAX_SHARE_SUPPLY/100 )
{
collateral.amount *= 1000;
debt.amount *= 1000;
}
fc::uint128 tmp( collateral.amount.value );
tmp *= 1000;
tmp /= collateral_ratio;
FC_ASSERT( tmp <= GRAPHENE_MAX_SHARE_SUPPLY );
asset col( tmp.to_uint64(), collateral.asset_id);
if( col.amount == 0 ) col.amount = 1;
return col / debt;
*/
} FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) }
bool price::is_null() const { return *this == price(); }
void price::validate() const
{ try {
FC_ASSERT( base.amount > share_type(0) );
FC_ASSERT( quote.amount > share_type(0) );
FC_ASSERT( base.asset_id != quote.asset_id );
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
void price_feed::validate() const
{ try {
if( !settlement_price.is_null() )
settlement_price.validate();
FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
//FC_ASSERT( maintenance_collateral_ratio >= maximum_short_squeeze_ratio );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
price price_feed::max_short_squeeze_price()const
{
asset collateral = settlement_price.quote;
fc::uint128 tmp( collateral.amount.value );
tmp *= maximum_short_squeeze_ratio;
tmp /= 1000;
FC_ASSERT( tmp <= GRAPHENE_MAX_SHARE_SUPPLY );
collateral.amount = tmp.to_uint64();
return settlement_price.base / collateral;
}
/*
price price_feed::maintenance_price()const
{
asset collateral = settlement_price.quote;
fc::uint128 tmp( collateral.amount.value );
tmp *= maintenance_collateral_ratio;
tmp /= 1000;
FC_ASSERT( tmp <= GRAPHENE_MAX_SHARE_SUPPLY );
collateral.amount = tmp.to_uint64();
return settlement_price.base / collateral;
}
*/
} } // graphene::chain
<commit_msg>fix bugs<commit_after>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <graphene/chain/asset.hpp>
#include <fc/uint128.hpp>
#include <boost/rational.hpp>
namespace graphene { namespace chain {
bool operator < ( const asset& a, const asset& b )
{
return std::tie( a.asset_id, a.amount ) < std::tie( b.asset_id, b.amount);
}
bool operator <= ( const asset& a, const asset& b )
{
return std::tie( a.asset_id, a.amount ) <= std::tie( b.asset_id, b.amount);
}
bool operator < ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
auto amult = fc::uint128(b.quote.amount.value) * a.base.amount.value;
auto bmult = fc::uint128(a.quote.amount.value) * b.base.amount.value;
assert( (a.to_real() < b.to_real()) == (amult < bmult) );
return amult < bmult;
}
bool operator <= ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
auto amult = fc::uint128(b.quote.amount.value) * a.base.amount.value;
auto bmult = fc::uint128(a.quote.amount.value) * b.base.amount.value;
assert( (a.to_real() <= b.to_real()) == (amult <= bmult) );
return amult <= bmult;
}
bool operator == ( const price& a, const price& b )
{
if( a.base.asset_id < b.base.asset_id ) return true;
if( a.base.asset_id > b.base.asset_id ) return false;
if( a.quote.asset_id < b.quote.asset_id ) return true;
if( a.quote.asset_id > b.quote.asset_id ) return false;
auto amult = fc::uint128(a.quote.amount.value) * b.base.amount.value;
auto bmult = fc::uint128(b.quote.amount.value) * a.base.amount.value;
return amult == bmult;
}
bool operator != ( const price& a, const price& b )
{
return !(a==b);
}
bool operator >= ( const price& a, const price& b )
{
return !(a < b);
}
bool operator > ( const price& a, const price& b )
{
return !(a <= b);
}
asset operator * ( const asset& a, const price& b )
{
if( a.asset_id == b.base.asset_id )
{
FC_ASSERT( b.base.amount.value > 0 );
auto result = (fc::uint128(a.amount.value) * b.quote.amount.value)/b.base.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.to_uint64(), b.quote.asset_id );
}
else if( a.asset_id == b.quote.asset_id )
{
FC_ASSERT( b.quote.amount.value > 0 );
auto result = (fc::uint128(a.amount.value) * b.base.amount.value)/b.quote.amount.value;
FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
return asset( result.to_uint64(), b.base.asset_id );
}
FC_ASSERT( !"invalid asset * price", "", ("asset",a)("price",b) );
}
price operator / ( const asset& base, const asset& quote )
{
FC_ASSERT( base.asset_id != quote.asset_id );
return price{base,quote};
}
price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }
price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); }
/**
* The black swan price is defined as debt/collateral, we want to perform a margin call
* before debt == collateral. Given a debt/collateral ratio of 1 USD / CORE and
* a maintenance collateral requirement of 2x we can define the call price to be
* 2 USD / CORE.
*
* This method divides the collateral by the maintenance collateral ratio to derive
* a call price for the given black swan ratio.
*
* There exists some cases where the debt and collateral values are so small that
* dividing by the collateral ratio will result in a 0 price or really poor
* rounding errors. No matter what the collateral part of the price ratio can
* never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY
*
* CR * DEBT/COLLAT or DEBT/(COLLAT/CR)
*/
price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio)
{ try {
//wdump((debt)(collateral)(collateral_ratio));
boost::rational<uint64_t> swan(debt.amount.value,collateral.amount.value);
boost::rational<uint64_t> ratio( collateral_ratio, 1000 );
auto cp = swan * ratio;
return ~(asset( cp.numerator(), debt.asset_id ) / asset( cp.denominator(), collateral.asset_id ));
/*
while( collateral.amount < 100000 && debt.amount < GRAPHENE_MAX_SHARE_SUPPLY/100 )
{
collateral.amount *= 1000;
debt.amount *= 1000;
}
fc::uint128 tmp( collateral.amount.value );
tmp *= 1000;
tmp /= collateral_ratio;
FC_ASSERT( tmp <= GRAPHENE_MAX_SHARE_SUPPLY );
asset col( tmp.to_uint64(), collateral.asset_id);
if( col.amount == 0 ) col.amount = 1;
return col / debt;
*/
} FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) }
bool price::is_null() const { return *this == price(); }
void price::validate() const
{ try {
FC_ASSERT( base.amount > share_type(0) );
FC_ASSERT( quote.amount > share_type(0) );
FC_ASSERT( base.asset_id != quote.asset_id );
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
void price_feed::validate() const
{ try {
if( !settlement_price.is_null() )
settlement_price.validate();
FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );
FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );
//FC_ASSERT( maintenance_collateral_ratio >= maximum_short_squeeze_ratio );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
price price_feed::max_short_squeeze_price()const
{
boost::rational<uint64_t> sp( settlement_price.base.amount.value, settlement_price.quote.amount.value ); //debt.amount.value,collateral.amount.value);
boost::rational<uint64_t> ratio( 1000, maximum_short_squeeze_ratio );
auto cp = sp * ratio;
return (asset( cp.numerator(), settlement_price.base.asset_id ) / asset( cp.denominator(), settlement_price.quote.asset_id ));
/*
asset collateral = settlement_price.quote;
fc::uint128 tmp( collateral.amount.value );
tmp *= maximum_short_squeeze_ratio;
tmp /= 1000;
FC_ASSERT( tmp <= GRAPHENE_MAX_SHARE_SUPPLY );
collateral.amount = tmp.to_uint64();
auto tmp2 = settlement_price.base / collateral;
wdump((rtn)(tmp2));
return rtn;
*/
}
/*
price price_feed::maintenance_price()const
{
asset collateral = settlement_price.quote;
fc::uint128 tmp( collateral.amount.value );
tmp *= maintenance_collateral_ratio;
tmp /= 1000;
FC_ASSERT( tmp <= GRAPHENE_MAX_SHARE_SUPPLY );
collateral.amount = tmp.to_uint64();
return settlement_price.base / collateral;
}
*/
} } // graphene::chain
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <cassert>
#include "CubeCmd.h"
#include "HdfWriter.h"
#include "TextWriter.h"
#include "VtkWriter.h"
#include "StringUtils.h"
using namespace std;
using namespace cigma;
// ---------------------------------------------------------------------------
cigma::CubeCmd::CubeCmd()
{
name = "cube";
L = M = N = 0;
mesh = 0;
writer = 0;
}
cigma::CubeCmd::~CubeCmd()
{
}
// ---------------------------------------------------------------------------
void cigma::CubeCmd::setupOptions(AnyOption *opt)
{
//cout << "Calling cigma::CubeCmd::setupOptions()" << endl;
assert(opt != 0);
/* setup usage */
opt->addUsage("Usage:");
opt->addUsage(" cigma cube [options]");
opt->addUsage(" -x Number of elements along x-dimension");
opt->addUsage(" -y Number of elements along y-dimension");
opt->addUsage(" -z Number of elements along z-dimension");
opt->addUsage(" --hex8 Create hexahedral partition (default)");
opt->addUsage(" --tet4 Create tetrahedral partition");
opt->addUsage(" --output Target output file");
opt->addUsage(" --coords-path Target path for coordinates (.h5 only)");
opt->addUsage(" --connect-path Target path for connectivity (.h5 only)");
/* setup flags and options */
opt->setFlag("help", 'h');
opt->setFlag("verbose", 'v');
opt->setFlag("hex8");
opt->setFlag("tet4");
opt->setOption('x');
opt->setOption('y');
opt->setOption('z');
opt->setOption("output");
opt->setOption("coords-path");
opt->setOption("connect-path");
}
void cigma::CubeCmd::configure(AnyOption *opt)
{
//std::cout << "Calling cigma::CubeCmd::configure()" << std::endl;
assert(opt != 0);
if (!opt->hasOptions())
{
//std::cerr << "No options?" << std::endl;
opt->printUsage();
exit(1);
}
char *in;
string inputstr;
// read verbose flag
verbose = opt->getFlag("verbose");
// read L
in = opt->getValue('x');
if (in == 0)
{
cerr << "cube: Please specify the option -x" << endl;
exit(1);
}
inputstr = in;
string_to_int(inputstr, L);
// read M
in = opt->getValue('y');
if (in == 0)
{
cerr << "cube: Please specify the option -y" << endl;
exit(1);
}
inputstr = in;
string_to_int(inputstr, M);
// read N
in = opt->getValue('z');
if (in == 0)
{
cerr << "cube: Please specify the option -z" << endl;
exit(1);
}
inputstr = in;
string_to_int(inputstr, N);
// read output file
in = opt->getValue("output");
if (in == 0)
{
cerr << "cube: Please specify the option --output" << endl;
exit(1);
}
output_filename = in;
// determine the extension and instantiate appropriate writer object
string root, ext;
path_splitext(output_filename, root, ext);
new_writer(&writer, ext);
if (writer == 0)
{
cerr << "cube: File with bad extension (" << ext << ")" << endl;
exit(1);
}
// read target path for coordinates array
in = opt->getValue("coords-path");
if (in == 0)
{
if (writer->getType() == Writer::HDF_WRITER)
{
coords_path = "/coordinates";
}
}
else
{
coords_path = in;
}
if ((coords_path != "") && (writer->getType() != Writer::HDF_WRITER))
{
cerr << "cube: Can only use --coords-path "
<< "when writing to an HDF5 (.h5) file" << endl;
exit(1);
}
// read target path for connectivity array
in = opt->getValue("connect-path");
if (in == 0)
{
if (writer->getType() == Writer::HDF_WRITER)
{
connect_path = "/connectivity";
}
}
else
{
connect_path = in;
}
if ((connect_path != "") && (writer->getType() != Writer::HDF_WRITER))
{
cerr << "cube: Can only use --connect-path "
<< "when writing to an HDF5 (.h5) file" << endl;
exit(1);
}
// read tet/hex flags
bool hexFlag = opt->getFlag("hex8");
bool tetFlag = opt->getFlag("tet4");
if (hexFlag && tetFlag)
{
std::cerr << "cube: Please specify only one of the flags "
<< "--hex8 or --tet8" << std::endl;
exit(1);
}
if (!tetFlag)
{
hexFlag = true;
}
assert(hexFlag != tetFlag);
// initialize mesh object
mesh = new cigma::CubeMeshPart();
mesh->calc_coordinates(L,M,N);
if (hexFlag) { mesh->calc_hex8_connectivity(); }
if (tetFlag) { mesh->calc_tet4_connectivity(); }
}
int cigma::CubeCmd::run()
{
//std::cout << "Calling cigma::CubeCmd::run()" << std::endl;
assert(mesh != 0);
assert(writer != 0);
if (verbose)
{
std::cout << "L, M, N = (" << L << ", " << M << ", " << N << ")" << std::endl;
std::cout << "mesh->nno = " << mesh->nno << std::endl;
std::cout << "mesh->nel = " << mesh->nel << std::endl;
std::cout << "mesh->ndofs = " << mesh->ndofs << std::endl;
}
if (verbose)
{
int e = 0;
double pts[2][3] = {{0.5, 0.5, 0.5},
{1.0, 1.0, 1.0}};
cout << "Looking for centroid..." << endl;
bool found = mesh->find_cell(pts[0], &e);
if (!found)
{
cerr << "Error: Could not find cell "
<< "containing centroid (0.5,0.5,0.5)" << endl;
exit(1);
}
else
{
cout << "Found centroid in cell " << e << endl;
}
}
int ierr;
if (writer->getType() == Writer::HDF_WRITER)
{
cout << "Creating file " << output_filename << endl;
HdfWriter *hdfWriter = static_cast<HdfWriter*>(writer);
ierr = hdfWriter->open(output_filename);
if (ierr < 0)
{
cerr << "Error: Could not open (or create) the HDF5 file " << output_filename << endl;
exit(1);
}
ierr = hdfWriter->write_coordinates(coords_path.c_str(), mesh->coords, mesh->nno, mesh->nsd);
if (ierr < 0)
{
cerr << "Error: Could not write dataset " << coords_path << endl;
exit(1);
}
ierr = hdfWriter->write_connectivity(connect_path.c_str(), mesh->connect, mesh->nel, mesh->ndofs);
if (ierr < 0)
{
cerr << "Error: Could not write dataset " << connect_path << endl;
exit(1);
}
hdfWriter->close();
}
else if (writer->getType() == Writer::TXT_WRITER)
{
cout << "Creating file " << output_filename << endl;
TextWriter *txtWriter = static_cast<TextWriter*>(writer);
ierr = txtWriter->open(output_filename);
if (ierr < 0)
{
cerr << "Error: Could not create output text file " << output_filename << endl;
exit(1);
}
txtWriter->write_coordinates(mesh->coords, mesh->nno, mesh->nsd);
txtWriter->write_connectivity(mesh->connect, mesh->nel, mesh->ndofs);
txtWriter->close();
}
else if (writer->getType() == Writer::VTK_WRITER)
{
cout << "Creating file " << output_filename << endl;
VtkWriter *vtkWriter = static_cast<VtkWriter*>(writer);
ierr = vtkWriter->open(output_filename);
if (ierr < 0)
{
cerr << "Error: Could not create output VTK file " << output_filename << endl;
exit(1);
}
vtkWriter->write_header();
vtkWriter->write_points(mesh->coords, mesh->nno, mesh->nsd);
vtkWriter->write_cells(mesh->connect, mesh->nel, mesh->ndofs);
vtkWriter->write_cell_types(mesh->nsd, mesh->nel, mesh->ndofs);
vtkWriter->close();
}
else
{
cerr << "cube: File with bad extension?" << endl;
return 1;
}
if (writer != 0)
{
delete writer;
}
return 0;
}
// ---------------------------------------------------------------------------
<commit_msg>Fixes to CubeCmd error messages<commit_after>#include <iostream>
#include <string>
#include <cassert>
#include "CubeCmd.h"
#include "HdfWriter.h"
#include "TextWriter.h"
#include "VtkWriter.h"
#include "StringUtils.h"
using namespace std;
using namespace cigma;
// ---------------------------------------------------------------------------
cigma::CubeCmd::CubeCmd()
{
name = "cube";
L = M = N = 0;
mesh = 0;
writer = 0;
}
cigma::CubeCmd::~CubeCmd()
{
}
// ---------------------------------------------------------------------------
void cigma::CubeCmd::setupOptions(AnyOption *opt)
{
//cout << "Calling cigma::CubeCmd::setupOptions()" << endl;
assert(opt != 0);
/* setup usage */
opt->addUsage("Usage:");
opt->addUsage(" cigma cube [options]");
opt->addUsage(" -x Number of elements along x-dimension");
opt->addUsage(" -y Number of elements along y-dimension");
opt->addUsage(" -z Number of elements along z-dimension");
opt->addUsage(" --hex8 Create hexahedral partition (default)");
opt->addUsage(" --tet4 Create tetrahedral partition");
opt->addUsage(" --output Target output file");
opt->addUsage(" --coords-path Target path for coordinates (.h5 only)");
opt->addUsage(" --connect-path Target path for connectivity (.h5 only)");
/* setup flags and options */
opt->setFlag("help", 'h');
opt->setFlag("verbose", 'v');
opt->setFlag("hex8");
opt->setFlag("tet4");
opt->setOption('x');
opt->setOption('y');
opt->setOption('z');
opt->setOption("output");
opt->setOption("coords-path");
opt->setOption("connect-path");
}
void cigma::CubeCmd::configure(AnyOption *opt)
{
//std::cout << "Calling cigma::CubeCmd::configure()" << std::endl;
assert(opt != 0);
if (!opt->hasOptions())
{
//std::cerr << "No options?" << std::endl;
opt->printUsage();
exit(1);
}
char *in;
string inputstr;
// read verbose flag
verbose = opt->getFlag("verbose");
// read L
in = opt->getValue('x');
if (in == 0)
{
cerr << "cube: Please specify the option -x" << endl;
exit(1);
}
inputstr = in;
string_to_int(inputstr, L);
// read M
in = opt->getValue('y');
if (in == 0)
{
cerr << "cube: Please specify the option -y" << endl;
exit(1);
}
inputstr = in;
string_to_int(inputstr, M);
// read N
in = opt->getValue('z');
if (in == 0)
{
cerr << "cube: Please specify the option -z" << endl;
exit(1);
}
inputstr = in;
string_to_int(inputstr, N);
// read output file
in = opt->getValue("output");
if (in == 0)
{
cerr << "cube: Please specify the option --output" << endl;
exit(1);
}
output_filename = in;
// determine the extension and instantiate appropriate writer object
string root, ext;
path_splitext(output_filename, root, ext);
new_writer(&writer, ext);
if (writer == 0)
{
cerr << "cube: File with bad extension (" << ext << ")" << endl;
exit(1);
}
// read target path for coordinates array
in = opt->getValue("coords-path");
if (in == 0)
{
if (writer->getType() == Writer::HDF_WRITER)
{
coords_path = "/coordinates";
}
}
else
{
coords_path = in;
}
if ((coords_path != "") && (writer->getType() != Writer::HDF_WRITER))
{
cerr << "cube: Can only use --coords-path "
<< "when writing to an HDF5 (.h5) file" << endl;
exit(1);
}
// read target path for connectivity array
in = opt->getValue("connect-path");
if (in == 0)
{
if (writer->getType() == Writer::HDF_WRITER)
{
connect_path = "/connectivity";
}
}
else
{
connect_path = in;
}
if ((connect_path != "") && (writer->getType() != Writer::HDF_WRITER))
{
cerr << "cube: Can only use --connect-path "
<< "when writing to an HDF5 (.h5) file" << endl;
exit(1);
}
// read tet/hex flags
bool hexFlag = opt->getFlag("hex8");
bool tetFlag = opt->getFlag("tet4");
if (hexFlag && tetFlag)
{
std::cerr << "cube: Please specify only one of the flags "
<< "--hex8 or --tet8" << std::endl;
exit(1);
}
if (!tetFlag)
{
hexFlag = true;
}
assert(hexFlag != tetFlag);
// initialize mesh object
mesh = new cigma::CubeMeshPart();
mesh->calc_coordinates(L,M,N);
if (hexFlag) { mesh->calc_hex8_connectivity(); }
if (tetFlag) { mesh->calc_tet4_connectivity(); }
}
int cigma::CubeCmd::run()
{
//std::cout << "Calling cigma::CubeCmd::run()" << std::endl;
assert(mesh != 0);
assert(writer != 0);
if (verbose)
{
std::cout << "L, M, N = (" << L << ", " << M << ", " << N << ")" << std::endl;
std::cout << "mesh->nno = " << mesh->nno << std::endl;
std::cout << "mesh->nel = " << mesh->nel << std::endl;
std::cout << "mesh->ndofs = " << mesh->ndofs << std::endl;
}
if (verbose)
{
int e = 0;
double pts[2][3] = {{0.5, 0.5, 0.5},
{1.0, 1.0, 1.0}};
cout << "Looking for centroid..." << endl;
bool found = mesh->find_cell(pts[0], &e);
if (!found)
{
cerr << "Error: Could not find cell "
<< "containing centroid (0.5,0.5,0.5)" << endl;
exit(1);
}
else
{
cout << "Found centroid in cell " << e << endl;
}
}
int ierr;
cout << "Creating file " << output_filename << endl;
if (writer->getType() == Writer::HDF_WRITER)
{
HdfWriter *hdfWriter = static_cast<HdfWriter*>(writer);
ierr = hdfWriter->open(output_filename);
if (ierr < 0)
{
cerr << "Error: Could not open (or create) the HDF5 file " << output_filename << endl;
exit(1);
}
ierr = hdfWriter->write_coordinates(coords_path.c_str(), mesh->coords, mesh->nno, mesh->nsd);
if (ierr < 0)
{
cerr << "Error: Could not write dataset " << coords_path << endl;
exit(1);
}
ierr = hdfWriter->write_connectivity(connect_path.c_str(), mesh->connect, mesh->nel, mesh->ndofs);
if (ierr < 0)
{
cerr << "Error: Could not write dataset " << connect_path << endl;
exit(1);
}
hdfWriter->close();
}
else if (writer->getType() == Writer::TXT_WRITER)
{
TextWriter *txtWriter = static_cast<TextWriter*>(writer);
ierr = txtWriter->open(output_filename);
if (ierr < 0)
{
cerr << "Error: Could not create output text file " << output_filename << endl;
exit(1);
}
txtWriter->write_coordinates(mesh->coords, mesh->nno, mesh->nsd);
txtWriter->write_connectivity(mesh->connect, mesh->nel, mesh->ndofs);
txtWriter->close();
}
else if (writer->getType() == Writer::VTK_WRITER)
{
VtkWriter *vtkWriter = static_cast<VtkWriter*>(writer);
ierr = vtkWriter->open(output_filename);
if (ierr < 0)
{
cerr << "Error: Could not create output VTK file " << output_filename << endl;
exit(1);
}
vtkWriter->write_header();
vtkWriter->write_points(mesh->coords, mesh->nno, mesh->nsd);
vtkWriter->write_cells(mesh->connect, mesh->nel, mesh->ndofs);
vtkWriter->write_cell_types(mesh->nsd, mesh->nel, mesh->ndofs);
vtkWriter->close();
}
else
{
/* this should be unreachable */
cerr << "Fatal Error: Unsupported extension in output filename?" << endl;
return 1;
}
if (writer != 0)
{
delete writer;
}
return 0;
}
// ---------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "components/usb_service/usb_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/api/usb/usb_api.h"
#include "net/base/io_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::AnyNumber;
using testing::_;
using testing::Return;
using content::BrowserThread;
using usb_service::UsbConfigDescriptor;
using usb_service::UsbDevice;
using usb_service::UsbDeviceHandle;
using usb_service::UsbEndpointDirection;
using usb_service::UsbService;
using usb_service::UsbTransferCallback;
namespace {
ACTION_TEMPLATE(InvokeUsbTransferCallback,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(p1)) {
::std::tr1::get<k>(args).Run(p1, new net::IOBuffer(1), 1);
}
// MSVC erroneously thinks that at least one of the arguments for the transfer
// methods differ by const or volatility and emits a warning about the old
// standards-noncompliant behaviour of their compiler.
#if defined(OS_WIN)
#pragma warning(push)
#pragma warning(disable : 4373)
#endif
class MockUsbDeviceHandle : public UsbDeviceHandle {
public:
MockUsbDeviceHandle() : UsbDeviceHandle() {}
MOCK_METHOD0(Close, void());
MOCK_METHOD10(ControlTransfer,
void(const UsbEndpointDirection direction,
const TransferRequestType request_type,
const TransferRecipient recipient,
const uint8 request,
const uint16 value,
const uint16 index,
net::IOBuffer* buffer,
const size_t length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD6(BulkTransfer,
void(const UsbEndpointDirection direction,
const uint8 endpoint,
net::IOBuffer* buffer,
const size_t length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD6(InterruptTransfer,
void(const UsbEndpointDirection direction,
const uint8 endpoint,
net::IOBuffer* buffer,
const size_t length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD8(IsochronousTransfer,
void(const UsbEndpointDirection direction,
const uint8 endpoint,
net::IOBuffer* buffer,
const size_t length,
const unsigned int packets,
const unsigned int packet_length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD0(ResetDevice, bool());
void set_device(UsbDevice* device) { device_ = device; }
protected:
virtual ~MockUsbDeviceHandle() {}
};
class MockUsbConfigDescriptor : public UsbConfigDescriptor {
public:
MOCK_CONST_METHOD0(GetNumInterfaces, size_t());
protected:
virtual ~MockUsbConfigDescriptor() {}
};
class MockUsbDevice : public UsbDevice {
public:
explicit MockUsbDevice(MockUsbDeviceHandle* mock_handle)
: UsbDevice(0, 0, 0), mock_handle_(mock_handle) {
mock_handle->set_device(this);
}
virtual scoped_refptr<UsbDeviceHandle> Open() OVERRIDE {
return mock_handle_;
}
virtual bool Close(scoped_refptr<UsbDeviceHandle> handle) OVERRIDE {
EXPECT_TRUE(false) << "Should not be reached";
return false;
}
#if defined(OS_CHROMEOS)
virtual void RequestUsbAcess(
int interface_id,
const base::Callback<void(bool success)>& callback) OVERRIDE {
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE, base::Bind(callback, true));
}
#endif // OS_CHROMEOS
MOCK_METHOD0(ListInterfaces, scoped_refptr<UsbConfigDescriptor>());
private:
MockUsbDeviceHandle* mock_handle_;
virtual ~MockUsbDevice() {}
};
class MockUsbService : public UsbService {
public:
explicit MockUsbService(scoped_refptr<UsbDevice> device) : device_(device) {}
protected:
virtual scoped_refptr<UsbDevice> GetDeviceById(uint32 unique_id) OVERRIDE {
EXPECT_EQ(unique_id, 0U);
return device_;
}
virtual void GetDevices(
std::vector<scoped_refptr<UsbDevice> >* devices) OVERRIDE {
STLClearObject(devices);
devices->push_back(device_);
}
scoped_refptr<UsbDevice> device_;
};
#if defined(OS_WIN)
#pragma warning(pop)
#endif
class UsbApiTest : public ExtensionApiTest {
public:
virtual void SetUpOnMainThread() OVERRIDE {
mock_device_handle_ = new MockUsbDeviceHandle();
mock_device_ = new MockUsbDevice(mock_device_handle_.get());
scoped_refptr<content::MessageLoopRunner> runner =
new content::MessageLoopRunner;
BrowserThread::PostTaskAndReply(BrowserThread::FILE,
FROM_HERE,
base::Bind(&UsbApiTest::SetUpService, this),
runner->QuitClosure());
runner->Run();
}
void SetUpService() {
UsbService::SetInstanceForTest(new MockUsbService(mock_device_));
}
virtual void CleanUpOnMainThread() OVERRIDE {
scoped_refptr<content::MessageLoopRunner> runner =
new content::MessageLoopRunner;
UsbService* service = NULL;
BrowserThread::PostTaskAndReply(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&UsbService::SetInstanceForTest, service),
runner->QuitClosure());
runner->Run();
}
protected:
scoped_refptr<MockUsbDeviceHandle> mock_device_handle_;
scoped_refptr<MockUsbDevice> mock_device_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(UsbApiTest, DeviceHandling) {
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(4);
ASSERT_TRUE(RunExtensionTest("usb/device_handling"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, ResetDevice) {
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(2);
EXPECT_CALL(*mock_device_handle_.get(), ResetDevice())
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(
*mock_device_handle_.get(),
InterruptTransfer(usb_service::USB_DIRECTION_OUTBOUND, 2, _, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
ASSERT_TRUE(RunExtensionTest("usb/reset_device"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, ListInterfaces) {
scoped_refptr<MockUsbConfigDescriptor> mock_descriptor =
new MockUsbConfigDescriptor();
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
EXPECT_CALL(*mock_descriptor.get(), GetNumInterfaces()).WillOnce(Return(0));
EXPECT_CALL(*mock_device_.get(), ListInterfaces())
.WillOnce(Return(mock_descriptor));
ASSERT_TRUE(RunExtensionTest("usb/list_interfaces"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferEvent) {
EXPECT_CALL(*mock_device_handle_.get(),
ControlTransfer(usb_service::USB_DIRECTION_OUTBOUND,
UsbDeviceHandle::STANDARD,
UsbDeviceHandle::DEVICE,
1,
2,
3,
_,
1,
_,
_))
.WillOnce(
InvokeUsbTransferCallback<9>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(),
BulkTransfer(usb_service::USB_DIRECTION_OUTBOUND, 1, _, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(
*mock_device_handle_.get(),
InterruptTransfer(usb_service::USB_DIRECTION_OUTBOUND, 2, _, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(),
IsochronousTransfer(
usb_service::USB_DIRECTION_OUTBOUND, 3, _, 1, 1, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<7>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/transfer_event"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, ZeroLengthTransfer) {
EXPECT_CALL(*mock_device_handle_.get(), BulkTransfer(_, _, _, 0, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/zero_length_transfer"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferFailure) {
EXPECT_CALL(*mock_device_handle_.get(), BulkTransfer(_, _, _, _, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED))
.WillOnce(InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_ERROR))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_TIMEOUT));
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/transfer_failure"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, InvalidLengthTransfer) {
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/invalid_length_transfer"));
}
<commit_msg>Initialize an IOBuffer in UsbApiTest.TransferEvent to avoid an uninitialized read.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "components/usb_service/usb_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/api/usb/usb_api.h"
#include "net/base/io_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::AnyNumber;
using testing::_;
using testing::Return;
using content::BrowserThread;
using usb_service::UsbConfigDescriptor;
using usb_service::UsbDevice;
using usb_service::UsbDeviceHandle;
using usb_service::UsbEndpointDirection;
using usb_service::UsbService;
using usb_service::UsbTransferCallback;
namespace {
ACTION_TEMPLATE(InvokeUsbTransferCallback,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(p1)) {
net::IOBuffer* io_buffer = new net::IOBuffer(1);
memset(io_buffer->data(), 0, 1); // Avoid uninitialized reads.
::std::tr1::get<k>(args).Run(p1, io_buffer, 1);
}
// MSVC erroneously thinks that at least one of the arguments for the transfer
// methods differ by const or volatility and emits a warning about the old
// standards-noncompliant behaviour of their compiler.
#if defined(OS_WIN)
#pragma warning(push)
#pragma warning(disable : 4373)
#endif
class MockUsbDeviceHandle : public UsbDeviceHandle {
public:
MockUsbDeviceHandle() : UsbDeviceHandle() {}
MOCK_METHOD0(Close, void());
MOCK_METHOD10(ControlTransfer,
void(const UsbEndpointDirection direction,
const TransferRequestType request_type,
const TransferRecipient recipient,
const uint8 request,
const uint16 value,
const uint16 index,
net::IOBuffer* buffer,
const size_t length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD6(BulkTransfer,
void(const UsbEndpointDirection direction,
const uint8 endpoint,
net::IOBuffer* buffer,
const size_t length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD6(InterruptTransfer,
void(const UsbEndpointDirection direction,
const uint8 endpoint,
net::IOBuffer* buffer,
const size_t length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD8(IsochronousTransfer,
void(const UsbEndpointDirection direction,
const uint8 endpoint,
net::IOBuffer* buffer,
const size_t length,
const unsigned int packets,
const unsigned int packet_length,
const unsigned int timeout,
const UsbTransferCallback& callback));
MOCK_METHOD0(ResetDevice, bool());
void set_device(UsbDevice* device) { device_ = device; }
protected:
virtual ~MockUsbDeviceHandle() {}
};
class MockUsbConfigDescriptor : public UsbConfigDescriptor {
public:
MOCK_CONST_METHOD0(GetNumInterfaces, size_t());
protected:
virtual ~MockUsbConfigDescriptor() {}
};
class MockUsbDevice : public UsbDevice {
public:
explicit MockUsbDevice(MockUsbDeviceHandle* mock_handle)
: UsbDevice(0, 0, 0), mock_handle_(mock_handle) {
mock_handle->set_device(this);
}
virtual scoped_refptr<UsbDeviceHandle> Open() OVERRIDE {
return mock_handle_;
}
virtual bool Close(scoped_refptr<UsbDeviceHandle> handle) OVERRIDE {
EXPECT_TRUE(false) << "Should not be reached";
return false;
}
#if defined(OS_CHROMEOS)
virtual void RequestUsbAcess(
int interface_id,
const base::Callback<void(bool success)>& callback) OVERRIDE {
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE, base::Bind(callback, true));
}
#endif // OS_CHROMEOS
MOCK_METHOD0(ListInterfaces, scoped_refptr<UsbConfigDescriptor>());
private:
MockUsbDeviceHandle* mock_handle_;
virtual ~MockUsbDevice() {}
};
class MockUsbService : public UsbService {
public:
explicit MockUsbService(scoped_refptr<UsbDevice> device) : device_(device) {}
protected:
virtual scoped_refptr<UsbDevice> GetDeviceById(uint32 unique_id) OVERRIDE {
EXPECT_EQ(unique_id, 0U);
return device_;
}
virtual void GetDevices(
std::vector<scoped_refptr<UsbDevice> >* devices) OVERRIDE {
STLClearObject(devices);
devices->push_back(device_);
}
scoped_refptr<UsbDevice> device_;
};
#if defined(OS_WIN)
#pragma warning(pop)
#endif
class UsbApiTest : public ExtensionApiTest {
public:
virtual void SetUpOnMainThread() OVERRIDE {
mock_device_handle_ = new MockUsbDeviceHandle();
mock_device_ = new MockUsbDevice(mock_device_handle_.get());
scoped_refptr<content::MessageLoopRunner> runner =
new content::MessageLoopRunner;
BrowserThread::PostTaskAndReply(BrowserThread::FILE,
FROM_HERE,
base::Bind(&UsbApiTest::SetUpService, this),
runner->QuitClosure());
runner->Run();
}
void SetUpService() {
UsbService::SetInstanceForTest(new MockUsbService(mock_device_));
}
virtual void CleanUpOnMainThread() OVERRIDE {
scoped_refptr<content::MessageLoopRunner> runner =
new content::MessageLoopRunner;
UsbService* service = NULL;
BrowserThread::PostTaskAndReply(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&UsbService::SetInstanceForTest, service),
runner->QuitClosure());
runner->Run();
}
protected:
scoped_refptr<MockUsbDeviceHandle> mock_device_handle_;
scoped_refptr<MockUsbDevice> mock_device_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(UsbApiTest, DeviceHandling) {
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(4);
ASSERT_TRUE(RunExtensionTest("usb/device_handling"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, ResetDevice) {
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(2);
EXPECT_CALL(*mock_device_handle_.get(), ResetDevice())
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(
*mock_device_handle_.get(),
InterruptTransfer(usb_service::USB_DIRECTION_OUTBOUND, 2, _, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
ASSERT_TRUE(RunExtensionTest("usb/reset_device"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, ListInterfaces) {
scoped_refptr<MockUsbConfigDescriptor> mock_descriptor =
new MockUsbConfigDescriptor();
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
EXPECT_CALL(*mock_descriptor.get(), GetNumInterfaces()).WillOnce(Return(0));
EXPECT_CALL(*mock_device_.get(), ListInterfaces())
.WillOnce(Return(mock_descriptor));
ASSERT_TRUE(RunExtensionTest("usb/list_interfaces"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferEvent) {
EXPECT_CALL(*mock_device_handle_.get(),
ControlTransfer(usb_service::USB_DIRECTION_OUTBOUND,
UsbDeviceHandle::STANDARD,
UsbDeviceHandle::DEVICE,
1,
2,
3,
_,
1,
_,
_))
.WillOnce(
InvokeUsbTransferCallback<9>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(),
BulkTransfer(usb_service::USB_DIRECTION_OUTBOUND, 1, _, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(
*mock_device_handle_.get(),
InterruptTransfer(usb_service::USB_DIRECTION_OUTBOUND, 2, _, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(),
IsochronousTransfer(
usb_service::USB_DIRECTION_OUTBOUND, 3, _, 1, 1, 1, _, _))
.WillOnce(
InvokeUsbTransferCallback<7>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/transfer_event"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, ZeroLengthTransfer) {
EXPECT_CALL(*mock_device_handle_.get(), BulkTransfer(_, _, _, 0, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED));
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/zero_length_transfer"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, TransferFailure) {
EXPECT_CALL(*mock_device_handle_.get(), BulkTransfer(_, _, _, _, _, _))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_COMPLETED))
.WillOnce(InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_ERROR))
.WillOnce(
InvokeUsbTransferCallback<5>(usb_service::USB_TRANSFER_TIMEOUT));
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/transfer_failure"));
}
IN_PROC_BROWSER_TEST_F(UsbApiTest, InvalidLengthTransfer) {
EXPECT_CALL(*mock_device_handle_.get(), Close()).Times(AnyNumber());
ASSERT_TRUE(RunExtensionTest("usb/invalid_length_transfer"));
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: abpservices.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 12:51:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#ifndef _EXTENSIONS_COMPONENT_MODULE_HXX_
#include "componentmodule.hxx"
#endif
//---------------------------------------------------------------------------------------
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_OABSPilotUno();
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL abp_initializeModule()
{
static sal_Bool s_bInit = sal_False;
if (!s_bInit)
{
createRegistryInfo_OABSPilotUno();
::abp::OModule::setResourceFilePrefix("abp");
s_bInit = sal_True;
}
}
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
abp_initializeModule();
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
return ::abp::OModule::writeComponentInfos(
static_cast<XMultiServiceFactory*>(pServiceManager),
static_cast<XRegistryKey*>(pRegistryKey));
}
catch (InvalidRegistryException& )
{
OSL_ASSERT("abp::component_writeInfo: could not create a registry key (InvalidRegistryException) !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
Reference< XInterface > xRet;
if (pServiceManager && pImplementationName)
{
xRet = ::abp::OModule::getComponentFactory(
::rtl::OUString::createFromAscii(pImplementationName),
static_cast< XMultiServiceFactory* >(pServiceManager));
}
if (xRet.is())
xRet->acquire();
return xRet.get();
};
<commit_msg>INTEGRATION: CWS wae4extensions (1.4.192); FILE MERGED 2007/09/27 07:18:21 fs 1.4.192.1: #i81612# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: abpservices.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:32:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#ifndef _EXTENSIONS_COMPONENT_MODULE_HXX_
#include "componentmodule.hxx"
#endif
//---------------------------------------------------------------------------------------
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_OABSPilotUno();
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL abp_initializeModule()
{
static sal_Bool s_bInit = sal_False;
if (!s_bInit)
{
createRegistryInfo_OABSPilotUno();
::abp::OModule::setResourceFilePrefix("abp");
s_bInit = sal_True;
}
}
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment ** /*ppEnv*/
)
{
abp_initializeModule();
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
return ::abp::OModule::writeComponentInfos(
static_cast<XMultiServiceFactory*>(pServiceManager),
static_cast<XRegistryKey*>(pRegistryKey));
}
catch (InvalidRegistryException& )
{
OSL_ASSERT("abp::component_writeInfo: could not create a registry key (InvalidRegistryException) !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* /*pRegistryKey*/)
{
Reference< XInterface > xRet;
if (pServiceManager && pImplementationName)
{
xRet = ::abp::OModule::getComponentFactory(
::rtl::OUString::createFromAscii(pImplementationName),
static_cast< XMultiServiceFactory* >(pServiceManager));
}
if (xRet.is())
xRet->acquire();
return xRet.get();
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pcrcommon.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:13:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#define _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#define EDITOR_LIST_APPEND (sal_uInt16)-1
#define EDITOR_LIST_REPLACE_EXISTING (sal_uInt16)-1
/** === begin UNO includes === **/
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
/** === end UNO includes === **/
#include <vcl/smartid.hxx>
#include <tools/string.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <comphelper/listenernotification.hxx>
//............................................................................
namespace pcr
{
//............................................................................
#define OWN_PROPERTY_ID_INTROSPECTEDOBJECT 0x0010
#define OWN_PROPERTY_ID_CURRENTPAGE 0x0011
#define OWN_PROPERTY_ID_CONTROLCONTEXT 0x0012
#define OWN_PROPERTY_ID_TABBINGMODEL 0x0013
//========================================================================
//= types
//========================================================================
typedef ::comphelper::OSimpleListenerContainer < ::com::sun::star::beans::XPropertyChangeListener
, ::com::sun::star::beans::PropertyChangeEvent
> PropertyChangeListeners;
//========================================================================
//= helper
//========================================================================
// small helper to make the "swap" call on an STL container a single-line call, which
// in it's canonic form "aFoo.swap( Container() )" doesn't compile with GCC
template< class CONTAINER >
void clearContainer( CONTAINER& _rContainer )
{
CONTAINER aEmpty;
_rContainer.swap( aEmpty );
}
//========================================================================
//= HelpIdUrl
//========================================================================
/// small helper to translate help ids into help urls
class HelpIdUrl
{
public:
static SmartId getHelpId( const ::rtl::OUString& _rHelpURL );
static ::rtl::OUString getHelpURL( sal_uInt32 _nHelpId );
};
//====================================================================
//= StlSyntaxSequence
//====================================================================
template< class ELEMENT >
class StlSyntaxSequence : public ::com::sun::star::uno::Sequence< ELEMENT >
{
private:
typedef ::com::sun::star::uno::Sequence< ELEMENT > UnoBase;
public:
inline StlSyntaxSequence() : UnoBase() { }
inline StlSyntaxSequence( const UnoBase& rSeq ) : UnoBase( rSeq ) { }
inline StlSyntaxSequence( const ELEMENT* pElements, sal_Int32 len ) : UnoBase( pElements, len ) { }
inline StlSyntaxSequence( sal_Int32 len ) : UnoBase( len ) { }
operator const UnoBase&() const { return *this; }
operator UnoBase&() { return *this; }
typedef const ELEMENT* const_iterator;
typedef ELEMENT* iterator;
inline const_iterator begin() const { return UnoBase::getConstArray(); }
inline const_iterator end() const { return UnoBase::getConstArray() + UnoBase::getLength(); }
inline iterator begin() { return UnoBase::getArray(); }
inline iterator end() { return UnoBase::getArray() + UnoBase::getLength(); }
inline sal_Int32 size() const { return UnoBase::getLength(); }
inline bool empty() const { return UnoBase::getLength() == 0; }
inline void resize( size_t _newSize ) { UnoBase::realloc( _newSize ); }
inline iterator erase( iterator _pos )
{
iterator loop = end();
while ( --loop != _pos )
*( loop - 1 ) = *loop;
resize( size() - 1 );
}
};
//========================================================================
//= UNO helpers
//========================================================================
#define DECLARE_XCOMPONENT() \
virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException); \
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); \
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
#define IMPLEMENT_FORWARD_XCOMPONENT( classname, baseclass ) \
void SAL_CALL classname::dispose( ) throw (::com::sun::star::uno::RuntimeException) \
{ \
baseclass::WeakComponentImplHelperBase::dispose(); \
} \
void SAL_CALL classname::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& _Listener ) throw (::com::sun::star::uno::RuntimeException) \
{ \
baseclass::WeakComponentImplHelperBase::addEventListener( _Listener ); \
} \
void SAL_CALL classname::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& _Listener ) throw (::com::sun::star::uno::RuntimeException) \
{ \
baseclass::WeakComponentImplHelperBase::removeEventListener( _Listener ); \
} \
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.7.14); FILE MERGED 2008/03/31 12:31:51 rt 1.7.14.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: pcrcommon.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#define _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#define EDITOR_LIST_APPEND (sal_uInt16)-1
#define EDITOR_LIST_REPLACE_EXISTING (sal_uInt16)-1
/** === begin UNO includes === **/
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
/** === end UNO includes === **/
#include <vcl/smartid.hxx>
#include <tools/string.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <comphelper/listenernotification.hxx>
//............................................................................
namespace pcr
{
//............................................................................
#define OWN_PROPERTY_ID_INTROSPECTEDOBJECT 0x0010
#define OWN_PROPERTY_ID_CURRENTPAGE 0x0011
#define OWN_PROPERTY_ID_CONTROLCONTEXT 0x0012
#define OWN_PROPERTY_ID_TABBINGMODEL 0x0013
//========================================================================
//= types
//========================================================================
typedef ::comphelper::OSimpleListenerContainer < ::com::sun::star::beans::XPropertyChangeListener
, ::com::sun::star::beans::PropertyChangeEvent
> PropertyChangeListeners;
//========================================================================
//= helper
//========================================================================
// small helper to make the "swap" call on an STL container a single-line call, which
// in it's canonic form "aFoo.swap( Container() )" doesn't compile with GCC
template< class CONTAINER >
void clearContainer( CONTAINER& _rContainer )
{
CONTAINER aEmpty;
_rContainer.swap( aEmpty );
}
//========================================================================
//= HelpIdUrl
//========================================================================
/// small helper to translate help ids into help urls
class HelpIdUrl
{
public:
static SmartId getHelpId( const ::rtl::OUString& _rHelpURL );
static ::rtl::OUString getHelpURL( sal_uInt32 _nHelpId );
};
//====================================================================
//= StlSyntaxSequence
//====================================================================
template< class ELEMENT >
class StlSyntaxSequence : public ::com::sun::star::uno::Sequence< ELEMENT >
{
private:
typedef ::com::sun::star::uno::Sequence< ELEMENT > UnoBase;
public:
inline StlSyntaxSequence() : UnoBase() { }
inline StlSyntaxSequence( const UnoBase& rSeq ) : UnoBase( rSeq ) { }
inline StlSyntaxSequence( const ELEMENT* pElements, sal_Int32 len ) : UnoBase( pElements, len ) { }
inline StlSyntaxSequence( sal_Int32 len ) : UnoBase( len ) { }
operator const UnoBase&() const { return *this; }
operator UnoBase&() { return *this; }
typedef const ELEMENT* const_iterator;
typedef ELEMENT* iterator;
inline const_iterator begin() const { return UnoBase::getConstArray(); }
inline const_iterator end() const { return UnoBase::getConstArray() + UnoBase::getLength(); }
inline iterator begin() { return UnoBase::getArray(); }
inline iterator end() { return UnoBase::getArray() + UnoBase::getLength(); }
inline sal_Int32 size() const { return UnoBase::getLength(); }
inline bool empty() const { return UnoBase::getLength() == 0; }
inline void resize( size_t _newSize ) { UnoBase::realloc( _newSize ); }
inline iterator erase( iterator _pos )
{
iterator loop = end();
while ( --loop != _pos )
*( loop - 1 ) = *loop;
resize( size() - 1 );
}
};
//========================================================================
//= UNO helpers
//========================================================================
#define DECLARE_XCOMPONENT() \
virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException); \
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); \
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
#define IMPLEMENT_FORWARD_XCOMPONENT( classname, baseclass ) \
void SAL_CALL classname::dispose( ) throw (::com::sun::star::uno::RuntimeException) \
{ \
baseclass::WeakComponentImplHelperBase::dispose(); \
} \
void SAL_CALL classname::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& _Listener ) throw (::com::sun::star::uno::RuntimeException) \
{ \
baseclass::WeakComponentImplHelperBase::addEventListener( _Listener ); \
} \
void SAL_CALL classname::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& _Listener ) throw (::com::sun::star::uno::RuntimeException) \
{ \
baseclass::WeakComponentImplHelperBase::removeEventListener( _Listener ); \
} \
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-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/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 10000;
// How long to wait for the extension to load before giving up.
const int kLoadTimeoutMs = 5000;
// The extension we're using as our test case.
const char* kExtensionId = "00123456789abcdef0123456789abcdef0123456";
// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionView : public ExtensionView {
public:
MockExtensionView(const GURL& url, Profile* profile)
: ExtensionView(url, profile), got_message_(false) {
InitHidden();
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kAlertTimeoutMs);
ui_test_utils::RunMessageLoop();
}
bool got_message() { return got_message_; }
private:
virtual void RunJavaScriptMessage(
const std::wstring& message,
const std::wstring& default_prompt,
const GURL& frame_url,
const int flags,
IPC::Message* reply_msg,
bool* did_suppress_message) {
got_message_ = true;
MessageLoopForUI::current()->Quit();
// Call super, otherwise we'll leak reply_msg.
ExtensionView::RunJavaScriptMessage(
message, default_prompt, frame_url, flags,
reply_msg, did_suppress_message);
}
bool got_message_;
};
// This class waits for a specific extension to be loaded.
class ExtensionLoadedObserver : public NotificationObserver {
public:
explicit ExtensionLoadedObserver() : extension_(NULL) {
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
}
Extension* WaitForExtension() {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kLoadTimeoutMs);
ui_test_utils::RunMessageLoop();
return extension_;
}
private:
virtual void Observe(NotificationType type, const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSIONS_LOADED) {
ExtensionList* extensions = Details<ExtensionList>(details).ptr();
for (size_t i = 0; i < (*extensions).size(); i++) {
if ((*extensions)[i]->id() == kExtensionId) {
extension_ = (*extensions)[i];
MessageLoopForUI::current()->Quit();
break;
}
}
} else {
NOTREACHED();
}
}
NotificationRegistrar registrar_;
Extension* extension_;
};
} // namespace
class ExtensionViewTest : public InProcessBrowserTest {
public:
virtual void SetUp() {
// Initialize the error reporter here, otherwise BrowserMain will create it
// with the wrong MessageLoop.
ExtensionErrorReporter::Init(false);
// Use single-process in an attempt to speed it up and make it less flaky.
EnableSingleProcess();
InProcessBrowserTest::SetUp();
}
};
// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's "index.html" file.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Index) {
// Create an observer first to be sure we have the notification registered
// before it's sent.
ExtensionLoadedObserver observer;
// Get the path to our extension.
FilePath path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
path = path.AppendASCII("extensions").
AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
ASSERT_TRUE(file_util::DirectoryExists(path)); // sanity check
// Load it.
Profile* profile = browser()->profile();
profile->GetExtensionsService()->Init();
profile->GetExtensionsService()->LoadExtension(path);
// Now wait for it to load, and grab a pointer to it.
Extension* extension = observer.WaitForExtension();
ASSERT_TRUE(extension);
GURL url = Extension::GetResourceURL(extension->url(), "toolstrip.html");
// Start the extension process and wait for it to show a javascript alert.
MockExtensionView view(url, profile);
EXPECT_TRUE(view.got_message());
}
<commit_msg>Disable single-process mode in ExtensionViewTest, to see if it's causing buildbot problems. Review URL: http://codereview.chromium.org/46052<commit_after>// Copyright (c) 2006-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/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 20000;
// How long to wait for the extension to load before giving up.
const int kLoadTimeoutMs = 10000;
// The extension we're using as our test case.
const char* kExtensionId = "00123456789abcdef0123456789abcdef0123456";
// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionView : public ExtensionView {
public:
MockExtensionView(const GURL& url, Profile* profile)
: ExtensionView(url, profile), got_message_(false) {
InitHidden();
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kAlertTimeoutMs);
ui_test_utils::RunMessageLoop();
}
bool got_message() { return got_message_; }
private:
virtual void RunJavaScriptMessage(
const std::wstring& message,
const std::wstring& default_prompt,
const GURL& frame_url,
const int flags,
IPC::Message* reply_msg,
bool* did_suppress_message) {
got_message_ = true;
MessageLoopForUI::current()->Quit();
// Call super, otherwise we'll leak reply_msg.
ExtensionView::RunJavaScriptMessage(
message, default_prompt, frame_url, flags,
reply_msg, did_suppress_message);
}
bool got_message_;
};
// This class waits for a specific extension to be loaded.
class ExtensionLoadedObserver : public NotificationObserver {
public:
explicit ExtensionLoadedObserver() : extension_(NULL) {
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
}
Extension* WaitForExtension() {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kLoadTimeoutMs);
ui_test_utils::RunMessageLoop();
return extension_;
}
private:
virtual void Observe(NotificationType type, const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSIONS_LOADED) {
ExtensionList* extensions = Details<ExtensionList>(details).ptr();
for (size_t i = 0; i < (*extensions).size(); i++) {
if ((*extensions)[i]->id() == kExtensionId) {
extension_ = (*extensions)[i];
MessageLoopForUI::current()->Quit();
break;
}
}
} else {
NOTREACHED();
}
}
NotificationRegistrar registrar_;
Extension* extension_;
};
} // namespace
class ExtensionViewTest : public InProcessBrowserTest {
public:
virtual void SetUp() {
// Initialize the error reporter here, otherwise BrowserMain will create it
// with the wrong MessageLoop.
ExtensionErrorReporter::Init(false);
// Use single-process in an attempt to speed it up and make it less flaky.
//EnableSingleProcess();
InProcessBrowserTest::SetUp();
}
};
// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's "index.html" file.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Index) {
// Create an observer first to be sure we have the notification registered
// before it's sent.
ExtensionLoadedObserver observer;
// Get the path to our extension.
FilePath path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
path = path.AppendASCII("extensions").
AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
ASSERT_TRUE(file_util::DirectoryExists(path)); // sanity check
// Load it.
Profile* profile = browser()->profile();
profile->GetExtensionsService()->Init();
profile->GetExtensionsService()->LoadExtension(path);
// Now wait for it to load, and grab a pointer to it.
Extension* extension = observer.WaitForExtension();
ASSERT_TRUE(extension);
GURL url = Extension::GetResourceURL(extension->url(), "toolstrip.html");
// Start the extension process and wait for it to show a javascript alert.
MockExtensionView view(url, profile);
EXPECT_TRUE(view.got_message());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2008-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/history/history_publisher.h"
#include <atlsafe.h>
#include <objbase.h>
#include <oleauto.h>
#include <wtypes.h>
#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
namespace {
// Instantiates a IChromeHistoryIndexer COM object. Takes a COM class id
// in |name| and returns the object in |indexer|. Returns false if the
// operation fails.
bool CoCreateIndexerFromName(const wchar_t* name,
IChromeHistoryIndexer** indexer) {
CLSID clsid;
HRESULT hr = CLSIDFromString(const_cast<wchar_t*>(name), &clsid);
if (FAILED(hr))
return false;
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC,
__uuidof(IChromeHistoryIndexer),
reinterpret_cast<void**>(indexer));
if (FAILED(hr))
return false;
return true;
}
// Instantiates the registered indexers from the registry |root| + |path| key
// and adds them to the |indexers| list.
void AddRegisteredIndexers(HKEY root, const wchar_t* path,
std::vector< ScopedComPtr<IChromeHistoryIndexer> >* indexers) {
IChromeHistoryIndexer* indexer;
RegistryKeyIterator r_iter(root, path);
while (r_iter.Valid()) {
if (CoCreateIndexerFromName(r_iter.Name(), &indexer)) {
indexers->push_back(ScopedComPtr<IChromeHistoryIndexer>(indexer));
indexer->Release();
}
++r_iter;
}
}
} // namespace
namespace history {
const wchar_t* const HistoryPublisher::kRegKeyRegisteredIndexersInfo =
L"Software\\Google\\Google Chrome\\IndexerPlugins";
// static
double HistoryPublisher::TimeToUTCVariantTime(const base::Time& time) {
double var_time = 0;
if (!time.is_null()) {
base::Time::Exploded exploded;
time.UTCExplode(&exploded);
// Create the system time struct representing our exploded time.
SYSTEMTIME system_time;
system_time.wYear = exploded.year;
system_time.wMonth = exploded.month;
system_time.wDayOfWeek = exploded.day_of_week;
system_time.wDay = exploded.day_of_month;
system_time.wHour = exploded.hour;
system_time.wMinute = exploded.minute;
system_time.wSecond = exploded.second;
system_time.wMilliseconds = exploded.millisecond;
SystemTimeToVariantTime(&system_time, &var_time);
}
return var_time;
}
HistoryPublisher::HistoryPublisher() {
CoInitialize(NULL);
}
HistoryPublisher::~HistoryPublisher() {
CoUninitialize();
}
bool HistoryPublisher::Init() {
return ReadRegisteredIndexersFromRegistry();
}
// Peruse the registry for Indexer to instantiate and store in |indexers_|.
// Return true if we found at least one indexer object. We look both in HKCU
// and HKLM.
bool HistoryPublisher::ReadRegisteredIndexersFromRegistry() {
AddRegisteredIndexers(HKEY_CURRENT_USER,
kRegKeyRegisteredIndexersInfo, &indexers_);
AddRegisteredIndexers(HKEY_LOCAL_MACHINE,
kRegKeyRegisteredIndexersInfo, &indexers_);
return indexers_.size() > 0;
}
void HistoryPublisher::PublishDataToIndexers(const PageData& page_data)
const {
double var_time = TimeToUTCVariantTime(page_data.time);
CComSafeArray<unsigned char> thumbnail_arr;
if (page_data.thumbnail) {
for (size_t i = 0; i < page_data.thumbnail->size(); ++i)
thumbnail_arr.Add((*page_data.thumbnail)[i]);
}
// Send data to registered indexers.
ScopedVariant time(var_time, VT_DATE);
ScopedBstr url(ASCIIToWide(page_data.url.spec()).c_str());
ScopedBstr html(page_data.html);
ScopedBstr title(page_data.title);
ScopedBstr format(ASCIIToWide(page_data.thumbnail_format).c_str());
ScopedVariant psa(thumbnail_arr.m_psa);
for (size_t i = 0; i < indexers_.size(); ++i) {
indexers_[i]->SendPageData(time, url, html, title, format, psa);
}
}
void HistoryPublisher::DeleteUserHistoryBetween(const base::Time& begin_time,
const base::Time& end_time)
const {
ScopedVariant var_begin_time(TimeToUTCVariantTime(begin_time), VT_DATE);
ScopedVariant var_end_time(TimeToUTCVariantTime(end_time), VT_DATE);
for (size_t i = 0; i < indexers_.size(); ++i) {
indexers_[i]->DeleteUserHistoryBetween(var_begin_time, var_end_time);
}
}
} // namespace history
<commit_msg>Fix a crash in the history publisher. This is caused by me changing the signature of ASCIIToWide to no longer take a string piece. This changed the behavior for NULL handling (NULL is no longer supported).<commit_after>// Copyright (c) 2008-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/history/history_publisher.h"
#include <atlsafe.h>
#include <objbase.h>
#include <oleauto.h>
#include <wtypes.h>
#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
namespace {
// Instantiates a IChromeHistoryIndexer COM object. Takes a COM class id
// in |name| and returns the object in |indexer|. Returns false if the
// operation fails.
bool CoCreateIndexerFromName(const wchar_t* name,
IChromeHistoryIndexer** indexer) {
CLSID clsid;
HRESULT hr = CLSIDFromString(const_cast<wchar_t*>(name), &clsid);
if (FAILED(hr))
return false;
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC,
__uuidof(IChromeHistoryIndexer),
reinterpret_cast<void**>(indexer));
if (FAILED(hr))
return false;
return true;
}
// Instantiates the registered indexers from the registry |root| + |path| key
// and adds them to the |indexers| list.
void AddRegisteredIndexers(HKEY root, const wchar_t* path,
std::vector< ScopedComPtr<IChromeHistoryIndexer> >* indexers) {
IChromeHistoryIndexer* indexer;
RegistryKeyIterator r_iter(root, path);
while (r_iter.Valid()) {
if (CoCreateIndexerFromName(r_iter.Name(), &indexer)) {
indexers->push_back(ScopedComPtr<IChromeHistoryIndexer>(indexer));
indexer->Release();
}
++r_iter;
}
}
} // namespace
namespace history {
const wchar_t* const HistoryPublisher::kRegKeyRegisteredIndexersInfo =
L"Software\\Google\\Google Chrome\\IndexerPlugins";
// static
double HistoryPublisher::TimeToUTCVariantTime(const base::Time& time) {
double var_time = 0;
if (!time.is_null()) {
base::Time::Exploded exploded;
time.UTCExplode(&exploded);
// Create the system time struct representing our exploded time.
SYSTEMTIME system_time;
system_time.wYear = exploded.year;
system_time.wMonth = exploded.month;
system_time.wDayOfWeek = exploded.day_of_week;
system_time.wDay = exploded.day_of_month;
system_time.wHour = exploded.hour;
system_time.wMinute = exploded.minute;
system_time.wSecond = exploded.second;
system_time.wMilliseconds = exploded.millisecond;
SystemTimeToVariantTime(&system_time, &var_time);
}
return var_time;
}
HistoryPublisher::HistoryPublisher() {
CoInitialize(NULL);
}
HistoryPublisher::~HistoryPublisher() {
CoUninitialize();
}
bool HistoryPublisher::Init() {
return ReadRegisteredIndexersFromRegistry();
}
// Peruse the registry for Indexer to instantiate and store in |indexers_|.
// Return true if we found at least one indexer object. We look both in HKCU
// and HKLM.
bool HistoryPublisher::ReadRegisteredIndexersFromRegistry() {
AddRegisteredIndexers(HKEY_CURRENT_USER,
kRegKeyRegisteredIndexersInfo, &indexers_);
AddRegisteredIndexers(HKEY_LOCAL_MACHINE,
kRegKeyRegisteredIndexersInfo, &indexers_);
return indexers_.size() > 0;
}
void HistoryPublisher::PublishDataToIndexers(const PageData& page_data)
const {
double var_time = TimeToUTCVariantTime(page_data.time);
CComSafeArray<unsigned char> thumbnail_arr;
if (page_data.thumbnail) {
for (size_t i = 0; i < page_data.thumbnail->size(); ++i)
thumbnail_arr.Add((*page_data.thumbnail)[i]);
}
// Send data to registered indexers.
ScopedVariant time(var_time, VT_DATE);
ScopedBstr url(ASCIIToWide(page_data.url.spec()).c_str());
ScopedBstr html(page_data.html);
ScopedBstr title(page_data.title);
// Don't send a NULL string through ASCIIToWide.
ScopedBstr format(page_data.thumbnail_format ?
ASCIIToWide(page_data.thumbnail_format).c_str() :
NULL);
ScopedVariant psa(thumbnail_arr.m_psa);
for (size_t i = 0; i < indexers_.size(); ++i) {
indexers_[i]->SendPageData(time, url, html, title, format, psa);
}
}
void HistoryPublisher::DeleteUserHistoryBetween(const base::Time& begin_time,
const base::Time& end_time)
const {
ScopedVariant var_begin_time(TimeToUTCVariantTime(begin_time), VT_DATE);
ScopedVariant var_end_time(TimeToUTCVariantTime(end_time), VT_DATE);
for (size_t i = 0; i < indexers_.size(); ++i) {
indexers_[i]->DeleteUserHistoryBetween(var_begin_time, var_end_time);
}
}
} // namespace history
<|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/common/extensions/extension_constants.h"
namespace extension_manifest_keys {
const char* kAllFrames = "all_frames";
const char* kApp = "app";
const char* kBackground = "background_page";
const char* kBrowserAction = "browser_action";
const char* kChromeURLOverrides = "chrome_url_overrides";
const char* kContentScripts = "content_scripts";
const char* kConvertedFromUserScript = "converted_from_user_script";
const char* kCss = "css";
const char* kCurrentLocale = "current_locale";
const char* kDefaultLocale = "default_locale";
const char* kDescription = "description";
const char* kDevToolsPage = "devtools_page";
const char* kExcludeGlobs = "exclude_globs";
const char* kHomepageURL = "homepage_url";
const char* kIcons = "icons";
const char* kIncognito = "incognito";
const char* kIncludeGlobs = "include_globs";
const char* kJs = "js";
const char* kLaunch = "app.launch";
const char* kLaunchContainer = "app.launch.container";
const char* kLaunchHeight = "app.launch.height";
const char* kLaunchLocalPath = "app.launch.local_path";
const char* kLaunchWebURL = "app.launch.web_url";
const char* kLaunchWidth = "app.launch.width";
const char* kMatches = "matches";
const char* kMinimumChromeVersion = "minimum_chrome_version";
const char* kName = "name";
const char* kOmnibox = "omnibox";
const char* kOmniboxKeyword = "omnibox.keyword";
const char* kOptionsPage = "options_page";
const char* kPageAction = "page_action";
const char* kPageActionDefaultIcon = "default_icon";
const char* kPageActionDefaultPopup = "default_popup";
const char* kPageActionDefaultTitle = "default_title";
const char* kPageActionIcons = "icons";
const char* kPageActionId = "id";
const char* kPageActionPopup = "popup";
const char* kPageActionPopupHeight = "height";
const char* kPageActionPopupPath = "path";
const char* kPageActions = "page_actions";
const char* kPermissions = "permissions";
const char* kPlugins = "plugins";
const char* kPluginsPath = "path";
const char* kPluginsPublic = "public";
const char* kPublicKey = "key";
const char* kRunAt = "run_at";
const char* kSidebar = "sidebar";
const char* kSidebarDefaultIcon = "default_icon";
const char* kSidebarDefaultTitle = "default_title";
const char* kSidebarDefaultUrl = "default_url";
const char* kSignature = "signature";
const char* kTheme = "theme";
const char* kThemeColors = "colors";
const char* kThemeDisplayProperties = "properties";
const char* kThemeImages = "images";
const char* kThemeTints = "tints";
const char* kToolstripPath = "path";
const char* kToolstrips = "toolstrips";
const char* kTts = "tts";
const char* kTtsGenderFemale = "female";
const char* kTtsGenderMale = "male";
const char* kTtsVoices = "voices";
const char* kTtsVoicesGender = "gender";
const char* kTtsVoicesLocale = "locale";
const char* kTtsVoicesVoiceName = "voiceName";
const char* kType = "type";
const char* kUpdateURL = "update_url";
const char* kVersion = "version";
const char* kWebURLs = "app.urls";
} // namespace extension_manifest_keys
namespace extension_manifest_values {
const char* kIncognitoSplit = "split";
const char* kIncognitoSpanning = "spanning";
const char* kRunAtDocumentStart = "document_start";
const char* kRunAtDocumentEnd = "document_end";
const char* kRunAtDocumentIdle = "document_idle";
const char* kPageActionTypeTab = "tab";
const char* kPageActionTypePermanent = "permanent";
const char* kLaunchContainerPanel = "panel";
const char* kLaunchContainerTab = "tab";
const char* kLaunchContainerWindow = "window";
} // namespace extension_manifest_values
// Extension-related error messages. Some of these are simple patterns, where a
// '*' is replaced at runtime with a specific value. This is used instead of
// printf because we want to unit test them and scanf is hard to make
// cross-platform.
namespace extension_manifest_errors {
const char* kAppsNotEnabled =
"Apps are not enabled.";
const char* kCannotAccessPage =
"Cannot access contents of url \"*\". "
"Extension manifest must request permission to access this host.";
const char* kCannotScriptGallery =
"The extensions gallery cannot be scripted.";
const char* kChromeVersionTooLow =
"This extension requires * version * or greater.";
const char* kDisabledByPolicy =
"This extension has been disabled by your administrator.";
const char* kDevToolsExperimental =
"You must request the 'experimental' permission in order to use the"
" DevTools API.";
const char* kExperimentalFlagRequired =
"Loading extensions with 'experimental' permission requires"
" --enable-experimental-extension-apis command line flag.";
const char* kHostedAppsCannotIncludeExtensionFeatures =
"Hosted apps cannot use extension features.";
const char* kInvalidAllFrames =
"Invalid value for 'content_scripts[*].all_frames'.";
const char* kInvalidBackground =
"Invalid value for 'background_page'.";
const char* kInvalidBrowserAction =
"Invalid value for 'browser_action'.";
const char* kInvalidChromeURLOverrides =
"Invalid value for 'chrome_url_overrides'.";
const char* kInvalidContentScript =
"Invalid value for 'content_scripts[*]'.";
const char* kInvalidContentScriptsList =
"Invalid value for 'content_scripts'.";
const char* kInvalidCss =
"Invalid value for 'content_scripts[*].css[*]'.";
const char* kInvalidCssList =
"Required value 'content_scripts[*].css' is invalid.";
const char* kInvalidDefaultLocale =
"Invalid value for default locale - locale name must be a string.";
const char* kInvalidDescription =
"Invalid value for 'description'.";
const char* kInvalidDevToolsPage =
"Invalid value for 'devtools_page'.";
const char* kInvalidGlob =
"Invalid value for 'content_scripts[*].*[*]'.";
const char* kInvalidGlobList =
"Invalid value for 'content_scripts[*].*'.";
const char* kInvalidHomepageURL =
"Invalid value for homepage url: '[*]'.";
const char* kInvalidIconPath =
"Invalid value for 'icons[\"*\"]'.";
const char* kInvalidIcons =
"Invalid value for 'icons'.";
const char* kInvalidIncognitoBehavior =
"Invalid value for 'incognito'.";
const char* kInvalidJs =
"Invalid value for 'content_scripts[*].js[*]'.";
const char* kInvalidJsList =
"Required value 'content_scripts[*].js' is invalid.";
const char* kInvalidKey =
"Value 'key' is missing or invalid.";
const char* kInvalidLaunchContainer =
"Invalid value for 'app.launch.container'.";
const char* kInvalidLaunchHeight =
"Invalid value for 'app.launch.height'.";
const char* kInvalidLaunchHeightContainer =
"Invalid container type for 'app.launch.height'.";
const char* kInvalidLaunchLocalPath =
"Invalid value for 'app.launch.local_path'.";
const char* kInvalidLaunchWebURL =
"Invalid value for 'app.launch.web_url'.";
const char* kInvalidLaunchWidth =
"Invalid value for 'app.launch.width'.";
const char* kInvalidLaunchWidthContainer =
"Invalid container type for 'app.launch.width'.";
const char* kInvalidManifest =
"Manifest file is invalid.";
const char* kInvalidMatch =
"Invalid value for 'content_scripts[*].matches[*]'.";
const char* kInvalidMatchCount =
"Invalid value for 'content_scripts[*].matches'. There must be at least"
"one match specified.";
const char* kInvalidMatches =
"Required value 'content_scripts[*].matches' is missing or invalid.";
const char* kInvalidMinimumChromeVersion =
"Invalid value for 'minimum_chrome_version'.";
const char* kInvalidName =
"Required value 'name' is missing or invalid.";
const char* kInvalidOmniboxKeyword =
"Invalid value for 'omnibox.keyword'.";
const char* kInvalidOptionsPage =
"Invalid value for 'options_page'.";
const char* kInvalidOptionsPageExpectUrlInPackage =
"Invalid value for 'options_page'. Value must be a relative path.";
const char* kInvalidOptionsPageInHostedApp =
"Invalid value for 'options_page'. Hosted apps must specify an "
"absolute URL.";
const char* kInvalidPageAction =
"Invalid value for 'page_action'.";
const char* kInvalidPageActionDefaultTitle =
"Invalid value for 'default_title'.";
const char* kInvalidPageActionIconPath =
"Invalid value for 'page_action.default_icon'.";
const char* kInvalidPageActionId =
"Required value 'id' is missing or invalid.";
const char* kInvalidPageActionName =
"Invalid value for 'page_action.name'.";
const char* kInvalidPageActionOldAndNewKeys =
"Key \"*\" is deprecated. Key \"*\" has the same meaning. You can not "
"use both.";
const char* kInvalidPageActionPopup =
"Invalid type for page action popup.";
const char* kInvalidPageActionPopupHeight =
"Invalid value for page action popup height [*].";
const char* kInvalidPageActionPopupPath =
"Invalid value for page action popup path [*].";
const char* kInvalidPageActionsList =
"Invalid value for 'page_actions'.";
const char* kInvalidPageActionsListSize =
"Invalid value for 'page_actions'. There can be at most one page action.";
const char* kInvalidPageActionTypeValue =
"Invalid value for 'page_actions[*].type', expected 'tab' or 'permanent'.";
const char* kInvalidPermission =
"Invalid value for 'permissions[*]'.";
const char* kInvalidPermissions =
"Required value 'permissions' is missing or invalid.";
const char* kInvalidPermissionScheme =
"Invalid scheme for 'permissions[*]'.";
const char* kInvalidPlugins =
"Invalid value for 'plugins'.";
const char* kInvalidPluginsPath =
"Invalid value for 'plugins[*].path'.";
const char* kInvalidPluginsPublic =
"Invalid value for 'plugins[*].public'.";
const char* kInvalidRunAt =
"Invalid value for 'content_scripts[*].run_at'.";
extern const char* kInvalidSidebar =
"Invalid value for 'sidebar'.";
extern const char* kInvalidSidebarDefaultIconPath =
"Invalid value for 'sidebar.default_icon'.";
extern const char* kInvalidSidebarDefaultTitle =
"Invalid value for 'sidebar.default_title'.";
extern const char* kInvalidSidebarDefaultUrl =
"Invalid value for 'sidebar.default_url'.";
const char* kInvalidSignature =
"Value 'signature' is missing or invalid.";
const char* kInvalidTheme =
"Invalid value for 'theme'.";
const char* kInvalidThemeColors =
"Invalid value for theme colors - colors must be integers";
const char* kInvalidThemeImages =
"Invalid value for theme images - images must be strings.";
const char* kInvalidThemeImagesMissing =
"An image specified in the theme is missing.";
const char* kInvalidThemeTints =
"Invalid value for theme images - tints must be decimal numbers.";
const char* kInvalidToolstrip =
"Invalid value for 'toolstrips[*]'";
const char* kInvalidToolstrips =
"Invalid value for 'toolstrips'.";
const char* kInvalidTts =
"Invalid value for 'tts'.";
const char* kInvalidTtsVoices =
"Invalid value for 'tts.voices'.";
const char* kInvalidTtsVoicesGender =
"Invalid value for 'tts.voices[*].gender'.";
const char* kInvalidTtsVoicesLocale =
"Invalid value for 'tts.voices[*].locale'.";
const char* kInvalidTtsVoicesVoiceName =
"Invalid value for 'tts.voices[*].voiceName'.";
const char* kInvalidUpdateURL =
"Invalid value for update url: '[*]'.";
const char* kInvalidVersion =
"Required value 'version' is missing or invalid. It must be between 1-4 "
"dot-separated integers each between 0 and 65536.";
const char* kInvalidWebURL =
"Invalid value for 'app.urls[*]'.";
const char* kInvalidWebURLs =
"Invalid value for 'app.urls'.";
const char* kInvalidZipHash =
"Required key 'zip_hash' is missing or invalid.";
const char* kLaunchPathAndURLAreExclusive =
"The 'app.launch.local_path' and 'launch.web_url' keys cannot both be set.";
const char* kLaunchURLRequired =
"Either 'app.launch.local_path' or 'app.launch.web_url' is required.";
const char* kLocalesMessagesFileMissing =
"Messages file is missing for locale.";
const char* kLocalesNoDefaultLocaleSpecified =
"Localization used, but default_locale wasn't specified in the manifest.";
const char* kLocalesNoDefaultMessages =
"Default locale is defined but default data couldn't be loaded.";
const char* kLocalesNoValidLocaleNamesListed =
"No valid locale name could be found in _locales directory.";
const char* kLocalesTreeMissing =
"Default locale was specified, but _locales subtree is missing.";
const char* kManifestParseError =
"Manifest is not valid JSON.";
const char* kManifestUnreadable =
"Manifest file is missing or unreadable.";
const char* kMissingFile =
"At least one js or css file is required for 'content_scripts[*]'.";
const char* kMultipleOverrides =
"An extension cannot override more than one page.";
const char* kOneUISurfaceOnly =
"Only one of 'browser_action', 'page_action', and 'app' can be specified.";
const char* kReservedMessageFound =
"Reserved key * found in message catalog.";
const char* kSidebarExperimental =
"You must request the 'experimental' permission in order to use the"
" Sidebar API.";
const char* kThemesCannotContainExtensions =
"A theme cannot contain extensions code.";
#if defined(OS_CHROMEOS)
const char* kIllegalPlugins =
"Extensions cannot install plugins on Chrome OS";
#endif
} // namespace extension_manifest_errors
namespace extension_urls {
const char* kGalleryBrowsePrefix = "https://chrome.google.com/webstore";
const char* kMiniGalleryBrowsePrefix = "https://tools.google.com/chrome/";
const char* kMiniGalleryDownloadPrefix = "https://dl-ssl.google.com/chrome/";
}
namespace extension_filenames {
const char* kTempExtensionName = "CRX_INSTALL";
// The file to write our decoded images to, relative to the extension_path.
const char* kDecodedImagesFilename = "DECODED_IMAGES";
// The file to write our decoded message catalogs to, relative to the
// extension_path.
const char* kDecodedMessageCatalogsFilename = "DECODED_MESSAGE_CATALOGS";
}
namespace extension_misc {
const char* kBookmarkManagerId = "eemcgdkfndhakfknompkggombfjjjeno";
const char* kWebStoreAppId = "ahfgeienlihckogmohjhadlkjgocpleb";
const char* kAppsPromoHistogram = "Extensions.AppsPromo";
}
<commit_msg>Remove stray externs in .cc code<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/common/extensions/extension_constants.h"
namespace extension_manifest_keys {
const char* kAllFrames = "all_frames";
const char* kApp = "app";
const char* kBackground = "background_page";
const char* kBrowserAction = "browser_action";
const char* kChromeURLOverrides = "chrome_url_overrides";
const char* kContentScripts = "content_scripts";
const char* kConvertedFromUserScript = "converted_from_user_script";
const char* kCss = "css";
const char* kCurrentLocale = "current_locale";
const char* kDefaultLocale = "default_locale";
const char* kDescription = "description";
const char* kDevToolsPage = "devtools_page";
const char* kExcludeGlobs = "exclude_globs";
const char* kHomepageURL = "homepage_url";
const char* kIcons = "icons";
const char* kIncognito = "incognito";
const char* kIncludeGlobs = "include_globs";
const char* kJs = "js";
const char* kLaunch = "app.launch";
const char* kLaunchContainer = "app.launch.container";
const char* kLaunchHeight = "app.launch.height";
const char* kLaunchLocalPath = "app.launch.local_path";
const char* kLaunchWebURL = "app.launch.web_url";
const char* kLaunchWidth = "app.launch.width";
const char* kMatches = "matches";
const char* kMinimumChromeVersion = "minimum_chrome_version";
const char* kName = "name";
const char* kOmnibox = "omnibox";
const char* kOmniboxKeyword = "omnibox.keyword";
const char* kOptionsPage = "options_page";
const char* kPageAction = "page_action";
const char* kPageActionDefaultIcon = "default_icon";
const char* kPageActionDefaultPopup = "default_popup";
const char* kPageActionDefaultTitle = "default_title";
const char* kPageActionIcons = "icons";
const char* kPageActionId = "id";
const char* kPageActionPopup = "popup";
const char* kPageActionPopupHeight = "height";
const char* kPageActionPopupPath = "path";
const char* kPageActions = "page_actions";
const char* kPermissions = "permissions";
const char* kPlugins = "plugins";
const char* kPluginsPath = "path";
const char* kPluginsPublic = "public";
const char* kPublicKey = "key";
const char* kRunAt = "run_at";
const char* kSidebar = "sidebar";
const char* kSidebarDefaultIcon = "default_icon";
const char* kSidebarDefaultTitle = "default_title";
const char* kSidebarDefaultUrl = "default_url";
const char* kSignature = "signature";
const char* kTheme = "theme";
const char* kThemeColors = "colors";
const char* kThemeDisplayProperties = "properties";
const char* kThemeImages = "images";
const char* kThemeTints = "tints";
const char* kToolstripPath = "path";
const char* kToolstrips = "toolstrips";
const char* kTts = "tts";
const char* kTtsGenderFemale = "female";
const char* kTtsGenderMale = "male";
const char* kTtsVoices = "voices";
const char* kTtsVoicesGender = "gender";
const char* kTtsVoicesLocale = "locale";
const char* kTtsVoicesVoiceName = "voiceName";
const char* kType = "type";
const char* kUpdateURL = "update_url";
const char* kVersion = "version";
const char* kWebURLs = "app.urls";
} // namespace extension_manifest_keys
namespace extension_manifest_values {
const char* kIncognitoSplit = "split";
const char* kIncognitoSpanning = "spanning";
const char* kRunAtDocumentStart = "document_start";
const char* kRunAtDocumentEnd = "document_end";
const char* kRunAtDocumentIdle = "document_idle";
const char* kPageActionTypeTab = "tab";
const char* kPageActionTypePermanent = "permanent";
const char* kLaunchContainerPanel = "panel";
const char* kLaunchContainerTab = "tab";
const char* kLaunchContainerWindow = "window";
} // namespace extension_manifest_values
// Extension-related error messages. Some of these are simple patterns, where a
// '*' is replaced at runtime with a specific value. This is used instead of
// printf because we want to unit test them and scanf is hard to make
// cross-platform.
namespace extension_manifest_errors {
const char* kAppsNotEnabled =
"Apps are not enabled.";
const char* kCannotAccessPage =
"Cannot access contents of url \"*\". "
"Extension manifest must request permission to access this host.";
const char* kCannotScriptGallery =
"The extensions gallery cannot be scripted.";
const char* kChromeVersionTooLow =
"This extension requires * version * or greater.";
const char* kDisabledByPolicy =
"This extension has been disabled by your administrator.";
const char* kDevToolsExperimental =
"You must request the 'experimental' permission in order to use the"
" DevTools API.";
const char* kExperimentalFlagRequired =
"Loading extensions with 'experimental' permission requires"
" --enable-experimental-extension-apis command line flag.";
const char* kHostedAppsCannotIncludeExtensionFeatures =
"Hosted apps cannot use extension features.";
const char* kInvalidAllFrames =
"Invalid value for 'content_scripts[*].all_frames'.";
const char* kInvalidBackground =
"Invalid value for 'background_page'.";
const char* kInvalidBrowserAction =
"Invalid value for 'browser_action'.";
const char* kInvalidChromeURLOverrides =
"Invalid value for 'chrome_url_overrides'.";
const char* kInvalidContentScript =
"Invalid value for 'content_scripts[*]'.";
const char* kInvalidContentScriptsList =
"Invalid value for 'content_scripts'.";
const char* kInvalidCss =
"Invalid value for 'content_scripts[*].css[*]'.";
const char* kInvalidCssList =
"Required value 'content_scripts[*].css' is invalid.";
const char* kInvalidDefaultLocale =
"Invalid value for default locale - locale name must be a string.";
const char* kInvalidDescription =
"Invalid value for 'description'.";
const char* kInvalidDevToolsPage =
"Invalid value for 'devtools_page'.";
const char* kInvalidGlob =
"Invalid value for 'content_scripts[*].*[*]'.";
const char* kInvalidGlobList =
"Invalid value for 'content_scripts[*].*'.";
const char* kInvalidHomepageURL =
"Invalid value for homepage url: '[*]'.";
const char* kInvalidIconPath =
"Invalid value for 'icons[\"*\"]'.";
const char* kInvalidIcons =
"Invalid value for 'icons'.";
const char* kInvalidIncognitoBehavior =
"Invalid value for 'incognito'.";
const char* kInvalidJs =
"Invalid value for 'content_scripts[*].js[*]'.";
const char* kInvalidJsList =
"Required value 'content_scripts[*].js' is invalid.";
const char* kInvalidKey =
"Value 'key' is missing or invalid.";
const char* kInvalidLaunchContainer =
"Invalid value for 'app.launch.container'.";
const char* kInvalidLaunchHeight =
"Invalid value for 'app.launch.height'.";
const char* kInvalidLaunchHeightContainer =
"Invalid container type for 'app.launch.height'.";
const char* kInvalidLaunchLocalPath =
"Invalid value for 'app.launch.local_path'.";
const char* kInvalidLaunchWebURL =
"Invalid value for 'app.launch.web_url'.";
const char* kInvalidLaunchWidth =
"Invalid value for 'app.launch.width'.";
const char* kInvalidLaunchWidthContainer =
"Invalid container type for 'app.launch.width'.";
const char* kInvalidManifest =
"Manifest file is invalid.";
const char* kInvalidMatch =
"Invalid value for 'content_scripts[*].matches[*]'.";
const char* kInvalidMatchCount =
"Invalid value for 'content_scripts[*].matches'. There must be at least"
"one match specified.";
const char* kInvalidMatches =
"Required value 'content_scripts[*].matches' is missing or invalid.";
const char* kInvalidMinimumChromeVersion =
"Invalid value for 'minimum_chrome_version'.";
const char* kInvalidName =
"Required value 'name' is missing or invalid.";
const char* kInvalidOmniboxKeyword =
"Invalid value for 'omnibox.keyword'.";
const char* kInvalidOptionsPage =
"Invalid value for 'options_page'.";
const char* kInvalidOptionsPageExpectUrlInPackage =
"Invalid value for 'options_page'. Value must be a relative path.";
const char* kInvalidOptionsPageInHostedApp =
"Invalid value for 'options_page'. Hosted apps must specify an "
"absolute URL.";
const char* kInvalidPageAction =
"Invalid value for 'page_action'.";
const char* kInvalidPageActionDefaultTitle =
"Invalid value for 'default_title'.";
const char* kInvalidPageActionIconPath =
"Invalid value for 'page_action.default_icon'.";
const char* kInvalidPageActionId =
"Required value 'id' is missing or invalid.";
const char* kInvalidPageActionName =
"Invalid value for 'page_action.name'.";
const char* kInvalidPageActionOldAndNewKeys =
"Key \"*\" is deprecated. Key \"*\" has the same meaning. You can not "
"use both.";
const char* kInvalidPageActionPopup =
"Invalid type for page action popup.";
const char* kInvalidPageActionPopupHeight =
"Invalid value for page action popup height [*].";
const char* kInvalidPageActionPopupPath =
"Invalid value for page action popup path [*].";
const char* kInvalidPageActionsList =
"Invalid value for 'page_actions'.";
const char* kInvalidPageActionsListSize =
"Invalid value for 'page_actions'. There can be at most one page action.";
const char* kInvalidPageActionTypeValue =
"Invalid value for 'page_actions[*].type', expected 'tab' or 'permanent'.";
const char* kInvalidPermission =
"Invalid value for 'permissions[*]'.";
const char* kInvalidPermissions =
"Required value 'permissions' is missing or invalid.";
const char* kInvalidPermissionScheme =
"Invalid scheme for 'permissions[*]'.";
const char* kInvalidPlugins =
"Invalid value for 'plugins'.";
const char* kInvalidPluginsPath =
"Invalid value for 'plugins[*].path'.";
const char* kInvalidPluginsPublic =
"Invalid value for 'plugins[*].public'.";
const char* kInvalidRunAt =
"Invalid value for 'content_scripts[*].run_at'.";
const char* kInvalidSidebar =
"Invalid value for 'sidebar'.";
const char* kInvalidSidebarDefaultIconPath =
"Invalid value for 'sidebar.default_icon'.";
const char* kInvalidSidebarDefaultTitle =
"Invalid value for 'sidebar.default_title'.";
const char* kInvalidSidebarDefaultUrl =
"Invalid value for 'sidebar.default_url'.";
const char* kInvalidSignature =
"Value 'signature' is missing or invalid.";
const char* kInvalidTheme =
"Invalid value for 'theme'.";
const char* kInvalidThemeColors =
"Invalid value for theme colors - colors must be integers";
const char* kInvalidThemeImages =
"Invalid value for theme images - images must be strings.";
const char* kInvalidThemeImagesMissing =
"An image specified in the theme is missing.";
const char* kInvalidThemeTints =
"Invalid value for theme images - tints must be decimal numbers.";
const char* kInvalidToolstrip =
"Invalid value for 'toolstrips[*]'";
const char* kInvalidToolstrips =
"Invalid value for 'toolstrips'.";
const char* kInvalidTts =
"Invalid value for 'tts'.";
const char* kInvalidTtsVoices =
"Invalid value for 'tts.voices'.";
const char* kInvalidTtsVoicesGender =
"Invalid value for 'tts.voices[*].gender'.";
const char* kInvalidTtsVoicesLocale =
"Invalid value for 'tts.voices[*].locale'.";
const char* kInvalidTtsVoicesVoiceName =
"Invalid value for 'tts.voices[*].voiceName'.";
const char* kInvalidUpdateURL =
"Invalid value for update url: '[*]'.";
const char* kInvalidVersion =
"Required value 'version' is missing or invalid. It must be between 1-4 "
"dot-separated integers each between 0 and 65536.";
const char* kInvalidWebURL =
"Invalid value for 'app.urls[*]'.";
const char* kInvalidWebURLs =
"Invalid value for 'app.urls'.";
const char* kInvalidZipHash =
"Required key 'zip_hash' is missing or invalid.";
const char* kLaunchPathAndURLAreExclusive =
"The 'app.launch.local_path' and 'launch.web_url' keys cannot both be set.";
const char* kLaunchURLRequired =
"Either 'app.launch.local_path' or 'app.launch.web_url' is required.";
const char* kLocalesMessagesFileMissing =
"Messages file is missing for locale.";
const char* kLocalesNoDefaultLocaleSpecified =
"Localization used, but default_locale wasn't specified in the manifest.";
const char* kLocalesNoDefaultMessages =
"Default locale is defined but default data couldn't be loaded.";
const char* kLocalesNoValidLocaleNamesListed =
"No valid locale name could be found in _locales directory.";
const char* kLocalesTreeMissing =
"Default locale was specified, but _locales subtree is missing.";
const char* kManifestParseError =
"Manifest is not valid JSON.";
const char* kManifestUnreadable =
"Manifest file is missing or unreadable.";
const char* kMissingFile =
"At least one js or css file is required for 'content_scripts[*]'.";
const char* kMultipleOverrides =
"An extension cannot override more than one page.";
const char* kOneUISurfaceOnly =
"Only one of 'browser_action', 'page_action', and 'app' can be specified.";
const char* kReservedMessageFound =
"Reserved key * found in message catalog.";
const char* kSidebarExperimental =
"You must request the 'experimental' permission in order to use the"
" Sidebar API.";
const char* kThemesCannotContainExtensions =
"A theme cannot contain extensions code.";
#if defined(OS_CHROMEOS)
const char* kIllegalPlugins =
"Extensions cannot install plugins on Chrome OS";
#endif
} // namespace extension_manifest_errors
namespace extension_urls {
const char* kGalleryBrowsePrefix = "https://chrome.google.com/webstore";
const char* kMiniGalleryBrowsePrefix = "https://tools.google.com/chrome/";
const char* kMiniGalleryDownloadPrefix = "https://dl-ssl.google.com/chrome/";
}
namespace extension_filenames {
const char* kTempExtensionName = "CRX_INSTALL";
// The file to write our decoded images to, relative to the extension_path.
const char* kDecodedImagesFilename = "DECODED_IMAGES";
// The file to write our decoded message catalogs to, relative to the
// extension_path.
const char* kDecodedMessageCatalogsFilename = "DECODED_MESSAGE_CATALOGS";
}
namespace extension_misc {
const char* kBookmarkManagerId = "eemcgdkfndhakfknompkggombfjjjeno";
const char* kWebStoreAppId = "ahfgeienlihckogmohjhadlkjgocpleb";
const char* kAppsPromoHistogram = "Extensions.AppsPromo";
}
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/metrics/thread_watcher_report_hang.h"
// We disable optimizations for the whole file so the compiler doesn't merge
// them all together.
MSVC_DISABLE_OPTIMIZE()
MSVC_PUSH_DISABLE_WARNING(4748)
#include "base/debug/debugger.h"
#include "base/debug/dump_without_crashing.h"
#include "build/build_config.h"
namespace metrics {
// The following are unique function names for forcing the crash when a thread
// is unresponsive. This makes it possible to tell from the callstack alone what
// thread was unresponsive.
NOINLINE void ReportThreadHang() {
#if defined(NDEBUG)
base::debug::DumpWithoutCrashing();
#else
base::debug::BreakDebugger();
#endif
}
#if !defined(OS_ANDROID) || !defined(NDEBUG)
// TODO(rtenneti): Enabled crashing, after getting data.
NOINLINE void StartupHang() {
ReportThreadHang();
}
#endif // OS_ANDROID
NOINLINE void ShutdownHang() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_UI() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_DB() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_FILE() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_FILE_USER_BLOCKING() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_PROCESS_LAUNCHER() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_CACHE() {
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_IO() {
ReportThreadHang();
}
NOINLINE void CrashBecauseThreadWasUnresponsive(int thread_id) {
// TODO(rtenneti): The following is a temporary change to check thread_id
// numbers explicitly so that we will have minimum code. Will change after the
// test run to use content::BrowserThread::ID enum.
if (thread_id == 0)
return ThreadUnresponsive_UI();
else if (thread_id == 1)
return ThreadUnresponsive_DB();
else if (thread_id == 2)
return ThreadUnresponsive_FILE();
else if (thread_id == 3)
return ThreadUnresponsive_FILE_USER_BLOCKING();
else if (thread_id == 4)
return ThreadUnresponsive_PROCESS_LAUNCHER();
else if (thread_id == 5)
return ThreadUnresponsive_CACHE();
else if (thread_id == 6)
return ThreadUnresponsive_IO();
}
} // namespace metrics
MSVC_POP_WARNING()
MSVC_ENABLE_OPTIMIZE();
<commit_msg>Fix for MSVS whole program optimization overriding local optimization flags to get call stacks of which Thread is creating jank/hang.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/metrics/thread_watcher_report_hang.h"
// We disable optimizations for the whole file so the compiler doesn't merge
// them all together.
MSVC_DISABLE_OPTIMIZE()
MSVC_PUSH_DISABLE_WARNING(4748)
#include "base/debug/debugger.h"
#include "base/debug/dump_without_crashing.h"
#include "build/build_config.h"
namespace metrics {
// The following are unique function names for forcing the crash when a thread
// is unresponsive. This makes it possible to tell from the callstack alone what
// thread was unresponsive.
NOINLINE void ReportThreadHang() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
#if defined(NDEBUG)
base::debug::DumpWithoutCrashing();
#else
base::debug::BreakDebugger();
#endif
}
#if !defined(OS_ANDROID) || !defined(NDEBUG)
// TODO(rtenneti): Enabled crashing, after getting data.
NOINLINE void StartupHang() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
#endif // OS_ANDROID
NOINLINE void ShutdownHang() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_UI() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_DB() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_FILE() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_FILE_USER_BLOCKING() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_PROCESS_LAUNCHER() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_CACHE() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void ThreadUnresponsive_IO() {
volatile const char* inhibit_comdat = __FUNCTION__;
ALLOW_UNUSED_LOCAL(inhibit_comdat);
ReportThreadHang();
}
NOINLINE void CrashBecauseThreadWasUnresponsive(int thread_id) {
// TODO(rtenneti): The following is a temporary change to check thread_id
// numbers explicitly so that we will have minimum code. Will change after the
// test run to use content::BrowserThread::ID enum.
if (thread_id == 0)
return ThreadUnresponsive_UI();
else if (thread_id == 1)
return ThreadUnresponsive_DB();
else if (thread_id == 2)
return ThreadUnresponsive_FILE();
else if (thread_id == 3)
return ThreadUnresponsive_FILE_USER_BLOCKING();
else if (thread_id == 4)
return ThreadUnresponsive_PROCESS_LAUNCHER();
else if (thread_id == 5)
return ThreadUnresponsive_CACHE();
else if (thread_id == 6)
return ThreadUnresponsive_IO();
}
} // namespace metrics
MSVC_POP_WARNING()
MSVC_ENABLE_OPTIMIZE();
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/generic_change_processor.h"
#include "base/location.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/sync/api/sync_change.h"
#include "chrome/browser/sync/api/sync_error.h"
#include "chrome/browser/sync/api/syncable_service.h"
#include "content/public/browser/browser_thread.h"
#include "sync/internal_api/base_node.h"
#include "sync/internal_api/change_record.h"
#include "sync/internal_api/read_node.h"
#include "sync/internal_api/read_transaction.h"
#include "sync/internal_api/write_node.h"
#include "sync/internal_api/write_transaction.h"
#include "sync/util/unrecoverable_error_handler.h"
using content::BrowserThread;
namespace browser_sync {
GenericChangeProcessor::GenericChangeProcessor(
DataTypeErrorHandler* error_handler,
const base::WeakPtr<SyncableService>& local_service,
sync_api::UserShare* user_share)
: ChangeProcessor(error_handler),
local_service_(local_service),
share_handle_(user_share) {
DCHECK(CalledOnValidThread());
}
GenericChangeProcessor::~GenericChangeProcessor() {
DCHECK(CalledOnValidThread());
}
void GenericChangeProcessor::ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::ImmutableChangeRecordList& changes) {
DCHECK(CalledOnValidThread());
DCHECK(running());
DCHECK(syncer_changes_.empty());
for (sync_api::ChangeRecordList::const_iterator it =
changes.Get().begin(); it != changes.Get().end(); ++it) {
if (it->action == sync_api::ChangeRecord::ACTION_DELETE) {
syncer_changes_.push_back(
SyncChange(SyncChange::ACTION_DELETE,
SyncData::CreateRemoteData(it->id, it->specifics)));
} else {
SyncChange::SyncChangeType action =
(it->action == sync_api::ChangeRecord::ACTION_ADD) ?
SyncChange::ACTION_ADD : SyncChange::ACTION_UPDATE;
// Need to load specifics from node.
sync_api::ReadNode read_node(trans);
if (read_node.InitByIdLookup(it->id) != sync_api::BaseNode::INIT_OK) {
error_handler()->OnUnrecoverableError(
FROM_HERE,
"Failed to look up data for received change with id " +
base::Int64ToString(it->id));
return;
}
syncer_changes_.push_back(
SyncChange(action,
SyncData::CreateRemoteData(
it->id, read_node.GetEntitySpecifics())));
}
}
}
void GenericChangeProcessor::CommitChangesFromSyncModel() {
DCHECK(CalledOnValidThread());
if (!running())
return;
if (syncer_changes_.empty())
return;
if (!local_service_) {
syncable::ModelType type = syncer_changes_[0].sync_data().GetDataType();
SyncError error(FROM_HERE, "Local service destroyed.", type);
error_handler()->OnUnrecoverableError(error.location(), error.message());
}
SyncError error = local_service_->ProcessSyncChanges(FROM_HERE,
syncer_changes_);
syncer_changes_.clear();
if (error.IsSet()) {
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
}
}
SyncError GenericChangeProcessor::GetSyncDataForType(
syncable::ModelType type,
SyncDataList* current_sync_data) {
DCHECK(CalledOnValidThread());
std::string type_name = syncable::ModelTypeToString(type);
sync_api::ReadTransaction trans(FROM_HERE, share_handle());
sync_api::ReadNode root(&trans);
if (root.InitByTagLookup(syncable::ModelTypeToRootTag(type)) !=
sync_api::BaseNode::INIT_OK) {
SyncError error(FROM_HERE,
"Server did not create the top-level " + type_name +
" node. We might be running against an out-of-date server.",
type);
return error;
}
// TODO(akalin): We'll have to do a tree traversal for bookmarks.
DCHECK_NE(type, syncable::BOOKMARKS);
int64 sync_child_id = root.GetFirstChildId();
while (sync_child_id != sync_api::kInvalidId) {
sync_api::ReadNode sync_child_node(&trans);
if (sync_child_node.InitByIdLookup(sync_child_id) !=
sync_api::BaseNode::INIT_OK) {
SyncError error(FROM_HERE,
"Failed to fetch child node for type " + type_name + ".",
type);
return error;
}
current_sync_data->push_back(SyncData::CreateRemoteData(
sync_child_node.GetId(), sync_child_node.GetEntitySpecifics()));
sync_child_id = sync_child_node.GetSuccessorId();
}
return SyncError();
}
namespace {
bool AttemptDelete(const SyncChange& change, sync_api::WriteNode* node) {
DCHECK_EQ(change.change_type(), SyncChange::ACTION_DELETE);
if (change.sync_data().IsLocal()) {
const std::string& tag = change.sync_data().GetTag();
if (tag.empty()) {
return false;
}
if (node->InitByClientTagLookup(
change.sync_data().GetDataType(), tag) !=
sync_api::BaseNode::INIT_OK) {
return false;
}
} else {
if (node->InitByIdLookup(change.sync_data().GetRemoteId()) !=
sync_api::BaseNode::INIT_OK) {
return false;
}
}
node->Remove();
return true;
}
} // namespace
SyncError GenericChangeProcessor::ProcessSyncChanges(
const tracked_objects::Location& from_here,
const SyncChangeList& list_of_changes) {
DCHECK(CalledOnValidThread());
sync_api::WriteTransaction trans(from_here, share_handle());
for (SyncChangeList::const_iterator iter = list_of_changes.begin();
iter != list_of_changes.end();
++iter) {
const SyncChange& change = *iter;
DCHECK_NE(change.sync_data().GetDataType(), syncable::UNSPECIFIED);
syncable::ModelType type = change.sync_data().GetDataType();
std::string type_str = syncable::ModelTypeToString(type);
sync_api::WriteNode sync_node(&trans);
if (change.change_type() == SyncChange::ACTION_DELETE) {
if (!AttemptDelete(change, &sync_node)) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to delete " + type_str + " node.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
} else if (change.change_type() == SyncChange::ACTION_ADD) {
// TODO(sync): Handle other types of creation (custom parents, folders,
// etc.).
sync_api::ReadNode root_node(&trans);
if (root_node.InitByTagLookup(
syncable::ModelTypeToRootTag(change.sync_data().GetDataType())) !=
sync_api::BaseNode::INIT_OK) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to look up root node for type " + type_str,
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
if (!sync_node.InitUniqueByCreation(change.sync_data().GetDataType(),
root_node,
change.sync_data().GetTag())) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to create " + type_str + " node.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
sync_node.SetTitle(UTF8ToWide(change.sync_data().GetTitle()));
sync_node.SetEntitySpecifics(change.sync_data().GetSpecifics());
} else if (change.change_type() == SyncChange::ACTION_UPDATE) {
if (change.sync_data().GetTag() == "" ||
sync_node.InitByClientTagLookup(change.sync_data().GetDataType(),
change.sync_data().GetTag()) !=
sync_api::BaseNode::INIT_OK) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to update " + type_str + " node.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
sync_node.SetTitle(UTF8ToWide(change.sync_data().GetTitle()));
sync_node.SetEntitySpecifics(change.sync_data().GetSpecifics());
// TODO(sync): Support updating other parts of the sync node (title,
// successor, parent, etc.).
} else {
NOTREACHED();
SyncError error(FROM_HERE,
"Received unset SyncChange in the change processor.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
}
return SyncError();
}
bool GenericChangeProcessor::SyncModelHasUserCreatedNodes(
syncable::ModelType type,
bool* has_nodes) {
DCHECK(CalledOnValidThread());
DCHECK(has_nodes);
DCHECK_NE(type, syncable::UNSPECIFIED);
std::string type_name = syncable::ModelTypeToString(type);
std::string err_str = "Server did not create the top-level " + type_name +
" node. We might be running against an out-of-date server.";
*has_nodes = false;
sync_api::ReadTransaction trans(FROM_HERE, share_handle());
sync_api::ReadNode type_root_node(&trans);
if (type_root_node.InitByTagLookup(syncable::ModelTypeToRootTag(type)) !=
sync_api::BaseNode::INIT_OK) {
LOG(ERROR) << err_str;
return false;
}
// The sync model has user created nodes if the type's root node has any
// children.
*has_nodes = type_root_node.HasChildren();
return true;
}
bool GenericChangeProcessor::CryptoReadyIfNecessary(syncable::ModelType type) {
DCHECK(CalledOnValidThread());
DCHECK_NE(type, syncable::UNSPECIFIED);
// We only access the cryptographer while holding a transaction.
sync_api::ReadTransaction trans(FROM_HERE, share_handle());
const syncable::ModelTypeSet encrypted_types = GetEncryptedTypes(&trans);
return !encrypted_types.Has(type) ||
trans.GetCryptographer()->is_ready();
}
void GenericChangeProcessor::StartImpl(Profile* profile) {
DCHECK(CalledOnValidThread());
}
void GenericChangeProcessor::StopImpl() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
sync_api::UserShare* GenericChangeProcessor::share_handle() const {
DCHECK(CalledOnValidThread());
return share_handle_;
}
} // namespace browser_sync
<commit_msg>[Sync] Add more visibility about sync update errors.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/generic_change_processor.h"
#include "base/location.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/sync/api/sync_change.h"
#include "chrome/browser/sync/api/sync_error.h"
#include "chrome/browser/sync/api/syncable_service.h"
#include "content/public/browser/browser_thread.h"
#include "sync/internal_api/base_node.h"
#include "sync/internal_api/change_record.h"
#include "sync/internal_api/read_node.h"
#include "sync/internal_api/read_transaction.h"
#include "sync/internal_api/write_node.h"
#include "sync/internal_api/write_transaction.h"
#include "sync/util/unrecoverable_error_handler.h"
using content::BrowserThread;
namespace browser_sync {
GenericChangeProcessor::GenericChangeProcessor(
DataTypeErrorHandler* error_handler,
const base::WeakPtr<SyncableService>& local_service,
sync_api::UserShare* user_share)
: ChangeProcessor(error_handler),
local_service_(local_service),
share_handle_(user_share) {
DCHECK(CalledOnValidThread());
}
GenericChangeProcessor::~GenericChangeProcessor() {
DCHECK(CalledOnValidThread());
}
void GenericChangeProcessor::ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::ImmutableChangeRecordList& changes) {
DCHECK(CalledOnValidThread());
DCHECK(running());
DCHECK(syncer_changes_.empty());
for (sync_api::ChangeRecordList::const_iterator it =
changes.Get().begin(); it != changes.Get().end(); ++it) {
if (it->action == sync_api::ChangeRecord::ACTION_DELETE) {
syncer_changes_.push_back(
SyncChange(SyncChange::ACTION_DELETE,
SyncData::CreateRemoteData(it->id, it->specifics)));
} else {
SyncChange::SyncChangeType action =
(it->action == sync_api::ChangeRecord::ACTION_ADD) ?
SyncChange::ACTION_ADD : SyncChange::ACTION_UPDATE;
// Need to load specifics from node.
sync_api::ReadNode read_node(trans);
if (read_node.InitByIdLookup(it->id) != sync_api::BaseNode::INIT_OK) {
error_handler()->OnUnrecoverableError(
FROM_HERE,
"Failed to look up data for received change with id " +
base::Int64ToString(it->id));
return;
}
syncer_changes_.push_back(
SyncChange(action,
SyncData::CreateRemoteData(
it->id, read_node.GetEntitySpecifics())));
}
}
}
void GenericChangeProcessor::CommitChangesFromSyncModel() {
DCHECK(CalledOnValidThread());
if (!running())
return;
if (syncer_changes_.empty())
return;
if (!local_service_) {
syncable::ModelType type = syncer_changes_[0].sync_data().GetDataType();
SyncError error(FROM_HERE, "Local service destroyed.", type);
error_handler()->OnUnrecoverableError(error.location(), error.message());
}
SyncError error = local_service_->ProcessSyncChanges(FROM_HERE,
syncer_changes_);
syncer_changes_.clear();
if (error.IsSet()) {
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
}
}
SyncError GenericChangeProcessor::GetSyncDataForType(
syncable::ModelType type,
SyncDataList* current_sync_data) {
DCHECK(CalledOnValidThread());
std::string type_name = syncable::ModelTypeToString(type);
sync_api::ReadTransaction trans(FROM_HERE, share_handle());
sync_api::ReadNode root(&trans);
if (root.InitByTagLookup(syncable::ModelTypeToRootTag(type)) !=
sync_api::BaseNode::INIT_OK) {
SyncError error(FROM_HERE,
"Server did not create the top-level " + type_name +
" node. We might be running against an out-of-date server.",
type);
return error;
}
// TODO(akalin): We'll have to do a tree traversal for bookmarks.
DCHECK_NE(type, syncable::BOOKMARKS);
int64 sync_child_id = root.GetFirstChildId();
while (sync_child_id != sync_api::kInvalidId) {
sync_api::ReadNode sync_child_node(&trans);
if (sync_child_node.InitByIdLookup(sync_child_id) !=
sync_api::BaseNode::INIT_OK) {
SyncError error(FROM_HERE,
"Failed to fetch child node for type " + type_name + ".",
type);
return error;
}
current_sync_data->push_back(SyncData::CreateRemoteData(
sync_child_node.GetId(), sync_child_node.GetEntitySpecifics()));
sync_child_id = sync_child_node.GetSuccessorId();
}
return SyncError();
}
namespace {
bool AttemptDelete(const SyncChange& change, sync_api::WriteNode* node) {
DCHECK_EQ(change.change_type(), SyncChange::ACTION_DELETE);
if (change.sync_data().IsLocal()) {
const std::string& tag = change.sync_data().GetTag();
if (tag.empty()) {
return false;
}
if (node->InitByClientTagLookup(
change.sync_data().GetDataType(), tag) !=
sync_api::BaseNode::INIT_OK) {
return false;
}
} else {
if (node->InitByIdLookup(change.sync_data().GetRemoteId()) !=
sync_api::BaseNode::INIT_OK) {
return false;
}
}
node->Remove();
return true;
}
} // namespace
SyncError GenericChangeProcessor::ProcessSyncChanges(
const tracked_objects::Location& from_here,
const SyncChangeList& list_of_changes) {
DCHECK(CalledOnValidThread());
sync_api::WriteTransaction trans(from_here, share_handle());
for (SyncChangeList::const_iterator iter = list_of_changes.begin();
iter != list_of_changes.end();
++iter) {
const SyncChange& change = *iter;
DCHECK_NE(change.sync_data().GetDataType(), syncable::UNSPECIFIED);
syncable::ModelType type = change.sync_data().GetDataType();
std::string type_str = syncable::ModelTypeToString(type);
sync_api::WriteNode sync_node(&trans);
if (change.change_type() == SyncChange::ACTION_DELETE) {
if (!AttemptDelete(change, &sync_node)) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to delete " + type_str + " node.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
} else if (change.change_type() == SyncChange::ACTION_ADD) {
// TODO(sync): Handle other types of creation (custom parents, folders,
// etc.).
sync_api::ReadNode root_node(&trans);
if (root_node.InitByTagLookup(
syncable::ModelTypeToRootTag(change.sync_data().GetDataType())) !=
sync_api::BaseNode::INIT_OK) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to look up root node for type " + type_str,
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
if (!sync_node.InitUniqueByCreation(change.sync_data().GetDataType(),
root_node,
change.sync_data().GetTag())) {
NOTREACHED();
SyncError error(FROM_HERE,
"Failed to create " + type_str + " node.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
sync_node.SetTitle(UTF8ToWide(change.sync_data().GetTitle()));
sync_node.SetEntitySpecifics(change.sync_data().GetSpecifics());
} else if (change.change_type() == SyncChange::ACTION_UPDATE) {
// TODO(zea): consider having this logic for all possible changes?
sync_api::BaseNode::InitByLookupResult result =
sync_node.InitByClientTagLookup(change.sync_data().GetDataType(),
change.sync_data().GetTag());
SyncError error;
if (result != sync_api::BaseNode::INIT_OK) {
if (result == sync_api::BaseNode::INIT_FAILED_PRECONDITION) {
error.Reset(FROM_HERE,
"Failed to load entry w/empty tag for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
} else if (result == sync_api::BaseNode::INIT_FAILED_ENTRY_NOT_GOOD) {
error.Reset(FROM_HERE,
"Failed to load bad entry for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
} else if (result == sync_api::BaseNode::INIT_FAILED_ENTRY_IS_DEL) {
error.Reset(FROM_HERE,
"Failed to load deleted entry for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
} else {
Cryptographer* crypto = trans.GetCryptographer();
syncable::ModelTypeSet encrypted_types(crypto->GetEncryptedTypes());
const sync_pb::EntitySpecifics& specifics =
sync_node.GetEntry()->Get(syncable::SPECIFICS);
CHECK(specifics.has_encrypted());
const bool can_decrypt = crypto->CanDecrypt(specifics.encrypted());
const bool agreement = encrypted_types.Has(type);
if (!agreement && !can_decrypt) {
error.Reset(FROM_HERE,
"Failed to load encrypted entry, missing key and "
"nigori mismatch for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
} else if (agreement && can_decrypt) {
error.Reset(FROM_HERE,
"Failed to load encrypted entry, we have the key "
"and the nigori matches (?!) for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
} else if (agreement) {
error.Reset(FROM_HERE,
"Failed to load encrypted entry, missing key and "
"the nigori matches for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
} else {
error.Reset(FROM_HERE,
"Failed to load encrypted entry, we have the key"
"(?!) and nigori mismatch for " + type_str + ".",
type);
NOTREACHED();
error_handler()->OnSingleDatatypeUnrecoverableError(
error.location(), error.message());
}
}
return error;
} else {
sync_node.SetTitle(UTF8ToWide(change.sync_data().GetTitle()));
sync_node.SetEntitySpecifics(change.sync_data().GetSpecifics());
// TODO(sync): Support updating other parts of the sync node (title,
// successor, parent, etc.).
}
} else {
NOTREACHED();
SyncError error(FROM_HERE,
"Received unset SyncChange in the change processor.",
type);
error_handler()->OnSingleDatatypeUnrecoverableError(error.location(),
error.message());
return error;
}
}
return SyncError();
}
bool GenericChangeProcessor::SyncModelHasUserCreatedNodes(
syncable::ModelType type,
bool* has_nodes) {
DCHECK(CalledOnValidThread());
DCHECK(has_nodes);
DCHECK_NE(type, syncable::UNSPECIFIED);
std::string type_name = syncable::ModelTypeToString(type);
std::string err_str = "Server did not create the top-level " + type_name +
" node. We might be running against an out-of-date server.";
*has_nodes = false;
sync_api::ReadTransaction trans(FROM_HERE, share_handle());
sync_api::ReadNode type_root_node(&trans);
if (type_root_node.InitByTagLookup(syncable::ModelTypeToRootTag(type)) !=
sync_api::BaseNode::INIT_OK) {
LOG(ERROR) << err_str;
return false;
}
// The sync model has user created nodes if the type's root node has any
// children.
*has_nodes = type_root_node.HasChildren();
return true;
}
bool GenericChangeProcessor::CryptoReadyIfNecessary(syncable::ModelType type) {
DCHECK(CalledOnValidThread());
DCHECK_NE(type, syncable::UNSPECIFIED);
// We only access the cryptographer while holding a transaction.
sync_api::ReadTransaction trans(FROM_HERE, share_handle());
const syncable::ModelTypeSet encrypted_types = GetEncryptedTypes(&trans);
return !encrypted_types.Has(type) ||
trans.GetCryptographer()->is_ready();
}
void GenericChangeProcessor::StartImpl(Profile* profile) {
DCHECK(CalledOnValidThread());
}
void GenericChangeProcessor::StopImpl() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
sync_api::UserShare* GenericChangeProcessor::share_handle() const {
DCHECK(CalledOnValidThread());
return share_handle_;
}
} // namespace browser_sync
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "chrome/browser/ui/panels/base_panel_browser_test.h"
#include "chrome/browser/ui/panels/docked_panel_collection.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_manager.h"
#include "chrome/browser/ui/panels/test_panel_collection_squeeze_observer.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_utils.h"
class DockedPanelBrowserTest : public BasePanelBrowserTest {
public:
virtual void SetUpOnMainThread() OVERRIDE {
BasePanelBrowserTest::SetUpOnMainThread();
// All the tests here assume using mocked 800x600 display area for the
// primary monitor. Do the check now.
gfx::Rect primary_display_area = PanelManager::GetInstance()->
display_settings_provider()->GetPrimaryDisplayArea();
DCHECK(primary_display_area.width() == 800);
DCHECK(primary_display_area.height() == 600);
}
};
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, SqueezePanelsInDock) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create some docked panels.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
ASSERT_EQ(3, docked_collection->num_panels());
// Check that nothing has been squeezed so far.
EXPECT_EQ(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_EQ(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
EXPECT_EQ(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
// Create more panels so they start getting squeezed.
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
EXPECT_GT(panel7->GetBounds().x(), docked_collection->work_area().x());
// The rest of them should be at reduced width.
EXPECT_LT(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_LT(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
EXPECT_LT(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
EXPECT_LT(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_LT(panel5->GetBounds().width(), panel5->GetRestoredBounds().width());
EXPECT_LT(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
// Activate a different panel.
ActivatePanel(panel2);
WaitForPanelActiveState(panel2, SHOW_AS_ACTIVE);
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel2_settled(docked_collection, panel2);
panel2_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
// The rest of them should be at reduced width.
EXPECT_LT(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_LT(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
EXPECT_LT(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_LT(panel5->GetBounds().width(), panel5->GetRestoredBounds().width());
EXPECT_LT(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
EXPECT_LT(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
panel_manager->CloseAll();
}
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, SqueezeAndThenSomeMore) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create enough docked panels to get into squeezing.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel6_settled(docked_collection, panel6);
panel6_settled.Wait();
// Record current widths of some panels.
int panel_1_width_less_squeezed = panel1->GetBounds().width();
int panel_2_width_less_squeezed = panel2->GetBounds().width();
int panel_3_width_less_squeezed = panel3->GetBounds().width();
int panel_4_width_less_squeezed = panel4->GetBounds().width();
int panel_5_width_less_squeezed = panel5->GetBounds().width();
// These widths should be reduced.
EXPECT_LT(panel_1_width_less_squeezed, panel1->GetRestoredBounds().width());
EXPECT_LT(panel_2_width_less_squeezed, panel2->GetRestoredBounds().width());
EXPECT_LT(panel_3_width_less_squeezed, panel3->GetRestoredBounds().width());
EXPECT_LT(panel_4_width_less_squeezed, panel4->GetRestoredBounds().width());
EXPECT_LT(panel_5_width_less_squeezed, panel5->GetRestoredBounds().width());
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
// The panels should shrink in width.
EXPECT_LT(panel1->GetBounds().width(), panel_1_width_less_squeezed);
EXPECT_LT(panel2->GetBounds().width(), panel_2_width_less_squeezed);
EXPECT_LT(panel3->GetBounds().width(), panel_3_width_less_squeezed);
EXPECT_LT(panel4->GetBounds().width(), panel_4_width_less_squeezed);
EXPECT_LT(panel5->GetBounds().width(), panel_5_width_less_squeezed);
panel_manager->CloseAll();
}
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, MinimizeSqueezedActive) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create enough docked panels to get into squeezing.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
// The rest of them should be at reduced width.
EXPECT_LT(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_LT(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
EXPECT_LT(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
EXPECT_LT(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_LT(panel5->GetBounds().width(), panel5->GetRestoredBounds().width());
EXPECT_LT(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
// Record the width of an inactive panel and minimize it.
int width_of_panel3_squeezed = panel3->GetBounds().width();
panel3->Minimize();
// Check that this panel is still at the same width.
EXPECT_EQ(width_of_panel3_squeezed, panel3->GetBounds().width());
// Minimize the active panel. It should become inactive and shrink in width.
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_PANEL_COLLECTION_UPDATED,
content::NotificationService::AllSources());
panel7->Minimize();
// Wait for active states to settle.
WaitForPanelActiveState(panel7, SHOW_AS_INACTIVE);
// Wait for the scheduled layout to run.
signal.Wait();
// The minimized panel should now be at reduced width.
EXPECT_LT(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
panel_manager->CloseAll();
}
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, CloseSqueezedPanels) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create enough docked panels to get into squeezing.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// Record current widths of some panels.
int panel_1_orig_width = panel1->GetBounds().width();
int panel_2_orig_width = panel2->GetBounds().width();
int panel_3_orig_width = panel3->GetBounds().width();
int panel_4_orig_width = panel4->GetBounds().width();
int panel_5_orig_width = panel5->GetBounds().width();
int panel_6_orig_width = panel6->GetBounds().width();
int panel_7_orig_width = panel7->GetBounds().width();
// The active panel should be at full width.
EXPECT_EQ(panel_7_orig_width, panel7->GetRestoredBounds().width());
// The rest of them should be at reduced width.
EXPECT_LT(panel_1_orig_width, panel1->GetRestoredBounds().width());
EXPECT_LT(panel_2_orig_width, panel2->GetRestoredBounds().width());
EXPECT_LT(panel_3_orig_width, panel3->GetRestoredBounds().width());
EXPECT_LT(panel_4_orig_width, panel4->GetRestoredBounds().width());
EXPECT_LT(panel_5_orig_width, panel5->GetRestoredBounds().width());
EXPECT_LT(panel_6_orig_width, panel6->GetRestoredBounds().width());
// Close one panel.
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_PANEL_COLLECTION_UPDATED,
content::NotificationService::AllSources());
CloseWindowAndWait(panel2);
signal.Wait();
// The widths of the remaining panels should have increased.
EXPECT_GT(panel1->GetBounds().width(), panel_1_orig_width);
EXPECT_GT(panel3->GetBounds().width(), panel_3_orig_width);
EXPECT_GT(panel4->GetBounds().width(), panel_4_orig_width);
EXPECT_GT(panel5->GetBounds().width(), panel_5_orig_width);
EXPECT_GT(panel6->GetBounds().width(), panel_6_orig_width);
// The active panel should have stayed at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel_7_orig_width);
// Close several panels.
CloseWindowAndWait(panel3);
CloseWindowAndWait(panel5);
// Wait for collection update after last close.
content::WindowedNotificationObserver signal2(
chrome::NOTIFICATION_PANEL_COLLECTION_UPDATED,
content::NotificationService::AllSources());
CloseWindowAndWait(panel7);
signal2.Wait();
// We should not have squeezing any more; all panels should be at full width.
EXPECT_EQ(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_EQ(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_EQ(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
panel_manager->CloseAll();
}
<commit_msg>Disable DockedPanelBrowserTest.SqueezePanelsInDock which has been failing on linux continuously since being reenabled in r210810.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "chrome/browser/ui/panels/base_panel_browser_test.h"
#include "chrome/browser/ui/panels/docked_panel_collection.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_manager.h"
#include "chrome/browser/ui/panels/test_panel_collection_squeeze_observer.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_utils.h"
class DockedPanelBrowserTest : public BasePanelBrowserTest {
public:
virtual void SetUpOnMainThread() OVERRIDE {
BasePanelBrowserTest::SetUpOnMainThread();
// All the tests here assume using mocked 800x600 display area for the
// primary monitor. Do the check now.
gfx::Rect primary_display_area = PanelManager::GetInstance()->
display_settings_provider()->GetPrimaryDisplayArea();
DCHECK(primary_display_area.width() == 800);
DCHECK(primary_display_area.height() == 600);
}
};
// http://crbug.com/143247
#if !defined(OS_WIN)
#define MAYBE_SqueezePanelsInDock DISABLED_SqueezePanelsInDock
#else
#define MAYBE_SqueezePanelsInDock SqueezePanelsInDock
#endif
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, MAYBE_SqueezePanelsInDock) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create some docked panels.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
ASSERT_EQ(3, docked_collection->num_panels());
// Check that nothing has been squeezed so far.
EXPECT_EQ(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_EQ(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
EXPECT_EQ(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
// Create more panels so they start getting squeezed.
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
EXPECT_GT(panel7->GetBounds().x(), docked_collection->work_area().x());
// The rest of them should be at reduced width.
EXPECT_LT(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_LT(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
EXPECT_LT(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
EXPECT_LT(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_LT(panel5->GetBounds().width(), panel5->GetRestoredBounds().width());
EXPECT_LT(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
// Activate a different panel.
ActivatePanel(panel2);
WaitForPanelActiveState(panel2, SHOW_AS_ACTIVE);
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel2_settled(docked_collection, panel2);
panel2_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
// The rest of them should be at reduced width.
EXPECT_LT(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_LT(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
EXPECT_LT(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_LT(panel5->GetBounds().width(), panel5->GetRestoredBounds().width());
EXPECT_LT(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
EXPECT_LT(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
panel_manager->CloseAll();
}
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, SqueezeAndThenSomeMore) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create enough docked panels to get into squeezing.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel6_settled(docked_collection, panel6);
panel6_settled.Wait();
// Record current widths of some panels.
int panel_1_width_less_squeezed = panel1->GetBounds().width();
int panel_2_width_less_squeezed = panel2->GetBounds().width();
int panel_3_width_less_squeezed = panel3->GetBounds().width();
int panel_4_width_less_squeezed = panel4->GetBounds().width();
int panel_5_width_less_squeezed = panel5->GetBounds().width();
// These widths should be reduced.
EXPECT_LT(panel_1_width_less_squeezed, panel1->GetRestoredBounds().width());
EXPECT_LT(panel_2_width_less_squeezed, panel2->GetRestoredBounds().width());
EXPECT_LT(panel_3_width_less_squeezed, panel3->GetRestoredBounds().width());
EXPECT_LT(panel_4_width_less_squeezed, panel4->GetRestoredBounds().width());
EXPECT_LT(panel_5_width_less_squeezed, panel5->GetRestoredBounds().width());
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
// The panels should shrink in width.
EXPECT_LT(panel1->GetBounds().width(), panel_1_width_less_squeezed);
EXPECT_LT(panel2->GetBounds().width(), panel_2_width_less_squeezed);
EXPECT_LT(panel3->GetBounds().width(), panel_3_width_less_squeezed);
EXPECT_LT(panel4->GetBounds().width(), panel_4_width_less_squeezed);
EXPECT_LT(panel5->GetBounds().width(), panel_5_width_less_squeezed);
panel_manager->CloseAll();
}
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, MinimizeSqueezedActive) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create enough docked panels to get into squeezing.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// The active panel should be at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
// The rest of them should be at reduced width.
EXPECT_LT(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_LT(panel2->GetBounds().width(), panel2->GetRestoredBounds().width());
EXPECT_LT(panel3->GetBounds().width(), panel3->GetRestoredBounds().width());
EXPECT_LT(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_LT(panel5->GetBounds().width(), panel5->GetRestoredBounds().width());
EXPECT_LT(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
// Record the width of an inactive panel and minimize it.
int width_of_panel3_squeezed = panel3->GetBounds().width();
panel3->Minimize();
// Check that this panel is still at the same width.
EXPECT_EQ(width_of_panel3_squeezed, panel3->GetBounds().width());
// Minimize the active panel. It should become inactive and shrink in width.
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_PANEL_COLLECTION_UPDATED,
content::NotificationService::AllSources());
panel7->Minimize();
// Wait for active states to settle.
WaitForPanelActiveState(panel7, SHOW_AS_INACTIVE);
// Wait for the scheduled layout to run.
signal.Wait();
// The minimized panel should now be at reduced width.
EXPECT_LT(panel7->GetBounds().width(), panel7->GetRestoredBounds().width());
panel_manager->CloseAll();
}
IN_PROC_BROWSER_TEST_F(DockedPanelBrowserTest, CloseSqueezedPanels) {
PanelManager* panel_manager = PanelManager::GetInstance();
DockedPanelCollection* docked_collection = panel_manager->docked_collection();
// Create enough docked panels to get into squeezing.
Panel* panel1 = CreateInactiveDockedPanel("1", gfx::Rect(0, 0, 200, 100));
Panel* panel2 = CreateInactiveDockedPanel("2", gfx::Rect(0, 0, 200, 100));
Panel* panel3 = CreateInactiveDockedPanel("3", gfx::Rect(0, 0, 200, 100));
Panel* panel4 = CreateInactiveDockedPanel("4", gfx::Rect(0, 0, 200, 100));
Panel* panel5 = CreateInactiveDockedPanel("5", gfx::Rect(0, 0, 200, 100));
Panel* panel6 = CreateInactiveDockedPanel("6", gfx::Rect(0, 0, 200, 100));
Panel* panel7 = CreateDockedPanel("7", gfx::Rect(0, 0, 200, 100));
// Wait for active states to settle.
PanelCollectionSqueezeObserver panel7_settled(docked_collection, panel7);
panel7_settled.Wait();
// Record current widths of some panels.
int panel_1_orig_width = panel1->GetBounds().width();
int panel_2_orig_width = panel2->GetBounds().width();
int panel_3_orig_width = panel3->GetBounds().width();
int panel_4_orig_width = panel4->GetBounds().width();
int panel_5_orig_width = panel5->GetBounds().width();
int panel_6_orig_width = panel6->GetBounds().width();
int panel_7_orig_width = panel7->GetBounds().width();
// The active panel should be at full width.
EXPECT_EQ(panel_7_orig_width, panel7->GetRestoredBounds().width());
// The rest of them should be at reduced width.
EXPECT_LT(panel_1_orig_width, panel1->GetRestoredBounds().width());
EXPECT_LT(panel_2_orig_width, panel2->GetRestoredBounds().width());
EXPECT_LT(panel_3_orig_width, panel3->GetRestoredBounds().width());
EXPECT_LT(panel_4_orig_width, panel4->GetRestoredBounds().width());
EXPECT_LT(panel_5_orig_width, panel5->GetRestoredBounds().width());
EXPECT_LT(panel_6_orig_width, panel6->GetRestoredBounds().width());
// Close one panel.
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_PANEL_COLLECTION_UPDATED,
content::NotificationService::AllSources());
CloseWindowAndWait(panel2);
signal.Wait();
// The widths of the remaining panels should have increased.
EXPECT_GT(panel1->GetBounds().width(), panel_1_orig_width);
EXPECT_GT(panel3->GetBounds().width(), panel_3_orig_width);
EXPECT_GT(panel4->GetBounds().width(), panel_4_orig_width);
EXPECT_GT(panel5->GetBounds().width(), panel_5_orig_width);
EXPECT_GT(panel6->GetBounds().width(), panel_6_orig_width);
// The active panel should have stayed at full width.
EXPECT_EQ(panel7->GetBounds().width(), panel_7_orig_width);
// Close several panels.
CloseWindowAndWait(panel3);
CloseWindowAndWait(panel5);
// Wait for collection update after last close.
content::WindowedNotificationObserver signal2(
chrome::NOTIFICATION_PANEL_COLLECTION_UPDATED,
content::NotificationService::AllSources());
CloseWindowAndWait(panel7);
signal2.Wait();
// We should not have squeezing any more; all panels should be at full width.
EXPECT_EQ(panel1->GetBounds().width(), panel1->GetRestoredBounds().width());
EXPECT_EQ(panel4->GetBounds().width(), panel4->GetRestoredBounds().width());
EXPECT_EQ(panel6->GetBounds().width(), panel6->GetRestoredBounds().width());
panel_manager->CloseAll();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/string16.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
}
void AssertIsOptionsPage(TabProxy* tab) {
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
// The only guarantee we can make about the title of a settings tab is that
// it should contain IDS_SETTINGS_TITLE somewhere.
ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos);
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Go to the options tab via URL.
NavigateToURL(GURL(chrome::kChromeUISettingsURL));
AssertIsOptionsPage(tab);
}
// Flaky, and takes very long to fail. http://crbug.com/64619.
TEST_F(OptionsUITest, DISABLED_CommandOpensOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
}
// Flaky, and takes very long to fail. http://crbug.com/48521
TEST_F(OptionsUITest, DISABLED_CommandAgainGoesBackToOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
// Switch to first tab and run command again.
ASSERT_TRUE(browser->ActivateTab(0));
ASSERT_TRUE(browser->WaitForTabToBecomeActive(
0, TestTimeouts::action_max_timeout_ms()));
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
// Ensure the options ui tab is active.
ASSERT_TRUE(browser->WaitForTabToBecomeActive(
1, TestTimeouts::action_max_timeout_ms()));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
// Flaky, and takes very long to fail. http://crbug.com/48521
TEST_F(OptionsUITest, DISABLED_TwoCommandsOneTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
} // namespace
<commit_msg>Temporarily disabling OptionsUITest.LoadOptionsByURL in debug mode.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/string16.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
}
void AssertIsOptionsPage(TabProxy* tab) {
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
// The only guarantee we can make about the title of a settings tab is that
// it should contain IDS_SETTINGS_TITLE somewhere.
ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos);
}
};
// http://crbug.com/77252
#if !defined(NDEBUG)
#define MAYBE_LoadOptionsByURL DISABLED_LoadOptionsByURL
#else
#define MAYBE_LoadOptionsByURL
#endif
TEST_F(OptionsUITest, MAYBE_LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Go to the options tab via URL.
NavigateToURL(GURL(chrome::kChromeUISettingsURL));
AssertIsOptionsPage(tab);
}
// Flaky, and takes very long to fail. http://crbug.com/64619.
TEST_F(OptionsUITest, DISABLED_CommandOpensOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
}
// Flaky, and takes very long to fail. http://crbug.com/48521
TEST_F(OptionsUITest, DISABLED_CommandAgainGoesBackToOptionsTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Bring up the options tab via command.
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
AssertIsOptionsPage(tab);
// Switch to first tab and run command again.
ASSERT_TRUE(browser->ActivateTab(0));
ASSERT_TRUE(browser->WaitForTabToBecomeActive(
0, TestTimeouts::action_max_timeout_ms()));
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
// Ensure the options ui tab is active.
ASSERT_TRUE(browser->WaitForTabToBecomeActive(
1, TestTimeouts::action_max_timeout_ms()));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
// Flaky, and takes very long to fail. http://crbug.com/48521
TEST_F(OptionsUITest, DISABLED_TwoCommandsOneTab) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
int tab_count = -1;
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));
ASSERT_TRUE(browser->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
}
} // namespace
<|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 <string>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/native_library.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/test/browser/browser_test_runner.h"
// This version of the browser test launcher loads a dynamic library containing
// the tests and executes the them in that library. When the test has been run
// the library is unloaded, to ensure atexit handlers are run and static
// initializers will be run again for the next test.
namespace {
const wchar_t* const kBrowserTesLibBaseName = L"browser_tests";
const wchar_t* const kGTestListTestsFlag = L"gtest_list_tests";
class InProcBrowserTestRunner : public browser_tests::BrowserTestRunner {
public:
InProcBrowserTestRunner() : dynamic_lib_(NULL), run_test_proc_(NULL) {
}
~InProcBrowserTestRunner() {
if (!dynamic_lib_)
return;
base::UnloadNativeLibrary(dynamic_lib_);
LOG(INFO) << "Unloaded " <<
base::GetNativeLibraryName(kBrowserTesLibBaseName);
}
bool Init() {
FilePath lib_path;
if (!file_util::GetCurrentDirectory(&lib_path)) {
LOG(ERROR) << "Failed to retrieve curret directory.";
return false;
}
string16 lib_name = base::GetNativeLibraryName(kBrowserTesLibBaseName);
#if defined(OS_WIN)
lib_path = lib_path.Append(lib_name);
#else
lib_path = lib_path.Append(WideToUTF8(lib_name));
#endif
LOG(INFO) << "Loading '" << lib_path.value() << "'";
dynamic_lib_ = base::LoadNativeLibrary(lib_path);
if (!dynamic_lib_) {
LOG(ERROR) << "Failed to find " << lib_name;
return false;
}
run_test_proc_ = reinterpret_cast<RunTestProc>(
base::GetFunctionPointerFromNativeLibrary(dynamic_lib_, "RunTests"));
if (!run_test_proc_) {
LOG(ERROR) <<
"Failed to find RunTest function in " << lib_name;
return false;
}
return true;
}
// Returns true if the test succeeded, false if it failed.
bool RunTest(const std::string& test_name) {
std::string filter_flag = StringPrintf("--gtest_filter=%s",
test_name.c_str());
char* argv[2];
argv[0] = const_cast<char*>("");
argv[1] = const_cast<char*>(filter_flag.c_str());
return RunAsIs(2, argv) == 0;
}
// Calls-in to GTest with the arguments we were started with.
int RunAsIs(int argc, char** argv) {
return (run_test_proc_)(argc, argv);
}
private:
typedef int (CDECL *RunTestProc)(int, char**);
base::NativeLibrary dynamic_lib_;
RunTestProc run_test_proc_;
DISALLOW_COPY_AND_ASSIGN(InProcBrowserTestRunner);
};
class InProcBrowserTestRunnerFactory
: public browser_tests::BrowserTestRunnerFactory {
public:
InProcBrowserTestRunnerFactory() { }
virtual browser_tests::BrowserTestRunner* CreateBrowserTestRunner() const {
return new InProcBrowserTestRunner();
}
private:
DISALLOW_COPY_AND_ASSIGN(InProcBrowserTestRunnerFactory);
};
} // namespace
int main(int argc, char** argv) {
base::AtExitManager at_exit_manager;
CommandLine::Init(argc, argv);
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kGTestListTestsFlag)) {
InProcBrowserTestRunner test_runner;
if (!test_runner.Init())
return 1;
return test_runner.RunAsIs(argc, argv);
}
InProcBrowserTestRunnerFactory test_runner_factory;
return browser_tests::RunTests(test_runner_factory) ? 0 : 1;
}
<commit_msg>This CL makes the browser_tests.exe runnable from outside its directory.<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 <string>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/native_library.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/test/browser/browser_test_runner.h"
// This version of the browser test launcher loads a dynamic library containing
// the tests and executes the them in that library. When the test has been run
// the library is unloaded, to ensure atexit handlers are run and static
// initializers will be run again for the next test.
namespace {
const wchar_t* const kBrowserTesLibBaseName = L"browser_tests";
const wchar_t* const kGTestListTestsFlag = L"gtest_list_tests";
class InProcBrowserTestRunner : public browser_tests::BrowserTestRunner {
public:
InProcBrowserTestRunner() : dynamic_lib_(NULL), run_test_proc_(NULL) {
}
~InProcBrowserTestRunner() {
if (!dynamic_lib_)
return;
base::UnloadNativeLibrary(dynamic_lib_);
LOG(INFO) << "Unloaded " <<
base::GetNativeLibraryName(kBrowserTesLibBaseName);
}
bool Init() {
FilePath lib_path;
CHECK(PathService::Get(base::FILE_EXE, &lib_path));
lib_path = lib_path.DirName().Append(
base::GetNativeLibraryName(kBrowserTesLibBaseName));
LOG(INFO) << "Loading '" << lib_path.value() << "'";
dynamic_lib_ = base::LoadNativeLibrary(lib_path);
if (!dynamic_lib_) {
LOG(ERROR) << "Failed to load " << lib_path.value();
return false;
}
run_test_proc_ = reinterpret_cast<RunTestProc>(
base::GetFunctionPointerFromNativeLibrary(dynamic_lib_, "RunTests"));
if (!run_test_proc_) {
LOG(ERROR) <<
"Failed to find RunTest function in " << lib_path.value();
return false;
}
return true;
}
// Returns true if the test succeeded, false if it failed.
bool RunTest(const std::string& test_name) {
std::string filter_flag = StringPrintf("--gtest_filter=%s",
test_name.c_str());
char* argv[2];
argv[0] = const_cast<char*>("");
argv[1] = const_cast<char*>(filter_flag.c_str());
return RunAsIs(2, argv) == 0;
}
// Calls-in to GTest with the arguments we were started with.
int RunAsIs(int argc, char** argv) {
return (run_test_proc_)(argc, argv);
}
private:
typedef int (CDECL *RunTestProc)(int, char**);
base::NativeLibrary dynamic_lib_;
RunTestProc run_test_proc_;
DISALLOW_COPY_AND_ASSIGN(InProcBrowserTestRunner);
};
class InProcBrowserTestRunnerFactory
: public browser_tests::BrowserTestRunnerFactory {
public:
InProcBrowserTestRunnerFactory() { }
virtual browser_tests::BrowserTestRunner* CreateBrowserTestRunner() const {
return new InProcBrowserTestRunner();
}
private:
DISALLOW_COPY_AND_ASSIGN(InProcBrowserTestRunnerFactory);
};
} // namespace
int main(int argc, char** argv) {
base::AtExitManager at_exit_manager;
CommandLine::Init(argc, argv);
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kGTestListTestsFlag)) {
InProcBrowserTestRunner test_runner;
if (!test_runner.Init())
return 1;
return test_runner.RunAsIs(argc, argv);
}
InProcBrowserTestRunnerFactory test_runner_factory;
return browser_tests::RunTests(test_runner_factory) ? 0 : 1;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/keyboard_codes.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
namespace {
class KeyboardAccessTest : public UITest {
public:
KeyboardAccessTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there are two menus and that
// New Tab is the first item in the app menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence);
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));
// The initial tab index should be 0.
int tab_index = -1;
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(0, tab_index);
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = -1;
ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_MENU, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_F10, 0));
int new_view_id = -1;
ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
original_view_id, &new_view_id));
ASSERT_TRUE(browser->StartTrackingPopupMenus());
// Press RIGHT to focus the app menu, then RETURN or DOWN to open it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RIGHT, 0));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait until the popup menu actually opens.
ASSERT_TRUE(browser->WaitForPopupMenuToOpen());
// Press DOWN to select the first item, then RETURN to select it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait for the new tab to appear.
ASSERT_TRUE(browser->WaitForTabCountToBecome(2, sleep_timeout_ms()));
// Make sure that the new tab index is 1.
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(1, tab_index);
}
TEST_F(KeyboardAccessTest, FLAKY_TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false);
}
TEST_F(KeyboardAccessTest, FLAKY_TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true);
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<commit_msg>Remove FLAKY_ from KeyboardAccessTests now that they work on both Vista and XP.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/keyboard_codes.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
namespace {
class KeyboardAccessTest : public UITest {
public:
KeyboardAccessTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there are two menus and that
// New Tab is the first item in the app menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence);
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));
// The initial tab index should be 0.
int tab_index = -1;
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(0, tab_index);
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = -1;
ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_MENU, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_F10, 0));
int new_view_id = -1;
ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
original_view_id, &new_view_id));
ASSERT_TRUE(browser->StartTrackingPopupMenus());
// Press RIGHT to focus the app menu, then RETURN or DOWN to open it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RIGHT, 0));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait until the popup menu actually opens.
ASSERT_TRUE(browser->WaitForPopupMenuToOpen());
// Press DOWN to select the first item, then RETURN to select it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait for the new tab to appear.
ASSERT_TRUE(browser->WaitForTabCountToBecome(2, sleep_timeout_ms()));
// Make sure that the new tab index is 1.
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(1, tab_index);
}
TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false);
}
TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true);
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<|endoftext|>
|
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#include "../../general/okina.hpp"
#include "vector.hpp"
// *****************************************************************************
#ifdef __NVCC__
#if __CUDA_ARCH__ > 300
// *****************************************************************************
#include <cub/cub.cuh>
__inline__ __device__ double4 operator*(double4 a, double4 b)
{
return make_double4(a.x*b.x, a.y*b.y, a.z*b.z, a.w*b.w);
}
// *****************************************************************************
static double cub_vector_dot(const int N,
const double* __restrict vec1,
const double* __restrict vec2)
{
push();
static double *h_dot = NULL;
if (!h_dot)
{
dbg("!h_dot");
void *ptr;
cuMemHostAlloc(&ptr, sizeof(double), CU_MEMHOSTALLOC_PORTABLE);
h_dot=(double*)ptr;
}
static double *d_dot = NULL;
if (!d_dot)
{
dbg("!d_dot");
cuMemAlloc((CUdeviceptr*)&d_dot, sizeof(double));
}
static void *d_storage = NULL;
static size_t storage_bytes = 0;
if (!d_storage)
{
dbg("[cub_vector_dot] !d_storage");
cub::DeviceReduce::Dot(d_storage, storage_bytes, vec1, vec2, d_dot, N);
cuMemAlloc((CUdeviceptr*)&d_storage, storage_bytes*sizeof(double));
}
cub::DeviceReduce::Dot(d_storage, storage_bytes, vec1, vec2, d_dot, N);
//mfem::mm::D2H(h_dot,d_dot,sizeof(double));
checkCudaErrors(cuMemcpy((CUdeviceptr)h_dot,(CUdeviceptr)d_dot,sizeof(double)));
//dbg("dot=%e",*h_dot);
//assert(false);
return *h_dot;
}
#else // __CUDA_ARCH__ > 300
// *****************************************************************************
void kdot(const size_t N, const double *d_x, const double *d_y, double *d_dot)
{
forall(k, 1,
{
double l_dot = 0.0;
for (int i=0; i<N; i+=1)
{
l_dot += d_x[i] * d_y[i];
}
*d_dot = l_dot;
});
}
#endif // __CUDA_ARCH__
#endif // __NVCC__
// *****************************************************************************
MFEM_NAMESPACE
// *****************************************************************************
double kVectorDot(const size_t N, const double *x, const double *y)
{
GET_CUDA;
GET_CONST_ADRS(x);
GET_CONST_ADRS(y);
#ifdef __NVCC__
#if __CUDA_ARCH__ > 300
if (cuda) { return cub_vector_dot(N, d_x, d_y); }
#else // __CUDA_ARCH__
if (cuda)
{
static double *h_dot = NULL;
if (!h_dot)
{
void *ptr;
cuMemHostAlloc(&ptr, sizeof(double), CU_MEMHOSTALLOC_PORTABLE);
h_dot=(double*)ptr;
}
static double *d_dot = NULL;
if (!d_dot)
{
dbg("!d_dot");
cuMemAlloc((CUdeviceptr*)&d_dot, sizeof(double));
}
kdot(N,d_x,d_y,d_dot);
mfem::mm::D2H(h_dot,d_dot,sizeof(double));
return *h_dot;
}
#endif // __CUDA_ARCH__
#endif // __NVCC__
double dot = 0.0;
for (size_t i=0; i<N; i+=1)
{
dot += d_x[i] * d_y[i];
}
return dot;
}
// *****************************************************************************
void kVectorMapDof(const int N, double *v0, const double *v1, const int *dof)
{
GET_ADRS(v0);
GET_CONST_ADRS(v1);
GET_CONST_ADRS_T(dof,int);
forall(i, N,
{
const int dof_i = d_dof[i];
d_v0[dof_i] = d_v1[dof_i];
});
}
// *****************************************************************************
void kVectorMapDof(double *v0, const double *v1, const int dof, const int j)
{
GET_ADRS(v0);
GET_CONST_ADRS(v1);
forall(i, 1, d_v0[dof] = d_v1[j]; );
}
// *****************************************************************************
void kVectorSetDof(double *v0, const double alpha, const int dof)
{
GET_ADRS(v0);
forall(i, 1, d_v0[dof] = alpha; );
}
// *****************************************************************************
void kVectorSetDof(const int N, double *v0, const double alpha, const int *dof)
{
GET_ADRS(v0);
GET_CONST_ADRS_T(dof,int);
forall(i, N,
{
const int dof_i = d_dof[i];
d_v0[dof_i] = alpha;
});
}
// *****************************************************************************
void kVectorGetSubvector(const int N,
double* v0,
const double* v1,
const int* v2)
{
GET_ADRS(v0);
GET_CONST_ADRS(v1);
GET_CONST_ADRS_T(v2,int);
forall(i, N,
{
const int dof_i = d_v2[i];
//printf("\n[kVectorGetSubvector] N=%d, i=%ld, dof_i=%d",N,i,dof_i);
assert(dof_i >= 0);
d_v0[i] = dof_i >= 0 ? d_v1[dof_i] : -d_v1[-dof_i-1];
});
}
// *****************************************************************************
void kVectorSetSubvector(const int N,
double* data,
const double* elemvect,
const int* dofs)
{
GET_ADRS(data);
GET_CONST_ADRS(elemvect);
GET_CONST_ADRS_T(dofs,int);
forall(i,N,
{
const int j = d_dofs[i];
//printf("\n\tj=%d, set: %f",j,d_elemvect[i]);
if (j >= 0)
{
d_data[j] = d_elemvect[i];
}
else {
assert(false);
d_data[-1-j] = -d_elemvect[i];
}
});
}
// *****************************************************************************
void kVectorSubtract(double *zp, const double *xp, const double *yp,
const size_t N)
{
GET_ADRS(zp);
GET_CONST_ADRS(xp);
GET_CONST_ADRS(yp);
forall(i, N, d_zp[i] = d_xp[i] - d_yp[i];);
}
// *****************************************************************************
void kVectorAlphaAdd(double *vp, const double* v1p,
const double alpha, const double *v2p, const size_t N)
{
GET_ADRS(vp);
GET_CONST_ADRS(v1p);
GET_CONST_ADRS(v2p);
forall(i, N, d_vp[i] = d_v1p[i] + alpha * d_v2p[i];);
}
// *****************************************************************************
void kVectorPrint(const size_t N, const double *data)
{
GET_CONST_ADRS(data); // Sequential printf
forall(k,1,for (int i=0; i<N; i+=1)printf("\n\t%f",d_data[i]););
}
// *****************************************************************************
void kVectorAssign(const size_t N, const double* v, double *data)
{
GET_ADRS(data);
GET_CONST_ADRS(v);
forall(i, N, d_data[i] = d_v[i];);
}
// **************************************************************************
void kVectorSet(const size_t N,
const double value,
double *data)
{
GET_ADRS(data);
forall(i, N, d_data[i] = value;);
}
// *****************************************************************************
void kVectorMultOp(const size_t N,
const double value,
double *data)
{
GET_ADRS(data);
forall(i, N, d_data[i] *= value;);
}
// *****************************************************************************
void kVectorDotOpPlusEQ(const size_t size, const double *v, double *data)
{
GET_CONST_ADRS(v);
GET_ADRS(data);
forall(i, size, d_data[i] += d_v[i];);
}
/*
// *****************************************************************************
void kSetSubVector(const size_t n, const int *dofs, const double *elemvect,
double *data){
GET_CONST_ADRS_T(dofs,int);
GET_CONST_ADRS(elemvect);
GET_ADRS(data);
//#warning make sure we can work on this outer loop
forall(i, n,{
const int j = d_dofs[i];
if (j >= 0) {
d_data[j] = d_elemvect[i];
}else{
d_data[-1-j] = -d_elemvect[i];
}
});
}*/
// *****************************************************************************
void kVectorOpSubtract(const size_t size, const double *v, double *data)
{
GET_CONST_ADRS(v);
GET_ADRS(data);
forall(i, size, d_data[i] -= d_v[i];);
}
// *****************************************************************************
void kAddElementVector(const size_t n, const int *dofs,
const double *elem_data, double *data)
{
GET_CONST_ADRS_T(dofs,int);
GET_CONST_ADRS(elem_data);
GET_ADRS(data);
forall(k,1,
{
for (int i = 0; i < n; i++)
{
const int j = d_dofs[i];
if (j >= 0)
{
d_data[j] += d_elem_data[i];
}
else
{
d_data[-1-j] -= d_elem_data[i];
}
}
});
}
// *****************************************************************************
MFEM_NAMESPACE_END
<commit_msg>Push back operator for cub<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#include "../../general/okina.hpp"
#include "vector.hpp"
#ifdef __NVCC__
// *****************************************************************************
#include <cub/cub.cuh>
__inline__ __device__ double4 operator*(double4 a, double4 b)
{
return make_double4(a.x*b.x, a.y*b.y, a.z*b.z, a.w*b.w);
}
// *****************************************************************************
#if __CUDA_ARCH__ > 300
// *****************************************************************************
static double cub_vector_dot(const int N,
const double* __restrict vec1,
const double* __restrict vec2)
{
push();
static double *h_dot = NULL;
if (!h_dot)
{
dbg("!h_dot");
void *ptr;
cuMemHostAlloc(&ptr, sizeof(double), CU_MEMHOSTALLOC_PORTABLE);
h_dot=(double*)ptr;
}
static double *d_dot = NULL;
if (!d_dot)
{
dbg("!d_dot");
cuMemAlloc((CUdeviceptr*)&d_dot, sizeof(double));
}
static void *d_storage = NULL;
static size_t storage_bytes = 0;
if (!d_storage)
{
dbg("[cub_vector_dot] !d_storage");
cub::DeviceReduce::Dot(d_storage, storage_bytes, vec1, vec2, d_dot, N);
cuMemAlloc((CUdeviceptr*)&d_storage, storage_bytes*sizeof(double));
}
cub::DeviceReduce::Dot(d_storage, storage_bytes, vec1, vec2, d_dot, N);
//mfem::mm::D2H(h_dot,d_dot,sizeof(double));
checkCudaErrors(cuMemcpy((CUdeviceptr)h_dot,(CUdeviceptr)d_dot,sizeof(double)));
//dbg("dot=%e",*h_dot);
//assert(false);
return *h_dot;
}
#else // __CUDA_ARCH__
// *****************************************************************************
void kdot(const size_t N, const double *d_x, const double *d_y, double *d_dot)
{
forall(k, 1,
{
double l_dot = 0.0;
for (int i=0; i<N; i+=1)
{
l_dot += d_x[i] * d_y[i];
}
*d_dot = l_dot;
});
}
#endif // __CUDA_ARCH__
#endif // __NVCC__
// *****************************************************************************
MFEM_NAMESPACE
// *****************************************************************************
double kVectorDot(const size_t N, const double *x, const double *y)
{
GET_CUDA;
GET_CONST_ADRS(x);
GET_CONST_ADRS(y);
#ifdef __NVCC__
#if __CUDA_ARCH__ > 300
if (cuda) { return cub_vector_dot(N, d_x, d_y); }
#else // __CUDA_ARCH__
if (cuda)
{
static double *h_dot = NULL;
if (!h_dot)
{
void *ptr;
cuMemHostAlloc(&ptr, sizeof(double), CU_MEMHOSTALLOC_PORTABLE);
h_dot=(double*)ptr;
}
static double *d_dot = NULL;
if (!d_dot)
{
dbg("!d_dot");
cuMemAlloc((CUdeviceptr*)&d_dot, sizeof(double));
}
kdot(N,d_x,d_y,d_dot);
mfem::mm::D2H(h_dot,d_dot,sizeof(double));
return *h_dot;
}
#endif // __CUDA_ARCH__
#endif // __NVCC__
double dot = 0.0;
for (size_t i=0; i<N; i+=1)
{
dot += d_x[i] * d_y[i];
}
return dot;
}
// *****************************************************************************
void kVectorMapDof(const int N, double *v0, const double *v1, const int *dof)
{
GET_ADRS(v0);
GET_CONST_ADRS(v1);
GET_CONST_ADRS_T(dof,int);
forall(i, N,
{
const int dof_i = d_dof[i];
d_v0[dof_i] = d_v1[dof_i];
});
}
// *****************************************************************************
void kVectorMapDof(double *v0, const double *v1, const int dof, const int j)
{
GET_ADRS(v0);
GET_CONST_ADRS(v1);
forall(i, 1, d_v0[dof] = d_v1[j]; );
}
// *****************************************************************************
void kVectorSetDof(double *v0, const double alpha, const int dof)
{
GET_ADRS(v0);
forall(i, 1, d_v0[dof] = alpha; );
}
// *****************************************************************************
void kVectorSetDof(const int N, double *v0, const double alpha, const int *dof)
{
GET_ADRS(v0);
GET_CONST_ADRS_T(dof,int);
forall(i, N,
{
const int dof_i = d_dof[i];
d_v0[dof_i] = alpha;
});
}
// *****************************************************************************
void kVectorGetSubvector(const int N,
double* v0,
const double* v1,
const int* v2)
{
GET_ADRS(v0);
GET_CONST_ADRS(v1);
GET_CONST_ADRS_T(v2,int);
forall(i, N,
{
const int dof_i = d_v2[i];
//printf("\n[kVectorGetSubvector] N=%d, i=%ld, dof_i=%d",N,i,dof_i);
assert(dof_i >= 0);
d_v0[i] = dof_i >= 0 ? d_v1[dof_i] : -d_v1[-dof_i-1];
});
}
// *****************************************************************************
void kVectorSetSubvector(const int N,
double* data,
const double* elemvect,
const int* dofs)
{
GET_ADRS(data);
GET_CONST_ADRS(elemvect);
GET_CONST_ADRS_T(dofs,int);
forall(i,N,
{
const int j = d_dofs[i];
//printf("\n\tj=%d, set: %f",j,d_elemvect[i]);
if (j >= 0)
{
d_data[j] = d_elemvect[i];
}
else {
assert(false);
d_data[-1-j] = -d_elemvect[i];
}
});
}
// *****************************************************************************
void kVectorSubtract(double *zp, const double *xp, const double *yp,
const size_t N)
{
GET_ADRS(zp);
GET_CONST_ADRS(xp);
GET_CONST_ADRS(yp);
forall(i, N, d_zp[i] = d_xp[i] - d_yp[i];);
}
// *****************************************************************************
void kVectorAlphaAdd(double *vp, const double* v1p,
const double alpha, const double *v2p, const size_t N)
{
GET_ADRS(vp);
GET_CONST_ADRS(v1p);
GET_CONST_ADRS(v2p);
forall(i, N, d_vp[i] = d_v1p[i] + alpha * d_v2p[i];);
}
// *****************************************************************************
void kVectorPrint(const size_t N, const double *data)
{
GET_CONST_ADRS(data); // Sequential printf
forall(k,1,for (int i=0; i<N; i+=1)printf("\n\t%f",d_data[i]););
}
// *****************************************************************************
void kVectorAssign(const size_t N, const double* v, double *data)
{
GET_ADRS(data);
GET_CONST_ADRS(v);
forall(i, N, d_data[i] = d_v[i];);
}
// **************************************************************************
void kVectorSet(const size_t N,
const double value,
double *data)
{
GET_ADRS(data);
forall(i, N, d_data[i] = value;);
}
// *****************************************************************************
void kVectorMultOp(const size_t N,
const double value,
double *data)
{
GET_ADRS(data);
forall(i, N, d_data[i] *= value;);
}
// *****************************************************************************
void kVectorDotOpPlusEQ(const size_t size, const double *v, double *data)
{
GET_CONST_ADRS(v);
GET_ADRS(data);
forall(i, size, d_data[i] += d_v[i];);
}
/*
// *****************************************************************************
void kSetSubVector(const size_t n, const int *dofs, const double *elemvect,
double *data){
GET_CONST_ADRS_T(dofs,int);
GET_CONST_ADRS(elemvect);
GET_ADRS(data);
//#warning make sure we can work on this outer loop
forall(i, n,{
const int j = d_dofs[i];
if (j >= 0) {
d_data[j] = d_elemvect[i];
}else{
d_data[-1-j] = -d_elemvect[i];
}
});
}*/
// *****************************************************************************
void kVectorOpSubtract(const size_t size, const double *v, double *data)
{
GET_CONST_ADRS(v);
GET_ADRS(data);
forall(i, size, d_data[i] -= d_v[i];);
}
// *****************************************************************************
void kAddElementVector(const size_t n, const int *dofs,
const double *elem_data, double *data)
{
GET_CONST_ADRS_T(dofs,int);
GET_CONST_ADRS(elem_data);
GET_ADRS(data);
forall(k,1,
{
for (int i = 0; i < n; i++)
{
const int j = d_dofs[i];
if (j >= 0)
{
d_data[j] += d_elem_data[i];
}
else
{
d_data[-1-j] -= d_elem_data[i];
}
}
});
}
// *****************************************************************************
MFEM_NAMESPACE_END
<|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 "base/keyboard_codes.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
namespace {
class KeyboardAccessTest : public UITest {
public:
KeyboardAccessTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there are two menus and that
// New Tab is the first item in the app menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence);
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));
// The initial tab index should be 0.
int tab_index = -1;
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(0, tab_index);
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = -1;
ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_MENU, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_F10, 0));
int new_view_id = -1;
ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
original_view_id, &new_view_id));
ASSERT_TRUE(browser->StartTrackingPopupMenus());
// Press RIGHT to focus the app menu, then RETURN or DOWN to open it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RIGHT, 0));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait until the popup menu actually opens.
ASSERT_TRUE(browser->WaitForPopupMenuToOpen());
// Press DOWN to select the first item, then RETURN to select it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait for the new tab to appear.
ASSERT_TRUE(browser->WaitForTabCountToBecome(2, sleep_timeout_ms()));
// Make sure that the new tab index is 1.
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(1, tab_index);
}
TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false);
}
TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true);
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<commit_msg>Mark keyboard access tests as flaky until I figure out why they're not running on the Interactive Tests buildbot.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/keyboard_codes.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
namespace {
class KeyboardAccessTest : public UITest {
public:
KeyboardAccessTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there are two menus and that
// New Tab is the first item in the app menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence);
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<WindowProxy> window = browser->GetWindow();
ASSERT_TRUE(window.get());
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));
// The initial tab index should be 0.
int tab_index = -1;
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(0, tab_index);
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = -1;
ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_MENU, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_F10, 0));
int new_view_id = -1;
ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
original_view_id, &new_view_id));
ASSERT_TRUE(browser->StartTrackingPopupMenus());
// Press RIGHT to focus the app menu, then RETURN or DOWN to open it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RIGHT, 0));
if (alternate_key_sequence)
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
else
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait until the popup menu actually opens.
ASSERT_TRUE(browser->WaitForPopupMenuToOpen());
// Press DOWN to select the first item, then RETURN to select it.
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));
// Wait for the new tab to appear.
ASSERT_TRUE(browser->WaitForTabCountToBecome(2, sleep_timeout_ms()));
// Make sure that the new tab index is 1.
ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
ASSERT_EQ(1, tab_index);
}
TEST_F(KeyboardAccessTest, FLAKY_TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false);
}
TEST_F(KeyboardAccessTest, FLAKY_TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true);
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.