text
stringlengths 54
60.6k
|
---|
<commit_before>#include "store.h"
#include <map>
#include <iostream>
#include <fstream>
using namespace std;
class Store_map : Store
{
public:
Store_map();
~Store_map();
// Open and close store
void open(string filename){
ifstream ifs;
string buff_word;
int buff_n;
ifs.open(filename);
if (!ifs.is_open() || !ifs.good()){
cerr << "ERROR : couldn't load file " << filename << endl;
}
else{
cin >> tot;
while (cin >> buff_word){
cin >> buff_n;
hits.insert(pair<string, int>(buff_word, buff_n));
}
}
ifs.close();
}
void close(string filename){
ofstream ofs;
if (!ofs.is_open() || !ofs.good()){
cerr << "ERROR : couldn't open file " << filename << endl;
}
else{
for (pair<string, int> p : hits){
cout << p.first << " " << p.second << endl;
}
}
ofs.close();
}
// Check if store is initialized (e.g. table was created, etc.) and initializes it
bool is_init(){
return true;
}
void init(){}
// Check if word exists and insert it
bool exists(string word){
return hits.find(word) != hits.end();
}
void create(string word, int nb){
hits.insert(pair<string, int>(word, nb));
tot += nb;
}
// Access or modify hits
int get_hits(string word){
return hits[word];
}
void set_hits(string word, int nb){
tot += nb - hits[word];
hits[word] = nb;
}
// Access proba
double get_proba(string word){
return ((float)hits[word])/((double)tot);
}
private:
int tot;
map<string, int> hits;
};
<commit_msg>remove useless file<commit_after><|endoftext|> |
<commit_before>/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* 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.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
#include <sstream>
#include <cstdio>
#include "UniSetTypes.h"
#include "SQLiteInterface.h"
// --------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// --------------------------------------------------------------------------
SQLiteInterface::SQLiteInterface():
db(0),
lastQ(""),
lastE(""),
queryok(false),
connected(false),
opTimeout(300),
opCheckPause(50)
{
}
SQLiteInterface::~SQLiteInterface()
{
close();
delete db;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::ping()
{
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK );
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::connect( const string& dbfile, bool create )
{
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) )
// return false;
int flags = create ? 0 : SQLITE_OPEN_READWRITE;
int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL);
if( rc != SQLITE_OK )
{
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
connected = false;
return false;
}
setOperationTimeout(opTimeout);
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::close()
{
if( db )
{
sqlite3_close(db);
db = 0;
}
return true;
}
// -----------------------------------------------------------------------------------------
void SQLiteInterface::setOperationTimeout( timeout_t msec )
{
opTimeout = msec;
if( db )
sqlite3_busy_timeout(db,opTimeout);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q )
{
if( !db )
return false;
// char* errmsg;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{
queryok = false;
return false;
}
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{
sqlite3_finalize(pStmt);
queryok = false;
return false;
}
sqlite3_finalize(pStmt);
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc )
{
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR )
return false;
return true;
}
// -----------------------------------------------------------------------------------------
SQLiteResult SQLiteInterface::query( const string& q )
{
if( !db )
return SQLiteResult();
// char* errmsg = 0;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{
sqlite3_finalize(pStmt);
queryok = false;
return SQLiteResult();
}
lastQ = q;
queryok=true;
return SQLiteResult(pStmt,true);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{
PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() )
{
sqlite3_reset(stmt);
int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE )
return true;
msleep(opCheckPause);
}
return false;
}
// -----------------------------------------------------------------------------------------
string SQLiteInterface::error()
{
if( db )
lastE = sqlite3_errmsg(db);
return lastE;
}
// -----------------------------------------------------------------------------------------
const string SQLiteInterface::lastQuery()
{
return lastQ;
}
// -----------------------------------------------------------------------------------------
int SQLiteInterface::insert_id()
{
if( !db )
return 0;
return sqlite3_last_insert_rowid(db);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::isConnection()
{
return connected;
}
// -----------------------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& it )
{
return it->size();
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col )
{
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
}
// -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::iterator& it, int col )
{
return atof( ((*it)[col]).c_str() );
}
// -----------------------------------------------------------------------------------------
string as_string( SQLiteResult::iterator& it, int col )
{
return ((*it)[col]);
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::COL::iterator& it )
{
return uni_atoi( (*it) );
}
// -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::COL::iterator& it )
{
return atof( (*it).c_str() );
}
// -----------------------------------------------------------------------------------------
std::string as_string( SQLiteResult::COL::iterator& it )
{
return (*it);
}
// -----------------------------------------------------------------------------------------
#if 0
SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it )
{
return (*it);
}
#endif
// -----------------------------------------------------------------------------------------
SQLiteResult::~SQLiteResult()
{
}
// -----------------------------------------------------------------------------------------
SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
{
do
{
int n = sqlite3_data_count(s);
COL c;
for( int i=0; i<n; i++ )
{
char* p = (char*)sqlite3_column_text(s,i);
if( p )
c.push_back(p);
else
c.push_back("");
}
res.push_back(c);
}
while( sqlite3_step(s) == SQLITE_ROW );
if( finalize )
sqlite3_finalize(s);
}
// -----------------------------------------------------------------------------------------
<commit_msg>(SQLite): добавил принудительное выставление флагов при создании соединения с БД( вместо умолчательное)<commit_after>/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* 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.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
#include <sstream>
#include <cstdio>
#include "UniSetTypes.h"
#include "SQLiteInterface.h"
// --------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// --------------------------------------------------------------------------
SQLiteInterface::SQLiteInterface():
db(0),
lastQ(""),
lastE(""),
queryok(false),
connected(false),
opTimeout(300),
opCheckPause(50)
{
}
SQLiteInterface::~SQLiteInterface()
{
close();
delete db;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::ping()
{
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK );
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::connect( const string& dbfile, bool create )
{
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) )
// return false;
int flags = SQLITE_OPEN_READWRITE;
if( create )
flags |= SQLITE_OPEN_CREATE;
int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL);
if( rc != SQLITE_OK )
{
// cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl;
lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db));
sqlite3_close(db);
db = 0;
connected = false;
return false;
}
setOperationTimeout(opTimeout);
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::close()
{
if( db )
{
sqlite3_close(db);
db = 0;
}
return true;
}
// -----------------------------------------------------------------------------------------
void SQLiteInterface::setOperationTimeout( timeout_t msec )
{
opTimeout = msec;
if( db )
sqlite3_busy_timeout(db,opTimeout);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q )
{
if( !db )
return false;
// char* errmsg;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK )
{
queryok = false;
return false;
}
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) )
{
sqlite3_finalize(pStmt);
queryok = false;
return false;
}
sqlite3_finalize(pStmt);
queryok=true;
return true;
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc )
{
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR ) // || rc==SQLITE_NOMEM || rc==SQLITE_FULL )
return false;
return true;
}
// -----------------------------------------------------------------------------------------
SQLiteResult SQLiteInterface::query( const string& q )
{
if( !db )
return SQLiteResult();
// char* errmsg = 0;
sqlite3_stmt* pStmt;
// Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{
sqlite3_finalize(pStmt);
queryok = false;
return SQLiteResult();
}
lastQ = q;
queryok=true;
return SQLiteResult(pStmt,true);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{
PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() )
{
sqlite3_reset(stmt);
int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE )
return true;
msleep(opCheckPause);
}
return false;
}
// -----------------------------------------------------------------------------------------
string SQLiteInterface::error()
{
if( db )
lastE = sqlite3_errmsg(db);
return lastE;
}
// -----------------------------------------------------------------------------------------
const string SQLiteInterface::lastQuery()
{
return lastQ;
}
// -----------------------------------------------------------------------------------------
int SQLiteInterface::insert_id()
{
if( !db )
return 0;
return sqlite3_last_insert_rowid(db);
}
// -----------------------------------------------------------------------------------------
bool SQLiteInterface::isConnection()
{
return connected;
}
// -----------------------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& it )
{
return it->size();
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col )
{
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
}
// -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::iterator& it, int col )
{
return atof( ((*it)[col]).c_str() );
}
// -----------------------------------------------------------------------------------------
string as_string( SQLiteResult::iterator& it, int col )
{
return ((*it)[col]);
}
// -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::COL::iterator& it )
{
return uni_atoi( (*it) );
}
// -----------------------------------------------------------------------------------------
double as_double( SQLiteResult::COL::iterator& it )
{
return atof( (*it).c_str() );
}
// -----------------------------------------------------------------------------------------
std::string as_string( SQLiteResult::COL::iterator& it )
{
return (*it);
}
// -----------------------------------------------------------------------------------------
#if 0
SQLiteResult::COL get_col( SQLiteResult::ROW::iterator& it )
{
return (*it);
}
#endif
// -----------------------------------------------------------------------------------------
SQLiteResult::~SQLiteResult()
{
}
// -----------------------------------------------------------------------------------------
SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
{
do
{
int n = sqlite3_data_count(s);
COL c;
for( int i=0; i<n; i++ )
{
char* p = (char*)sqlite3_column_text(s,i);
if( p )
c.push_back(p);
else
c.push_back("");
}
res.push_back(c);
}
while( sqlite3_step(s) == SQLITE_ROW );
if( finalize )
sqlite3_finalize(s);
}
// -----------------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "window.h"
#include "control.h"
#include "logger.h"
#include "string_utils.h"
#include <FL/fl_ask.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Input_Choice.H>
#include <cassert>
#include <algorithm>
#include <vector>
void Vindow::FileNew(Fl_Widget*, void*)
{}
void Vindow::FileOpen(Fl_Widget*, void*)
{}
void Vindow::FileSave(Fl_Widget*, void* p)
{
extern void save_model(std::shared_ptr<Model>, std::wstring);
auto* me = (Vindow*)p;
std::wstring testPath(L"test.txt");
save_model(me->model_, testPath);
}
void Vindow::FileSaveAs(Fl_Widget*, void*)
{}
void Vindow::FileReload(Fl_Widget*, void*)
{}
void Vindow::FileExit(Fl_Widget*, void*)
{
extern bool is_any_model_dirty();
if(is_any_model_dirty())
{
int which = fl_choice("There are unsaved documents.\nAre you sure you want to exit?\n(Hint: use Vindow/Close to close just one window)", "&No", nullptr, "&Yes");
if(which != 2) return;
}
exit(0);
}
void Vindow::EditUndo(Fl_Widget*, void*)
{}
void Vindow::EditCut(Fl_Widget*, void*)
{}
void Vindow::EditCopy(Fl_Widget*, void*)
{}
void Vindow::EditPaste(Fl_Widget*, void*)
{}
void Vindow::EditInsertRest(Fl_Widget*, void* p)
{
LOGGER(l);
auto me = (Vindow*)p;
assert(me->editor_);
Control ctrl(me->model_, me);
if(me->layout_ == Vindow::Layout::OUTPUT) {
#if 1
l(L"using text editor, this should not be called\n");
#else
auto pos = me->model_->output.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, L'.');
assert(me->editor_);
me->editor_->Update(me->model_->whats.size());
#endif
} else if(me->layout_ == Vindow::Layout::WHAT) {
auto found = std::find_if(me->model_->whats.begin(), me->model_->whats.end(), [me](WhatEntry& what) -> bool {
return what.name == me->active_;
});
if(found == me->model_->whats.end()) {
l(L"%ls not found\n", me->active_.c_str());
return;
}
auto pos = found->columns.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, L'.');
assert(me->editor_);
me->editor_->Update(me->model_->whos.size());
}
}
void Vindow::EditInsertBlank(Fl_Widget*, void* p)
{
LOGGER(l);
auto me = (Vindow*)p;
assert(me->editor_);
Control ctrl(me->model_, me);
if(me->layout_ == Vindow::Layout::OUTPUT) {
#if 1
l(L"using text editor, should not be called\n");
#else
auto pos = me->model_->output.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, ' ');
assert(me->editor_);
me->editor_->Update(me->model_->whats.size());
#endif
} else if(me->layout_ == Vindow::Layout::WHAT) {
auto found = std::find_if(me->model_->whats.begin(), me->model_->whats.end(), [me](WhatEntry& what) -> bool {
return what.name == me->active_;
});
if(found == me->model_->whats.end()) {
l(L"%s not found\n", me->active_);
return;
}
auto pos = found->columns.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, ' ');
assert(me->editor_);
me->editor_->Update(me->model_->whos.size());
}
}
// if selection, goto sel
// if cursorx == 0, return
// if previous char == ' ', move cursor left, return
// if previous char != ' ', replace with '.' and move cursor left, return
// sel: for each cell
// if previous char == ' ', continue
// if previous char != ' ', replace with '.', continue
void Vindow::EditClearColumns(Fl_Widget*, void* p)
{
LOGGER(l);
auto* me = (Vindow*)p;
if(!me->editor_) return;
if(me->layout_ == Vindow::Layout::WHO) {
l(L"Nothing to do in WHO layout\n");
return;
}
if(!me->editor_) {
l(L"missing editor!\n");
return;
}
if(me->editor_->mx() == 0) {
l(L"no character to the left\n");
return;
}
Control ctrl(me->model_, me);
ctrl.BlankCell(me->active_, me->editor_->mx() - 1, me->editor_->my());
me->editor_->SetCursor(me->editor_->my(), me->editor_->mx() - 1);
me->editor_->Update();
}
void Vindow::EditDeleteColumns(Fl_Widget*, void*)
{}
void Vindow::EditAddWhat(Fl_Widget*, void*)
{}
void Vindow::EditAddWho(Fl_Widget*, void*)
{}
void Vindow::EditDeleteSection(Fl_Widget*, void*)
{}
void Vindow::WindowNew(Fl_Widget*, void* p)
{
extern void create_window(std::shared_ptr<Model>);
Vindow* me = (Vindow*)p;
create_window(me->model_);
}
void Vindow::WindowClose(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty
&& me->model_->views.size() == 1)
{
int which = fl_choice("There are unsaved changes in the document.\nClosing this window will discard all changes.\nDo you want to close this document?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
return destroy_window(me);
}
void Vindow::WindowCloseAll(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty)
{
int which = fl_choice("There are unsaved changes in the document.\nDo you want to close this document, discarding changes?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
std::vector<View*> toDestroy;
std::copy_if(me->model_->views.begin(), me->model_->views.end(), std::back_inserter(toDestroy), [me](View* view) -> bool {
auto* w = dynamic_cast<Vindow*>(view);
if(w == me) return false;
return w != nullptr;
});
for(auto* view : toDestroy)
{
auto* w = dynamic_cast<Vindow*>(view);
if(w) destroy_window(w);
}
return destroy_window(me);
}
void Vindow::HelpAbout(Fl_Widget*, void*)
{
fl_alert("JakBeat GUI\nCopyright (c) 2015-2017 Vlad Meșco\nAvailable under the 2-Clause BSD License");
}
void Vindow::WhatClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHAT, MB2W(label));
me->redraw();
}
void Vindow::WhoClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHO, MB2W(label));
me->redraw();
}
void Vindow::OutputClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
me->SetLayout(Layout::OUTPUT);
me->redraw();
}
void Vindow::WindowCallback(Fl_Widget* w, void* p)
{
WindowClose(w, p);
}
void Vindow::WhoNameChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input*)w;
auto* me = (Vindow*)p;
std::wstring newName = MB2W(inp->value());
std::wstring oldName = me->active_;
if(std::any_of(me->model_->whos.begin(), me->model_->whos.end(), [newName](WhoEntry const& e) -> bool {
return e.name == newName;
})
|| newName.empty())
{
fl_alert("Name needs to be unique and not null");
inp->value(W2MB(oldName).get());
// Fl::focus(inp); // doesn't work because e.g. the tab key is
// handled later...
return;
}
Control ctrl(me->model_, me);
ctrl.SetWhosName(oldName, newName);
}
void Vindow::WhatNameChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input*)w;
auto* me = (Vindow*)p;
std::wstring newName = MB2W(inp->value());
std::wstring oldName = me->active_;
if(std::any_of(me->model_->whats.begin(), me->model_->whats.end(), [newName](WhatEntry const& e) -> bool {
return e.name == newName;
})
|| newName.empty()
|| newName == L"OUTPUT")
{
fl_alert("Name needs to be unique and not null");
inp->value(W2MB(oldName).get());
// Fl::focus(inp); // doesn't work because e.g. the tab key is
// handled later...
return;
}
Control ctrl(me->model_, me);
ctrl.SetWhatsName(oldName, newName);
}
void Vindow::WhatBpmChanged(Fl_Widget* w, void* p)
{
auto* inp = dynamic_cast<Fl_Input*>(w);
auto* me = (Vindow*)p;
auto&& what = me->active_;
auto bpm = MB2W(inp->value());
Control ctrl(me->model_, me);
ctrl.SetWhatsBpm(what, bpm);
}
void Vindow::SchemaChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input_Choice*)w;
auto* me = (Vindow*)p;
auto&& who = me->active_;
int idx = inp->menubutton()->value();
assert(idx >= 0 && idx < me->drumSchemas_.size());
Schema const* schema = &me->drumSchemas_[idx];
Control ctrl(me->model_, me);
ctrl.SetWhosSchema(who, schema);
}
void Vindow::ParamChanged(Fl_Widget* w, void* p)
{
auto* inp = dynamic_cast<Fl_Input*>(w);
auto* me = (Vindow*)p;
auto&& who = me->active_;
std::wstring param = MB2W(inp->label());
std::wstring value = MB2W(inp->value());
Control ctrl(me->model_, me);
ctrl.SetWhosParam(who, param, value);
}
void Vindow::OutputChanged(int pos, int inserted, int deleted, int restyled, const char* deletedText, void* cbArg)
{
LOGGER(l);
auto* me = (Vindow*)cbArg;
if(me->blockBufferChanged_) {
l(L"refreshed, not triggering event\n");
return;
}
l(L"pos=%d inserted=%d deleted=%d restyled=%d\n", pos, inserted, deleted, restyled);
if(deletedText)
l(L"deletedText=%ls\n", MB2W(deletedText).c_str());
auto* ss = me->buffer_->address(pos);
auto text = MB2W(ss, inserted);
l(L"text=%ls\n", text.c_str());
Control ctrl(me->model_, me);
if(deleted) {
ctrl.DeleteText(pos, deleted);
}
if(inserted) {
ctrl.InsertText(pos, text);
}
}
<commit_msg>prevent the creation of reserved sections<commit_after>#include "window.h"
#include "control.h"
#include "logger.h"
#include "string_utils.h"
#include <FL/fl_ask.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Input_Choice.H>
#include <cassert>
#include <algorithm>
#include <vector>
void Vindow::FileNew(Fl_Widget*, void*)
{}
void Vindow::FileOpen(Fl_Widget*, void*)
{}
void Vindow::FileSave(Fl_Widget*, void* p)
{
extern void save_model(std::shared_ptr<Model>, std::wstring);
auto* me = (Vindow*)p;
std::wstring testPath(L"test.txt");
save_model(me->model_, testPath);
}
void Vindow::FileSaveAs(Fl_Widget*, void*)
{}
void Vindow::FileReload(Fl_Widget*, void*)
{}
void Vindow::FileExit(Fl_Widget*, void*)
{
extern bool is_any_model_dirty();
if(is_any_model_dirty())
{
int which = fl_choice("There are unsaved documents.\nAre you sure you want to exit?\n(Hint: use Vindow/Close to close just one window)", "&No", nullptr, "&Yes");
if(which != 2) return;
}
exit(0);
}
void Vindow::EditUndo(Fl_Widget*, void*)
{}
void Vindow::EditCut(Fl_Widget*, void*)
{}
void Vindow::EditCopy(Fl_Widget*, void*)
{}
void Vindow::EditPaste(Fl_Widget*, void*)
{}
void Vindow::EditInsertRest(Fl_Widget*, void* p)
{
LOGGER(l);
auto me = (Vindow*)p;
assert(me->editor_);
Control ctrl(me->model_, me);
if(me->layout_ == Vindow::Layout::OUTPUT) {
#if 1
l(L"using text editor, this should not be called\n");
#else
auto pos = me->model_->output.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, L'.');
assert(me->editor_);
me->editor_->Update(me->model_->whats.size());
#endif
} else if(me->layout_ == Vindow::Layout::WHAT) {
auto found = std::find_if(me->model_->whats.begin(), me->model_->whats.end(), [me](WhatEntry& what) -> bool {
return what.name == me->active_;
});
if(found == me->model_->whats.end()) {
l(L"%ls not found\n", me->active_.c_str());
return;
}
auto pos = found->columns.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, L'.');
assert(me->editor_);
me->editor_->Update(me->model_->whos.size());
}
}
void Vindow::EditInsertBlank(Fl_Widget*, void* p)
{
LOGGER(l);
auto me = (Vindow*)p;
assert(me->editor_);
Control ctrl(me->model_, me);
if(me->layout_ == Vindow::Layout::OUTPUT) {
#if 1
l(L"using text editor, should not be called\n");
#else
auto pos = me->model_->output.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, ' ');
assert(me->editor_);
me->editor_->Update(me->model_->whats.size());
#endif
} else if(me->layout_ == Vindow::Layout::WHAT) {
auto found = std::find_if(me->model_->whats.begin(), me->model_->whats.end(), [me](WhatEntry& what) -> bool {
return what.name == me->active_;
});
if(found == me->model_->whats.end()) {
l(L"%s not found\n", me->active_);
return;
}
auto pos = found->columns.begin();
std::advance(pos, me->editor_->mx());
ctrl.InsertColumn(me->active_, pos, ' ');
assert(me->editor_);
me->editor_->Update(me->model_->whos.size());
}
}
// if selection, goto sel
// if cursorx == 0, return
// if previous char == ' ', move cursor left, return
// if previous char != ' ', replace with '.' and move cursor left, return
// sel: for each cell
// if previous char == ' ', continue
// if previous char != ' ', replace with '.', continue
void Vindow::EditClearColumns(Fl_Widget*, void* p)
{
LOGGER(l);
auto* me = (Vindow*)p;
if(!me->editor_) return;
if(me->layout_ == Vindow::Layout::WHO) {
l(L"Nothing to do in WHO layout\n");
return;
}
if(!me->editor_) {
l(L"missing editor!\n");
return;
}
if(me->editor_->mx() == 0) {
l(L"no character to the left\n");
return;
}
Control ctrl(me->model_, me);
ctrl.BlankCell(me->active_, me->editor_->mx() - 1, me->editor_->my());
me->editor_->SetCursor(me->editor_->my(), me->editor_->mx() - 1);
me->editor_->Update();
}
void Vindow::EditDeleteColumns(Fl_Widget*, void*)
{}
void Vindow::EditAddWhat(Fl_Widget*, void*)
{}
void Vindow::EditAddWho(Fl_Widget*, void*)
{}
void Vindow::EditDeleteSection(Fl_Widget*, void*)
{}
void Vindow::WindowNew(Fl_Widget*, void* p)
{
extern void create_window(std::shared_ptr<Model>);
Vindow* me = (Vindow*)p;
create_window(me->model_);
}
void Vindow::WindowClose(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty
&& me->model_->views.size() == 1)
{
int which = fl_choice("There are unsaved changes in the document.\nClosing this window will discard all changes.\nDo you want to close this document?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
return destroy_window(me);
}
void Vindow::WindowCloseAll(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty)
{
int which = fl_choice("There are unsaved changes in the document.\nDo you want to close this document, discarding changes?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
std::vector<View*> toDestroy;
std::copy_if(me->model_->views.begin(), me->model_->views.end(), std::back_inserter(toDestroy), [me](View* view) -> bool {
auto* w = dynamic_cast<Vindow*>(view);
if(w == me) return false;
return w != nullptr;
});
for(auto* view : toDestroy)
{
auto* w = dynamic_cast<Vindow*>(view);
if(w) destroy_window(w);
}
return destroy_window(me);
}
void Vindow::HelpAbout(Fl_Widget*, void*)
{
fl_alert("JakBeat GUI\nCopyright (c) 2015-2017 Vlad Meșco\nAvailable under the 2-Clause BSD License");
}
void Vindow::WhatClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHAT, MB2W(label));
me->redraw();
}
void Vindow::WhoClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHO, MB2W(label));
me->redraw();
}
void Vindow::OutputClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
me->SetLayout(Layout::OUTPUT);
me->redraw();
}
void Vindow::WindowCallback(Fl_Widget* w, void* p)
{
WindowClose(w, p);
}
void Vindow::WhoNameChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input*)w;
auto* me = (Vindow*)p;
std::wstring newName = MB2W(inp->value());
std::wstring oldName = me->active_;
if(std::any_of(me->model_->whos.begin(), me->model_->whos.end(), [newName](WhoEntry const& e) -> bool {
return e.name == newName;
})
|| newName.empty())
{
fl_alert("Name needs to be unique and not null");
inp->value(W2MB(oldName).get());
// Fl::focus(inp); // doesn't work because e.g. the tab key is
// handled later...
return;
}
Control ctrl(me->model_, me);
ctrl.SetWhosName(oldName, newName);
}
void Vindow::WhatNameChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input*)w;
auto* me = (Vindow*)p;
std::wstring newName = MB2W(inp->value());
std::wstring oldName = me->active_;
if(std::any_of(me->model_->whats.begin(), me->model_->whats.end(), [newName](WhatEntry const& e) -> bool {
return e.name == newName;
})
|| newName.empty()
/* reserved */
|| newName == L"OUTPUT"
|| newName == L"Output"
|| newName == L"WHO"
|| newName == L"WHAT")
{
fl_alert("Name needs to be unique, not reserved, and not null");
inp->value(W2MB(oldName).get());
// Fl::focus(inp); // doesn't work because e.g. the tab key is
// handled later...
return;
}
Control ctrl(me->model_, me);
ctrl.SetWhatsName(oldName, newName);
}
void Vindow::WhatBpmChanged(Fl_Widget* w, void* p)
{
auto* inp = dynamic_cast<Fl_Input*>(w);
auto* me = (Vindow*)p;
auto&& what = me->active_;
auto bpm = MB2W(inp->value());
Control ctrl(me->model_, me);
ctrl.SetWhatsBpm(what, bpm);
}
void Vindow::SchemaChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input_Choice*)w;
auto* me = (Vindow*)p;
auto&& who = me->active_;
int idx = inp->menubutton()->value();
assert(idx >= 0 && idx < me->drumSchemas_.size());
Schema const* schema = &me->drumSchemas_[idx];
Control ctrl(me->model_, me);
ctrl.SetWhosSchema(who, schema);
}
void Vindow::ParamChanged(Fl_Widget* w, void* p)
{
auto* inp = dynamic_cast<Fl_Input*>(w);
auto* me = (Vindow*)p;
auto&& who = me->active_;
std::wstring param = MB2W(inp->label());
std::wstring value = MB2W(inp->value());
Control ctrl(me->model_, me);
ctrl.SetWhosParam(who, param, value);
}
void Vindow::OutputChanged(int pos, int inserted, int deleted, int restyled, const char* deletedText, void* cbArg)
{
LOGGER(l);
auto* me = (Vindow*)cbArg;
if(me->blockBufferChanged_) {
l(L"refreshed, not triggering event\n");
return;
}
l(L"pos=%d inserted=%d deleted=%d restyled=%d\n", pos, inserted, deleted, restyled);
if(deletedText)
l(L"deletedText=%ls\n", MB2W(deletedText).c_str());
auto* ss = me->buffer_->address(pos);
auto text = MB2W(ss, inserted);
l(L"text=%ls\n", text.c_str());
Control ctrl(me->model_, me);
if(deleted) {
ctrl.DeleteText(pos, deleted);
}
if(inserted) {
ctrl.InsertText(pos, text);
}
}
<|endoftext|> |
<commit_before>//
// Managed C++ wrapper class around the Hugs server API.
//
#using <mscorlib.dll>
extern "C" {
#include "prelude.h"
#include "storage.h"
#include "connect.h"
};
#include "prim.h"
#include "HugsServ.h"
#define ToCharString(str) \
static_cast<char*>(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str).ToPointer())
#define FreeCharString(pstr) System::Runtime::InteropServices::Marshal::FreeHGlobal(pstr)
extern "C" {
extern char* lastError;
extern char* ClearError();
extern Void setError (char*);
extern Bool safeEval (Cell c);
extern Void startEval (Void);
};
/* All server entry points set CStackBase for the benefit of the (conservative)
* GC and do error catching. Any calls to Hugs functions should be "protected"
* by being placed inside this macro.
*
* void entryPoint(arg1, arg2, result)
* T1 arg1;
* T2 arg2;
* T3 *result;
* {
* protect(doNothing(),
* ...
* );
* }
*
* Macro decomposed into BEGIN_PROTECT and END_PROTECT pieces so that i
* can be used on some compilers (Mac?) that have limits on the size of
* macro arguments.
*/
#define BEGIN_PROTECT \
if (NULL == lastError) { \
Cell dummy; \
CStackBase = &dummy; /* Save stack base for use in gc */ \
consGC = TRUE; /* conservative GC is the default */ \
if (1) {
#define END_PROTECT \
} else { \
setError("Error occurred"); \
normalTerminal(); \
} \
}
#define protect(s) BEGIN_PROTECT s; END_PROTECT
static Void MkObject Args((System::Object*));
static Object* EvalObject Args((Void));
static Int DoIO_Object Args((Object* __gc&));
/* Push an Object/DotNetPtr onto the stack */
static Void MkObject(Object* a)
{
#ifndef NO_DYNAMIC_TYPES
Cell d = getTypeableDict(type);
if (isNull(d)) {
setError("MkObject: can't create Typeable instance");
return 0;
}
protect(push(ap(ap(nameToDynamic,d),mkDotNetPtr(a,freeNetPtr))));
#else
protect(push(mkDotNetPtr(a,freeNetPtr)));
#endif
}
static Object* EvalObject() /* Evaluate a cell (:: Object) */
{
Cell d;
BEGIN_PROTECT
startEval();
#ifndef NO_DYNAMIC_TYPES
d = getTypeableDict(type);
if (isNull(d)) {
setError("EvalObject: can't create Typeable instance");
return 0;
}
safeEval(ap(ap(nameToDynamic,d),pop()));
#else
safeEval(pop());
#endif
normalTerminal();
return getNP(whnfHead);
END_PROTECT
return 0;
}
/*
* Evaluate a cell (:: IO DotNetPtr) return exit status
*/
static Int DoIO_Object(Object* __gc& phval)
{
BEGIN_PROTECT
Int exitCode = 0;
Bool ok;
StackPtr oldsp = sp;
startEval();
#ifndef NO_DYNAMIC_TYPES
ok = safeEval(ap(nameIORun,ap(nameRunDyn,pop())));
#else
ok = safeEval(ap(nameIORun,pop()));
#endif
if (!ok)
{
sp = oldsp-1;
exitCode = 1;
} else if (whnfHead == nameLeft) {
safeEval(pop());
exitCode = whnfInt;
} else {
if (phval) {
safeEval(pop());
phval = getNP(whnfHead);
} else {
drop();
}
exitCode = 0;
}
normalTerminal();
if (sp != oldsp-1) {
setError("doIO: unbalanced stack");
return 1;
}
return exitCode;
END_PROTECT;
return -1; /* error code */
}
namespace Hugs {
System::String* Server::ClearError() {
char* s = m_server->clearError();
return new System::String(s);
}
//
// Method: SetHugsArgs(String* argv[])
//
// Purpose: Configure the argument vector which
// H98's System.getArgs returns.
//
void Server::SetHugsArgs(System::String* argv[]) {
char __nogc* __nogc* args = new char*[argv.Length];
int len = argv.Length;
for (int i=0; i < len; i++) {
args[i] = new char[argv[i]->Length + 1];
args[i] = ToCharString(argv[i]);
}
m_server->setHugsArgs(len,args);
/* Looks kind of silly; a better way? */
for (int i=0; i < len; i++) {
delete args[i];
}
delete args;
return;
}
int Server::GetNumScripts() {
return m_server->getNumScripts();
}
void Server::Reset(int i) {
m_server->reset(i);
return;
}
void Server::SetOutputEnable (int i) {
m_server->setOutputEnable(i);
return;
}
void Server::ChangeDir(System::String* dir) {
char __nogc* dirStr = ToCharString(dir);
m_server->changeDir(dirStr);
FreeCharString(dirStr);
return;
}
void Server::LoadProject(System::String* proj) {
char __nogc* projStr = ToCharString(proj);
m_server->loadProject(projStr);
FreeCharString(projStr);
return;
}
void Server::LoadFile(System::String* fname) {
char __nogc* fnameStr = ToCharString(fname);
m_server->loadProject(fnameStr);
FreeCharString(fnameStr);
return;
}
void Server::LoadFromBuffer(System::String* haskMod) {
char __nogc* hStr = ToCharString(haskMod);
m_server->loadFromBuffer(hStr);
FreeCharString(hStr);
return;
}
void Server::SetOptions(System::String* opts) {
char __nogc* hStr = ToCharString(opts);
m_server->setOptions(hStr);
FreeCharString(hStr);
return;
}
System::String* Server::GetOptions() {
char* r = m_server->getOptions();
return System::Runtime::InteropServices::Marshal::PtrToStringAnsi(r);
}
HVal Server::CompileExpr(System::String* mo,System::String* v) {
char __nogc* moStr = ToCharString(mo);
char __nogc* vStr = ToCharString(v);
HVal res = m_server->compileExpr(moStr,vStr);
FreeCharString(moStr);
FreeCharString(vStr);
return res;
}
void Server::GarbageCollect() {
m_server->garbageCollect();
return;
}
void Server::LookupName(System::String* mo,System::String* v) {
char __nogc* moStr = ToCharString(mo);
char __nogc* vStr = ToCharString(v);
m_server->lookupName(moStr,vStr);
FreeCharString(moStr);
FreeCharString(vStr);
return;
}
void Server::mkInt(int i) {
m_server->mkInt(i);
return;
}
void Server::mkAddr(void* ptr) {
m_server->mkAddr(ptr);
return;
}
void Server::mkObject(Object* obj) {
MkObject(obj);
return;
}
void Server::mkString(System::String* s) {
char* str = ToCharString(s);
m_server->mkString(str);
FreeCharString(str);
return;
}
void Server::apply() {
m_server->apply();
return;
}
int Server::evalInt() {
return m_server->evalInt();
}
void* Server::evalAddr() {
return m_server->evalAddr();
}
Object* Server::evalObject() {
return EvalObject();
}
System::String* Server::evalString() {
char* str = m_server->evalString();
return System::Runtime::InteropServices::Marshal::PtrToStringAnsi(str);
}
int Server::doIO() {
return m_server->doIO();
}
int Server::doIO_Int(int* pRes) {
return 0;
}
int Server::doIO_Addr(void** pRes) {
return 0;
}
int Server::doIO_Object(Object* __gc& pRes) {
return DoIO_Object(pRes);
}
HVal Server::popHVal() {
HVal h = m_server->popHVal();
return h;
}
void Server::pushHVal(HVal arg) {
m_server->pushHVal(arg);
return;
}
void Server::freeHVal(HVal arg) {
m_server->freeHVal(arg);
return;
}
};
<commit_msg>added machdep.h include<commit_after>//
// Managed C++ wrapper class around the Hugs server API.
//
#using <mscorlib.dll>
extern "C" {
#include "prelude.h"
#include "storage.h"
#include "machdep.h"
#include "connect.h"
};
#include "prim.h"
#include "HugsServ.h"
#define ToCharString(str) \
static_cast<char*>(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str).ToPointer())
#define FreeCharString(pstr) System::Runtime::InteropServices::Marshal::FreeHGlobal(pstr)
extern "C" {
extern char* lastError;
extern char* ClearError();
extern Void setError (char*);
extern Bool safeEval (Cell c);
extern Void startEval (Void);
};
/* All server entry points set CStackBase for the benefit of the (conservative)
* GC and do error catching. Any calls to Hugs functions should be "protected"
* by being placed inside this macro.
*
* void entryPoint(arg1, arg2, result)
* T1 arg1;
* T2 arg2;
* T3 *result;
* {
* protect(doNothing(),
* ...
* );
* }
*
* Macro decomposed into BEGIN_PROTECT and END_PROTECT pieces so that i
* can be used on some compilers (Mac?) that have limits on the size of
* macro arguments.
*/
#define BEGIN_PROTECT \
if (NULL == lastError) { \
Cell dummy; \
CStackBase = &dummy; /* Save stack base for use in gc */ \
consGC = TRUE; /* conservative GC is the default */ \
if (1) {
#define END_PROTECT \
} else { \
setError("Error occurred"); \
normalTerminal(); \
} \
}
#define protect(s) BEGIN_PROTECT s; END_PROTECT
static Void MkObject Args((System::Object*));
static Object* EvalObject Args((Void));
static Int DoIO_Object Args((Object* __gc&));
/* Push an Object/DotNetPtr onto the stack */
static Void MkObject(Object* a)
{
#ifndef NO_DYNAMIC_TYPES
Cell d = getTypeableDict(type);
if (isNull(d)) {
setError("MkObject: can't create Typeable instance");
return 0;
}
protect(push(ap(ap(nameToDynamic,d),mkDotNetPtr(a,freeNetPtr))));
#else
protect(push(mkDotNetPtr(a,freeNetPtr)));
#endif
}
static Object* EvalObject() /* Evaluate a cell (:: Object) */
{
Cell d;
BEGIN_PROTECT
startEval();
#ifndef NO_DYNAMIC_TYPES
d = getTypeableDict(type);
if (isNull(d)) {
setError("EvalObject: can't create Typeable instance");
return 0;
}
safeEval(ap(ap(nameToDynamic,d),pop()));
#else
safeEval(pop());
#endif
normalTerminal();
return getNP(whnfHead);
END_PROTECT
return 0;
}
/*
* Evaluate a cell (:: IO DotNetPtr) return exit status
*/
static Int DoIO_Object(Object* __gc& phval)
{
BEGIN_PROTECT
Int exitCode = 0;
Bool ok;
StackPtr oldsp = sp;
startEval();
#ifndef NO_DYNAMIC_TYPES
ok = safeEval(ap(nameIORun,ap(nameRunDyn,pop())));
#else
ok = safeEval(ap(nameIORun,pop()));
#endif
if (!ok)
{
sp = oldsp-1;
exitCode = 1;
} else if (whnfHead == nameLeft) {
safeEval(pop());
exitCode = whnfInt;
} else {
if (phval) {
safeEval(pop());
phval = getNP(whnfHead);
} else {
drop();
}
exitCode = 0;
}
normalTerminal();
if (sp != oldsp-1) {
setError("doIO: unbalanced stack");
return 1;
}
return exitCode;
END_PROTECT;
return -1; /* error code */
}
namespace Hugs {
System::String* Server::ClearError() {
char* s = m_server->clearError();
return new System::String(s);
}
//
// Method: SetHugsArgs(String* argv[])
//
// Purpose: Configure the argument vector which
// H98's System.getArgs returns.
//
void Server::SetHugsArgs(System::String* argv[]) {
char __nogc* __nogc* args = new char*[argv.Length];
int len = argv.Length;
for (int i=0; i < len; i++) {
args[i] = new char[argv[i]->Length + 1];
args[i] = ToCharString(argv[i]);
}
m_server->setHugsArgs(len,args);
/* Looks kind of silly; a better way? */
for (int i=0; i < len; i++) {
delete args[i];
}
delete args;
return;
}
int Server::GetNumScripts() {
return m_server->getNumScripts();
}
void Server::Reset(int i) {
m_server->reset(i);
return;
}
void Server::SetOutputEnable (int i) {
m_server->setOutputEnable(i);
return;
}
void Server::ChangeDir(System::String* dir) {
char __nogc* dirStr = ToCharString(dir);
m_server->changeDir(dirStr);
FreeCharString(dirStr);
return;
}
void Server::LoadProject(System::String* proj) {
char __nogc* projStr = ToCharString(proj);
m_server->loadProject(projStr);
FreeCharString(projStr);
return;
}
void Server::LoadFile(System::String* fname) {
char __nogc* fnameStr = ToCharString(fname);
m_server->loadProject(fnameStr);
FreeCharString(fnameStr);
return;
}
void Server::LoadFromBuffer(System::String* haskMod) {
char __nogc* hStr = ToCharString(haskMod);
m_server->loadFromBuffer(hStr);
FreeCharString(hStr);
return;
}
void Server::SetOptions(System::String* opts) {
char __nogc* hStr = ToCharString(opts);
m_server->setOptions(hStr);
FreeCharString(hStr);
return;
}
System::String* Server::GetOptions() {
char* r = m_server->getOptions();
return System::Runtime::InteropServices::Marshal::PtrToStringAnsi(r);
}
HVal Server::CompileExpr(System::String* mo,System::String* v) {
char __nogc* moStr = ToCharString(mo);
char __nogc* vStr = ToCharString(v);
HVal res = m_server->compileExpr(moStr,vStr);
FreeCharString(moStr);
FreeCharString(vStr);
return res;
}
void Server::GarbageCollect() {
m_server->garbageCollect();
return;
}
void Server::LookupName(System::String* mo,System::String* v) {
char __nogc* moStr = ToCharString(mo);
char __nogc* vStr = ToCharString(v);
m_server->lookupName(moStr,vStr);
FreeCharString(moStr);
FreeCharString(vStr);
return;
}
void Server::mkInt(int i) {
m_server->mkInt(i);
return;
}
void Server::mkAddr(void* ptr) {
m_server->mkAddr(ptr);
return;
}
void Server::mkObject(Object* obj) {
MkObject(obj);
return;
}
void Server::mkString(System::String* s) {
char* str = ToCharString(s);
m_server->mkString(str);
FreeCharString(str);
return;
}
void Server::apply() {
m_server->apply();
return;
}
int Server::evalInt() {
return m_server->evalInt();
}
void* Server::evalAddr() {
return m_server->evalAddr();
}
Object* Server::evalObject() {
return EvalObject();
}
System::String* Server::evalString() {
char* str = m_server->evalString();
return System::Runtime::InteropServices::Marshal::PtrToStringAnsi(str);
}
int Server::doIO() {
return m_server->doIO();
}
int Server::doIO_Int(int* pRes) {
return 0;
}
int Server::doIO_Addr(void** pRes) {
return 0;
}
int Server::doIO_Object(Object* __gc& pRes) {
return DoIO_Object(pRes);
}
HVal Server::popHVal() {
HVal h = m_server->popHVal();
return h;
}
void Server::pushHVal(HVal arg) {
m_server->pushHVal(arg);
return;
}
void Server::freeHVal(HVal arg) {
m_server->freeHVal(arg);
return;
}
};
<|endoftext|> |
<commit_before>#include "drivers/mpu6000.hpp"
#include "unit_config.hpp"
void MPU6000::init() {
// Reset device.
txbuf[0] = mpu6000::PWR_MGMT_1;
txbuf[1] = 0x80;
exchange(2);
chThdSleepMilliseconds(100); // TODO(yoos): Check whether or not datasheet specifies this holdoff.
// Set sample rate to 1 kHz.
txbuf[0] = mpu6000::SMPLRT_DIV;
txbuf[1] = 0x00;
exchange(2);
// Set DLPF to 4 (20 Hz gyro bandwidth1 Hz accelerometer bandwidth)
txbuf[0] = mpu6000::CONFIG;
txbuf[1] = 0x04;
exchange(2);
// Wake up device and set clock source to Gyro Z.
txbuf[0] = mpu6000::PWR_MGMT_1;
txbuf[1] = 0x03;
exchange(2);
// Set gyro full range to 2000 dps. We first read in the current register
// value so we can change what we need and leave everything else alone.
// See DS p. 12.
txbuf[0] = mpu6000::GYRO_CONFIG | (1<<7);
exchange(2);
chThdSleepMicroseconds(0); // TODO(yoos): Without this, the GYRO_CONFIG register does not get set. This was not the case in the old C firmware. Why?
txbuf[0] = mpu6000::GYRO_CONFIG;
txbuf[1] = (rxbuf[1] & ~0x18) | 0x18;
exchange(2);
// Set accelerometer full range to 4 g. See DS p. 13.
txbuf[0] = mpu6000::ACCEL_CONFIG | (1<<7);
exchange(2);
txbuf[0] = mpu6000::ACCEL_CONFIG;
txbuf[1] = (rxbuf[1] & ~0x18) | 0x08;
exchange(2);
// Read once to clear out bad data?
readGyro();
readAccel();
}
gyroscope_reading_t MPU6000::readGyro() {
gyroscope_reading_t reading;
// Poll gyro
txbuf[0] = mpu6000::GYRO_XOUT_H | (1<<7);
exchange(7);
// TODO(yoos): correct for thermal bias.
reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 16.384 * 3.1415926535 / 180.0 + unit_config::GYR_X_OFFSET;
reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 16.384 * 3.1415926535 / 180.0 + unit_config::GYR_Y_OFFSET;
reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 16.384 * 3.1415926535 / 180.0 + unit_config::GYR_Z_OFFSET;
// Poll temp
txbuf[0] = mpu6000::TEMP_OUT_H | (1<<7);
exchange(3);
float temp = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 340 + 36.53;
// DEBUG
//char dbg_buf[16];
//for (int i=0; i<16; i++) {
// dbg_buf[i] = 0;
//}
//chsnprintf(dbg_buf, 12, "%0.6f\r\n", reading.axes[2]);
//chnWriteTimeout((BaseChannel*)&SD3, (uint8_t*)dbg_buf, 12, MS2ST(20));
return reading;
}
accelerometer_reading_t MPU6000::readAccel() {
accelerometer_reading_t reading;
// Get data
txbuf[0] = mpu6000::ACCEL_XOUT_H | (1<<7);
exchange(7);
reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 8192.0 + unit_config::ACC_X_OFFSET;
reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 8192.0 + unit_config::ACC_Y_OFFSET;
reading.axes[2] = -((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 8192.0 + unit_config::ACC_Z_OFFSET;
return reading;
}
<commit_msg>Negate MPU6000 X and Y axes.<commit_after>#include "drivers/mpu6000.hpp"
#include "unit_config.hpp"
void MPU6000::init() {
// Reset device.
txbuf[0] = mpu6000::PWR_MGMT_1;
txbuf[1] = 0x80;
exchange(2);
chThdSleepMilliseconds(100); // TODO(yoos): Check whether or not datasheet specifies this holdoff.
// Set sample rate to 1 kHz.
txbuf[0] = mpu6000::SMPLRT_DIV;
txbuf[1] = 0x00;
exchange(2);
// Set DLPF to 4 (20 Hz gyro bandwidth1 Hz accelerometer bandwidth)
txbuf[0] = mpu6000::CONFIG;
txbuf[1] = 0x04;
exchange(2);
// Wake up device and set clock source to Gyro Z.
txbuf[0] = mpu6000::PWR_MGMT_1;
txbuf[1] = 0x03;
exchange(2);
// Set gyro full range to 2000 dps. We first read in the current register
// value so we can change what we need and leave everything else alone.
// See DS p. 12.
txbuf[0] = mpu6000::GYRO_CONFIG | (1<<7);
exchange(2);
chThdSleepMicroseconds(0); // TODO(yoos): Without this, the GYRO_CONFIG register does not get set. This was not the case in the old C firmware. Why?
txbuf[0] = mpu6000::GYRO_CONFIG;
txbuf[1] = (rxbuf[1] & ~0x18) | 0x18;
exchange(2);
// Set accelerometer full range to 4 g. See DS p. 13.
txbuf[0] = mpu6000::ACCEL_CONFIG | (1<<7);
exchange(2);
txbuf[0] = mpu6000::ACCEL_CONFIG;
txbuf[1] = (rxbuf[1] & ~0x18) | 0x08;
exchange(2);
// Read once to clear out bad data?
readGyro();
readAccel();
}
gyroscope_reading_t MPU6000::readGyro() {
gyroscope_reading_t reading;
// Poll gyro
txbuf[0] = mpu6000::GYRO_XOUT_H | (1<<7);
exchange(7);
// TODO(yoos): correct for thermal bias.
reading.axes[0] = -((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 16.384 * 3.1415926535 / 180.0 + unit_config::GYR_X_OFFSET;
reading.axes[1] = -((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 16.384 * 3.1415926535 / 180.0 + unit_config::GYR_Y_OFFSET;
reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 16.384 * 3.1415926535 / 180.0 + unit_config::GYR_Z_OFFSET;
// Poll temp
txbuf[0] = mpu6000::TEMP_OUT_H | (1<<7);
exchange(3);
float temp = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 340 + 36.53;
// DEBUG
//char dbg_buf[16];
//for (int i=0; i<16; i++) {
// dbg_buf[i] = 0;
//}
//chsnprintf(dbg_buf, 12, "%0.6f\r\n", reading.axes[2]);
//chnWriteTimeout((BaseChannel*)&SD3, (uint8_t*)dbg_buf, 12, MS2ST(20));
return reading;
}
accelerometer_reading_t MPU6000::readAccel() {
accelerometer_reading_t reading;
// Get data
txbuf[0] = mpu6000::ACCEL_XOUT_H | (1<<7);
exchange(7);
reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 8192.0 + unit_config::ACC_X_OFFSET;
reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 8192.0 + unit_config::ACC_Y_OFFSET;
reading.axes[2] = -((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 8192.0 + unit_config::ACC_Z_OFFSET;
return reading;
}
<|endoftext|> |
<commit_before><commit_msg>glsl: Move the definition of precision_qualifier_allowed<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "nan.h"
#include "steam/steam_api.h"
#include "steam/steamencryptedappticket.h"
#include "v8.h"
#include "greenworks_async_workers.h"
#include "steam_api_registry.h"
#include "steam_id.h"
namespace greenworks {
namespace api {
namespace {
NAN_METHOD(GetAuthSessionTicket) {
Nan::HandleScope scope;
if (info.Length() < 1 || !info[0]->IsFunction()) {
THROW_BAD_ARGS("Bad arguments");
}
Nan::Callback* success_callback =
new Nan::Callback(info[0].As<v8::Function>());
Nan::Callback* error_callback = NULL;
if (info.Length() > 1 && info[1]->IsFunction())
error_callback = new Nan::Callback(info[1].As<v8::Function>());
Nan::AsyncQueueWorker(new greenworks::GetAuthSessionTicketWorker(
success_callback, error_callback));
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(CancelAuthTicket) {
Nan::HandleScope scope;
if (info.Length() < 1 || !info[0]->IsNumber()) {
THROW_BAD_ARGS("Bad arguments");
}
HAuthTicket h = info[1].As<v8::Number>()->Int32Value();
SteamUser()->CancelAuthTicket(h);
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(GetEncryptedAppTicket) {
Nan::HandleScope scope;
if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
THROW_BAD_ARGS("Bad arguments");
}
char* user_data = *(static_cast<v8::String::Utf8Value>(info[0]->ToString()));
if (!user_data) {
THROW_BAD_ARGS("Bad arguments");
}
Nan::Callback* success_callback =
new Nan::Callback(info[1].As<v8::Function>());
Nan::Callback* error_callback = NULL;
if (info.Length() > 2 && info[2]->IsFunction())
error_callback = new Nan::Callback(info[2].As<v8::Function>());
Nan::AsyncQueueWorker(new greenworks::RequestEncryptedAppTicketWorker(
user_data, success_callback, error_callback));
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(DecryptAppTicket) {
Nan::HandleScope scope;
if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
!node::Buffer::HasInstance(info[1])) {
THROW_BAD_ARGS("Bad arguments");
}
char* encrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t encrypted_ticket_buf_size = node::Buffer::Length(info[0]);
char* key_buf = node::Buffer::Data(info[1]);
if (node::Buffer::Length(info[1]) !=
k_nSteamEncryptedAppTicketSymmetricKeyLen) {
THROW_BAD_ARGS("The key length is not matched");
}
uint8 key[k_nSteamEncryptedAppTicketSymmetricKeyLen];
memcpy(key, key_buf, k_nSteamEncryptedAppTicketSymmetricKeyLen);
uint8 decrypted_ticket[1024];
uint32 decrypted_ticket_size = 1024;
bool is_success = SteamEncryptedAppTicket_BDecryptTicket(
reinterpret_cast<const uint8*>(encrypted_ticket_buf),
encrypted_ticket_buf_size, decrypted_ticket, &decrypted_ticket_size, key,
k_nSteamEncryptedAppTicketSymmetricKeyLen);
if (!is_success) {
info.GetReturnValue().Set(Nan::Undefined());
return;
}
info.GetReturnValue().Set(
Nan::CopyBuffer(reinterpret_cast<const char *>(decrypted_ticket),
decrypted_ticket_size)
.ToLocalChecked());
}
NAN_METHOD(IsTicketForApp) {
Nan::HandleScope scope;
if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
info[1]->IsUint32()) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
uint32 app_id = info[1]->Uint32Value();
bool result = SteamEncryptedAppTicket_BIsTicketForApp(
reinterpret_cast<uint8*>(decrypted_ticket_buf), decrypted_ticket_buf_size,
app_id);
info.GetReturnValue().Set(result);
}
NAN_METHOD(getTicketIssueTime) {
Nan::HandleScope scope;
if (info.Length() < 1 || !node::Buffer::HasInstance(info[0])) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
uint32 time = SteamEncryptedAppTicket_GetTicketIssueTime(
reinterpret_cast<uint8*>(decrypted_ticket_buf),
decrypted_ticket_buf_size);
info.GetReturnValue().Set(time);
}
NAN_METHOD(getTicketSteamId) {
Nan::HandleScope scope;
if (info.Length() < 1 || !node::Buffer::HasInstance(info[0])) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
CSteamID steam_id;
SteamEncryptedAppTicket_GetTicketSteamID(
reinterpret_cast<uint8*>(decrypted_ticket_buf), decrypted_ticket_buf_size,
&steam_id);
info.GetReturnValue().Set(greenworks::SteamID::Create(steam_id));
}
void RegisterAPIs(v8::Handle<v8::Object> target) {
Nan::Set(target,
Nan::New("getAuthSessionTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(GetAuthSessionTicket)->GetFunction());
Nan::Set(target,
Nan::New("getEncryptedAppTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
GetEncryptedAppTicket)->GetFunction());
Nan::Set(target,
Nan::New("decryptAppTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
DecryptAppTicket)->GetFunction());
Nan::Set(target,
Nan::New("isTicketForApp").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
IsTicketForApp)->GetFunction());
Nan::Set(target,
Nan::New("getTicketIssueTime").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
getTicketIssueTime)->GetFunction());
Nan::Set(target,
Nan::New("getTicketSteamId").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
getTicketSteamId)->GetFunction());
Nan::Set(target,
Nan::New("cancelAuthTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(CancelAuthTicket)->GetFunction());
}
SteamAPIRegistry::Add X(RegisterAPIs);
} // namespace
} // namespace api
} // namespace greenworks
<commit_msg>Add getTicketAppId API.<commit_after>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "nan.h"
#include "steam/steam_api.h"
#include "steam/steamencryptedappticket.h"
#include "v8.h"
#include "greenworks_async_workers.h"
#include "steam_api_registry.h"
#include "steam_id.h"
namespace greenworks {
namespace api {
namespace {
NAN_METHOD(GetAuthSessionTicket) {
Nan::HandleScope scope;
if (info.Length() < 1 || !info[0]->IsFunction()) {
THROW_BAD_ARGS("Bad arguments");
}
Nan::Callback* success_callback =
new Nan::Callback(info[0].As<v8::Function>());
Nan::Callback* error_callback = NULL;
if (info.Length() > 1 && info[1]->IsFunction())
error_callback = new Nan::Callback(info[1].As<v8::Function>());
Nan::AsyncQueueWorker(new greenworks::GetAuthSessionTicketWorker(
success_callback, error_callback));
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(CancelAuthTicket) {
Nan::HandleScope scope;
if (info.Length() < 1 || !info[0]->IsNumber()) {
THROW_BAD_ARGS("Bad arguments");
}
HAuthTicket h = info[1].As<v8::Number>()->Int32Value();
SteamUser()->CancelAuthTicket(h);
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(GetEncryptedAppTicket) {
Nan::HandleScope scope;
if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
THROW_BAD_ARGS("Bad arguments");
}
char* user_data = *(static_cast<v8::String::Utf8Value>(info[0]->ToString()));
if (!user_data) {
THROW_BAD_ARGS("Bad arguments");
}
Nan::Callback* success_callback =
new Nan::Callback(info[1].As<v8::Function>());
Nan::Callback* error_callback = NULL;
if (info.Length() > 2 && info[2]->IsFunction())
error_callback = new Nan::Callback(info[2].As<v8::Function>());
Nan::AsyncQueueWorker(new greenworks::RequestEncryptedAppTicketWorker(
user_data, success_callback, error_callback));
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(DecryptAppTicket) {
Nan::HandleScope scope;
if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
!node::Buffer::HasInstance(info[1])) {
THROW_BAD_ARGS("Bad arguments");
}
char* encrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t encrypted_ticket_buf_size = node::Buffer::Length(info[0]);
char* key_buf = node::Buffer::Data(info[1]);
if (node::Buffer::Length(info[1]) !=
k_nSteamEncryptedAppTicketSymmetricKeyLen) {
THROW_BAD_ARGS("The key length is not matched");
}
uint8 key[k_nSteamEncryptedAppTicketSymmetricKeyLen];
memcpy(key, key_buf, k_nSteamEncryptedAppTicketSymmetricKeyLen);
uint8 decrypted_ticket[1024];
uint32 decrypted_ticket_size = 1024;
bool is_success = SteamEncryptedAppTicket_BDecryptTicket(
reinterpret_cast<const uint8*>(encrypted_ticket_buf),
encrypted_ticket_buf_size, decrypted_ticket, &decrypted_ticket_size, key,
k_nSteamEncryptedAppTicketSymmetricKeyLen);
if (!is_success) {
info.GetReturnValue().Set(Nan::Undefined());
return;
}
info.GetReturnValue().Set(
Nan::CopyBuffer(reinterpret_cast<const char *>(decrypted_ticket),
decrypted_ticket_size)
.ToLocalChecked());
}
NAN_METHOD(IsTicketForApp) {
Nan::HandleScope scope;
if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
info[1]->IsUint32()) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
uint32 app_id = info[1]->Uint32Value();
bool result = SteamEncryptedAppTicket_BIsTicketForApp(
reinterpret_cast<uint8*>(decrypted_ticket_buf), decrypted_ticket_buf_size,
app_id);
info.GetReturnValue().Set(result);
}
NAN_METHOD(getTicketIssueTime) {
Nan::HandleScope scope;
if (info.Length() < 1 || !node::Buffer::HasInstance(info[0])) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
uint32 time = SteamEncryptedAppTicket_GetTicketIssueTime(
reinterpret_cast<uint8*>(decrypted_ticket_buf),
decrypted_ticket_buf_size);
info.GetReturnValue().Set(time);
}
NAN_METHOD(getTicketSteamId) {
Nan::HandleScope scope;
if (info.Length() < 1 || !node::Buffer::HasInstance(info[0])) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
CSteamID steam_id;
SteamEncryptedAppTicket_GetTicketSteamID(
reinterpret_cast<uint8*>(decrypted_ticket_buf), decrypted_ticket_buf_size,
&steam_id);
info.GetReturnValue().Set(greenworks::SteamID::Create(steam_id));
}
NAN_METHOD(getTicketAppId) {
Nan::HandleScope scope;
if (info.Length() < 1 || !node::Buffer::HasInstance(info[0])) {
THROW_BAD_ARGS("Bad arguments");
}
char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
uint32 app_id = SteamEncryptedAppTicket_GetTicketAppID(
reinterpret_cast<uint8*>(decrypted_ticket_buf),
decrypted_ticket_buf_size);
info.GetReturnValue().Set(app_id);
}
void RegisterAPIs(v8::Handle<v8::Object> target) {
Nan::Set(target,
Nan::New("getAuthSessionTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(GetAuthSessionTicket)->GetFunction());
Nan::Set(target,
Nan::New("getEncryptedAppTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
GetEncryptedAppTicket)->GetFunction());
Nan::Set(target,
Nan::New("decryptAppTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
DecryptAppTicket)->GetFunction());
Nan::Set(target,
Nan::New("isTicketForApp").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
IsTicketForApp)->GetFunction());
Nan::Set(target,
Nan::New("getTicketIssueTime").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
getTicketIssueTime)->GetFunction());
Nan::Set(target,
Nan::New("getTicketSteamId").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
getTicketSteamId)->GetFunction());
Nan::Set(target,
Nan::New("getTicketAppId").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(
getTicketAppId)->GetFunction());
Nan::Set(target,
Nan::New("cancelAuthTicket").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(CancelAuthTicket)->GetFunction());
}
SteamAPIRegistry::Add X(RegisterAPIs);
} // namespace
} // namespace api
} // namespace greenworks
<|endoftext|> |
<commit_before>///
/// @file main.cpp
/// @brief primesieve console application.
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/ParallelPrimeSieve.hpp>
#include "cmdoptions.hpp"
#include <iostream>
#include <exception>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
using namespace primesieve;
namespace {
void printResults(ParallelPrimeSieve& pps, CmdOptions& opts)
{
cout << left;
const string labels[] =
{
"Primes",
"Twin primes",
"Prime triplets",
"Prime quadruplets",
"Prime quintuplets",
"Prime sextuplets"
};
// largest label size, computed below
int size = 0;
for (int i = 0; i < 6; i++)
{
if (pps.isCount(i))
{
int label_size = (int) labels[i].size();
size = max(size, label_size);
}
}
if (opts.time)
{
int label_size = (int) string("Seconds").size();
size = max(size, label_size);
}
// print results
for (int i = 0; i < 6; i++)
{
if (pps.isCount(i))
cout << setw(size) << labels[i] << " : "
<< pps.getCount(i) << endl;
}
if (opts.time)
cout << setw(size) << "Seconds" << " : "
<< fixed << setprecision(3) << pps.getSeconds()
<< endl;
}
/// Used to count and print primes and prime k-tuplets
void sieve(CmdOptions& opts)
{
ParallelPrimeSieve pps;
deque<uint64_t>& numbers = opts.numbers;
if (opts.flags != 0) pps.setFlags(opts.flags);
if (opts.sieveSize != 0) pps.setSieveSize(opts.sieveSize);
if (opts.threads != 0) pps.setNumThreads(opts.threads);
else if (pps.isPrint()) pps.setNumThreads(1);
if (numbers.size() < 2)
numbers.push_front(0);
pps.setStart(numbers[0]);
pps.setStop(numbers[1]);
if (!opts.quiet)
{
cout << "Sieve size = " << pps.getSieveSize() << " kilobytes" << endl;
cout << "Threads = " << pps.idealNumThreads() << endl;
}
if (opts.status)
pps.addFlags(pps.PRINT_STATUS);
pps.sieve();
printResults(pps, opts);
}
void nthPrime(CmdOptions& opts)
{
ParallelPrimeSieve pps;
deque<uint64_t>& numbers = opts.numbers;
if (opts.flags != 0) pps.setFlags(opts.flags);
if (opts.sieveSize != 0) pps.setSieveSize(opts.sieveSize);
if (opts.threads != 0) pps.setNumThreads(opts.threads);
if (numbers.size() < 2)
numbers.push_back(0);
uint64_t n = numbers[0];
uint64_t start = numbers[1];
uint64_t nthPrime = pps.nthPrime(n, start);
cout << "Nth prime : " << nthPrime << endl;
if (opts.time)
cout << "Seconds : " << fixed << setprecision(3)
<< pps.getSeconds() << endl;
}
} // namespace
int main(int argc, char** argv)
{
CmdOptions opts = parseOptions(argc, argv);
try
{
if (opts.nthPrime)
nthPrime(opts);
else
sieve(opts);
}
catch (exception& e)
{
cerr << "Error: " << e.what() << "." << endl
<< "Try `primesieve --help' for more information." << endl;
return 1;
}
return 0;
}
<commit_msg>Print time before primes<commit_after>///
/// @file main.cpp
/// @brief primesieve console application.
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/ParallelPrimeSieve.hpp>
#include "cmdoptions.hpp"
#include <iostream>
#include <exception>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
using namespace primesieve;
namespace {
void printResults(ParallelPrimeSieve& pps, CmdOptions& opts)
{
cout << left;
const string labels[] =
{
"Primes",
"Twin primes",
"Prime triplets",
"Prime quadruplets",
"Prime quintuplets",
"Prime sextuplets"
};
// largest label size, computed below
int size = 0;
for (int i = 0; i < 6; i++)
{
if (pps.isCount(i))
{
int label_size = (int) labels[i].size();
size = max(size, label_size);
}
}
if (opts.time)
{
int label_size = (int) string("Seconds").size();
size = max(size, label_size);
}
if (opts.time)
cout << setw(size) << "Seconds" << " : "
<< fixed << setprecision(3) << pps.getSeconds()
<< endl;
// print results
for (int i = 0; i < 6; i++)
{
if (pps.isCount(i))
cout << setw(size) << labels[i] << " : "
<< pps.getCount(i) << endl;
}
}
/// Used to count and print primes and prime k-tuplets
void sieve(CmdOptions& opts)
{
ParallelPrimeSieve pps;
deque<uint64_t>& numbers = opts.numbers;
if (opts.flags != 0) pps.setFlags(opts.flags);
if (opts.sieveSize != 0) pps.setSieveSize(opts.sieveSize);
if (opts.threads != 0) pps.setNumThreads(opts.threads);
else if (pps.isPrint()) pps.setNumThreads(1);
if (numbers.size() < 2)
numbers.push_front(0);
pps.setStart(numbers[0]);
pps.setStop(numbers[1]);
if (!opts.quiet)
{
cout << "Sieve size = " << pps.getSieveSize() << " kilobytes" << endl;
cout << "Threads = " << pps.idealNumThreads() << endl;
}
if (opts.status)
pps.addFlags(pps.PRINT_STATUS);
pps.sieve();
printResults(pps, opts);
}
void nthPrime(CmdOptions& opts)
{
ParallelPrimeSieve pps;
deque<uint64_t>& numbers = opts.numbers;
if (opts.flags != 0) pps.setFlags(opts.flags);
if (opts.sieveSize != 0) pps.setSieveSize(opts.sieveSize);
if (opts.threads != 0) pps.setNumThreads(opts.threads);
if (numbers.size() < 2)
numbers.push_back(0);
uint64_t n = numbers[0];
uint64_t start = numbers[1];
uint64_t nthPrime = pps.nthPrime(n, start);
if (opts.time)
cout << "Seconds : " << fixed << setprecision(3)
<< pps.getSeconds() << endl;
cout << "Nth prime : " << nthPrime << endl;
}
} // namespace
int main(int argc, char** argv)
{
CmdOptions opts = parseOptions(argc, argv);
try
{
if (opts.nthPrime)
nthPrime(opts);
else
sieve(opts);
}
catch (exception& e)
{
cerr << "Error: " << e.what() << "." << endl
<< "Try `primesieve --help' for more information." << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-2005 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.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Ali Saidi
*/
#include <string>
#include "arch/alpha/ev5.hh"
#include "arch/alpha/vtophys.hh"
#include "base/chunk_generator.hh"
#include "base/trace.hh"
#include "cpu/thread_context.hh"
#include "mem/vport.hh"
using namespace std;
using namespace AlphaISA;
AlphaISA::PageTableEntry
AlphaISA::kernel_pte_lookup(FunctionalPort *mem, Addr ptbr, AlphaISA::VAddr vaddr)
{
Addr level1_pte = ptbr + vaddr.level1();
AlphaISA::PageTableEntry level1 = mem->read<uint64_t>(level1_pte);
if (!level1.valid()) {
DPRINTF(VtoPhys, "level 1 PTE not valid, va = %#\n", vaddr);
return 0;
}
Addr level2_pte = level1.paddr() + vaddr.level2();
AlphaISA::PageTableEntry level2 = mem->read<uint64_t>(level2_pte);
if (!level2.valid()) {
DPRINTF(VtoPhys, "level 2 PTE not valid, va = %#x\n", vaddr);
return 0;
}
Addr level3_pte = level2.paddr() + vaddr.level3();
AlphaISA::PageTableEntry level3 = mem->read<uint64_t>(level3_pte);
if (!level3.valid()) {
DPRINTF(VtoPhys, "level 3 PTE not valid, va = %#x\n", vaddr);
return 0;
}
return level3;
}
Addr
AlphaISA::vtophys(Addr vaddr)
{
Addr paddr = 0;
if (AlphaISA::IsUSeg(vaddr))
DPRINTF(VtoPhys, "vtophys: invalid vaddr %#x", vaddr);
else if (AlphaISA::IsK0Seg(vaddr))
paddr = AlphaISA::K0Seg2Phys(vaddr);
else
panic("vtophys: ptbr is not set on virtual lookup");
DPRINTF(VtoPhys, "vtophys(%#x) -> %#x\n", vaddr, paddr);
return paddr;
}
Addr
AlphaISA::vtophys(ThreadContext *tc, Addr addr)
{
AlphaISA::VAddr vaddr = addr;
Addr ptbr = tc->readMiscReg(AlphaISA::IPR_PALtemp20);
Addr paddr = 0;
//@todo Andrew couldn't remember why he commented some of this code
//so I put it back in. Perhaps something to do with gdb debugging?
if (AlphaISA::PcPAL(vaddr) && (vaddr < EV5::PalMax)) {
paddr = vaddr & ~ULL(1);
} else {
if (AlphaISA::IsK0Seg(vaddr)) {
paddr = AlphaISA::K0Seg2Phys(vaddr);
} else if (!ptbr) {
paddr = vaddr;
} else {
AlphaISA::PageTableEntry pte =
kernel_pte_lookup(tc->getPhysPort(), ptbr, vaddr);
if (pte.valid())
paddr = pte.paddr() | vaddr.offset();
}
}
DPRINTF(VtoPhys, "vtophys(%#x) -> %#x\n", vaddr, paddr);
return paddr;
}
void
AlphaISA::CopyOut(ThreadContext *tc, void *dest, Addr src, size_t cplen)
{
uint8_t *dst = (uint8_t *)dest;
VirtualPort *vp = tc->getVirtPort(tc);
vp->readBlob(src, dst, cplen);
tc->delVirtPort(vp);
}
void
AlphaISA::CopyIn(ThreadContext *tc, Addr dest, void *source, size_t cplen)
{
uint8_t *src = (uint8_t *)source;
VirtualPort *vp = tc->getVirtPort(tc);
vp->writeBlob(dest, src, cplen);
tc->delVirtPort(vp);
}
void
AlphaISA::CopyStringOut(ThreadContext *tc, char *dst, Addr vaddr, size_t maxlen)
{
int len = 0;
VirtualPort *vp = tc->getVirtPort(tc);
do {
vp->readBlob(vaddr++, (uint8_t*)dst++, 1);
len++;
} while (len < maxlen && dst[len] != 0 );
tc->delVirtPort(vp);
dst[len] = 0;
}
void
AlphaISA::CopyStringIn(ThreadContext *tc, char *src, Addr vaddr)
{
VirtualPort *vp = tc->getVirtPort(tc);
for (ChunkGenerator gen(vaddr, strlen(src), AlphaISA::PageBytes); !gen.done();
gen.next())
{
vp->writeBlob(gen.addr(), (uint8_t*)src, gen.size());
src += gen.size();
}
tc->delVirtPort(vp);
}
<commit_msg>fix a bug in CopyStringOut. dprintk appears to work again.<commit_after>/*
* Copyright (c) 2002-2005 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.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Ali Saidi
*/
#include <string>
#include "arch/alpha/ev5.hh"
#include "arch/alpha/vtophys.hh"
#include "base/chunk_generator.hh"
#include "base/trace.hh"
#include "cpu/thread_context.hh"
#include "mem/vport.hh"
using namespace std;
using namespace AlphaISA;
AlphaISA::PageTableEntry
AlphaISA::kernel_pte_lookup(FunctionalPort *mem, Addr ptbr, AlphaISA::VAddr vaddr)
{
Addr level1_pte = ptbr + vaddr.level1();
AlphaISA::PageTableEntry level1 = mem->read<uint64_t>(level1_pte);
if (!level1.valid()) {
DPRINTF(VtoPhys, "level 1 PTE not valid, va = %#\n", vaddr);
return 0;
}
Addr level2_pte = level1.paddr() + vaddr.level2();
AlphaISA::PageTableEntry level2 = mem->read<uint64_t>(level2_pte);
if (!level2.valid()) {
DPRINTF(VtoPhys, "level 2 PTE not valid, va = %#x\n", vaddr);
return 0;
}
Addr level3_pte = level2.paddr() + vaddr.level3();
AlphaISA::PageTableEntry level3 = mem->read<uint64_t>(level3_pte);
if (!level3.valid()) {
DPRINTF(VtoPhys, "level 3 PTE not valid, va = %#x\n", vaddr);
return 0;
}
return level3;
}
Addr
AlphaISA::vtophys(Addr vaddr)
{
Addr paddr = 0;
if (AlphaISA::IsUSeg(vaddr))
DPRINTF(VtoPhys, "vtophys: invalid vaddr %#x", vaddr);
else if (AlphaISA::IsK0Seg(vaddr))
paddr = AlphaISA::K0Seg2Phys(vaddr);
else
panic("vtophys: ptbr is not set on virtual lookup");
DPRINTF(VtoPhys, "vtophys(%#x) -> %#x\n", vaddr, paddr);
return paddr;
}
Addr
AlphaISA::vtophys(ThreadContext *tc, Addr addr)
{
AlphaISA::VAddr vaddr = addr;
Addr ptbr = tc->readMiscReg(AlphaISA::IPR_PALtemp20);
Addr paddr = 0;
//@todo Andrew couldn't remember why he commented some of this code
//so I put it back in. Perhaps something to do with gdb debugging?
if (AlphaISA::PcPAL(vaddr) && (vaddr < EV5::PalMax)) {
paddr = vaddr & ~ULL(1);
} else {
if (AlphaISA::IsK0Seg(vaddr)) {
paddr = AlphaISA::K0Seg2Phys(vaddr);
} else if (!ptbr) {
paddr = vaddr;
} else {
AlphaISA::PageTableEntry pte =
kernel_pte_lookup(tc->getPhysPort(), ptbr, vaddr);
if (pte.valid())
paddr = pte.paddr() | vaddr.offset();
}
}
DPRINTF(VtoPhys, "vtophys(%#x) -> %#x\n", vaddr, paddr);
return paddr;
}
void
AlphaISA::CopyOut(ThreadContext *tc, void *dest, Addr src, size_t cplen)
{
uint8_t *dst = (uint8_t *)dest;
VirtualPort *vp = tc->getVirtPort(tc);
vp->readBlob(src, dst, cplen);
tc->delVirtPort(vp);
}
void
AlphaISA::CopyIn(ThreadContext *tc, Addr dest, void *source, size_t cplen)
{
uint8_t *src = (uint8_t *)source;
VirtualPort *vp = tc->getVirtPort(tc);
vp->writeBlob(dest, src, cplen);
tc->delVirtPort(vp);
}
void
AlphaISA::CopyStringOut(ThreadContext *tc, char *dst, Addr vaddr, size_t maxlen)
{
int len = 0;
char *start = dst;
VirtualPort *vp = tc->getVirtPort(tc);
do {
vp->readBlob(vaddr++, (uint8_t*)dst++, 1);
} while (len < maxlen && start[len++] != 0 );
tc->delVirtPort(vp);
dst[len] = 0;
}
void
AlphaISA::CopyStringIn(ThreadContext *tc, char *src, Addr vaddr)
{
VirtualPort *vp = tc->getVirtPort(tc);
for (ChunkGenerator gen(vaddr, strlen(src), AlphaISA::PageBytes); !gen.done();
gen.next())
{
vp->writeBlob(gen.addr(), (uint8_t*)src, gen.size());
src += gen.size();
}
tc->delVirtPort(vp);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include "pandora/File.hpp"
#include "pandora/Block.hpp"
#include "pandora/Section.hpp"
#include "pandora/Source.hpp"
#include "pandora/SourceIterator.hpp"
#include "pandora/SourceTreeIterator.hpp"
using namespace std;
using namespace pandora;
class TestSource:public CPPUNIT_NS::TestFixture {
private:
CPPUNIT_TEST_SUITE(TestSource);
CPPUNIT_TEST(testCreateAndRemove);
CPPUNIT_TEST(testIterators);
CPPUNIT_TEST(testFindSources);
CPPUNIT_TEST_SUITE_END ();
File *f1;
public:
void setUp() {
f1 = new File("test_block.h5", FileMode::ReadWrite);
}
void tearDown() {
delete f1;
}
void testCreateAndRemove() {
Block b1 = f1->createBlock("test block","test");
Source s1 = b1.createSource("S1","test");
Source s2 = b1.createSource("S2","test");
stringstream msg;
msg << "Creating s1 or s2 failed!" ;
CPPUNIT_ASSERT_MESSAGE(msg.str(), b1.hasSource(s1.id()) && b1.hasSource(s2.id()) );
size_t count = b1.sourceCount();
stringstream errmsg;
errmsg << "Source count does not match! Found " << count << " should have been 2";
CPPUNIT_ASSERT_MESSAGE(errmsg.str(), count == 2);
b1.removeSource(s1.id());
stringstream msg2;
msg2 << "Removing s1 failed!" ;
CPPUNIT_ASSERT_MESSAGE(msg2.str(), !b1.hasSource(s1.id()));
b1.removeSource(s2.id());
f1->removeBlock(b1.id());
}
void testIterators(){
Block b1 = f1->createBlock("test block","test");
Source s1 = b1.createSource("S1","test");
s1.createSource("S3","test");
s1.createSource("S4","test");
Source s2 = b1.createSource("S2","test");
s2.createSource("S5","test");
size_t count = s1.sourceCount();
CPPUNIT_ASSERT_EQUAL(count,(size_t)2);
count = s2.sourceCount();
CPPUNIT_ASSERT_EQUAL(count,(size_t)1);
b1.removeSource(s1.id());
b1.removeSource(s2.id());
f1->removeBlock(b1.id());
}
void testFindSources(){
Block b1 = f1->createBlock("test block","test");
Source s1 = b1.createSource("S1","test");
Source s2 = b1.createSource("S2","test");
Source s3 = s1.createSource("S3","test");
Source s4 = s1.createSource("S4","test");
Source s5 = s2.createSource("S5","test");
vector<Source> res = s1.findSources([&](const Source &source) {
bool found = source.id() == s4.id();
return found;
});
CPPUNIT_ASSERT_EQUAL(static_cast<vector<Source>::size_type>(1), res.size());
CPPUNIT_ASSERT_EQUAL(s4.id(), res[0].id());
// CPPUNIT_ASSERT_EQUAL(b1.hasSource("invalid_id"),false);
// CPPUNIT_ASSERT_EQUAL(b1.hasSource(s3.id()),true);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"test"),true);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"no test"),false);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"test",1),false);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"test",2),true);
b1.removeSource(s1.id());
b1.removeSource(s2.id());
f1->removeBlock(b1.id());
}
};
<commit_msg>[test] TestSource: add some more checks for findSources<commit_after>#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include "pandora/File.hpp"
#include "pandora/Block.hpp"
#include "pandora/Section.hpp"
#include "pandora/Source.hpp"
#include "pandora/SourceIterator.hpp"
#include "pandora/SourceTreeIterator.hpp"
using namespace std;
using namespace pandora;
class TestSource:public CPPUNIT_NS::TestFixture {
private:
CPPUNIT_TEST_SUITE(TestSource);
CPPUNIT_TEST(testCreateAndRemove);
CPPUNIT_TEST(testIterators);
CPPUNIT_TEST(testFindSources);
CPPUNIT_TEST_SUITE_END ();
File *f1;
public:
void setUp() {
f1 = new File("test_block.h5", FileMode::ReadWrite);
}
void tearDown() {
delete f1;
}
void testCreateAndRemove() {
Block b1 = f1->createBlock("test block","test");
Source s1 = b1.createSource("S1","test");
Source s2 = b1.createSource("S2","test");
stringstream msg;
msg << "Creating s1 or s2 failed!" ;
CPPUNIT_ASSERT_MESSAGE(msg.str(), b1.hasSource(s1.id()) && b1.hasSource(s2.id()) );
size_t count = b1.sourceCount();
stringstream errmsg;
errmsg << "Source count does not match! Found " << count << " should have been 2";
CPPUNIT_ASSERT_MESSAGE(errmsg.str(), count == 2);
b1.removeSource(s1.id());
stringstream msg2;
msg2 << "Removing s1 failed!" ;
CPPUNIT_ASSERT_MESSAGE(msg2.str(), !b1.hasSource(s1.id()));
b1.removeSource(s2.id());
f1->removeBlock(b1.id());
}
void testIterators(){
Block b1 = f1->createBlock("test block","test");
Source s1 = b1.createSource("S1","test");
s1.createSource("S3","test");
s1.createSource("S4","test");
Source s2 = b1.createSource("S2","test");
s2.createSource("S5","test");
size_t count = s1.sourceCount();
CPPUNIT_ASSERT_EQUAL(count,(size_t)2);
count = s2.sourceCount();
CPPUNIT_ASSERT_EQUAL(count,(size_t)1);
b1.removeSource(s1.id());
b1.removeSource(s2.id());
f1->removeBlock(b1.id());
}
void testFindSources(){
Block b1 = f1->createBlock("test block","test");
Source s1 = b1.createSource("S1","test");
Source s2 = b1.createSource("S2","test");
Source s3 = s1.createSource("S3","test");
Source s4 = s1.createSource("S4","test");
Source s5 = s2.createSource("S5","test");
//sanity check
vector<Source> res = s1.findSources([&](const Source &source) {
return false;
});
CPPUNIT_ASSERT_EQUAL(static_cast<vector<Source>::size_type>(0), res.size());
//now some actual work
res = s1.findSources([&](const Source &source) {
bool found = source.id() == s4.id();
return found;
});
CPPUNIT_ASSERT_EQUAL(static_cast<vector<Source>::size_type>(1), res.size());
CPPUNIT_ASSERT_EQUAL(s4.id(), res[0].id());
res = s1.findSources([&](const Source &source) {
return true;
}, true, 1);
CPPUNIT_ASSERT_EQUAL(res.size(), s1.sourceCount());
vector<Source> children = s1.sources();
for (int i = 0; i < res.size(); i++) {
CPPUNIT_ASSERT_EQUAL(res[i].id(), children[i].id());
}
// CPPUNIT_ASSERT_EQUAL(b1.hasSource("invalid_id"),false);
// CPPUNIT_ASSERT_EQUAL(b1.hasSource(s3.id()),true);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"test"),true);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"no test"),false);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"test",1),false);
// CPPUNIT_ASSERT_EQUAL(b1.existsSource(s3.id(),"test",2),true);
b1.removeSource(s1.id());
b1.removeSource(s2.id());
f1->removeBlock(b1.id());
}
};
<|endoftext|> |
<commit_before><commit_msg>More tests<commit_after><|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "variant.hpp"
#include "StringPool.hpp"
#include "VisitorUtils.hpp"
#include "ast/StringChecker.hpp"
#include "ast/SourceFile.hpp"
#include "ast/ASTVisitor.hpp"
using namespace eddic;
class StringCheckerVisitor : public boost::static_visitor<> {
private:
StringPool& pool;
public:
StringCheckerVisitor(StringPool& p) : pool(p) {}
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_STRUCT()
AUTO_RECURSE_CONSTRUCTOR()
AUTO_RECURSE_DESTRUCTOR()
AUTO_RECURSE_FUNCTION_DECLARATION()
AUTO_RECURSE_GLOBAL_DECLARATION()
AUTO_RECURSE_FUNCTION_CALLS()
AUTO_RECURSE_BUILTIN_OPERATORS()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_FOREACH()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
AUTO_RECURSE_COMPOSED_VALUES()
AUTO_RECURSE_RETURN_VALUES()
AUTO_RECURSE_ARRAY_VALUES()
AUTO_RECURSE_VARIABLE_OPERATIONS()
AUTO_RECURSE_TERNARY()
AUTO_RECURSE_SWITCH()
AUTO_RECURSE_SWITCH_CASE()
AUTO_RECURSE_DEFAULT_CASE()
AUTO_RECURSE_NEW()
void operator()(ast::Litteral& litteral){
litteral.label = pool.label(litteral.value);
}
AUTO_IGNORE_OTHERS()
};
void ast::checkStrings(ast::SourceFile& program, StringPool& pool){
StringCheckerVisitor visitor(pool);
visitor(program);
}
<commit_msg>Fix recursion<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "variant.hpp"
#include "StringPool.hpp"
#include "VisitorUtils.hpp"
#include "ast/StringChecker.hpp"
#include "ast/SourceFile.hpp"
#include "ast/ASTVisitor.hpp"
using namespace eddic;
class StringCheckerVisitor : public boost::static_visitor<> {
private:
StringPool& pool;
public:
StringCheckerVisitor(StringPool& p) : pool(p) {}
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_STRUCT()
AUTO_RECURSE_CONSTRUCTOR()
AUTO_RECURSE_DESTRUCTOR()
AUTO_RECURSE_FUNCTION_DECLARATION()
AUTO_RECURSE_GLOBAL_DECLARATION()
AUTO_RECURSE_FUNCTION_CALLS()
AUTO_RECURSE_BUILTIN_OPERATORS()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_FOREACH()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
AUTO_RECURSE_COMPOSED_VALUES()
AUTO_RECURSE_RETURN_VALUES()
AUTO_RECURSE_ARRAY_VALUES()
AUTO_RECURSE_VARIABLE_OPERATIONS()
AUTO_RECURSE_STRUCT_DECLARATION()
AUTO_RECURSE_TERNARY()
AUTO_RECURSE_SWITCH()
AUTO_RECURSE_SWITCH_CASE()
AUTO_RECURSE_DEFAULT_CASE()
AUTO_RECURSE_NEW()
void operator()(ast::Litteral& litteral){
litteral.label = pool.label(litteral.value);
}
AUTO_IGNORE_OTHERS()
};
void ast::checkStrings(ast::SourceFile& program, StringPool& pool){
StringCheckerVisitor visitor(pool);
visitor(program);
}
<|endoftext|> |
<commit_before><commit_msg>Disable test-explorer.cpp<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sysdata.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-11-02 12:43: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
*
************************************************************************/
#ifndef _SV_SYSDATA_HXX
#define _SV_SYSDATA_HXX
#if defined( QUARTZ )
#include <premac.h>
#include <Carbon/Carbon.h>
#include <postmac.h>
#endif
// -----------------
// - SystemEnvData -
// -----------------
struct SystemEnvData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) || defined( OS2 )
HWND hWnd; // the window hwnd
#elif defined( QUARTZ )
WindowRef rWindow; // Window reference
#endif
#if defined( UNX )
void* pDisplay; // the relevant display connection
long aWindow; // the window of the object
void* pSalFrame; // contains a salframe, if object has one
void* pWidget; // the corresponding widget
void* pVisual; // the visual in use
int nDepth; // depth of said visual
long aColormap; // the colormap being used
void* pAppContext; // the application context in use
long aShellWindow; // the window of the frame's shell
void* pShellWidget; // the frame's shell widget
#endif
};
#define SystemChildData SystemEnvData
// --------------------
// - SystemParentData -
// --------------------
struct SystemParentData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) || defined( OS2 )
HWND hWnd; // the window hwnd
#elif defined( QUARTZ )
WindowRef rWindow; // Window reference
#elif defined( UNX )
long aWindow; // the window of the object
bool bXEmbedSupport:1; // decides whether the object in question
// should support the XEmbed protocol
#endif
};
// --------------------
// - SystemMenuData -
// --------------------
struct SystemMenuData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HMENU hMenu; // the menu handle of the menu bar
#elif defined( UNX )
long aMenu; // ???
#endif
};
// --------------------
// - SystemGraphicsData -
// --------------------
struct SystemGraphicsData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HDC hDC; // handle to a device context
#elif defined( QUARTZ )
CGContextRef rCGContext; // QUARTZ graphic context
#elif defined( UNX )
long hDrawable; // a drawable
void* pRenderFormat; // render format for drawable
#endif
};
// --------------------
// - SystemWindowData -
// --------------------
struct SystemWindowData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) // meaningless on Windows
#elif defined( QUARTZ ) // meaningless on Mac OS X / Quartz
#elif defined( UNX )
void* pVisual; // the visual to be used
#endif
};
#endif // _SV_SYSDATA_HXX
<commit_msg>INTEGRATION: CWS macosxquicktime01 (1.4.52); FILE MERGED 2007/10/15 11:11:26 pl 1.4.52.1: #i82621# initial implementation of SalObject for MacOSX aqua<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sysdata.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2007-12-07 11:50:12 $
*
* 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 _SV_SYSDATA_HXX
#define _SV_SYSDATA_HXX
// -----------------
// - SystemEnvData -
// -----------------
struct SystemEnvData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) || defined( OS2 )
HWND hWnd; // the window hwnd
#elif defined( QUARTZ )
NSView* pView; // the cocoa view ptr implementing this object
#endif
#if defined( UNX )
void* pDisplay; // the relevant display connection
long aWindow; // the window of the object
void* pSalFrame; // contains a salframe, if object has one
void* pWidget; // the corresponding widget
void* pVisual; // the visual in use
int nDepth; // depth of said visual
long aColormap; // the colormap being used
void* pAppContext; // the application context in use
long aShellWindow; // the window of the frame's shell
void* pShellWidget; // the frame's shell widget
#endif
};
#define SystemChildData SystemEnvData
// --------------------
// - SystemParentData -
// --------------------
struct SystemParentData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) || defined( OS2 )
HWND hWnd; // the window hwnd
#elif defined( QUARTZ )
NSView* pView; // the cocoa view ptr implementing this object
#elif defined( UNX )
long aWindow; // the window of the object
bool bXEmbedSupport:1; // decides whether the object in question
// should support the XEmbed protocol
#endif
};
// --------------------
// - SystemMenuData -
// --------------------
struct SystemMenuData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HMENU hMenu; // the menu handle of the menu bar
#elif defined( UNX )
long aMenu; // ???
#endif
};
// --------------------
// - SystemGraphicsData -
// --------------------
struct SystemGraphicsData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HDC hDC; // handle to a device context
#elif defined( QUARTZ )
CGContextRef rCGContext; // QUARTZ graphic context
#elif defined( UNX )
long hDrawable; // a drawable
void* pRenderFormat; // render format for drawable
#endif
};
// --------------------
// - SystemWindowData -
// --------------------
struct SystemWindowData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) // meaningless on Windows
#elif defined( QUARTZ ) // meaningless on Mac OS X / Quartz
#elif defined( UNX )
void* pVisual; // the visual to be used
#endif
};
#endif // _SV_SYSDATA_HXX
<|endoftext|> |
<commit_before>#include "acmacs-base/virus-name.hh"
#include "acmacs-base/range.hh"
#include "acmacs-draw/surface-cairo.hh"
#include "acmacs-draw/geographic-map.hh"
#include "geographic-map.hh"
// ----------------------------------------------------------------------
void GeographicMapPoints::draw(Surface& aSurface) const
{
for (const auto& point: *this) {
point.draw(aSurface);
}
} // GeographicMapPoints::draw
// ----------------------------------------------------------------------
GeographicMapDraw::~GeographicMapDraw()
{
} // GeographicMapDraw::~GeographicMapDraw
// ----------------------------------------------------------------------
void GeographicMapDraw::prepare(Surface&)
{
} // GeographicMapDraw::prepare
// ----------------------------------------------------------------------
void GeographicMapDraw::draw(Surface& aOutlineSurface, Surface& aPointSurface) const
{
geographic_map_draw(aOutlineSurface, mOutline, mOutlineWidth);
mPoints.draw(aPointSurface);
mTitle.draw(aOutlineSurface);
} // GeographicMapDraw::draw
// ----------------------------------------------------------------------
void GeographicMapDraw::draw(std::string aFilename, double aImageWidth)
{
const acmacs::Size size = geographic_map_size();
PdfCairo outline_surface(aFilename, aImageWidth, aImageWidth / size.width * size.height, size.width);
auto& point_surface = outline_surface.subsurface(outline_surface.viewport().origin, Scaled{outline_surface.viewport().size.width}, geographic_map_viewport(), false);
prepare(point_surface);
draw(outline_surface, point_surface);
} // GeographicMapDraw::draw
// ----------------------------------------------------------------------
void GeographicMapDraw::add_point(long aPriority, double aLat, double aLong, Color aFill, Pixels aSize, Color aOutline, Pixels aOutlineWidth)
{
mPoints.emplace_back(LongLat{aLong, -aLat}, aPriority);
auto& style = mPoints.back();
style.shape = acmacs::PointShape::Circle;
style.fill = aFill;
style.outline = aOutline;
style.outline_width = aOutlineWidth;
style.size = aSize;
} // GeographicMapDraw::add_point
// ----------------------------------------------------------------------
GeographicMapColoring::~GeographicMapColoring()
{
}
// ----------------------------------------------------------------------
ColorOverride::TagColor ColoringByClade::color(const hidb::Antigen& aAntigen) const
{
ColoringData result("grey50");
std::string tag{"UNKNOWN"};
try {
const auto* entry_seq = seqdb::get(report_time::Yes).find_hi_name(aAntigen.full_name());
if (entry_seq) {
for (const auto& clade: entry_seq->seq().clades()) {
try {
result = mColors.at(clade); // find first clade that has corresponding entry in mColors and use it
tag = clade;
break;
}
catch (...) {
}
}
}
}
catch (std::exception& err) {
std::cerr << "ERROR: ColoringByClade " << aAntigen.full_name() << ": " << err.what() << '\n';
}
catch (...) {
}
// std::cerr << "INFO: ColoringByClade " << aAntigen.full_name() << ": " << tag << '\n';
return {tag, result};
} // ColoringByClade::color
// ----------------------------------------------------------------------
void GeographicMapWithPointsFromHidb::prepare(Surface& aSurface)
{
GeographicMapDraw::prepare(aSurface);
const double point_scaled = aSurface.convert(mPointSize).value();
for (const auto& location_color: mPointsAtLocation) {
try {
const auto location = get_locdb().find(location_color.first);
const double center_lat = location.latitude(), center_long = location.longitude();
auto iter = location_color.second.iterator();
auto [coloring_data, priority] = *iter;
add_point(priority, center_lat, center_long, coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width);
++iter;
for (size_t circle_no = 1; iter; ++circle_no) {
const double distance = point_scaled * mDensity * circle_no;
const size_t circle_capacity = static_cast<size_t>(M_PI * 2.0 * distance * circle_no / (point_scaled * mDensity));
const size_t points_on_circle = std::min(circle_capacity, iter.left());
const double step = 2.0 * M_PI / points_on_circle;
for (auto index: acmacs::incrementer(0UL, points_on_circle)) {
std::tie(coloring_data, priority) = *iter;
add_point(priority, center_lat + distance * std::cos(index * step), center_long + distance * std::sin(index * step), coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width);
++iter;
}
}
}
catch (LocationNotFound&) {
}
}
sort_points();
} // GeographicMapWithPointsFromHidb::prepare
// ----------------------------------------------------------------------
void GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by(const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, const std::vector<std::string>& aPriority, std::string aStartDate, std::string aEndDate)
{
// std::cerr << "add_points_from_hidb_colored_by" << '\n';
const auto& hidb = hidb::get(mVirusType);
auto antigens = hidb.antigens()->date_range(aStartDate, aEndDate);
std::cerr << "INFO: dates: " << aStartDate << ".." << aEndDate << " antigens: " << antigens.size() << std::endl;
if (!aPriority.empty())
std::cerr << "INFO: priority: " << aPriority << " (the last in this list to be drawn on top of others)\n";
for (auto antigen: antigens) {
auto [tag, coloring_data] = aColorOverride.color(*antigen);
if (coloring_data.fill.empty())
std::tie(tag, coloring_data) = aColoring.color(*antigen);
try {
auto location = virus_name::location(antigen->name());
if (location == "GEORGIA" && hidb.tables()->most_recent(antigen->tables())->lab() == "CDC")
location = "GEORGIA STATE"; // somehow disambiguate
const auto found = std::find(std::begin(aPriority), std::end(aPriority), tag);
mPointsAtLocation.add(location, found == std::end(aPriority) ? 0 : (found - std::begin(aPriority) + 1), coloring_data);
}
catch (virus_name::Unrecognized&) {
}
}
// std::transform(mPoints.begin(), mPoints.end(), std::ostream_iterator<std::string>(std::cerr, "\n"), [](const auto& e) -> std::string { return e.first; });
} // GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by
// ----------------------------------------------------------------------
GeographicTimeSeriesBase::~GeographicTimeSeriesBase()
{
} // GeographicTimeSeriesBase::~GeographicTimeSeriesBase
// ----------------------------------------------------------------------
void GeographicTimeSeriesBase::draw(std::string aFilenamePrefix, TimeSeriesIterator& aBegin, const TimeSeriesIterator& aEnd, const std::vector<std::string>& aPriority, const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, double aImageWidth) const
{
for (; aBegin != aEnd; ++aBegin) {
auto map = mMap; // make a copy!
map.add_points_from_hidb_colored_by(aColoring, aColorOverride, aPriority, *aBegin, aBegin.next());
map.title().add_line(aBegin.text_name());
map.draw(aFilenamePrefix + aBegin.numeric_name() + ".pdf", aImageWidth);
}
} // GeographicTimeSeriesBase::draw
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs:incrementer renamed to acmacs::range<commit_after>#include "acmacs-base/virus-name.hh"
#include "acmacs-base/range.hh"
#include "acmacs-draw/surface-cairo.hh"
#include "acmacs-draw/geographic-map.hh"
#include "geographic-map.hh"
// ----------------------------------------------------------------------
void GeographicMapPoints::draw(Surface& aSurface) const
{
for (const auto& point: *this) {
point.draw(aSurface);
}
} // GeographicMapPoints::draw
// ----------------------------------------------------------------------
GeographicMapDraw::~GeographicMapDraw()
{
} // GeographicMapDraw::~GeographicMapDraw
// ----------------------------------------------------------------------
void GeographicMapDraw::prepare(Surface&)
{
} // GeographicMapDraw::prepare
// ----------------------------------------------------------------------
void GeographicMapDraw::draw(Surface& aOutlineSurface, Surface& aPointSurface) const
{
geographic_map_draw(aOutlineSurface, mOutline, mOutlineWidth);
mPoints.draw(aPointSurface);
mTitle.draw(aOutlineSurface);
} // GeographicMapDraw::draw
// ----------------------------------------------------------------------
void GeographicMapDraw::draw(std::string aFilename, double aImageWidth)
{
const acmacs::Size size = geographic_map_size();
PdfCairo outline_surface(aFilename, aImageWidth, aImageWidth / size.width * size.height, size.width);
auto& point_surface = outline_surface.subsurface(outline_surface.viewport().origin, Scaled{outline_surface.viewport().size.width}, geographic_map_viewport(), false);
prepare(point_surface);
draw(outline_surface, point_surface);
} // GeographicMapDraw::draw
// ----------------------------------------------------------------------
void GeographicMapDraw::add_point(long aPriority, double aLat, double aLong, Color aFill, Pixels aSize, Color aOutline, Pixels aOutlineWidth)
{
mPoints.emplace_back(LongLat{aLong, -aLat}, aPriority);
auto& style = mPoints.back();
style.shape = acmacs::PointShape::Circle;
style.fill = aFill;
style.outline = aOutline;
style.outline_width = aOutlineWidth;
style.size = aSize;
} // GeographicMapDraw::add_point
// ----------------------------------------------------------------------
GeographicMapColoring::~GeographicMapColoring()
{
}
// ----------------------------------------------------------------------
ColorOverride::TagColor ColoringByClade::color(const hidb::Antigen& aAntigen) const
{
ColoringData result("grey50");
std::string tag{"UNKNOWN"};
try {
const auto* entry_seq = seqdb::get(report_time::Yes).find_hi_name(aAntigen.full_name());
if (entry_seq) {
for (const auto& clade: entry_seq->seq().clades()) {
try {
result = mColors.at(clade); // find first clade that has corresponding entry in mColors and use it
tag = clade;
break;
}
catch (...) {
}
}
}
}
catch (std::exception& err) {
std::cerr << "ERROR: ColoringByClade " << aAntigen.full_name() << ": " << err.what() << '\n';
}
catch (...) {
}
// std::cerr << "INFO: ColoringByClade " << aAntigen.full_name() << ": " << tag << '\n';
return {tag, result};
} // ColoringByClade::color
// ----------------------------------------------------------------------
void GeographicMapWithPointsFromHidb::prepare(Surface& aSurface)
{
GeographicMapDraw::prepare(aSurface);
const double point_scaled = aSurface.convert(mPointSize).value();
for (const auto& location_color: mPointsAtLocation) {
try {
const auto location = get_locdb().find(location_color.first);
const double center_lat = location.latitude(), center_long = location.longitude();
auto iter = location_color.second.iterator();
auto [coloring_data, priority] = *iter;
add_point(priority, center_lat, center_long, coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width);
++iter;
for (size_t circle_no = 1; iter; ++circle_no) {
const double distance = point_scaled * mDensity * circle_no;
const size_t circle_capacity = static_cast<size_t>(M_PI * 2.0 * distance * circle_no / (point_scaled * mDensity));
const size_t points_on_circle = std::min(circle_capacity, iter.left());
const double step = 2.0 * M_PI / points_on_circle;
for (auto index: acmacs::range(0UL, points_on_circle)) {
std::tie(coloring_data, priority) = *iter;
add_point(priority, center_lat + distance * std::cos(index * step), center_long + distance * std::sin(index * step), coloring_data.fill, mPointSize, coloring_data.outline, coloring_data.outline_width);
++iter;
}
}
}
catch (LocationNotFound&) {
}
}
sort_points();
} // GeographicMapWithPointsFromHidb::prepare
// ----------------------------------------------------------------------
void GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by(const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, const std::vector<std::string>& aPriority, std::string aStartDate, std::string aEndDate)
{
// std::cerr << "add_points_from_hidb_colored_by" << '\n';
const auto& hidb = hidb::get(mVirusType);
auto antigens = hidb.antigens()->date_range(aStartDate, aEndDate);
std::cerr << "INFO: dates: " << aStartDate << ".." << aEndDate << " antigens: " << antigens.size() << std::endl;
if (!aPriority.empty())
std::cerr << "INFO: priority: " << aPriority << " (the last in this list to be drawn on top of others)\n";
for (auto antigen: antigens) {
auto [tag, coloring_data] = aColorOverride.color(*antigen);
if (coloring_data.fill.empty())
std::tie(tag, coloring_data) = aColoring.color(*antigen);
try {
auto location = virus_name::location(antigen->name());
if (location == "GEORGIA" && hidb.tables()->most_recent(antigen->tables())->lab() == "CDC")
location = "GEORGIA STATE"; // somehow disambiguate
const auto found = std::find(std::begin(aPriority), std::end(aPriority), tag);
mPointsAtLocation.add(location, found == std::end(aPriority) ? 0 : (found - std::begin(aPriority) + 1), coloring_data);
}
catch (virus_name::Unrecognized&) {
}
}
// std::transform(mPoints.begin(), mPoints.end(), std::ostream_iterator<std::string>(std::cerr, "\n"), [](const auto& e) -> std::string { return e.first; });
} // GeographicMapWithPointsFromHidb::add_points_from_hidb_colored_by
// ----------------------------------------------------------------------
GeographicTimeSeriesBase::~GeographicTimeSeriesBase()
{
} // GeographicTimeSeriesBase::~GeographicTimeSeriesBase
// ----------------------------------------------------------------------
void GeographicTimeSeriesBase::draw(std::string aFilenamePrefix, TimeSeriesIterator& aBegin, const TimeSeriesIterator& aEnd, const std::vector<std::string>& aPriority, const GeographicMapColoring& aColoring, const ColorOverride& aColorOverride, double aImageWidth) const
{
for (; aBegin != aEnd; ++aBegin) {
auto map = mMap; // make a copy!
map.add_points_from_hidb_colored_by(aColoring, aColorOverride, aPriority, *aBegin, aBegin.next());
map.title().add_line(aBegin.text_name());
map.draw(aFilenamePrefix + aBegin.numeric_name() + ".pdf", aImageWidth);
}
} // GeographicTimeSeriesBase::draw
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "bananagrams.hpp"
using std::cerr;
using std::endl;
using std::string;
Typer::Typer()
{
ch = 'A' - 1;
}
bool Typer::get_ch(char* chr)
{
if (ch >= 'A' && ch <= 'Z')
{
*chr = ch;
ch = 'A' - 1;
return true;
}
return false;
}
bool Typer::process_event(sf::Event& event)
{
if (event.type == sf::Event::KeyPressed && event.key.code >= sf::Keyboard::Key::A && event.key.code <= sf::Keyboard::Key::Z)
ch = event.key.code - sf::Keyboard::Key::A + 'A';
return true;
}
MouseControls::MouseControls(State* m)
{
state = m;
}
bool MouseControls::process_event(sf::Event& event)
{
switch(event.type)
{
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Left)
state->start_selection = true;
else if (event.mouseButton.button == sf::Mouse::Right)
state->mremove = true;
break;
case sf::Event::MouseButtonReleased:
state->update = true;
if (event.mouseButton.button == sf::Mouse::Left)
state->end_selection = true;
else if (event.mouseButton.button == sf::Mouse::Right)
state->mremove = false;
break;
case sf::Event::MouseMoved:
{
state->update = true;
state->pos[0] = event.mouseMove.x;
state->pos[1] = event.mouseMove.y;
}
break;
case sf::Event::MouseWheelMoved:
state->wheel_delta = event.mouseWheel.delta;
break;
default:
break;
}
return true;
}
KeyControls::Command::Command(repeat_t rep)
{
pressed = false;
ready = true;
repeat = rep;
}
KeyControls::KeyControls()
{
set_defaults();
}
void KeyControls::bind(const sf::Event::KeyEvent& key, const string& command, repeat_t rep)
{
binds[key] = command;
commands[command] = Command(rep);
}
void KeyControls::rebind(const sf::Event::KeyEvent& key, const string& command)
{
if (!has_bind(command))
throw NotFound(command);
binds[key] = command;
commands[command].pressed = false;
commands[command].ready = true;
}
void KeyControls::set_defaults()
{
// TODO is there a better way to structure these?
binds.clear();
commands.clear();
sf::Event::KeyEvent key;
key.alt = false;
key.control = false;
key.shift = false;
key.system = false;
key.code = sf::Keyboard::Key::Left;
bind(key, "left", REPEAT);
key.code = sf::Keyboard::Right;
bind(key, "right", REPEAT);
key.code = sf::Keyboard::Up;
bind(key, "up", REPEAT);
key.code = sf::Keyboard::Down;
bind(key, "down", REPEAT);
key.shift = true;
key.code = sf::Keyboard::Left;
bind(key, "left_fast", REPEAT);
key.code = sf::Keyboard::Right;
bind(key, "right_fast", REPEAT);
key.code = sf::Keyboard::Up;
bind(key, "up_fast", REPEAT);
key.code = sf::Keyboard::Down;
bind(key, "down_fast", REPEAT);
key.control = true;
key.shift = false;
key.code = sf::Keyboard::Key::Up;
bind(key, "zoom_in", HOLD);
key.code = sf::Keyboard::Key::Down;
bind(key, "zoom_out", HOLD);
key.shift = true;
key.code = sf::Keyboard::Key::Up;
bind(key, "zoom_in_fast", HOLD);
key.code = sf::Keyboard::Key::Down;
bind(key, "zoom_out_fast", HOLD);
key.control = false;
key.shift = false;
key.code = sf::Keyboard::BackSpace;
bind(key, "remove", REPEAT);
key.code = sf::Keyboard::Space;
bind(key, "peel", PRESS);
key.control = true;
key.code = sf::Keyboard::C;
bind(key, "center", PRESS);
key.code = sf::Keyboard::D;
bind(key, "dump", PRESS);
key.code = sf::Keyboard::X;
bind(key, "cut", PRESS);
key.code = sf::Keyboard::V;
bind(key, "paste", PRESS);
key.code = sf::Keyboard::F;
bind(key, "flip", PRESS);
key.control = false;
key.code = sf::Keyboard::LControl;
bind(key, "quick_place", HOLD);
}
bool KeyControls::load_from_file(const string& filename)
{
bool bad = false;
YAML::Node bindings;
try
{
bindings = YAML::LoadFile(filename);
}
catch (YAML::BadFile)
{
bad = true;
}
if (bad || !bindings.IsMap())
{
cerr << "Ignoring bad/missing config file\n";
return false;
}
for (auto binding : bindings)
{
try
{
rebind(binding.second.as<sf::Event::KeyEvent>(), binding.first.as<string>());
}
catch (NotFound)
{
cerr << "Unrecognized command: " << binding.first.as<string>() << endl;
}
catch (YAML::TypedBadConversion<sf::Event::KeyEvent>)
{
// YAML conversion already prints errors
}
}
return true;
}
bool KeyControls::operator[](const string& command)
{
Command& c = commands[command];
bool press = c.pressed;
if (c.get_repeat() != HOLD)
c.pressed = false;
return press;
}
bool KeyControls::process_event(sf::Event& event)
{
if (event.type == sf::Event::KeyPressed)
{
// TODO this doesn't work if you release modifier keys in different orders
auto it = binds.find(event.key);
if (it != binds.end())
{
Command& c = commands[it->second];
switch (c.get_repeat())
{
case PRESS:
if (c.ready)
{
c.pressed = true;
c.ready = false;
}
break;
case REPEAT:
case HOLD:
c.pressed = true;
break;
}
// don't continue bound keypresses
return false;
}
}
else if (event.type == sf::Event::KeyReleased)
{
switch (event.key.code)
{
case sf::Keyboard::Key::LAlt:
case sf::Keyboard::Key::RAlt:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.alt || pair.first.code == sf::Keyboard::Key::LAlt || pair.first.code == sf::Keyboard::Key::RAlt))
commands[pair.second].pressed = false;
break;
case sf::Keyboard::Key::LControl:
case sf::Keyboard::Key::RControl:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.control || pair.first.code == sf::Keyboard::Key::LControl || pair.first.code == sf::Keyboard::Key::RControl))
commands[pair.second].pressed = false;
break;
case sf::Keyboard::Key::LShift:
case sf::Keyboard::Key::RShift:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.shift || pair.first.code == sf::Keyboard::Key::LShift || pair.first.code == sf::Keyboard::Key::RShift))
commands[pair.second].pressed = false;
break;
case sf::Keyboard::Key::LSystem:
case sf::Keyboard::Key::RSystem:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.system || pair.first.code == sf::Keyboard::Key::LSystem || pair.first.code == sf::Keyboard::Key::RSystem))
commands[pair.second].pressed = false;
break;
default:
break;
}
auto it = binds.find(event.key);
if (it != binds.end())
{
Command& c = commands[it->second];
switch (c.get_repeat())
{
case PRESS:
c.ready = true;
break;
case REPEAT:
break;
case HOLD:
c.pressed = false;
break;
}
}
}
return true;
}
<commit_msg>Soft error for blank bindings in config<commit_after>#include "bananagrams.hpp"
using std::cerr;
using std::endl;
using std::string;
Typer::Typer()
{
ch = 'A' - 1;
}
bool Typer::get_ch(char* chr)
{
if (ch >= 'A' && ch <= 'Z')
{
*chr = ch;
ch = 'A' - 1;
return true;
}
return false;
}
bool Typer::process_event(sf::Event& event)
{
if (event.type == sf::Event::KeyPressed && event.key.code >= sf::Keyboard::Key::A && event.key.code <= sf::Keyboard::Key::Z)
ch = event.key.code - sf::Keyboard::Key::A + 'A';
return true;
}
MouseControls::MouseControls(State* m)
{
state = m;
}
bool MouseControls::process_event(sf::Event& event)
{
switch(event.type)
{
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Left)
state->start_selection = true;
else if (event.mouseButton.button == sf::Mouse::Right)
state->mremove = true;
break;
case sf::Event::MouseButtonReleased:
state->update = true;
if (event.mouseButton.button == sf::Mouse::Left)
state->end_selection = true;
else if (event.mouseButton.button == sf::Mouse::Right)
state->mremove = false;
break;
case sf::Event::MouseMoved:
{
state->update = true;
state->pos[0] = event.mouseMove.x;
state->pos[1] = event.mouseMove.y;
}
break;
case sf::Event::MouseWheelMoved:
state->wheel_delta = event.mouseWheel.delta;
break;
default:
break;
}
return true;
}
KeyControls::Command::Command(repeat_t rep)
{
pressed = false;
ready = true;
repeat = rep;
}
KeyControls::KeyControls()
{
set_defaults();
}
void KeyControls::bind(const sf::Event::KeyEvent& key, const string& command, repeat_t rep)
{
binds[key] = command;
commands[command] = Command(rep);
}
void KeyControls::rebind(const sf::Event::KeyEvent& key, const string& command)
{
if (!has_bind(command))
throw NotFound(command);
binds[key] = command;
commands[command].pressed = false;
commands[command].ready = true;
}
void KeyControls::set_defaults()
{
// TODO is there a better way to structure these?
binds.clear();
commands.clear();
sf::Event::KeyEvent key;
key.alt = false;
key.control = false;
key.shift = false;
key.system = false;
key.code = sf::Keyboard::Key::Left;
bind(key, "left", REPEAT);
key.code = sf::Keyboard::Right;
bind(key, "right", REPEAT);
key.code = sf::Keyboard::Up;
bind(key, "up", REPEAT);
key.code = sf::Keyboard::Down;
bind(key, "down", REPEAT);
key.shift = true;
key.code = sf::Keyboard::Left;
bind(key, "left_fast", REPEAT);
key.code = sf::Keyboard::Right;
bind(key, "right_fast", REPEAT);
key.code = sf::Keyboard::Up;
bind(key, "up_fast", REPEAT);
key.code = sf::Keyboard::Down;
bind(key, "down_fast", REPEAT);
key.control = true;
key.shift = false;
key.code = sf::Keyboard::Key::Up;
bind(key, "zoom_in", HOLD);
key.code = sf::Keyboard::Key::Down;
bind(key, "zoom_out", HOLD);
key.shift = true;
key.code = sf::Keyboard::Key::Up;
bind(key, "zoom_in_fast", HOLD);
key.code = sf::Keyboard::Key::Down;
bind(key, "zoom_out_fast", HOLD);
key.control = false;
key.shift = false;
key.code = sf::Keyboard::BackSpace;
bind(key, "remove", REPEAT);
key.code = sf::Keyboard::Space;
bind(key, "peel", PRESS);
key.control = true;
key.code = sf::Keyboard::C;
bind(key, "center", PRESS);
key.code = sf::Keyboard::D;
bind(key, "dump", PRESS);
key.code = sf::Keyboard::X;
bind(key, "cut", PRESS);
key.code = sf::Keyboard::V;
bind(key, "paste", PRESS);
key.code = sf::Keyboard::F;
bind(key, "flip", PRESS);
key.control = false;
key.code = sf::Keyboard::LControl;
bind(key, "quick_place", HOLD);
}
bool KeyControls::load_from_file(const string& filename)
{
bool bad = false;
YAML::Node bindings;
try
{
bindings = YAML::LoadFile(filename);
}
catch (YAML::BadFile)
{
bad = true;
}
if (bad || !bindings.IsMap())
{
cerr << "Ignoring bad/missing config file\n";
return false;
}
for (auto binding : bindings)
{
try
{
rebind(binding.second.as<sf::Event::KeyEvent>(), binding.first.as<string>());
}
catch (NotFound)
{
cerr << "Unrecognized command: " << binding.first.as<string>() << endl;
}
catch (YAML::TypedBadConversion<sf::Event::KeyEvent>)
{
// YAML conversion already prints errors
}
catch (YAML::TypedBadConversion<std::string>)
{
cerr << "Empty binding: " << binding.first.as<string>() << endl;
}
}
return true;
}
bool KeyControls::operator[](const string& command)
{
Command& c = commands[command];
bool press = c.pressed;
if (c.get_repeat() != HOLD)
c.pressed = false;
return press;
}
bool KeyControls::process_event(sf::Event& event)
{
if (event.type == sf::Event::KeyPressed)
{
// TODO this doesn't work if you release modifier keys in different orders
auto it = binds.find(event.key);
if (it != binds.end())
{
Command& c = commands[it->second];
switch (c.get_repeat())
{
case PRESS:
if (c.ready)
{
c.pressed = true;
c.ready = false;
}
break;
case REPEAT:
case HOLD:
c.pressed = true;
break;
}
// don't continue bound keypresses
return false;
}
}
else if (event.type == sf::Event::KeyReleased)
{
switch (event.key.code)
{
case sf::Keyboard::Key::LAlt:
case sf::Keyboard::Key::RAlt:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.alt || pair.first.code == sf::Keyboard::Key::LAlt || pair.first.code == sf::Keyboard::Key::RAlt))
commands[pair.second].pressed = false;
break;
case sf::Keyboard::Key::LControl:
case sf::Keyboard::Key::RControl:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.control || pair.first.code == sf::Keyboard::Key::LControl || pair.first.code == sf::Keyboard::Key::RControl))
commands[pair.second].pressed = false;
break;
case sf::Keyboard::Key::LShift:
case sf::Keyboard::Key::RShift:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.shift || pair.first.code == sf::Keyboard::Key::LShift || pair.first.code == sf::Keyboard::Key::RShift))
commands[pair.second].pressed = false;
break;
case sf::Keyboard::Key::LSystem:
case sf::Keyboard::Key::RSystem:
for (auto pair : binds)
if (commands[pair.second].get_repeat() == HOLD && (pair.first.system || pair.first.code == sf::Keyboard::Key::LSystem || pair.first.code == sf::Keyboard::Key::RSystem))
commands[pair.second].pressed = false;
break;
default:
break;
}
auto it = binds.find(event.key);
if (it != binds.end())
{
Command& c = commands[it->second];
switch (c.get_repeat())
{
case PRESS:
c.ready = true;
break;
case REPEAT:
break;
case HOLD:
c.pressed = false;
break;
}
}
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright 2017 Global Phasing Ltd.
#include <iostream> // temporary, for debugging
#include "gemmi/cifgz.hpp"
#include "gemmi/mmcif.hpp"
#include "gemmi/pdbgz.hpp"
#include "gemmi/to_cif.hpp"
#include "gemmi/to_json.hpp"
#include "gemmi/to_pdb.hpp"
// set this before only one of stb_sprintf.h includes
#define STB_SPRINTF_IMPLEMENTATION
#include "gemmi/to_mmcif.hpp"
#include <cstring>
#include <iostream>
#include <map>
#include <optionparser.h>
#define EXE_NAME "gemmi-convert"
enum class FileType : char { Json, Pdb, Cif, Null, Unknown };
struct Arg: public option::Arg {
static option::ArgStatus Required(const option::Option& option, bool msg) {
if (option.arg != nullptr)
return option::ARG_OK;
if (msg)
std::cerr << "Option '" << option.name << "' requires an argument\n";
return option::ARG_ILLEGAL;
}
static option::ArgStatus Choice(const option::Option& option, bool msg,
std::vector<const char*> choices) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
for (const char* a : choices)
if (strcmp(option.arg, a) == 0)
return option::ARG_OK;
if (msg)
std::cerr << "Invalid argument for "
<< std::string(option.name, option.namelen) << ": "
<< option.arg << "\n";
return option::ARG_ILLEGAL;
}
static option::ArgStatus FileFormat(const option::Option& option, bool msg) {
// the hidden option "none" is for testing only
return Arg::Choice(option, msg, {"json", "pdb", "cif", "none"});
}
static option::ArgStatus NumbChoice(const option::Option& option, bool msg) {
return Arg::Choice(option, msg, {"quote", "nosu", "mix"});
}
};
enum OptionIndex { Unknown, Help, Verbose, FormatIn, FormatOut,
Bare, Numb, QMark };
static const option::Descriptor usage[] = {
{ Unknown, 0, "", "", Arg::None,
"Usage:"
"\n " EXE_NAME " [options] INPUT_FILE OUTPUT_FILE"
"\n\nwith possible conversions: cif->json and cif<->pdb."
"\n\nGeneral options:" },
{ Help, 0, "h", "help", Arg::None, " -h, --help \tPrint usage and exit." },
{ Verbose, 0, "", "verbose", Arg::None, " --verbose \tVerbose output." },
{ FormatIn, 0, "", "from", Arg::FileFormat,
" --from=pdb|cif \tInput format (default: from the file extension)." },
{ FormatOut, 0, "", "to", Arg::FileFormat,
" --to=json|pdb \tOutput format (default: from the file extension)." },
{ Unknown, 0, "", "", Arg::None, "\nCIF output options:" },
{ Bare, 0, "b", "bare-tags", Arg::None,
" -b, --bare-tags \tOutput tags without the first underscore." },
{ Numb, 0, "", "numb", Arg::NumbChoice,
" --numb=quote|nosu|mix \tConvert the CIF numb type to one of:"
"\v quote - string in quotes,"
"\v nosu - number without s.u.,"
"\v mix (default) - quote only numbs with s.u." },
{ QMark, 0, "", "unknown", Arg::Required,
" --unknown=STRING \tJSON representation of CIF's '?' (default: null)." },
{ Unknown, 0, "", "", Arg::None, "\nMacromolecular options:" },
{ ExpandNcs, 0, "", "expand-ncs", Arg::None,
" --expand-ncs \tExpand NCS mates specified in MTRIXn or equivalent." },
{ Unknown, 0, "", "", Arg::None,
"\nWhen output file is -, write to standard output." },
{ 0, 0, 0, 0, 0, 0 }
};
FileType get_format_from_extension(const std::string& path) {
using gemmi::iends_with;
if (iends_with(path, ".pdb") || iends_with(path, ".ent") ||
iends_with(path, ".pdb.gz") || iends_with(path, ".ent.gz"))
return FileType::Pdb;
if (iends_with(path, ".js") || iends_with(path, ".json"))
return FileType::Json;
if (iends_with(path, ".cif") || iends_with(path, ".cif.gz"))
return FileType::Cif;
if (path == "/dev/null")
return FileType::Null;
return FileType::Unknown;
}
[[noreturn]]
inline void fail(const std::string& msg) { throw std::runtime_error(msg); }
static std::string get_chain_letter(const std::vector<Chain>& chains,
bool short_chain_names) {
if (short_chain_names) {
char symbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz01234567890";
for (char symbol : symbols)
if (find_if(chains.begin(), chains.end(),
[&](const Chain& ch) { return ch.name == symbol; })
== std::end(symbols))
return std::string(1, symbol);
}
}
static void expand_ncs(Structure& st, bool short_chain_names) {
int n_ops = std::count_if(st.ncs.begin(), st.ncs.end(),
[](NcsOp& op){ return !op.given; });
if (n_ops == 0)
return;
for (Model& model : st.models) {
size_t new_length = model.chains.size() * (n_ops + 1);
if (new_length >= 63)
short_chain_names = false;
std::string next_name;
model.chains.reserve(new_length);
for (const NcsOp& op : st.ncs)
if (!op.given)
for (chain : model.chains) {
model.chains.push_back(chain);
Chain& new_chain = model.chains.back();
new_chain.name = next_chain_letter(model.chains, short_chain_names)
: "2";
new_chain.auth_name = "";
for (Residue& res : new_chain.residues)
for (Atom& a : res.atoms) {
//TODO
}
}
for (NcsOp& op : st.ncs)
op.given = true;
}
void convert(const char* input, FileType input_type,
const char* output, FileType output_type,
const std::vector<option::Option>& options) {
gemmi::cif::Document cif_in;
gemmi::mol::Structure st;
// for cif->cif we do either cif->DOM->Structure->DOM->cif or cif->DOM->cif
bool need_structure = options[ExpandNcs];
if (input_type == FileType::Cif) {
cif_in = gemmi::cif::read_any(input);
if (output_type == FileType::Pdb || output_type == FileType::Null ||
need_structure) {
st = gemmi::mol::read_atoms(cif_in);
if (st.models.empty())
fail("No atoms in the input file. Is it mmCIF?");
}
} else if (input_type == FileType::Pdb) {
st = gemmi::mol::read_pdb_any(input);
} else {
fail("Unexpected input format.");
}
if (options[ExpandNcs])
expand_ncs(st);
std::ostream* os;
std::unique_ptr<std::ostream> os_deleter;
if (output != std::string("-")) {
os_deleter.reset(new std::ofstream(output));
os = os_deleter.get();
if (!os || !*os)
fail("Failed to open for writing: " + std::string(output));
} else {
os = &std::cout;
}
if (output_type == FileType::Json) {
if (input_type != FileType::Cif)
fail("Conversion to JSON is possible only from CIF");
gemmi::cif::JsonWriter writer(*os);
writer.use_bare_tags = options[Bare];
if (options[Numb]) {
char first_letter = options[Numb].arg[0];
if (first_letter == 'q')
writer.quote_numbers = 2;
else if (first_letter == 'n')
writer.quote_numbers = 0;
}
if (options[QMark])
writer.unknown = options[QMark].arg;
writer.write_json(cif_in);
}
else if (output_type == FileType::Pdb || output_type == FileType::Null) {
if (output_type == FileType::Pdb)
gemmi::mol::write_pdb(st, *os);
else {
*os << st.name << ": " << count_atom_sites(st) << " atom locations";
if (st.models.size() > 1)
*os << " (total in " << st.models.size() << " models)";
*os << ".\n";
}
} else if (output_type == FileType::Cif) {
// cif to cif round trip is for testing only
if (input_type != FileType::Cif || need_structure) {
cif_in.blocks.clear(); // temporary, for testing
cif_in.blocks.resize(1);
gemmi::mol::update_cif_block(st, cif_in.blocks[0]);
}
*os << cif_in;
}
}
int main(int argc, char **argv) {
if (argc < 1)
return 2;
std::ios_base::sync_with_stdio(false);
option::Stats stats(usage, argc-1, argv+1);
std::vector<option::Option> options(stats.options_max);
std::vector<option::Option> buffer(stats.buffer_max);
option::Parser parse(usage, argc-1, argv+1, options.data(), buffer.data());
if (parse.error()) {
option::printUsage(std::cerr, usage);
return 1;
}
if (options[Help]) {
option::printUsage(std::cout, usage);
return 0;
}
if (options[Unknown]) {
std::cerr << "Invalid option.\n";
option::printUsage(std::cerr, usage);
return 1;
}
if (parse.nonOptionsCount() != 2) {
std::cerr << "This program requires 2 arguments (input and output), "
<< parse.nonOptionsCount() << " given.\n"
"Try '" EXE_NAME " --help' for more information.\n";
return 1;
}
const char* input = parse.nonOption(0);
const char* output = parse.nonOption(1);
std::map<std::string, FileType> filetypes {{"json", FileType::Json},
{"pdb", FileType::Pdb},
{"cif", FileType::Cif},
{"none", FileType::Null}};
FileType in_type = options[FormatIn] ? filetypes[options[FormatIn].arg]
: get_format_from_extension(input);
if (in_type == FileType::Unknown) {
std::cerr << "The input format cannot be determined from input"
" filename. Use option --from.\n";
return 1;
}
FileType out_type = options[FormatOut] ? filetypes[options[FormatOut].arg]
: get_format_from_extension(output);
if (out_type == FileType::Unknown) {
std::cerr << "The output format cannot be determined from output"
" filename. Use option --to.\n";
return 1;
}
if (options[Verbose])
std::cerr << "Converting " << input << " ..." << std::endl;
try {
convert(input, in_type, output, out_type, options);
} catch (tao::pegtl::parse_error& e) {
std::cerr << e.what() << std::endl;
return 1;
} catch (std::runtime_error& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return 2;
}
return 0;
}
// vim:sw=2:ts=2:et
<commit_msg>convert --expand-ncs: needs testing<commit_after>// Copyright 2017 Global Phasing Ltd.
#include <iostream> // temporary, for debugging
#include "gemmi/cifgz.hpp"
#include "gemmi/mmcif.hpp"
#include "gemmi/pdbgz.hpp"
#include "gemmi/to_cif.hpp"
#include "gemmi/to_json.hpp"
#include "gemmi/to_pdb.hpp"
// set this before only one of stb_sprintf.h includes
#define STB_SPRINTF_IMPLEMENTATION
#include "gemmi/to_mmcif.hpp"
#include <cstring>
#include <iostream>
#include <map>
#include <optionparser.h>
#define EXE_NAME "gemmi-convert"
enum class FileType : char { Json, Pdb, Cif, Null, Unknown };
struct Arg: public option::Arg {
static option::ArgStatus Required(const option::Option& option, bool msg) {
if (option.arg != nullptr)
return option::ARG_OK;
if (msg)
std::cerr << "Option '" << option.name << "' requires an argument\n";
return option::ARG_ILLEGAL;
}
static option::ArgStatus Choice(const option::Option& option, bool msg,
std::vector<const char*> choices) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
for (const char* a : choices)
if (strcmp(option.arg, a) == 0)
return option::ARG_OK;
if (msg)
std::cerr << "Invalid argument for "
<< std::string(option.name, option.namelen) << ": "
<< option.arg << "\n";
return option::ARG_ILLEGAL;
}
static option::ArgStatus FileFormat(const option::Option& option, bool msg) {
// the hidden option "none" is for testing only
return Arg::Choice(option, msg, {"json", "pdb", "cif", "none"});
}
static option::ArgStatus NumbChoice(const option::Option& option, bool msg) {
return Arg::Choice(option, msg, {"quote", "nosu", "mix"});
}
};
enum OptionIndex { Unknown, Help, Verbose, FormatIn, FormatOut,
Bare, Numb, QMark, ExpandNcs };
static const option::Descriptor usage[] = {
{ Unknown, 0, "", "", Arg::None,
"Usage:"
"\n " EXE_NAME " [options] INPUT_FILE OUTPUT_FILE"
"\n\nwith possible conversions: cif->json and cif<->pdb."
"\n\nGeneral options:" },
{ Help, 0, "h", "help", Arg::None, " -h, --help \tPrint usage and exit." },
{ Verbose, 0, "", "verbose", Arg::None, " --verbose \tVerbose output." },
{ FormatIn, 0, "", "from", Arg::FileFormat,
" --from=pdb|cif \tInput format (default: from the file extension)." },
{ FormatOut, 0, "", "to", Arg::FileFormat,
" --to=json|pdb \tOutput format (default: from the file extension)." },
{ Unknown, 0, "", "", Arg::None, "\nCIF output options:" },
{ Bare, 0, "b", "bare-tags", Arg::None,
" -b, --bare-tags \tOutput tags without the first underscore." },
{ Numb, 0, "", "numb", Arg::NumbChoice,
" --numb=quote|nosu|mix \tConvert the CIF numb type to one of:"
"\v quote - string in quotes,"
"\v nosu - number without s.u.,"
"\v mix (default) - quote only numbs with s.u." },
{ QMark, 0, "", "unknown", Arg::Required,
" --unknown=STRING \tJSON representation of CIF's '?' (default: null)." },
{ Unknown, 0, "", "", Arg::None, "\nMacromolecular options:" },
{ ExpandNcs, 0, "", "expand-ncs", Arg::None,
" --expand-ncs \tExpand strict NCS specified in MTRIXn or equivalent." },
{ Unknown, 0, "", "", Arg::None,
"\nWhen output file is -, write to standard output." },
{ 0, 0, 0, 0, 0, 0 }
};
FileType get_format_from_extension(const std::string& path) {
using gemmi::iends_with;
if (iends_with(path, ".pdb") || iends_with(path, ".ent") ||
iends_with(path, ".pdb.gz") || iends_with(path, ".ent.gz"))
return FileType::Pdb;
if (iends_with(path, ".js") || iends_with(path, ".json"))
return FileType::Json;
if (iends_with(path, ".cif") || iends_with(path, ".cif.gz"))
return FileType::Cif;
if (path == "/dev/null")
return FileType::Null;
return FileType::Unknown;
}
[[noreturn]]
inline void fail(const std::string& msg) { throw std::runtime_error(msg); }
static char symbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz01234567890";
static void expand_ncs(gemmi::mol::Structure& st, bool short_chain_names) {
namespace mol = gemmi::mol;
int n_ops = std::count_if(st.ncs.begin(), st.ncs.end(),
[](mol::NcsOp& op){ return !op.given; });
if (n_ops == 0)
return;
for (mol::Model& model : st.models) {
size_t new_length = model.chains.size() * (n_ops + 1);
if (new_length >= 63)
short_chain_names = false;
model.chains.reserve(new_length);
for (const mol::Chain& chain : model.chains) {
int op_num = 0;
for (const mol::NcsOp& op : st.ncs)
if (!op.given) {
op_num++;
// the most difficult part - choosing names for new chains
std::string name;
if (short_chain_names) {
for (char symbol : symbols) {
name = std::string(1, symbol);
if (!model.find_chain(name))
break;
}
}
else {
name = chain.name + std::to_string(op_num+1);
while (model.find_chain(name))
name += "a";
}
model.chains.push_back(chain);
mol::Chain& new_chain = model.chains.back();
new_chain.name = name;
new_chain.auth_name = "";
for (mol::Residue& res : new_chain.residues)
for (mol::Atom& a : res.atoms) {
linalg::vec<double,4> pos = {a.pos.x, a.pos.y, a.pos.z, 1.0};
pos = linalg::mul(op.transform, pos);
a.pos = {pos.x, pos.y, pos.z};
}
}
}
}
for (mol::NcsOp& op : st.ncs)
op.given = true;
}
void convert(const char* input, FileType input_type,
const char* output, FileType output_type,
const std::vector<option::Option>& options) {
gemmi::cif::Document cif_in;
gemmi::mol::Structure st;
// for cif->cif we do either cif->DOM->Structure->DOM->cif or cif->DOM->cif
bool need_structure = options[ExpandNcs];
if (input_type == FileType::Cif) {
cif_in = gemmi::cif::read_any(input);
if (output_type == FileType::Pdb || output_type == FileType::Null ||
need_structure) {
st = gemmi::mol::read_atoms(cif_in);
if (st.models.empty())
fail("No atoms in the input file. Is it mmCIF?");
}
} else if (input_type == FileType::Pdb) {
st = gemmi::mol::read_pdb_any(input);
} else {
fail("Unexpected input format.");
}
if (options[ExpandNcs])
expand_ncs(st, output_type == FileType::Pdb);
std::ostream* os;
std::unique_ptr<std::ostream> os_deleter;
if (output != std::string("-")) {
os_deleter.reset(new std::ofstream(output));
os = os_deleter.get();
if (!os || !*os)
fail("Failed to open for writing: " + std::string(output));
} else {
os = &std::cout;
}
if (output_type == FileType::Json) {
if (input_type != FileType::Cif)
fail("Conversion to JSON is possible only from CIF");
gemmi::cif::JsonWriter writer(*os);
writer.use_bare_tags = options[Bare];
if (options[Numb]) {
char first_letter = options[Numb].arg[0];
if (first_letter == 'q')
writer.quote_numbers = 2;
else if (first_letter == 'n')
writer.quote_numbers = 0;
}
if (options[QMark])
writer.unknown = options[QMark].arg;
writer.write_json(cif_in);
}
else if (output_type == FileType::Pdb || output_type == FileType::Null) {
if (output_type == FileType::Pdb)
gemmi::mol::write_pdb(st, *os);
else {
*os << st.name << ": " << count_atom_sites(st) << " atom locations";
if (st.models.size() > 1)
*os << " (total in " << st.models.size() << " models)";
*os << ".\n";
}
} else if (output_type == FileType::Cif) {
// cif to cif round trip is for testing only
if (input_type != FileType::Cif || need_structure) {
cif_in.blocks.clear(); // temporary, for testing
cif_in.blocks.resize(1);
gemmi::mol::update_cif_block(st, cif_in.blocks[0]);
}
*os << cif_in;
}
}
int main(int argc, char **argv) {
if (argc < 1)
return 2;
std::ios_base::sync_with_stdio(false);
option::Stats stats(usage, argc-1, argv+1);
std::vector<option::Option> options(stats.options_max);
std::vector<option::Option> buffer(stats.buffer_max);
option::Parser parse(usage, argc-1, argv+1, options.data(), buffer.data());
if (parse.error()) {
option::printUsage(std::cerr, usage);
return 1;
}
if (options[Help]) {
option::printUsage(std::cout, usage);
return 0;
}
if (options[Unknown]) {
std::cerr << "Invalid option.\n";
option::printUsage(std::cerr, usage);
return 1;
}
if (parse.nonOptionsCount() != 2) {
std::cerr << "This program requires 2 arguments (input and output), "
<< parse.nonOptionsCount() << " given.\n"
"Try '" EXE_NAME " --help' for more information.\n";
return 1;
}
const char* input = parse.nonOption(0);
const char* output = parse.nonOption(1);
std::map<std::string, FileType> filetypes {{"json", FileType::Json},
{"pdb", FileType::Pdb},
{"cif", FileType::Cif},
{"none", FileType::Null}};
FileType in_type = options[FormatIn] ? filetypes[options[FormatIn].arg]
: get_format_from_extension(input);
if (in_type == FileType::Unknown) {
std::cerr << "The input format cannot be determined from input"
" filename. Use option --from.\n";
return 1;
}
FileType out_type = options[FormatOut] ? filetypes[options[FormatOut].arg]
: get_format_from_extension(output);
if (out_type == FileType::Unknown) {
std::cerr << "The output format cannot be determined from output"
" filename. Use option --to.\n";
return 1;
}
if (options[Verbose])
std::cerr << "Converting " << input << " ..." << std::endl;
try {
convert(input, in_type, output, out_type, options);
} catch (tao::pegtl::parse_error& e) {
std::cerr << e.what() << std::endl;
return 1;
} catch (std::runtime_error& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return 2;
}
return 0;
}
// vim:sw=2:ts=2:et
<|endoftext|> |
<commit_before>/*
* PuckManager.cpp
*
* Created on: 09.06.2017
* Author: aca592
*/
#include "PuckManager.h"
PuckManager::PuckManager() {
// TODO Auto-generated constructor stub
}
PuckManager::~PuckManager() {
// TODO Auto-generated destructor stub
}
void PuckManager::addPuck(PuckContext *puck) {
puck->setPuckID(nextPuckID++);
puckList.push_back(puck);
}
PuckManager::ManagerReturn PuckManager::process(PuckSignal::Signal signal) {
ManagerReturn prioReturnVal; // the prioritized return value
prioReturnVal.puckSpeed = PuckSignal::PuckSpeed::FAST;
prioReturnVal.actorFlag = false;
prioReturnVal.errorFlag = false;
prioReturnVal.slideFullFlag = false;
prioReturnVal.puck = nullptr;
if(signal.signalType == PuckSignal::SignalType::TIMER_SIGNAL) {
std::list<PuckContext*>::iterator it = puckList.begin();
do {
if((*it)->getCurrentSpeed() > prioReturnVal.puckSpeed) { // Check for speed prio
prioReturnVal.puckSpeed = (*it)->getCurrentSpeed();
}
uint16_t currentPuckID = (*it)->getPuckID();
if(currentPuckID == signal.timerSignal.puckID) {
PuckSignal::Return returnVal = (*it)->process(signal);
switch(returnVal.puckReturn) {
case PuckSignal::PuckReturn::ACCEPT:
break;
case PuckSignal::PuckReturn::DELETE:
delete *it; // delete the puck from memory
it = puckList.erase(it); // delete the puck from list
break;
case PuckSignal::PuckReturn::SEND:
prioReturnVal.puck = (*it);
prioReturnVal.actorFlag = true;
prioReturnVal.actorSignal = ActorSignal::SEND_PUCK;
break;
case PuckSignal::PuckReturn::EVALUATE:
// todo: sort
break;
case PuckSignal::PuckReturn::HEIGHT:
prioReturnVal.actorFlag = true;
prioReturnVal.actorSignal = ActorSignal::START_MEASUREMENT;
break;
case PuckSignal::PuckReturn::SLIDE_FULL:
prioReturnVal.slideFullFlag = true;
break;
//
case PuckSignal::PuckReturn::WARNING:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
break;
case PuckSignal::PuckReturn::DENY:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
break;
case PuckSignal::PuckReturn::ERROR:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST;
break;
default:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
}
}
} while (it != puckList.end());
return prioReturnVal;
}
int32_t acceptCounter = 0; // count all accepted signals
int32_t warningCounter = 0; // count all warnings
std::list<PuckContext*>::iterator it = puckList.begin();
do {
PuckSignal::Return returnVal = (*it)->process(signal);
if(returnVal.puckSpeed > prioReturnVal.puckSpeed) { // Check for speed prio
prioReturnVal.puckSpeed = returnVal.puckSpeed;
}
switch(returnVal.puckReturn) {
case PuckSignal::PuckReturn::ACCEPT:
acceptCounter++;
break;
case PuckSignal::PuckReturn::DELETE:
acceptCounter++;
delete *it; // delete the puck from memory
it = puckList.erase(it); // delete the puck from list
break;
case PuckSignal::PuckReturn::SEND:
acceptCounter++;
prioReturnVal.puck = (*it);
prioReturnVal.actorFlag = true;
prioReturnVal.actorSignal = ActorSignal::SEND_PUCK;
break;
case PuckSignal::PuckReturn::EVALUATE:
acceptCounter++;
// todo: sort
break;
case PuckSignal::PuckReturn::HEIGHT:
acceptCounter++;
prioReturnVal.actorFlag = true;
prioReturnVal.actorSignal = ActorSignal::START_MEASUREMENT;
break;
case PuckSignal::PuckReturn::SLIDE_FULL:
acceptCounter++;
prioReturnVal.slideFullFlag = true;
break;
//
case PuckSignal::PuckReturn::WARNING:
warningCounter++;
break;
case PuckSignal::PuckReturn::DENY:
break;
case PuckSignal::PuckReturn::ERROR:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST;
break;
default:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
return prioReturnVal;
}
if(returnVal.puckReturn != PuckSignal::PuckReturn::DELETE) {
++it;
}
} while ( it != puckList.end());
if(!prioReturnVal.errorFlag) {
if(acceptCounter > 1 || acceptCounter < 0) {
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::MULTIPLE_ACCEPT;
return prioReturnVal;
}
if(acceptCount == 0) {
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
return prioReturnVal;
}
// acceptCounter == 1
if(warningCounter > 1 || warningCounter < 0) {
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::MULTIPLE_WARNING;
return prioReturnVal;
}
// warning can be ignored
}
// everything OK
return prioReturnVal;
}
<commit_msg>Timer signal functionality<commit_after>/*
* PuckManager.cpp
*
* Created on: 09.06.2017
* Author: aca592
*/
#include "PuckManager.h"
PuckManager::PuckManager() {
// TODO Auto-generated constructor stub
}
PuckManager::~PuckManager() {
// TODO Auto-generated destructor stub
}
void PuckManager::addPuck(PuckContext *puck) {
puck->setPuckID(nextPuckID++);
puckList.push_back(puck);
}
PuckManager::ManagerReturn PuckManager::process(PuckSignal::Signal signal) {
ManagerReturn prioReturnVal; // the prioritized return value
prioReturnVal.puckSpeed = PuckSignal::PuckSpeed::FAST;
prioReturnVal.actorFlag = false;
prioReturnVal.errorFlag = false;
prioReturnVal.slideFullFlag = false;
prioReturnVal.puck = nullptr;
// Pass the timer signal to the given puckID
if(signal.signalType == PuckSignal::SignalType::TIMER_SIGNAL) {
std::list<PuckContext*>::iterator it = puckList.begin();
do {
if((*it)->getCurrentSpeed() > prioReturnVal.puckSpeed) { // Check for speed prio
prioReturnVal.puckSpeed = (*it)->getCurrentSpeed();
}
// check for puckID
uint16_t currentPuckID = (*it)->getPuckID();
if(currentPuckID == signal.timerSignal.puckID) {
// pass the timer signal
PuckSignal::Return returnVal = (*it)->process(signal);
// check return value
if( returnVal.puckReturn != PuckSignal::PuckReturn::ACCEPT &&
returnVal.puckReturn != PuckSignal::PuckReturn::ERROR) {
// puck should be triggered on accept or error -> unexpected otherwise
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
}
}
} while (it != puckList.end());
return prioReturnVal;
}
int32_t acceptCounter = 0; // count all accepted signals
int32_t warningCounter = 0; // count all warnings
std::list<PuckContext*>::iterator it = puckList.begin();
do {
PuckSignal::Return returnVal = (*it)->process(signal);
if(returnVal.puckSpeed > prioReturnVal.puckSpeed) { // Check for speed prio
prioReturnVal.puckSpeed = returnVal.puckSpeed;
}
switch(returnVal.puckReturn) {
case PuckSignal::PuckReturn::ACCEPT:
acceptCounter++;
break;
case PuckSignal::PuckReturn::DELETE:
acceptCounter++;
delete *it; // delete the puck from memory
it = puckList.erase(it); // delete the puck from list
break;
case PuckSignal::PuckReturn::SEND:
acceptCounter++;
prioReturnVal.puck = (*it);
prioReturnVal.actorFlag = true;
prioReturnVal.actorSignal = ActorSignal::SEND_PUCK;
break;
case PuckSignal::PuckReturn::EVALUATE:
acceptCounter++;
// todo: sort
break;
case PuckSignal::PuckReturn::HEIGHT:
acceptCounter++;
prioReturnVal.actorFlag = true;
prioReturnVal.actorSignal = ActorSignal::START_MEASUREMENT;
break;
case PuckSignal::PuckReturn::SLIDE_FULL:
acceptCounter++;
prioReturnVal.slideFullFlag = true;
break;
//
case PuckSignal::PuckReturn::WARNING:
warningCounter++;
break;
case PuckSignal::PuckReturn::DENY:
break;
case PuckSignal::PuckReturn::ERROR:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::PUCK_LOST;
break;
default:
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
return prioReturnVal;
}
if(returnVal.puckReturn != PuckSignal::PuckReturn::DELETE) {
++it;
}
} while ( it != puckList.end());
if(!prioReturnVal.errorFlag) {
if(acceptCounter > 1 || acceptCounter < 0) {
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::MULTIPLE_ACCEPT;
return prioReturnVal;
}
if(acceptCount == 0) {
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::UNEXPECTED_SIGNAL;
return prioReturnVal;
}
// acceptCounter == 1
if(warningCounter > 1 || warningCounter < 0) {
prioReturnVal.errorFlag = true;
prioReturnVal.errorSignal = ErrorSignal::MULTIPLE_WARNING;
return prioReturnVal;
}
// warning can be ignored
}
// everything OK
return prioReturnVal;
}
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_FLAGS_PARSE_HPP__
#define __STOUT_FLAGS_PARSE_HPP__
#include <sstream> // For istringstream.
#include <string>
#include <stout/bytes.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/json.hpp>
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
#include <stout/os/read.hpp>
namespace flags {
template <typename T>
Try<T> parse(const std::string& value)
{
T t;
std::istringstream in(value);
in >> t;
if (in && in.eof()) {
return t;
}
return Error("Failed to convert into required type");
}
template <>
inline Try<std::string> parse(const std::string& value)
{
return value;
}
template <>
inline Try<bool> parse(const std::string& value)
{
if (value == "true" || value == "1") {
return true;
} else if (value == "false" || value == "0") {
return false;
}
return Error("Expecting a boolean (e.g., true or false)");
}
template <>
inline Try<Duration> parse(const std::string& value)
{
return Duration::parse(value);
}
template <>
inline Try<Bytes> parse(const std::string& value)
{
return Bytes::parse(value);
}
template <>
inline Try<JSON::Object> parse(const std::string& value)
{
// A value that already starts with 'file://' will properly be
// loaded from the file and put into 'value' but if it starts with
// '/' we need to explicitly handle it for backwards compatibility
// reasons (because we used to handle it before we introduced the
// 'fetch' mechanism for flags that first fetches the data from URIs
// such as 'file://').
if (strings::startsWith(value, "/")) {
LOG(WARNING) << "Specifying an absolute filename to read a command line "
"option out of without using 'file:// is deprecated and "
"will be removed in a future release. Simply adding "
"'file://' to the beginning of the path should eliminate "
"this warning.";
Try<std::string> read = os::read(value);
if (read.isError()) {
return Error("Error reading file '" + value + "': " + read.error());
}
return JSON::parse<JSON::Object>(read.get());
}
return JSON::parse<JSON::Object>(value);
}
template <>
inline Try<Path> parse(const std::string& value)
{
return Path(value);
}
} // namespace flags {
#endif // __STOUT_FLAGS_PARSE_HPP__
<commit_msg>Stout: Added parse() for JSON::Array.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_FLAGS_PARSE_HPP__
#define __STOUT_FLAGS_PARSE_HPP__
#include <sstream> // For istringstream.
#include <string>
#include <stout/bytes.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/json.hpp>
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
#include <stout/os/read.hpp>
namespace flags {
template <typename T>
Try<T> parse(const std::string& value)
{
T t;
std::istringstream in(value);
in >> t;
if (in && in.eof()) {
return t;
}
return Error("Failed to convert into required type");
}
template <>
inline Try<std::string> parse(const std::string& value)
{
return value;
}
template <>
inline Try<bool> parse(const std::string& value)
{
if (value == "true" || value == "1") {
return true;
} else if (value == "false" || value == "0") {
return false;
}
return Error("Expecting a boolean (e.g., true or false)");
}
template <>
inline Try<Duration> parse(const std::string& value)
{
return Duration::parse(value);
}
template <>
inline Try<Bytes> parse(const std::string& value)
{
return Bytes::parse(value);
}
template <>
inline Try<JSON::Object> parse(const std::string& value)
{
// A value that already starts with 'file://' will properly be
// loaded from the file and put into 'value' but if it starts with
// '/' we need to explicitly handle it for backwards compatibility
// reasons (because we used to handle it before we introduced the
// 'fetch' mechanism for flags that first fetches the data from URIs
// such as 'file://').
if (strings::startsWith(value, "/")) {
LOG(WARNING) << "Specifying an absolute filename to read a command line "
"option out of without using 'file:// is deprecated and "
"will be removed in a future release. Simply adding "
"'file://' to the beginning of the path should eliminate "
"this warning.";
Try<std::string> read = os::read(value);
if (read.isError()) {
return Error("Error reading file '" + value + "': " + read.error());
}
return JSON::parse<JSON::Object>(read.get());
}
return JSON::parse<JSON::Object>(value);
}
template <>
inline Try<JSON::Array> parse(const std::string& value)
{
// A value that already starts with 'file://' will properly be
// loaded from the file and put into 'value' but if it starts with
// '/' we need to explicitly handle it for backwards compatibility
// reasons (because we used to handle it before we introduced the
// 'fetch' mechanism for flags that first fetches the data from URIs
// such as 'file://').
if (strings::startsWith(value, "/")) {
LOG(WARNING) << "Specifying an absolute filename to read a command line "
"option out of without using 'file:// is deprecated and "
"will be removed in a future release. Simply adding "
"'file://' to the beginning of the path should eliminate "
"this warning.";
Try<std::string> read = os::read(value);
if (read.isError()) {
return Error("Error reading file '" + value + "': " + read.error());
}
return JSON::parse<JSON::Array>(read.get());
}
return JSON::parse<JSON::Array>(value);
}
template <>
inline Try<Path> parse(const std::string& value)
{
return Path(value);
}
} // namespace flags {
#endif // __STOUT_FLAGS_PARSE_HPP__
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ime/input_method_imm32.h"
#include "base/basictypes.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/text_input_client.h"
namespace ui {
InputMethodIMM32::InputMethodIMM32(internal::InputMethodDelegate* delegate,
HWND toplevel_window_handle)
: InputMethodWin(delegate, toplevel_window_handle),
enabled_(false), is_candidate_popup_open_(false),
composing_window_handle_(NULL) {
// In non-Aura environment, appropriate callbacks to OnFocus() and OnBlur()
// are not implemented yet. To work around this limitation, here we use
// "always focused" model.
// TODO(ime): Fix the caller of OnFocus() and OnBlur() so that appropriate
// focus event will be passed.
InputMethodWin::OnFocus();
}
void InputMethodIMM32::OnFocus() {
// Ignore OnFocus event for "always focused" model. See the comment in the
// constructor.
// TODO(ime): Implement OnFocus once the callers are fixed.
}
void InputMethodIMM32::OnBlur() {
// Ignore OnBlur event for "always focused" model. See the comment in the
// constructor.
// TODO(ime): Implement OnFocus once the callers are fixed.
}
bool InputMethodIMM32::OnUntranslatedIMEMessage(
const base::NativeEvent& event, InputMethod::NativeEventResult* result) {
LRESULT original_result = 0;
BOOL handled = FALSE;
switch (event.message) {
case WM_IME_SETCONTEXT:
original_result = OnImeSetContext(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_STARTCOMPOSITION:
original_result = OnImeStartComposition(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_COMPOSITION:
original_result = OnImeComposition(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_ENDCOMPOSITION:
original_result = OnImeEndComposition(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_REQUEST:
original_result = OnImeRequest(
event.message, event.wParam, event.lParam, &handled);
break;
case WM_CHAR:
case WM_SYSCHAR:
original_result = OnChar(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_DEADCHAR:
case WM_SYSDEADCHAR:
original_result = OnDeadChar(
event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_NOTIFY:
original_result = OnImeNotify(
event.message, event.wParam, event.lParam, &handled);
break;
default:
NOTREACHED() << "Unknown IME message:" << event.message;
break;
}
if (result)
*result = original_result;
return !!handled;
}
void InputMethodIMM32::OnTextInputTypeChanged(const TextInputClient* client) {
if (IsTextInputClientFocused(client) && IsWindowFocused(client)) {
imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
UpdateIMEState();
}
InputMethodWin::OnTextInputTypeChanged(client);
}
void InputMethodIMM32::OnCaretBoundsChanged(const TextInputClient* client) {
if (!enabled_ || !IsTextInputClientFocused(client) ||
!IsWindowFocused(client)) {
return;
}
// The current text input type should not be NONE if |client| is focused.
DCHECK(!IsTextInputTypeNone());
gfx::Rect screen_bounds(GetTextInputClient()->GetCaretBounds());
HWND attached_window = GetAttachedWindowHandle(client);
// TODO(ime): see comment in TextInputClient::GetCaretBounds(), this
// conversion shouldn't be necessary.
RECT r;
GetClientRect(attached_window, &r);
POINT window_point = { screen_bounds.x(), screen_bounds.y() };
ScreenToClient(attached_window, &window_point);
imm32_manager_.UpdateCaretRect(
attached_window,
gfx::Rect(gfx::Point(window_point.x, window_point.y),
screen_bounds.size()));
}
void InputMethodIMM32::CancelComposition(const TextInputClient* client) {
if (enabled_ && IsTextInputClientFocused(client))
imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
}
bool InputMethodIMM32::IsCandidatePopupOpen() const {
return is_candidate_popup_open_;
}
void InputMethodIMM32::OnWillChangeFocusedClient(
TextInputClient* focused_before,
TextInputClient* focused) {
if (IsWindowFocused(focused_before)) {
ConfirmCompositionText();
}
}
void InputMethodIMM32::OnDidChangeFocusedClient(TextInputClient* focused_before,
TextInputClient* focused) {
if (IsWindowFocused(focused)) {
// Force to update the input type since client's TextInputStateChanged()
// function might not be called if text input types before the client loses
// focus and after it acquires focus again are the same.
OnTextInputTypeChanged(focused);
UpdateIMEState();
// Force to update caret bounds, in case the client thinks that the caret
// bounds has not changed.
OnCaretBoundsChanged(focused);
}
}
LRESULT InputMethodIMM32::OnImeSetContext(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
if (!!wparam)
imm32_manager_.CreateImeWindow(window_handle);
OnInputMethodChanged();
return imm32_manager_.SetImeWindowStyle(
window_handle, message, wparam, lparam, handled);
}
LRESULT InputMethodIMM32::OnImeStartComposition(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
// We have to prevent WTL from calling ::DefWindowProc() because the function
// calls ::ImmSetCompositionWindow() and ::ImmSetCandidateWindow() to
// over-write the position of IME windows.
*handled = TRUE;
// Reset the composition status and create IME windows.
composing_window_handle_ = window_handle;
imm32_manager_.CreateImeWindow(window_handle);
imm32_manager_.ResetComposition(window_handle);
return 0;
}
LRESULT InputMethodIMM32::OnImeComposition(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
// We have to prevent WTL from calling ::DefWindowProc() because we do not
// want for the IMM (Input Method Manager) to send WM_IME_CHAR messages.
*handled = TRUE;
// At first, update the position of the IME window.
imm32_manager_.UpdateImeWindow(window_handle);
// Retrieve the result string and its attributes of the ongoing composition
// and send it to a renderer process.
ui::CompositionText composition;
if (imm32_manager_.GetResult(window_handle, lparam, &composition.text)) {
if (!IsTextInputTypeNone())
GetTextInputClient()->InsertText(composition.text);
imm32_manager_.ResetComposition(window_handle);
// Fall though and try reading the composition string.
// Japanese IMEs send a message containing both GCS_RESULTSTR and
// GCS_COMPSTR, which means an ongoing composition has been finished
// by the start of another composition.
}
// Retrieve the composition string and its attributes of the ongoing
// composition and send it to a renderer process.
if (imm32_manager_.GetComposition(window_handle, lparam, &composition) &&
!IsTextInputTypeNone())
GetTextInputClient()->SetCompositionText(composition);
return 0;
}
LRESULT InputMethodIMM32::OnImeEndComposition(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
// Let WTL call ::DefWindowProc() and release its resources.
*handled = FALSE;
composing_window_handle_ = NULL;
if (!IsTextInputTypeNone() && GetTextInputClient()->HasCompositionText())
GetTextInputClient()->ClearCompositionText();
imm32_manager_.ResetComposition(window_handle);
imm32_manager_.DestroyImeWindow(window_handle);
return 0;
}
LRESULT InputMethodIMM32::OnImeNotify(UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
*handled = FALSE;
// Update |is_candidate_popup_open_|, whether a candidate window is open.
switch (wparam) {
case IMN_OPENCANDIDATE:
is_candidate_popup_open_ = true;
break;
case IMN_CLOSECANDIDATE:
is_candidate_popup_open_ = false;
break;
}
return 0;
}
void InputMethodIMM32::ConfirmCompositionText() {
if (composing_window_handle_)
imm32_manager_.CleanupComposition(composing_window_handle_);
if (!IsTextInputTypeNone()) {
// Though above line should confirm the client's composition text by sending
// a result text to us, in case the input method and the client are in
// inconsistent states, we check the client's composition state again.
if (GetTextInputClient()->HasCompositionText())
GetTextInputClient()->ConfirmCompositionText();
}
}
void InputMethodIMM32::UpdateIMEState() {
// Use switch here in case we are going to add more text input types.
// We disable input method in password field.
const HWND window_handle = GetAttachedWindowHandle(GetTextInputClient());
switch (GetTextInputType()) {
case ui::TEXT_INPUT_TYPE_NONE:
case ui::TEXT_INPUT_TYPE_PASSWORD:
imm32_manager_.DisableIME(window_handle);
enabled_ = false;
break;
default:
imm32_manager_.EnableIME(window_handle);
enabled_ = true;
break;
}
imm32_manager_.SetTextInputMode(window_handle, GetTextInputMode());
}
} // namespace ui
<commit_msg>Add InputScope support into InputMethodIMM32<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ime/input_method_imm32.h"
#include "base/basictypes.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/ime/win/tsf_input_scope.h"
namespace ui {
InputMethodIMM32::InputMethodIMM32(internal::InputMethodDelegate* delegate,
HWND toplevel_window_handle)
: InputMethodWin(delegate, toplevel_window_handle),
enabled_(false), is_candidate_popup_open_(false),
composing_window_handle_(NULL) {
// In non-Aura environment, appropriate callbacks to OnFocus() and OnBlur()
// are not implemented yet. To work around this limitation, here we use
// "always focused" model.
// TODO(ime): Fix the caller of OnFocus() and OnBlur() so that appropriate
// focus event will be passed.
InputMethodWin::OnFocus();
}
void InputMethodIMM32::OnFocus() {
// Ignore OnFocus event for "always focused" model. See the comment in the
// constructor.
// TODO(ime): Implement OnFocus once the callers are fixed.
}
void InputMethodIMM32::OnBlur() {
// Ignore OnBlur event for "always focused" model. See the comment in the
// constructor.
// TODO(ime): Implement OnFocus once the callers are fixed.
}
bool InputMethodIMM32::OnUntranslatedIMEMessage(
const base::NativeEvent& event, InputMethod::NativeEventResult* result) {
LRESULT original_result = 0;
BOOL handled = FALSE;
switch (event.message) {
case WM_IME_SETCONTEXT:
original_result = OnImeSetContext(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_STARTCOMPOSITION:
original_result = OnImeStartComposition(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_COMPOSITION:
original_result = OnImeComposition(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_ENDCOMPOSITION:
original_result = OnImeEndComposition(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_REQUEST:
original_result = OnImeRequest(
event.message, event.wParam, event.lParam, &handled);
break;
case WM_CHAR:
case WM_SYSCHAR:
original_result = OnChar(
event.hwnd, event.message, event.wParam, event.lParam, &handled);
break;
case WM_DEADCHAR:
case WM_SYSDEADCHAR:
original_result = OnDeadChar(
event.message, event.wParam, event.lParam, &handled);
break;
case WM_IME_NOTIFY:
original_result = OnImeNotify(
event.message, event.wParam, event.lParam, &handled);
break;
default:
NOTREACHED() << "Unknown IME message:" << event.message;
break;
}
if (result)
*result = original_result;
return !!handled;
}
void InputMethodIMM32::OnTextInputTypeChanged(const TextInputClient* client) {
if (IsTextInputClientFocused(client) && IsWindowFocused(client)) {
imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
UpdateIMEState();
}
InputMethodWin::OnTextInputTypeChanged(client);
}
void InputMethodIMM32::OnCaretBoundsChanged(const TextInputClient* client) {
if (!enabled_ || !IsTextInputClientFocused(client) ||
!IsWindowFocused(client)) {
return;
}
// The current text input type should not be NONE if |client| is focused.
DCHECK(!IsTextInputTypeNone());
gfx::Rect screen_bounds(GetTextInputClient()->GetCaretBounds());
HWND attached_window = GetAttachedWindowHandle(client);
// TODO(ime): see comment in TextInputClient::GetCaretBounds(), this
// conversion shouldn't be necessary.
RECT r;
GetClientRect(attached_window, &r);
POINT window_point = { screen_bounds.x(), screen_bounds.y() };
ScreenToClient(attached_window, &window_point);
imm32_manager_.UpdateCaretRect(
attached_window,
gfx::Rect(gfx::Point(window_point.x, window_point.y),
screen_bounds.size()));
}
void InputMethodIMM32::CancelComposition(const TextInputClient* client) {
if (enabled_ && IsTextInputClientFocused(client))
imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
}
bool InputMethodIMM32::IsCandidatePopupOpen() const {
return is_candidate_popup_open_;
}
void InputMethodIMM32::OnWillChangeFocusedClient(
TextInputClient* focused_before,
TextInputClient* focused) {
if (IsWindowFocused(focused_before)) {
ConfirmCompositionText();
}
}
void InputMethodIMM32::OnDidChangeFocusedClient(TextInputClient* focused_before,
TextInputClient* focused) {
if (IsWindowFocused(focused)) {
// Force to update the input type since client's TextInputStateChanged()
// function might not be called if text input types before the client loses
// focus and after it acquires focus again are the same.
OnTextInputTypeChanged(focused);
UpdateIMEState();
// Force to update caret bounds, in case the client thinks that the caret
// bounds has not changed.
OnCaretBoundsChanged(focused);
}
}
LRESULT InputMethodIMM32::OnImeSetContext(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
if (!!wparam)
imm32_manager_.CreateImeWindow(window_handle);
OnInputMethodChanged();
return imm32_manager_.SetImeWindowStyle(
window_handle, message, wparam, lparam, handled);
}
LRESULT InputMethodIMM32::OnImeStartComposition(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
// We have to prevent WTL from calling ::DefWindowProc() because the function
// calls ::ImmSetCompositionWindow() and ::ImmSetCandidateWindow() to
// over-write the position of IME windows.
*handled = TRUE;
// Reset the composition status and create IME windows.
composing_window_handle_ = window_handle;
imm32_manager_.CreateImeWindow(window_handle);
imm32_manager_.ResetComposition(window_handle);
return 0;
}
LRESULT InputMethodIMM32::OnImeComposition(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
// We have to prevent WTL from calling ::DefWindowProc() because we do not
// want for the IMM (Input Method Manager) to send WM_IME_CHAR messages.
*handled = TRUE;
// At first, update the position of the IME window.
imm32_manager_.UpdateImeWindow(window_handle);
// Retrieve the result string and its attributes of the ongoing composition
// and send it to a renderer process.
ui::CompositionText composition;
if (imm32_manager_.GetResult(window_handle, lparam, &composition.text)) {
if (!IsTextInputTypeNone())
GetTextInputClient()->InsertText(composition.text);
imm32_manager_.ResetComposition(window_handle);
// Fall though and try reading the composition string.
// Japanese IMEs send a message containing both GCS_RESULTSTR and
// GCS_COMPSTR, which means an ongoing composition has been finished
// by the start of another composition.
}
// Retrieve the composition string and its attributes of the ongoing
// composition and send it to a renderer process.
if (imm32_manager_.GetComposition(window_handle, lparam, &composition) &&
!IsTextInputTypeNone())
GetTextInputClient()->SetCompositionText(composition);
return 0;
}
LRESULT InputMethodIMM32::OnImeEndComposition(HWND window_handle,
UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
// Let WTL call ::DefWindowProc() and release its resources.
*handled = FALSE;
composing_window_handle_ = NULL;
if (!IsTextInputTypeNone() && GetTextInputClient()->HasCompositionText())
GetTextInputClient()->ClearCompositionText();
imm32_manager_.ResetComposition(window_handle);
imm32_manager_.DestroyImeWindow(window_handle);
return 0;
}
LRESULT InputMethodIMM32::OnImeNotify(UINT message,
WPARAM wparam,
LPARAM lparam,
BOOL* handled) {
*handled = FALSE;
// Update |is_candidate_popup_open_|, whether a candidate window is open.
switch (wparam) {
case IMN_OPENCANDIDATE:
is_candidate_popup_open_ = true;
break;
case IMN_CLOSECANDIDATE:
is_candidate_popup_open_ = false;
break;
}
return 0;
}
void InputMethodIMM32::ConfirmCompositionText() {
if (composing_window_handle_)
imm32_manager_.CleanupComposition(composing_window_handle_);
if (!IsTextInputTypeNone()) {
// Though above line should confirm the client's composition text by sending
// a result text to us, in case the input method and the client are in
// inconsistent states, we check the client's composition state again.
if (GetTextInputClient()->HasCompositionText())
GetTextInputClient()->ConfirmCompositionText();
}
}
void InputMethodIMM32::UpdateIMEState() {
// Use switch here in case we are going to add more text input types.
// We disable input method in password field.
const HWND window_handle = GetAttachedWindowHandle(GetTextInputClient());
const TextInputType text_input_type = GetTextInputType();
const TextInputMode text_input_mode = GetTextInputMode();
switch (text_input_type) {
case ui::TEXT_INPUT_TYPE_NONE:
case ui::TEXT_INPUT_TYPE_PASSWORD:
imm32_manager_.DisableIME(window_handle);
enabled_ = false;
break;
default:
imm32_manager_.EnableIME(window_handle);
enabled_ = true;
break;
}
imm32_manager_.SetTextInputMode(window_handle, text_input_mode);
tsf_inputscope::SetInputScopeForTsfUnawareWindow(
window_handle, text_input_type, text_input_mode);
}
} // namespace ui
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Texture Analysis
Module: $$
Language: C++
Date: $Date: xxx-xx-xx $
Version: $Revision: xxx $
Copyright (c) University of North Carolina at Chapel Hill (UNC-CH) All Rights Reserved.
See License.txt or http://www.slicer.org/copyright/copyright.txt for details.
==========================================================================*/
#ifndef __itkScalarImageToIntensitySizeListSampleFilter_hxx
#define __itkScalarImageToIntensitySizeListSampleFilter_hxx
#include <itkLabelStatisticsImageFilter.h>
#include <itkBinaryThresholdImageFilter.h>
#include <itkConnectedComponentImageFilter.h>
#include "itkScalarImageToIntensitySizeListSampleFilter.h"
#include "itkImageFileWriter.h"
namespace itk
{
namespace Statistics {
/**
* Constructor
*/
template< typename TInputImage >
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::ScalarImageToIntensitySizeListSampleFilter()
{
m_MinIntensity = 0;
m_MaxIntensity = 0;
m_NumberOfIntensityBins = 1;
m_MinSize = 1;
m_MaxSize = numeric_limits<int>::max();
m_BackgroundValue = 0;
this->SetNumberOfRequiredInputs(1);
this->SetNumberOfRequiredOutputs(1);
this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) );
}
/**
*
*/
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(const InputImageType *input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput( 0,
const_cast< InputImageType * >( input ) );
}
/**
* Connect one of the operands for pixel-wise addition
*/
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(unsigned int index, const TInputImage *image)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput( index,
const_cast< TInputImage * >( image ) );
}
/**
*
*/
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GetInput(void) const
{
return itkDynamicCastInDebugMode< const TInputImage * >( this->GetPrimaryInput() );
}
/**
*
*/
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GetInput(unsigned int idx) const
{
const TInputImage *in = dynamic_cast< const TInputImage * >
( this->ProcessObject::GetInput(idx) );
if ( in == ITK_NULLPTR && this->ProcessObject::GetInput(idx) != ITK_NULLPTR )
{
itkWarningMacro (<< "Unable to convert input number " << idx << " to type " << typeid( InputImageType ).name () );
}
return in;
}
template< typename TInputImage >
typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::DataObjectPointer
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(idx)){
return SampleType::New().GetPointer();
}
template< typename TImage >
void
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method. this should
// copy the output requested region to the input requested region
Superclass::GenerateInputRequestedRegion();
}
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GenerateOutputInformation(){
Superclass::GenerateOutputInformation();
SampleType *output =
static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );
output->SetMeasurementVectorSize( 2 );
}
template< typename TImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TImage >::SampleType *
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GetOutput() const
{
const SampleType *output =
static_cast< const SampleType * >( this->ProcessObject::GetOutput(0) );
return output;
}
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GenerateData()
{
typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > ThresholdImageFilterType;
typedef typename ThresholdImageFilterType::Pointer ThresholdImageFilterPointerType;
typedef itk::ConnectedComponentImageFilter <OutputImageType, OutputImageType > ConnectedComponentImageFilterType;
typedef typename ConnectedComponentImageFilterType::Pointer ConnectedComponentImageFilterPointerType;
typedef itk::LabelStatisticsImageFilter< OutputImageType, OutputImageType > LabelStatisticsImageFilterType;
typedef typename LabelStatisticsImageFilterType::Pointer LabelStatisticsImageFilterPointerType;
InputImageConstPointer inputImage = this->GetInput();
SampleType *output = static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );
//Calculate the step size given the maximum intensity, minimum and the number of desired intensity bins.
this->SetIntensityBinSize((this->GetMaxIntensity() - this->GetMinIntensity())/this->GetNumberOfIntensityBins());
double binsize = this->GetIntensityBinSize();
if(binsize <= 0){
cerr<<"MaxIntesity: "<<this->GetMaxIntensity()<<endl;
cerr<<"MinIntesity: "<<this->GetMinIntensity()<<endl;
cerr<<"NumberOfIntensityBins: "<<this->GetNumberOfIntensityBins()<<endl;
cerr<<"Binsize = (maxIntensity - minIntensity)/numberOfBins"<<endl;
itkExceptionMacro("ERROR: Intensity bin size is 0. Please reduce the number of intensity bins.")
}
InputImagePixelType minintensity = this->GetMinIntensity();
InputImagePixelType maxintensity = this->GetMinIntensity();
for(int i = 0; i < this->GetNumberOfIntensityBins() && maxintensity < this->GetMaxIntensity(); i++){
minintensity = maxintensity;
maxintensity = minintensity + (i+1)*binsize;
if(minintensity == this->GetBackgroundValue()){
minintensity = maxintensity;
}
//Threshold the image using the threshold values
ThresholdImageFilterPointerType thresholdfilter = ThresholdImageFilterType::New();
thresholdfilter->SetInput(inputImage);
thresholdfilter->SetLowerThreshold(minintensity);
thresholdfilter->SetUpperThreshold(maxintensity);
thresholdfilter->SetOutsideValue(0);
thresholdfilter->SetInsideValue(255);
thresholdfilter->Update();
OutputImagePointerType imgthresh = thresholdfilter->GetOutput();
//Calculate the connected components and label each one of them with a unique value
ConnectedComponentImageFilterPointerType connectedcomponents = ConnectedComponentImageFilterType::New();
connectedcomponents->SetInput(imgthresh);
OutputImagePointerType imglabel = connectedcomponents->GetOutput();
// typedef itk::ImageFileWriter< OutputImageType > ImageFileWriterType;
// typename ImageFileWriterType::Pointer writer = ImageFileWriterType::New();
// writer->SetInput(imglabel);
// writer->SetFileName("temp.nrrd");
// writer->Update();
//Compute statistics for each label
LabelStatisticsImageFilterPointerType labelstatistics = LabelStatisticsImageFilterType::New();
labelstatistics->SetLabelInput(imglabel);
labelstatistics->SetInput(imgthresh);
labelstatistics->Update();
typedef typename LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType;
typedef typename ValidLabelValuesType::const_iterator ValidLabelsIteratorType;
typedef typename LabelStatisticsImageFilterType::LabelPixelType LabelPixelType;
ValidLabelValuesType validlabels = labelstatistics->GetValidLabelValues();
//Get each label and insert it into the list sample
for(ValidLabelsIteratorType vIt = validlabels.begin(); vIt != validlabels.end(); ++vIt){
LabelPixelType labelValue = *vIt;
if ( labelstatistics->HasLabel(labelValue) && labelValue != 0){
double size = labelstatistics->GetCount( labelValue );
if(this->GetMinSize() <= size && size <= this->GetMaxSize()){
double bincenter = (minintensity + maxintensity)/2.0;
MeasurementVectorType mv;
mv[0] = bincenter;
mv[1] = size;
output->PushBack(mv);
}
// std::cout << "min: " << labelstatistics->GetMinimum( labelValue ) << std::endl;
// std::cout << "max: " << labelstatistics->GetMaximum( labelValue ) << std::endl;
// std::cout << "median: " << labelstatistics->GetMedian( labelValue ) << std::endl;
// std::cout << "mean: " << labelstatistics->GetMean( labelValue ) << std::endl;
// std::cout << "sigma: " << labelstatistics->GetSigma( labelValue ) << std::endl;
// std::cout << "variance: " << labelstatistics->GetVariance( labelValue ) << std::endl;
// std::cout << "sum: " << labelstatistics->GetSum( labelValue ) << std::endl;
// std::cout << "count: " << labelstatistics->GetCount( labelValue ) << std::endl;
// std::cout << "region: " << labelstatistics->GetRegion( labelValue ) << std::endl;
// std::cout << std::endl << std::endl;
}
}
}
}
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "ScalarImageToIntensityListSampleFilter: "<< std::endl;
os << indent << "SamplePointerType: "<< this->GetOutput() <<endl;
os << indent << "MinIntensity: "<<m_MinIntensity <<endl;
os << indent << "MaxIntensity: "<<m_MaxIntensity<<endl;
os << indent << "BackgroundValue: "<< m_BackgroundValue <<endl;
os << indent << "NumberOfIntensityBins: "<< m_NumberOfIntensityBins <<endl;
os << indent << "MinSize: "<< m_MinSize <<endl;
os << indent << "MaxSize: "<< m_MaxSize <<endl;
}
}// namespace statistics
}// namespace itk
#endif
<commit_msg>BUG: Increase of bin size<commit_after>/*=========================================================================
Program: Texture Analysis
Module: $$
Language: C++
Date: $Date: xxx-xx-xx $
Version: $Revision: xxx $
Copyright (c) University of North Carolina at Chapel Hill (UNC-CH) All Rights Reserved.
See License.txt or http://www.slicer.org/copyright/copyright.txt for details.
==========================================================================*/
#ifndef __itkScalarImageToIntensitySizeListSampleFilter_hxx
#define __itkScalarImageToIntensitySizeListSampleFilter_hxx
#include <itkLabelStatisticsImageFilter.h>
#include <itkBinaryThresholdImageFilter.h>
#include <itkConnectedComponentImageFilter.h>
#include "itkScalarImageToIntensitySizeListSampleFilter.h"
#include "itkImageFileWriter.h"
namespace itk
{
namespace Statistics {
/**
* Constructor
*/
template< typename TInputImage >
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::ScalarImageToIntensitySizeListSampleFilter()
{
m_MinIntensity = 0;
m_MaxIntensity = 0;
m_NumberOfIntensityBins = 1;
m_MinSize = 1;
m_MaxSize = numeric_limits<int>::max();
m_BackgroundValue = 0;
this->SetNumberOfRequiredInputs(1);
this->SetNumberOfRequiredOutputs(1);
this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) );
}
/**
*
*/
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(const InputImageType *input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput( 0,
const_cast< InputImageType * >( input ) );
}
/**
* Connect one of the operands for pixel-wise addition
*/
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(unsigned int index, const TInputImage *image)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput( index,
const_cast< TInputImage * >( image ) );
}
/**
*
*/
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GetInput(void) const
{
return itkDynamicCastInDebugMode< const TInputImage * >( this->GetPrimaryInput() );
}
/**
*
*/
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GetInput(unsigned int idx) const
{
const TInputImage *in = dynamic_cast< const TInputImage * >
( this->ProcessObject::GetInput(idx) );
if ( in == ITK_NULLPTR && this->ProcessObject::GetInput(idx) != ITK_NULLPTR )
{
itkWarningMacro (<< "Unable to convert input number " << idx << " to type " << typeid( InputImageType ).name () );
}
return in;
}
template< typename TInputImage >
typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::DataObjectPointer
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(idx)){
return SampleType::New().GetPointer();
}
template< typename TImage >
void
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method. this should
// copy the output requested region to the input requested region
Superclass::GenerateInputRequestedRegion();
}
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GenerateOutputInformation(){
Superclass::GenerateOutputInformation();
SampleType *output =
static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );
output->SetMeasurementVectorSize( 2 );
}
template< typename TImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TImage >::SampleType *
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GetOutput() const
{
const SampleType *output =
static_cast< const SampleType * >( this->ProcessObject::GetOutput(0) );
return output;
}
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GenerateData()
{
typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > ThresholdImageFilterType;
typedef typename ThresholdImageFilterType::Pointer ThresholdImageFilterPointerType;
typedef itk::ConnectedComponentImageFilter <OutputImageType, OutputImageType > ConnectedComponentImageFilterType;
typedef typename ConnectedComponentImageFilterType::Pointer ConnectedComponentImageFilterPointerType;
typedef itk::LabelStatisticsImageFilter< OutputImageType, OutputImageType > LabelStatisticsImageFilterType;
typedef typename LabelStatisticsImageFilterType::Pointer LabelStatisticsImageFilterPointerType;
InputImageConstPointer inputImage = this->GetInput();
SampleType *output = static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );
//Calculate the step size given the maximum intensity, minimum and the number of desired intensity bins.
this->SetIntensityBinSize((this->GetMaxIntensity() - this->GetMinIntensity())/this->GetNumberOfIntensityBins());
double binsize = this->GetIntensityBinSize();
if(binsize <= 0){
cerr<<"MaxIntesity: "<<this->GetMaxIntensity()<<endl;
cerr<<"MinIntesity: "<<this->GetMinIntensity()<<endl;
cerr<<"NumberOfIntensityBins: "<<this->GetNumberOfIntensityBins()<<endl;
cerr<<"Binsize = (maxIntensity - minIntensity)/numberOfBins"<<endl;
itkExceptionMacro("ERROR: Intensity bin size is 0.")
}
InputImagePixelType minintensity = this->GetMinIntensity();
InputImagePixelType maxintensity = this->GetMinIntensity();
for(int i = 0; i < this->GetNumberOfIntensityBins() && maxintensity < this->GetMaxIntensity(); i++){
minintensity = maxintensity;
maxintensity = minintensity + binsize;
//Threshold the image using the threshold values
ThresholdImageFilterPointerType thresholdfilter = ThresholdImageFilterType::New();
thresholdfilter->SetInput(inputImage);
thresholdfilter->SetLowerThreshold(minintensity);
thresholdfilter->SetUpperThreshold(maxintensity);
thresholdfilter->SetOutsideValue(0);
thresholdfilter->SetInsideValue(255);
thresholdfilter->Update();
OutputImagePointerType imgthresh = thresholdfilter->GetOutput();
//Calculate the connected components and label each one of them with a unique value
ConnectedComponentImageFilterPointerType connectedcomponents = ConnectedComponentImageFilterType::New();
connectedcomponents->SetInput(imgthresh);
OutputImagePointerType imglabel = connectedcomponents->GetOutput();
// typedef itk::ImageFileWriter< OutputImageType > ImageFileWriterType;
// typename ImageFileWriterType::Pointer writer = ImageFileWriterType::New();
// writer->SetInput(imglabel);
// writer->SetFileName("temp.nrrd");
// writer->Update();
//Compute statistics for each label
LabelStatisticsImageFilterPointerType labelstatistics = LabelStatisticsImageFilterType::New();
labelstatistics->SetLabelInput(imglabel);
labelstatistics->SetInput(imgthresh);
labelstatistics->Update();
typedef typename LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType;
typedef typename ValidLabelValuesType::const_iterator ValidLabelsIteratorType;
typedef typename LabelStatisticsImageFilterType::LabelPixelType LabelPixelType;
ValidLabelValuesType validlabels = labelstatistics->GetValidLabelValues();
//Get each label and insert it into the list sample
for(ValidLabelsIteratorType vIt = validlabels.begin(); vIt != validlabels.end(); ++vIt){
LabelPixelType labelValue = *vIt;
if ( labelstatistics->HasLabel(labelValue) && labelValue != 0){
double size = labelstatistics->GetCount( labelValue );
if(this->GetMinSize() <= size && size <= this->GetMaxSize()){
double bincenter = (minintensity + maxintensity)/2.0;
MeasurementVectorType mv;
mv[0] = bincenter;
mv[1] = size;
output->PushBack(mv);
}
// std::cout << "min: " << labelstatistics->GetMinimum( labelValue ) << std::endl;
// std::cout << "max: " << labelstatistics->GetMaximum( labelValue ) << std::endl;
// std::cout << "median: " << labelstatistics->GetMedian( labelValue ) << std::endl;
// std::cout << "mean: " << labelstatistics->GetMean( labelValue ) << std::endl;
// std::cout << "sigma: " << labelstatistics->GetSigma( labelValue ) << std::endl;
// std::cout << "variance: " << labelstatistics->GetVariance( labelValue ) << std::endl;
// std::cout << "sum: " << labelstatistics->GetSum( labelValue ) << std::endl;
// std::cout << "count: " << labelstatistics->GetCount( labelValue ) << std::endl;
// std::cout << "region: " << labelstatistics->GetRegion( labelValue ) << std::endl;
// std::cout << std::endl << std::endl;
}
}
}
}
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "ScalarImageToIntensityListSampleFilter: "<< std::endl;
os << indent << "SamplePointerType: "<< this->GetOutput() <<endl;
os << indent << "MinIntensity: "<<m_MinIntensity <<endl;
os << indent << "MaxIntensity: "<<m_MaxIntensity<<endl;
os << indent << "BackgroundValue: "<< m_BackgroundValue <<endl;
os << indent << "NumberOfIntensityBins: "<< m_NumberOfIntensityBins <<endl;
os << indent << "MinSize: "<< m_MinSize <<endl;
os << indent << "MaxSize: "<< m_MaxSize <<endl;
}
}// namespace statistics
}// namespace itk
#endif
<|endoftext|> |
<commit_before>/*
Al parecer, también se puede hacer gestión de lectura/escritura
mediante otras funciones propias de C++ y sus librerias.
El ejemplo anterior sería válido tanto para C y C++ (las funciones).
*/<commit_msg>file medium/04-ReadWrite2<commit_after>/*
Al parecer, también se puede hacer gestión de lectura/escritura
mediante otras funciones propias de C++ y sus librerias.
El ejemplo anterior sería válido tanto para C y C++ (las funciones).
ofstream: para escribir
ifstream: para leer
fstream: para leer/escribir
*/
#include <iostream>
#include <fstream>
#include <string>
int main() {
//fichero para leer/escribir
std::fstream fd;
fd.open("readWrite2", std::ios::in | std::ios::out | std::ios::trunc);
//Todo ok
if (fd.is_open()) {
//Write in file
fd << "Linea 1\n";
fd << "Linea 2\n";
//Para que se escriba, por que se guarda en buffer hasta que se cierra
fd.close();
fd.open("readWrite2");
//Read from file
std::string line;
while (std::getline(fd,line)) {
std::cout << line << "\n";
}
return 0;
} else {
return 1;
}
}<|endoftext|> |
<commit_before>
void GetSampleName( TString inputFile="") {
string ret;
ret = inputFile;
//Drell Yan
if (inputFile.Contains("DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph")) ret = "ZJets" ;
if (inputFile.Contains("DYJetsToLL_HT-200To400_TuneZ2Star_8TeV-madgraph")) ret = "ZJets200";
if (inputFile.Contains("DYJetsToLL_HT-400ToInf_TuneZ2Star_8TeV-madgraph")) ret = "ZJets400";
//Pythia QCD - all LO PREP
if (inputFile.Contains("QCD_Pt-1000to1400")) ret = "QCD1000";
if (inputFile.Contains("QCD_Pt-120to170")) ret = "QCD120" ;
if (inputFile.Contains("QCD_Pt-1400to1800")) ret = "QCD1400";
if (inputFile.Contains("QCD_Pt-170to300")) ret = "QCD170" ;
if (inputFile.Contains("QCD_Pt-1800")) ret = "QCD1800";
if (inputFile.Contains("QCD_Pt-300to470")) ret = "QCD300" ;
if (inputFile.Contains("QCD30")) ret = "QCD30" ;
if (inputFile.Contains("QCD_Pt-470to600")) ret = "QCD470" ;
if (inputFile.Contains("QCD_Pt-600to800")) ret = "QCD600" ;
if (inputFile.Contains("QCD_Pt-800to1000")) ret = "QCD800" ;
if (inputFile.Contains("QCD80")) ret = "QCD80" ;
//B-jets
if (inputFile.Contains("BJets_HT-250To500_8TeV-madgraph")) ret = "B250" ;
if (inputFile.Contains("BJets_HT-500To1000_8TeV-madgraph")) ret = "B500" ;
if (inputFile.Contains("BJets_HT-1000ToInf_8TeV-madgraph")) ret = "B1000";
//single top
if (inputFile.Contains("_tW-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
if (inputFile.Contains("_t-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_t" ;
if (inputFile.Contains("_s-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_s" ;
if (inputFile.Contains("_tW-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
if (inputFile.Contains("_t-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_t" ;
if (inputFile.Contains("_s-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_s" ;
//W+Jets
if (inputFile.Contains("WJetsToLNu_HT-400ToInf_8TeV-madgraph")) ret = "WJets400";
if (inputFile.Contains("WJetsToLNu_HT-250To300_8TeV-madgraph")) ret = "WJets250";
if (inputFile.Contains("WJetsToLNu_HT-300To400_8TeV-madgraph")) ret = "WJets300";
if (inputFile.Contains("WJetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "WJets" ;
if (inputFile.Contains("W2JetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "W2Jets" ;
if (inputFile.Contains("W3JetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "W3Jets" ;
if (inputFile.Contains("W4JetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "W4Jets" ;
if (inputFile.Contains("WbbJetsToLNu_Massive_TuneZ2star_8TeV-madgraph-pythia6_tauola")) ret = "Wbb";
//diboson
if (inputFile.Contains("WZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "WZ";
if (inputFile.Contains("WW_TuneZ2star_8TeV_pythia6_tauola")) ret = "WW";
if (inputFile.Contains("ZZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "ZZ";
//Z -> nu nu
if (inputFile.Contains("ZJetsToNuNu_100_HT_200_TuneZ2Star_8TeV_madgraph")) ret = "Zinv100";
if (inputFile.Contains("ZJetsToNuNu_200_HT_400_TuneZ2Star_8TeV_madgraph")) ret = "Zinv200";
if (inputFile.Contains("ZJetsToNuNu_400_HT_inf_TuneZ2Star_8TeV_madgraph")) ret = "Zinv400";
if (inputFile.Contains("ZJetsToNuNu_50_HT_100_TuneZ2Star_8TeV_madgraph")) ret = "Zinv50" ;
//LM
if (inputFile.Contains("SUSY_LM9_sftsht_8TeV")) ret = "LM9";
//ttbar
if (inputFile.Contains("TTJets") && inputFile.Contains("madgraph")) ret = "TTJetsMG" ;
if (inputFile.Contains("TTJets") && inputFile.Contains("sherpa")) ret = "TTJetsSherpa";
if (inputFile.Contains("TTJets") ) ret = "TTJets" ;
if (inputFile.Contains("TT") && inputFile.Contains("mcatnlo")) ret = "TTJets" ;
if (inputFile.Contains("TT") && inputFile.Contains("powheg")) ret = "TTJets" ;
//
if (inputFile.Contains("WH_WToLNu_HToBB_M-125_8TeV-powheg-herwigpp")) ret = "WH";
if (inputFile.Contains("ZH_ZToBB_HToBB_M-125_8TeV-powheg-herwigpp")) ret = "ZH";
if (inputFile.Contains("TTH_HToBB_M-125_8TeV-pythia6")) ret = "TTH";
if (inputFile.Contains("TTZJets_8TeV-madgraph_v2")) ret = "TTZ";
if (inputFile.Contains("TTWJets_8TeV-madgraph")) ret = "TTW";
//SMS
if (inputFile.Contains("MadGraph_T1bbbb")) ret = "T1bbbbMG";
if (inputFile.Contains("MadGraph_T1tttt")) ret = "T1ttttMG";
if (inputFile.Contains("T1bbbb")) ret = "T1bbbb" ;
if (inputFile.Contains("T1tttt")) ret = "T1tttt" ;
if (inputFile.Contains("T2tt")) ret = "T2tt" ;
if (inputFile.Contains("T2bb")) ret = "T2bb" ;
if (inputFile.Contains("T5tttt")) ret = "T5tttt" ;
if (inputFile.Contains("T1t1t")) ret = "T1t1t" ;
if (inputFile.Contains("T1ttcc")) ret = "T1ttcc" ;
if (inputFile.Contains("T7btw")) ret = "T7btw" ;
if (inputFile.Contains("TChiZH")) ret = "TChiZH" ;
if (inputFile.Contains("TChiHH")) ret = "TChiHH" ;
if (inputFile.Contains("T6bbHH")) ret = "T6bbHH" ;
if (inputFile.Contains("T6ttHH")) ret = "T6ttHH" ;
if (inputFile.Contains("T5Wh")) ret = "T5Wh" ;
if (inputFile.Contains("T5WH")) ret = "T5WH" ;
if (inputFile.Contains("T1tbbb")) ret = "T1tbbb" ;
if (inputFile.Contains("T1ttbb")) ret = "T1ttbb" ;
if (inputFile.Contains("T1tttb")) ret = "T1tttb" ;
if (inputFile.Contains("T2tb")) ret = "T2tb" ;
//pMSSM
if (inputFile.Contains("pMSSM")) {
if ( inputFile.Contains("batch1") ) ret = "pMSSM_b1";
if ( inputFile.Contains("batch2") ) ret = "pMSSM_b2";
if ( inputFile.Contains("batch3") ) ret = "pMSSM_b3";
if ( inputFile.Contains("batch4") ) ret = "pMSSM_b4";
}
if (inputFile.Contains("HbbHbb") ) ret = "hbbhbb";
if (inputFile.Contains("TChihh") ) ret = "TChihh";
//Otherwise not found--be careful..
cout << ret << endl;
return;
}
<commit_msg>add sample anmes<commit_after>
void GetSampleName( TString inputFile="") {
string ret;
ret = inputFile;
//Drell Yan
if (inputFile.Contains("DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph")) ret = "ZJets" ;
if (inputFile.Contains("DYJetsToLL_HT-200To400_TuneZ2Star_8TeV-madgraph")) ret = "ZJets200";
if (inputFile.Contains("DYJetsToLL_HT-400ToInf_TuneZ2Star_8TeV-madgraph")) ret = "ZJets400";
//Pythia QCD - all LO PREP
if (inputFile.Contains("QCD_Pt-1000to1400")) ret = "QCD1000";
if (inputFile.Contains("QCD_Pt-120to170")) ret = "QCD120" ;
if (inputFile.Contains("QCD_Pt-1400to1800")) ret = "QCD1400";
if (inputFile.Contains("QCD_Pt-170to300")) ret = "QCD170" ;
if (inputFile.Contains("QCD_Pt-1800")) ret = "QCD1800";
if (inputFile.Contains("QCD_Pt-300to470")) ret = "QCD300" ;
if (inputFile.Contains("QCD30")) ret = "QCD30" ;
if (inputFile.Contains("QCD_Pt-470to600")) ret = "QCD470" ;
if (inputFile.Contains("QCD_Pt-600to800")) ret = "QCD600" ;
if (inputFile.Contains("QCD_Pt-800to1000")) ret = "QCD800" ;
if (inputFile.Contains("QCD80")) ret = "QCD80" ;
//B-jets
if (inputFile.Contains("BJets_HT-250To500_8TeV-madgraph")) ret = "B250" ;
if (inputFile.Contains("BJets_HT-500To1000_8TeV-madgraph")) ret = "B500" ;
if (inputFile.Contains("BJets_HT-1000ToInf_8TeV-madgraph")) ret = "B1000";
//single top
if (inputFile.Contains("_tW-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
if (inputFile.Contains("_t-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_t" ;
if (inputFile.Contains("_s-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_s" ;
if (inputFile.Contains("_tW-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
if (inputFile.Contains("_t-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_t" ;
if (inputFile.Contains("_s-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_s" ;
//W+Jets
if (inputFile.Contains("WJetsToLNu_HT-400ToInf_8TeV-madgraph")) ret = "WJets400";
if (inputFile.Contains("WJetsToLNu_HT-250To300_8TeV-madgraph")) ret = "WJets250";
if (inputFile.Contains("WJetsToLNu_HT-300To400_8TeV-madgraph")) ret = "WJets300";
if (inputFile.Contains("WJetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "WJets" ;
if (inputFile.Contains("W2JetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "W2Jets" ;
if (inputFile.Contains("W3JetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "W3Jets" ;
if (inputFile.Contains("W4JetsToLNu_TuneZ2Star_8TeV-madgraph")) ret = "W4Jets" ;
if (inputFile.Contains("WbbJetsToLNu_Massive_TuneZ2star_8TeV-madgraph-pythia6_tauola")) ret = "Wbb";
//diboson
if (inputFile.Contains("WZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "WZ";
if (inputFile.Contains("WW_TuneZ2star_8TeV_pythia6_tauola")) ret = "WW";
if (inputFile.Contains("ZZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "ZZ";
//Z -> nu nu
if (inputFile.Contains("ZJetsToNuNu_100_HT_200_TuneZ2Star_8TeV_madgraph")) ret = "Zinv100";
if (inputFile.Contains("ZJetsToNuNu_200_HT_400_TuneZ2Star_8TeV_madgraph")) ret = "Zinv200";
if (inputFile.Contains("ZJetsToNuNu_400_HT_inf_TuneZ2Star_8TeV_madgraph")) ret = "Zinv400";
if (inputFile.Contains("ZJetsToNuNu_50_HT_100_TuneZ2Star_8TeV_madgraph")) ret = "Zinv50" ;
//LM
if (inputFile.Contains("SUSY_LM9_sftsht_8TeV")) ret = "LM9";
//ttbar
if (inputFile.Contains("TTJets") && inputFile.Contains("madgraph")) ret = "TTJetsMG" ;
if (inputFile.Contains("TTJets") && inputFile.Contains("sherpa")) ret = "TTJetsSherpa";
if (inputFile.Contains("TTJets") ) ret = "TTJets" ;
if (inputFile.Contains("TT") && inputFile.Contains("mcatnlo")) ret = "TTJets" ;
if (inputFile.Contains("TT") && inputFile.Contains("powheg")) ret = "TTJets" ;
//
if (inputFile.Contains("WH_WToLNu_HToBB_M-125_8TeV-powheg-herwigpp")) ret = "WH";
if (inputFile.Contains("ZH_ZToBB_HToBB_M-125_8TeV-powheg-herwigpp")) ret = "ZH";
if (inputFile.Contains("TTH_HToBB_M-125_8TeV-pythia6")) ret = "TTH";
if (inputFile.Contains("TTZJets_8TeV-madgraph_v2")) ret = "TTZ";
if (inputFile.Contains("TTWJets_8TeV-madgraph")) ret = "TTW";
//SMS
if (inputFile.Contains("MadGraph_T1bbbb")) ret = "T1bbbbMG";
if (inputFile.Contains("MadGraph_T1tttt")) ret = "T1ttttMG";
if (inputFile.Contains("T1bbbb")) ret = "T1bbbb" ;
if (inputFile.Contains("T1tttt")) ret = "T1tttt" ;
if (inputFile.Contains("T2tt")) ret = "T2tt" ;
if (inputFile.Contains("T2bb")) ret = "T2bb" ;
if (inputFile.Contains("T5tttt")) ret = "T5tttt" ;
if (inputFile.Contains("T1t1t")) ret = "T1t1t" ;
if (inputFile.Contains("T1ttcc")) ret = "T1ttcc" ;
if (inputFile.Contains("T7btw")) ret = "T7btw" ;
if (inputFile.Contains("TChiZH")) ret = "TChiZH" ;
if (inputFile.Contains("TChiHH")) ret = "TChiHH" ;
if (inputFile.Contains("T6bbHH")) ret = "T6bbHH" ;
if (inputFile.Contains("T6ttHH")) ret = "T6ttHH" ;
if (inputFile.Contains("T5Wh")) ret = "T5Wh" ;
if (inputFile.Contains("T5WH")) ret = "T5WH" ;
if (inputFile.Contains("T1tbbb")) ret = "T1tbbb" ;
if (inputFile.Contains("T1ttbb")) ret = "T1ttbb" ;
if (inputFile.Contains("T1tttb")) ret = "T1tttb" ;
if (inputFile.Contains("T2tb")) ret = "T2tb" ;
//pMSSM
if (inputFile.Contains("pMSSM")) {
if ( inputFile.Contains("batch1") ) ret = "pMSSM_b1";
if ( inputFile.Contains("batch2") ) ret = "pMSSM_b2";
if ( inputFile.Contains("batch3") ) ret = "pMSSM_b3";
if ( inputFile.Contains("batch4") ) ret = "pMSSM_b4";
}
if (inputFile.Contains("HbbHbb") ) ret = "hbbhbb";
if (inputFile.Contains("TChihh") ) ret = "TChihh";
if (inputFile.Contains("MET_Run2012A")) ret = "META";
if (inputFile.Contains("MET_Run2012B")) ret = "METB";
if (inputFile.Contains("MET_Run2012C")) ret = "METC";
if (inputFile.Contains("MET_Run2012D")) ret = "METD";
//Otherwise not found--be careful..
cout << ret << endl;
return;
}
<|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 <math.h>
#include <stdio.h> // FIXME(brettw) erase me.
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <time.h>
#include <algorithm>
#include "ppapi/c/dev/ppp_printing_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/pp_input_event.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/dev/scriptable_object_deprecated.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/var.h"
static const int kStepsPerCircle = 800;
void FlushCallback(void* data, int32_t result);
void FillRect(pp::ImageData* image, int left, int top, int width, int height,
uint32_t color) {
for (int y = std::max(0, top);
y < std::min(image->size().height() - 1, top + height);
y++) {
for (int x = std::max(0, left);
x < std::min(image->size().width() - 1, left + width);
x++)
*image->GetAddr32(pp::Point(x, y)) = color;
}
}
class MyScriptableObject : public pp::deprecated::ScriptableObject {
public:
explicit MyScriptableObject(pp::Instance* instance) : instance_(instance) {}
virtual bool HasMethod(const pp::Var& method, pp::Var* exception) {
return method.AsString() == "toString";
}
virtual bool HasProperty(const pp::Var& name, pp::Var* exception) {
if (name.is_string() && name.AsString() == "blah")
return true;
return false;
}
virtual pp::Var GetProperty(const pp::Var& name, pp::Var* exception) {
if (name.is_string() && name.AsString() == "blah")
return pp::Var(instance_, new MyScriptableObject(instance_));
return pp::Var();
}
virtual void GetAllPropertyNames(std::vector<pp::Var>* names,
pp::Var* exception) {
names->push_back("blah");
}
virtual pp::Var Call(const pp::Var& method,
const std::vector<pp::Var>& args,
pp::Var* exception) {
if (method.AsString() == "toString")
return pp::Var("hello world");
return pp::Var();
}
private:
pp::Instance* instance_;
};
class MyFetcherClient {
public:
virtual void DidFetch(bool success, const std::string& data) = 0;
};
class MyFetcher {
public:
MyFetcher() : client_(NULL) {
callback_factory_.Initialize(this);
}
void Start(const pp::Instance& instance,
const pp::Var& url,
MyFetcherClient* client) {
pp::URLRequestInfo request;
request.SetURL(url);
request.SetMethod("GET");
loader_ = pp::URLLoader(instance);
client_ = client;
pp::CompletionCallback callback =
callback_factory_.NewCallback(&MyFetcher::DidOpen);
int rv = loader_.Open(request, callback);
if (rv != PP_ERROR_WOULDBLOCK)
callback.Run(rv);
}
void StartWithOpenedLoader(const pp::URLLoader& loader,
MyFetcherClient* client) {
loader_ = loader;
client_ = client;
ReadMore();
}
private:
void ReadMore() {
pp::CompletionCallback callback =
callback_factory_.NewCallback(&MyFetcher::DidRead);
int rv = loader_.ReadResponseBody(buf_, sizeof(buf_), callback);
if (rv != PP_ERROR_WOULDBLOCK)
callback.Run(rv);
}
void DidOpen(int32_t result) {
if (result == PP_OK) {
ReadMore();
} else {
DidFinish(result);
}
}
void DidRead(int32_t result) {
if (result > 0) {
data_.append(buf_, result);
ReadMore();
} else {
DidFinish(result);
}
}
void DidFinish(int32_t result) {
if (client_)
client_->DidFetch(result == PP_OK, data_);
}
pp::CompletionCallbackFactory<MyFetcher> callback_factory_;
pp::URLLoader loader_;
MyFetcherClient* client_;
char buf_[4096];
std::string data_;
};
class MyInstance : public pp::Instance, public MyFetcherClient {
public:
MyInstance(PP_Instance instance)
: pp::Instance(instance),
time_at_last_check_(0.0),
fetcher_(NULL),
width_(0),
height_(0),
animation_counter_(0),
print_settings_valid_(false) {}
virtual ~MyInstance() {
if (fetcher_) {
delete fetcher_;
fetcher_ = NULL;
}
}
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
return true;
}
virtual bool HandleDocumentLoad(const pp::URLLoader& loader) {
fetcher_ = new MyFetcher();
fetcher_->StartWithOpenedLoader(loader, this);
return true;
}
virtual bool HandleInputEvent(const PP_InputEvent& event) {
switch (event.type) {
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
//SayHello();
return true;
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
return true;
case PP_INPUTEVENT_TYPE_KEYDOWN:
return true;
default:
return false;
}
}
virtual pp::Var GetInstanceObject() {
return pp::Var(this, new MyScriptableObject(this));
}
pp::ImageData PaintImage(int width, int height) {
pp::ImageData image(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL,
pp::Size(width, height), false);
if (image.is_null()) {
printf("Couldn't allocate the image data\n");
return image;
}
// Fill with semitransparent gradient.
for (int y = 0; y < image.size().height(); y++) {
char* row = &static_cast<char*>(image.data())[y * image.stride()];
for (int x = 0; x < image.size().width(); x++) {
row[x * 4 + 0] = y;
row[x * 4 + 1] = y;
row[x * 4 + 2] = 0;
row[x * 4 + 3] = y;
}
}
float radians = static_cast<float>(animation_counter_) / kStepsPerCircle *
2 * 3.14159265358979F;
float radius = static_cast<float>(std::min(width, height)) / 2.0f - 3.0f;
int x = static_cast<int>(cos(radians) * radius + radius + 2);
int y = static_cast<int>(sin(radians) * radius + radius + 2);
FillRect(&image, x - 3, y - 3, 7, 7, 0x80000000);
return image;
}
void Paint() {
pp::ImageData image = PaintImage(width_, height_);
if (!image.is_null()) {
device_context_.ReplaceContents(&image);
device_context_.Flush(pp::CompletionCallback(&FlushCallback, this));
}
}
virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
if (position.size().width() == width_ &&
position.size().height() == height_)
return; // We don't care about the position, only the size.
width_ = position.size().width();
height_ = position.size().height();
device_context_ = pp::Graphics2D(this, pp::Size(width_, height_), false);
if (!BindGraphics(device_context_)) {
printf("Couldn't bind the device context\n");
return;
}
Paint();
}
void UpdateFps() {
// Time code doesn't currently compile on Windows, just skip FPS for now.
#ifndef _WIN32
pp::Var window = GetWindowObject();
pp::Var doc = window.GetProperty("document");
pp::Var fps = doc.Call("getElementById", "fps");
struct timeval tv;
struct timezone tz = {0, 0};
gettimeofday(&tv, &tz);
double time_now = tv.tv_sec + tv.tv_usec / 1000000.0;
if (animation_counter_ > 0) {
char fps_text[64];
sprintf(fps_text, "%g fps",
kStepsPerCircle / (time_now - time_at_last_check_));
fps.SetProperty("innerHTML", fps_text);
}
time_at_last_check_ = time_now;
#endif
}
// Print interfaces.
virtual PP_PrintOutputFormat_Dev* QuerySupportedPrintOutputFormats(
uint32_t* format_count) {
PP_PrintOutputFormat_Dev* format =
reinterpret_cast<PP_PrintOutputFormat_Dev*>(
pp::Module::Get()->core()->MemAlloc(
sizeof(PP_PrintOutputFormat_Dev)));
*format = PP_PRINTOUTPUTFORMAT_RASTER;
*format_count = 1;
return format;
}
virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) {
if (print_settings_.format != PP_PRINTOUTPUTFORMAT_RASTER)
return 0;
print_settings_ = print_settings;
print_settings_valid_ = true;
return 1;
}
virtual pp::Resource PrintPages(
const PP_PrintPageNumberRange_Dev* page_ranges,
uint32_t page_range_count) {
if (!print_settings_valid_)
return pp::Resource();
if (page_range_count != 1)
return pp::Resource();
// Check if the page numbers are valid. We returned 1 in PrintBegin so we
// only have 1 page to print.
if (page_ranges[0].first_page_number || page_ranges[0].last_page_number) {
return pp::Resource();
}
int width = static_cast<int>(
(print_settings_.printable_area.size.width / 72.0) *
print_settings_.dpi);
int height = static_cast<int>(
(print_settings_.printable_area.size.height / 72.0) *
print_settings_.dpi);
return PaintImage(width, height);
}
virtual void PrintEnd() {
print_settings_valid_ = false;
}
void OnFlush() {
if (animation_counter_ % kStepsPerCircle == 0)
UpdateFps();
animation_counter_++;
Paint();
}
private:
void Log(const pp::Var& var) {
pp::Var doc = GetWindowObject().GetProperty("document");
if (console_.is_undefined()) {
pp::Var body = doc.GetProperty("body");
console_ = doc.Call("createElement", "pre");
console_.GetProperty("style").SetProperty("backgroundColor", "lightgray");
body.Call("appendChild", console_);
}
console_.Call("appendChild", doc.Call("createTextNode", var));
console_.Call("appendChild", doc.Call("createTextNode", "\n"));
}
void SayHello() {
pp::Var window = GetWindowObject();
pp::Var doc = window.GetProperty("document");
pp::Var body = doc.GetProperty("body");
pp::Var obj(this, new MyScriptableObject(this));
// Our object should have its toString method called.
Log("Testing MyScriptableObject::toString():");
Log(obj);
// body.appendChild(body) should throw an exception
Log("\nCalling body.appendChild(body):");
pp::Var exception;
body.Call("appendChild", body, &exception);
Log(exception);
Log("\nEnumeration of window properties:");
std::vector<pp::Var> props;
window.GetAllPropertyNames(&props);
for (size_t i = 0; i < props.size(); ++i)
Log(props[i]);
pp::Var location = window.GetProperty("location");
pp::Var href = location.GetProperty("href");
if (!fetcher_) {
fetcher_ = new MyFetcher();
fetcher_->Start(*this, href, this);
}
}
void DidFetch(bool success, const std::string& data) {
Log("\nDownloaded location.href:");
if (success) {
Log(data);
} else {
Log("Failed to download.");
}
delete fetcher_;
fetcher_ = NULL;
}
pp::Var console_;
pp::Graphics2D device_context_;
double time_at_last_check_;
MyFetcher* fetcher_;
int width_;
int height_;
// Incremented for each flush we get.
int animation_counter_;
bool print_settings_valid_;
PP_PrintSettings_Dev print_settings_;
};
void FlushCallback(void* data, int32_t result) {
static_cast<MyInstance*>(data)->OnFlush();
}
class MyModule : public pp::Module {
public:
MyModule() : pp::Module() {}
virtual ~MyModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new MyInstance(instance);
}
};
namespace pp {
// Factory function for your specialization of the Module object.
Module* CreateModule() {
return new MyModule();
}
} // namespace pp
<commit_msg>Added plugin size to error logging and a logging statement when the plugin size changes. I found these changes useful while debugging issues when modifying the plugin.<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 <math.h>
#include <stdio.h> // FIXME(brettw) erase me.
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <time.h>
#include <algorithm>
#include "ppapi/c/dev/ppp_printing_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/pp_input_event.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/dev/scriptable_object_deprecated.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/var.h"
static const int kStepsPerCircle = 800;
void FlushCallback(void* data, int32_t result);
void FillRect(pp::ImageData* image, int left, int top, int width, int height,
uint32_t color) {
for (int y = std::max(0, top);
y < std::min(image->size().height() - 1, top + height);
y++) {
for (int x = std::max(0, left);
x < std::min(image->size().width() - 1, left + width);
x++)
*image->GetAddr32(pp::Point(x, y)) = color;
}
}
class MyScriptableObject : public pp::deprecated::ScriptableObject {
public:
explicit MyScriptableObject(pp::Instance* instance) : instance_(instance) {}
virtual bool HasMethod(const pp::Var& method, pp::Var* exception) {
return method.AsString() == "toString";
}
virtual bool HasProperty(const pp::Var& name, pp::Var* exception) {
if (name.is_string() && name.AsString() == "blah")
return true;
return false;
}
virtual pp::Var GetProperty(const pp::Var& name, pp::Var* exception) {
if (name.is_string() && name.AsString() == "blah")
return pp::Var(instance_, new MyScriptableObject(instance_));
return pp::Var();
}
virtual void GetAllPropertyNames(std::vector<pp::Var>* names,
pp::Var* exception) {
names->push_back("blah");
}
virtual pp::Var Call(const pp::Var& method,
const std::vector<pp::Var>& args,
pp::Var* exception) {
if (method.AsString() == "toString")
return pp::Var("hello world");
return pp::Var();
}
private:
pp::Instance* instance_;
};
class MyFetcherClient {
public:
virtual void DidFetch(bool success, const std::string& data) = 0;
};
class MyFetcher {
public:
MyFetcher() : client_(NULL) {
callback_factory_.Initialize(this);
}
void Start(const pp::Instance& instance,
const pp::Var& url,
MyFetcherClient* client) {
pp::URLRequestInfo request;
request.SetURL(url);
request.SetMethod("GET");
loader_ = pp::URLLoader(instance);
client_ = client;
pp::CompletionCallback callback =
callback_factory_.NewCallback(&MyFetcher::DidOpen);
int rv = loader_.Open(request, callback);
if (rv != PP_ERROR_WOULDBLOCK)
callback.Run(rv);
}
void StartWithOpenedLoader(const pp::URLLoader& loader,
MyFetcherClient* client) {
loader_ = loader;
client_ = client;
ReadMore();
}
private:
void ReadMore() {
pp::CompletionCallback callback =
callback_factory_.NewCallback(&MyFetcher::DidRead);
int rv = loader_.ReadResponseBody(buf_, sizeof(buf_), callback);
if (rv != PP_ERROR_WOULDBLOCK)
callback.Run(rv);
}
void DidOpen(int32_t result) {
if (result == PP_OK) {
ReadMore();
} else {
DidFinish(result);
}
}
void DidRead(int32_t result) {
if (result > 0) {
data_.append(buf_, result);
ReadMore();
} else {
DidFinish(result);
}
}
void DidFinish(int32_t result) {
if (client_)
client_->DidFetch(result == PP_OK, data_);
}
pp::CompletionCallbackFactory<MyFetcher> callback_factory_;
pp::URLLoader loader_;
MyFetcherClient* client_;
char buf_[4096];
std::string data_;
};
class MyInstance : public pp::Instance, public MyFetcherClient {
public:
MyInstance(PP_Instance instance)
: pp::Instance(instance),
time_at_last_check_(0.0),
fetcher_(NULL),
width_(0),
height_(0),
animation_counter_(0),
print_settings_valid_(false) {}
virtual ~MyInstance() {
if (fetcher_) {
delete fetcher_;
fetcher_ = NULL;
}
}
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
return true;
}
virtual bool HandleDocumentLoad(const pp::URLLoader& loader) {
fetcher_ = new MyFetcher();
fetcher_->StartWithOpenedLoader(loader, this);
return true;
}
virtual bool HandleInputEvent(const PP_InputEvent& event) {
switch (event.type) {
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
//SayHello();
return true;
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
return true;
case PP_INPUTEVENT_TYPE_KEYDOWN:
return true;
default:
return false;
}
}
virtual pp::Var GetInstanceObject() {
return pp::Var(this, new MyScriptableObject(this));
}
pp::ImageData PaintImage(int width, int height) {
pp::ImageData image(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL,
pp::Size(width, height), false);
if (image.is_null()) {
printf("Couldn't allocate the image data: %d, %d\n", width, height);
return image;
}
// Fill with semitransparent gradient.
for (int y = 0; y < image.size().height(); y++) {
char* row = &static_cast<char*>(image.data())[y * image.stride()];
for (int x = 0; x < image.size().width(); x++) {
row[x * 4 + 0] = y;
row[x * 4 + 1] = y;
row[x * 4 + 2] = 0;
row[x * 4 + 3] = y;
}
}
// Draw the orbiting box.
float radians = static_cast<float>(animation_counter_) / kStepsPerCircle *
2 * 3.14159265358979F;
float radius = static_cast<float>(std::min(width, height)) / 2.0f - 3.0f;
int x = static_cast<int>(cos(radians) * radius + radius + 2);
int y = static_cast<int>(sin(radians) * radius + radius + 2);
const uint32_t box_bgra = 0x80000000; // Alpha 50%.
FillRect(&image, x - 3, y - 3, 7, 7, box_bgra);
return image;
}
void Paint() {
pp::ImageData image = PaintImage(width_, height_);
if (!image.is_null()) {
device_context_.ReplaceContents(&image);
device_context_.Flush(pp::CompletionCallback(&FlushCallback, this));
} else {
printf("NullImage: %d, %d\n", width_, height_);
}
}
virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
if (position.size().width() == width_ &&
position.size().height() == height_)
return; // We don't care about the position, only the size.
width_ = position.size().width();
height_ = position.size().height();
printf("DidChangeView relevant change: width=%d height:%d\n",
width_, height_);
device_context_ = pp::Graphics2D(this, pp::Size(width_, height_), false);
if (!BindGraphics(device_context_)) {
printf("Couldn't bind the device context\n");
return;
}
Paint();
}
void UpdateFps() {
// Time code doesn't currently compile on Windows, just skip FPS for now.
#ifndef _WIN32
pp::Var window = GetWindowObject();
pp::Var doc = window.GetProperty("document");
pp::Var fps = doc.Call("getElementById", "fps");
struct timeval tv;
struct timezone tz = {0, 0};
gettimeofday(&tv, &tz);
double time_now = tv.tv_sec + tv.tv_usec / 1000000.0;
if (animation_counter_ > 0) {
char fps_text[64];
sprintf(fps_text, "%g fps",
kStepsPerCircle / (time_now - time_at_last_check_));
fps.SetProperty("innerHTML", fps_text);
}
time_at_last_check_ = time_now;
#endif
}
// Print interfaces.
virtual PP_PrintOutputFormat_Dev* QuerySupportedPrintOutputFormats(
uint32_t* format_count) {
PP_PrintOutputFormat_Dev* format =
reinterpret_cast<PP_PrintOutputFormat_Dev*>(
pp::Module::Get()->core()->MemAlloc(
sizeof(PP_PrintOutputFormat_Dev)));
*format = PP_PRINTOUTPUTFORMAT_RASTER;
*format_count = 1;
return format;
}
virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) {
if (print_settings_.format != PP_PRINTOUTPUTFORMAT_RASTER)
return 0;
print_settings_ = print_settings;
print_settings_valid_ = true;
return 1;
}
virtual pp::Resource PrintPages(
const PP_PrintPageNumberRange_Dev* page_ranges,
uint32_t page_range_count) {
if (!print_settings_valid_)
return pp::Resource();
if (page_range_count != 1)
return pp::Resource();
// Check if the page numbers are valid. We returned 1 in PrintBegin so we
// only have 1 page to print.
if (page_ranges[0].first_page_number || page_ranges[0].last_page_number) {
return pp::Resource();
}
int width = static_cast<int>(
(print_settings_.printable_area.size.width / 72.0) *
print_settings_.dpi);
int height = static_cast<int>(
(print_settings_.printable_area.size.height / 72.0) *
print_settings_.dpi);
return PaintImage(width, height);
}
virtual void PrintEnd() {
print_settings_valid_ = false;
}
void OnFlush() {
if (animation_counter_ % kStepsPerCircle == 0)
UpdateFps();
animation_counter_++;
Paint();
}
private:
void Log(const pp::Var& var) {
pp::Var doc = GetWindowObject().GetProperty("document");
if (console_.is_undefined()) {
pp::Var body = doc.GetProperty("body");
console_ = doc.Call("createElement", "pre");
console_.GetProperty("style").SetProperty("backgroundColor", "lightgray");
body.Call("appendChild", console_);
}
console_.Call("appendChild", doc.Call("createTextNode", var));
console_.Call("appendChild", doc.Call("createTextNode", "\n"));
}
void SayHello() {
pp::Var window = GetWindowObject();
pp::Var doc = window.GetProperty("document");
pp::Var body = doc.GetProperty("body");
pp::Var obj(this, new MyScriptableObject(this));
// Our object should have its toString method called.
Log("Testing MyScriptableObject::toString():");
Log(obj);
// body.appendChild(body) should throw an exception
Log("\nCalling body.appendChild(body):");
pp::Var exception;
body.Call("appendChild", body, &exception);
Log(exception);
Log("\nEnumeration of window properties:");
std::vector<pp::Var> props;
window.GetAllPropertyNames(&props);
for (size_t i = 0; i < props.size(); ++i)
Log(props[i]);
pp::Var location = window.GetProperty("location");
pp::Var href = location.GetProperty("href");
if (!fetcher_) {
fetcher_ = new MyFetcher();
fetcher_->Start(*this, href, this);
}
}
void DidFetch(bool success, const std::string& data) {
Log("\nDownloaded location.href:");
if (success) {
Log(data);
} else {
Log("Failed to download.");
}
delete fetcher_;
fetcher_ = NULL;
}
pp::Var console_;
pp::Graphics2D device_context_;
double time_at_last_check_;
MyFetcher* fetcher_;
int width_;
int height_;
// Incremented for each flush we get.
int animation_counter_;
bool print_settings_valid_;
PP_PrintSettings_Dev print_settings_;
};
void FlushCallback(void* data, int32_t result) {
static_cast<MyInstance*>(data)->OnFlush();
}
class MyModule : public pp::Module {
public:
MyModule() : pp::Module() {}
virtual ~MyModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new MyInstance(instance);
}
};
namespace pp {
// Factory function for your specialization of the Module object.
Module* CreateModule() {
return new MyModule();
}
} // namespace pp
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "CustomWeapon.h"
/* system headers */
#include <sstream>
#include <string>
#include <math.h>
/* local implementation headers */
#include "WorldWeapons.h"
#include "TextUtils.h"
TimeKeeper CustomWeapon::sync = TimeKeeper::getCurrent();
const float CustomWeapon::minWeaponDelay = 0.1f;
CustomWeapon::CustomWeapon()
{
pos[0] = pos[1] = pos[2] = 0.0f;
rotation = 0.0f;
size[0] = size[1] = size[2] = 1.0f;
tilt = 0.0f;
initdelay = 10.0f;
delay.push_back(10.0f);
type = Flags::Null;
triggerType = eNullEvent;
eventTeam = -1;
}
bool CustomWeapon::read(const char *cmd, std::istream& input) {
if (strcmp(cmd, "initdelay") == 0) {
input >> initdelay;
}
else if (strcmp(cmd, "delay") == 0) {
std::string args;
float d;
delay.clear();
std::getline(input, args);
std::istringstream parms(args);
while (parms >> d) {
if (d < minWeaponDelay) {
std::cout << "skipping weapon delay of " << d << " seconds" << std::endl;
continue;
}
else {
delay.push_back(d);
}
}
input.putback('\n');
if (delay.size() == 0)
return false;
}
else if (strcmp(cmd, "type") == 0) {
std::string abbv;
input >> abbv;
type = Flag::getDescFromAbbreviation(abbv.c_str());
if (type == NULL)
return false;
}
else if (strcmp(cmd, "tilt") == 0) {
if (!(input >> tilt)) {
std::cout << "weapon tilt requires a value" << std::endl;
}
// convert to radians
tilt = (float)(tilt * (M_PI / 180.0));
}
else if (strcmp(cmd, "trigger") == 0)
{
std::string triggerType;
input >> triggerType;
triggerType = eNullEvent;
TextUtils::tolower(triggerType);
if ( triggerType == "oncap")
triggerType = eCaptureEvent;
else if ( triggerType == "onspawn")
triggerType = ePlayerSpawnEvent;
else if ( triggerType == "ondie")
triggerType = ePlayerDieEvent;
else
{
std::cout << "weapon trigger type:" << triggerType << " unknown" << std::endl;
}
}
else if (strcmp(cmd, "eventteam") == 0)
{
input >> eventTeam;
}
else if (!WorldFileLocation::read(cmd, input)) {
return false;
}
return true;
}
void CustomWeapon::writeToWorld(WorldInfo* world) const
{
if (triggerType == eNullEvent)
world->addWeapon(type, pos, rotation, tilt, initdelay, delay, sync);
else
worldEventManager.addEvent(triggerType,eventTeam,new WorldWeaponGlobalEventHandaler(type, pos, rotation, tilt));
}
// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>names names names<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "CustomWeapon.h"
/* system headers */
#include <sstream>
#include <string>
#include <math.h>
/* local implementation headers */
#include "WorldWeapons.h"
#include "TextUtils.h"
TimeKeeper CustomWeapon::sync = TimeKeeper::getCurrent();
const float CustomWeapon::minWeaponDelay = 0.1f;
CustomWeapon::CustomWeapon()
{
pos[0] = pos[1] = pos[2] = 0.0f;
rotation = 0.0f;
size[0] = size[1] = size[2] = 1.0f;
tilt = 0.0f;
initdelay = 10.0f;
delay.push_back(10.0f);
type = Flags::Null;
triggerType = eNullEvent;
eventTeam = -1;
}
bool CustomWeapon::read(const char *cmd, std::istream& input) {
if (strcmp(cmd, "initdelay") == 0) {
input >> initdelay;
}
else if (strcmp(cmd, "delay") == 0) {
std::string args;
float d;
delay.clear();
std::getline(input, args);
std::istringstream parms(args);
while (parms >> d) {
if (d < minWeaponDelay) {
std::cout << "skipping weapon delay of " << d << " seconds" << std::endl;
continue;
}
else {
delay.push_back(d);
}
}
input.putback('\n');
if (delay.size() == 0)
return false;
}
else if (strcmp(cmd, "type") == 0) {
std::string abbv;
input >> abbv;
type = Flag::getDescFromAbbreviation(abbv.c_str());
if (type == NULL)
return false;
}
else if (strcmp(cmd, "tilt") == 0) {
if (!(input >> tilt)) {
std::cout << "weapon tilt requires a value" << std::endl;
}
// convert to radians
tilt = (float)(tilt * (M_PI / 180.0));
}
else if (strcmp(cmd, "trigger") == 0)
{
std::string triggerName;
input >> triggerName;
triggerType = eNullEvent;
TextUtils::tolower(triggerName);
if ( triggerName == "oncap")
triggerType = eCaptureEvent;
else if ( triggerName == "onspawn")
triggerType = ePlayerSpawnEvent;
else if ( triggerName == "ondie")
triggerType = ePlayerDieEvent;
else
{
std::cout << "weapon trigger type:" << triggerName << " unknown" << std::endl;
}
}
else if (strcmp(cmd, "eventteam") == 0)
{
input >> eventTeam;
}
else if (!WorldFileLocation::read(cmd, input)) {
return false;
}
return true;
}
void CustomWeapon::writeToWorld(WorldInfo* world) const
{
if (triggerType == eNullEvent)
world->addWeapon(type, pos, rotation, tilt, initdelay, delay, sync);
else
worldEventManager.addEvent(triggerType,eventTeam,new WorldWeaponGlobalEventHandaler(type, pos, rotation, tilt));
}
// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>
#include "NNSound.h"
#include "NNApplication.h"
wchar_t* GetFileExtenstion (const wchar_t * file_name)
{
wchar_t* _file_name;
wcscpy_s(_file_name, wcslen(file_name), file_name);
int file_name_len = wcslen (_file_name);
_file_name +=file_name_len ;
wchar_t *file_ext ;
for(int i =0 ; i <file_name_len ; i ++)
{
if(* _file_name == '.' )
{
file_ext = _file_name +1 ;
break;
}
_file_name --;
}
return file_ext ;
}
NNSound::NNSound()
: m_Playing(false)
{
}
NNSound::~NNSound()
{
Destroy();
}
void NNSound::Create( std::wstring path )
{
MCI_OPEN_PARMS mciOpen = {0};
MCIERROR mciError = {0};
if(wcscmp(GetFileExtenstion(path.c_str()), L"mp3") == 0 )
{
//mp3
mciOpen.lpstrDeviceType = L"MPEGVideo";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
}
else if(wcscmp(GetFileExtenstion(path.c_str()), L"wav") == 0 )
{
mciOpen.lpstrDeviceType = L"waveaudio";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
}
mciOpen.lpstrElementName = path.c_str();
mciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );
if ( mciError )
{
return;
}
m_MciDevice = mciOpen.wDeviceID;
m_Playing = false;
}
void NNSound::Destroy()
{
if ( m_Playing )
{
Stop();
}
if ( m_MciDevice )
{
mciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );
}
}
void NNSound::Play()
{
if ( !m_MciDevice )
{
return;
}
MCI_PLAY_PARMS mciPlay = {0};
MCIERROR mciError = {0};
mciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();
mciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );
if ( !mciError )
{
m_Playing = true;
}
}
void NNSound::Pause()
{
if ( !m_MciDevice )
{
return;
}
mciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );
}
void NNSound::Resume()
{
if ( !m_MciDevice )
{
return;
}
mciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );
}
void NNSound::Stop()
{
if ( !m_MciDevice )
{
return;
}
mciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );
m_Playing = false;
}
<commit_msg>mp3, wav 재생 함수 에러 수정<commit_after>
#include "NNSound.h"
#include "NNApplication.h"
wchar_t* GetFileExtenstion (const wchar_t * file_name)
{
wchar_t* _file_name = nullptr;
_file_name = (wchar_t*)malloc(1024);
wcscpy_s(_file_name, 256, file_name);
int file_name_len = wcslen (_file_name);
_file_name +=file_name_len ;
wchar_t *file_ext = nullptr;
for(int i =0 ; i <file_name_len ; i ++)
{
if(* _file_name == '.' )
{
file_ext = _file_name +1 ;
break;
}
_file_name --;
}
return file_ext ;
}
NNSound::NNSound()
: m_Playing(false)
{
}
NNSound::~NNSound()
{
Destroy();
}
void NNSound::Create( std::wstring path )
{
MCI_OPEN_PARMS mciOpen = {0};
MCIERROR mciError = {0};
if(wcscmp(GetFileExtenstion(path.c_str()), L"mp3") == 0 )
{
//mp3
mciOpen.lpstrDeviceType = L"MPEGVideo";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
}
else if(wcscmp(GetFileExtenstion(path.c_str()), L"wav") == 0 )
{
mciOpen.lpstrDeviceType = L"waveaudio";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
}
mciOpen.lpstrElementName = path.c_str();
mciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );
if ( mciError )
{
return;
}
m_MciDevice = mciOpen.wDeviceID;
m_Playing = false;
}
void NNSound::Destroy()
{
if ( m_Playing )
{
Stop();
}
if ( m_MciDevice )
{
mciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );
}
}
void NNSound::Play()
{
if ( !m_MciDevice )
{
return;
}
MCI_PLAY_PARMS mciPlay = {0};
MCIERROR mciError = {0};
mciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();
mciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );
if ( !mciError )
{
m_Playing = true;
}
}
void NNSound::Pause()
{
if ( !m_MciDevice )
{
return;
}
mciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );
}
void NNSound::Resume()
{
if ( !m_MciDevice )
{
return;
}
mciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );
}
void NNSound::Stop()
{
if ( !m_MciDevice )
{
return;
}
mciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );
m_Playing = false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "voyager/core/tcp_monitor.h"
#include "voyager/util/logging.h"
namespace voyager {
TcpMonitor::TcpMonitor(int max_all_connections, int max_ip_connections)
: kMaxAllConnections(max_all_connections),
kMaxIpConnections(max_ip_connections) {}
TcpMonitor::~TcpMonitor() {}
bool TcpMonitor::OnConnection(const TcpConnectionPtr& p) {
bool result = true;
const std::string& ip = p->PeerSockAddr().Ip();
mutex_.lock();
if (++counter_ > kMaxAllConnections) {
result = false;
VOYAGER_LOG(WARN) << "the all connection size is " << counter_
<< ", more than " << kMaxAllConnections
<< ", so force to close it.";
} else {
auto it = ip_counter_.find(ip);
if (it != ip_counter_.end()) {
if (++(it->second) > kMaxIpConnections) {
VOYAGER_LOG(WARN) << "the connection size of ip=" << ip << " is "
<< it->second << ", more than " << kMaxIpConnections
<< ", so force to close it.";
result = false;
}
} else {
ip_counter_.insert(std::make_pair(ip, 1));
}
}
mutex_.unlock();
if (!result) {
p->ForceClose();
}
return result;
}
void TcpMonitor::OnClose(const TcpConnectionPtr& p) {
const std::string& ip = p->PeerSockAddr().Ip();
std::lock_guard<std::mutex> lock(mutex_);
auto it = ip_counter_.find(ip);
if (it != ip_counter_.end()) {
if (--(it->second) <= 0) {
ip_counter_.erase(it);
}
}
--counter_;
}
} // namespace voyager
<commit_msg>fix bug, init the counter in tcp monitor<commit_after>// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "voyager/core/tcp_monitor.h"
#include "voyager/util/logging.h"
namespace voyager {
TcpMonitor::TcpMonitor(int max_all_connections, int max_ip_connections)
: kMaxAllConnections(max_all_connections),
kMaxIpConnections(max_ip_connections),
counter_(0) {}
TcpMonitor::~TcpMonitor() {}
bool TcpMonitor::OnConnection(const TcpConnectionPtr& p) {
bool result = true;
const std::string& ip = p->PeerSockAddr().Ip();
mutex_.lock();
if (++counter_ > kMaxAllConnections) {
result = false;
VOYAGER_LOG(WARN) << "the all connection size is " << counter_
<< ", more than " << kMaxAllConnections
<< ", so force to close it.";
} else {
auto it = ip_counter_.find(ip);
if (it != ip_counter_.end()) {
if (++(it->second) > kMaxIpConnections) {
VOYAGER_LOG(WARN) << "the connection size of ip=" << ip << " is "
<< it->second << ", more than " << kMaxIpConnections
<< ", so force to close it.";
result = false;
}
} else {
ip_counter_.insert(std::make_pair(ip, 1));
}
}
mutex_.unlock();
if (!result) {
p->ForceClose();
}
return result;
}
void TcpMonitor::OnClose(const TcpConnectionPtr& p) {
const std::string& ip = p->PeerSockAddr().Ip();
std::lock_guard<std::mutex> lock(mutex_);
auto it = ip_counter_.find(ip);
if (it != ip_counter_.end()) {
if (--(it->second) <= 0) {
ip_counter_.erase(it);
}
}
--counter_;
}
} // namespace voyager
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ContentInfo.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-20 06:14:03 $
*
* 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 _CONTENT_INFO_HXX_
#define _CONTENT_INFO_HXX_
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEl_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#include <ZipPackageFolder.hxx>
#endif
#ifndef _ZIP_PACKAGE_STREAM_HXX
#include <ZipPackageStream.hxx>
#endif
namespace com { namespace sun { namespace star { namespace packages {
class ContentInfo : public cppu::OWeakObject
{
public:
com::sun::star::uno::Reference < com::sun::star::lang::XUnoTunnel > xTunnel;
bool bFolder;
union
{
ZipPackageFolder *pFolder;
ZipPackageStream *pStream;
};
ContentInfo ( ZipPackageStream * pNewStream )
: xTunnel ( pNewStream )
, bFolder ( false )
, pStream ( pNewStream )
{
}
ContentInfo ( ZipPackageFolder * pNewFolder )
: xTunnel ( pNewFolder )
, bFolder ( true )
, pFolder ( pNewFolder )
{
}
virtual ~ContentInfo ()
{
if ( bFolder )
pFolder->releaseUpwardRef();
else
pStream->clearParent();
}
};
} } } }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.66); FILE MERGED 2008/04/01 12:32:14 thb 1.8.66.2: #i85898# Stripping all external header guards 2008/03/31 16:19:09 rt 1.8.66.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: ContentInfo.hxx,v $
* $Revision: 1.9 $
*
* 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 _CONTENT_INFO_HXX_
#define _CONTENT_INFO_HXX_
#include <com/sun/star/container/XNameContainer.hpp>
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEl_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#include <ZipPackageFolder.hxx>
#include <ZipPackageStream.hxx>
namespace com { namespace sun { namespace star { namespace packages {
class ContentInfo : public cppu::OWeakObject
{
public:
com::sun::star::uno::Reference < com::sun::star::lang::XUnoTunnel > xTunnel;
bool bFolder;
union
{
ZipPackageFolder *pFolder;
ZipPackageStream *pStream;
};
ContentInfo ( ZipPackageStream * pNewStream )
: xTunnel ( pNewStream )
, bFolder ( false )
, pStream ( pNewStream )
{
}
ContentInfo ( ZipPackageFolder * pNewFolder )
: xTunnel ( pNewFolder )
, bFolder ( true )
, pFolder ( pNewFolder )
{
}
virtual ~ContentInfo ()
{
if ( bFolder )
pFolder->releaseUpwardRef();
else
pStream->clearParent();
}
};
} } } }
#endif
<|endoftext|> |
<commit_before>//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
#include <string>
namespace clang {
namespace tooling {
namespace {
/// Takes an ast consumer and returns it from CreateASTConsumer. This only
/// works with single translation unit compilations.
class TestAction : public clang::ASTFrontendAction {
public:
/// Takes ownership of TestConsumer.
explicit TestAction(clang::ASTConsumer *TestConsumer)
: TestConsumer(TestConsumer) {}
protected:
virtual clang::ASTConsumer* CreateASTConsumer(
clang::CompilerInstance& compiler, StringRef dummy) {
/// TestConsumer will be deleted by the framework calling us.
return TestConsumer;
}
private:
clang::ASTConsumer * const TestConsumer;
};
class FindTopLevelDeclConsumer : public clang::ASTConsumer {
public:
explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
: FoundTopLevelDecl(FoundTopLevelDecl) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) {
*FoundTopLevelDecl = true;
return true;
}
private:
bool * const FoundTopLevelDecl;
};
} // end namespace
TEST(runToolOnCode, FindsTopLevelDeclOnEmptyCode) {
bool FoundTopLevelDecl = false;
EXPECT_TRUE(runToolOnCode(
new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), ""));
EXPECT_TRUE(FoundTopLevelDecl);
}
namespace {
class FindClassDeclXConsumer : public clang::ASTConsumer {
public:
FindClassDeclXConsumer(bool *FoundClassDeclX)
: FoundClassDeclX(FoundClassDeclX) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
*GroupRef.begin())) {
if (Record->getName() == "X") {
*FoundClassDeclX = true;
}
}
return true;
}
private:
bool *FoundClassDeclX;
};
} // end namespace
TEST(runToolOnCode, FindsClassDecl) {
bool FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;"));
EXPECT_TRUE(FoundClassDeclX);
FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;"));
EXPECT_FALSE(FoundClassDeclX);
}
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
llvm::OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory<SyntaxOnlyAction>());
llvm::OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
struct IndependentFrontendActionCreator {
FrontendAction *newFrontendAction() { return new SyntaxOnlyAction; }
};
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
IndependentFrontendActionCreator Creator;
llvm::OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Creator));
llvm::OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
TEST(ToolInvocation, TestMapVirtualFile) {
clang::FileManager Files((clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, &Files);
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
EXPECT_TRUE(Invocation.run());
}
} // end namespace tooling
} // end namespace clang
<commit_msg>#ifdef out a broken test on win32<commit_after>//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
#include <string>
namespace clang {
namespace tooling {
namespace {
/// Takes an ast consumer and returns it from CreateASTConsumer. This only
/// works with single translation unit compilations.
class TestAction : public clang::ASTFrontendAction {
public:
/// Takes ownership of TestConsumer.
explicit TestAction(clang::ASTConsumer *TestConsumer)
: TestConsumer(TestConsumer) {}
protected:
virtual clang::ASTConsumer* CreateASTConsumer(
clang::CompilerInstance& compiler, StringRef dummy) {
/// TestConsumer will be deleted by the framework calling us.
return TestConsumer;
}
private:
clang::ASTConsumer * const TestConsumer;
};
class FindTopLevelDeclConsumer : public clang::ASTConsumer {
public:
explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
: FoundTopLevelDecl(FoundTopLevelDecl) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) {
*FoundTopLevelDecl = true;
return true;
}
private:
bool * const FoundTopLevelDecl;
};
} // end namespace
TEST(runToolOnCode, FindsTopLevelDeclOnEmptyCode) {
bool FoundTopLevelDecl = false;
EXPECT_TRUE(runToolOnCode(
new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), ""));
EXPECT_TRUE(FoundTopLevelDecl);
}
namespace {
class FindClassDeclXConsumer : public clang::ASTConsumer {
public:
FindClassDeclXConsumer(bool *FoundClassDeclX)
: FoundClassDeclX(FoundClassDeclX) {}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
*GroupRef.begin())) {
if (Record->getName() == "X") {
*FoundClassDeclX = true;
}
}
return true;
}
private:
bool *FoundClassDeclX;
};
} // end namespace
TEST(runToolOnCode, FindsClassDecl) {
bool FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;"));
EXPECT_TRUE(FoundClassDeclX);
FoundClassDeclX = false;
EXPECT_TRUE(runToolOnCode(new TestAction(
new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;"));
EXPECT_FALSE(FoundClassDeclX);
}
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
llvm::OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory<SyntaxOnlyAction>());
llvm::OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
struct IndependentFrontendActionCreator {
FrontendAction *newFrontendAction() { return new SyntaxOnlyAction; }
};
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
IndependentFrontendActionCreator Creator;
llvm::OwningPtr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Creator));
llvm::OwningPtr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != NULL);
}
#ifndef LLVM_ON_WIN32
// This test breaks on Windows.
TEST(ToolInvocation, TestMapVirtualFile) {
clang::FileManager Files((clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, &Files);
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
EXPECT_TRUE(Invocation.run());
}
#endif
} // end namespace tooling
} // end namespace clang
<|endoftext|> |
<commit_before>#include <stan/prob/distributions/univariate/discrete/neg_binomial.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
TEST(ProbDistributionsNegBinomial, error_check) {
boost::random::mt19937 rng;
EXPECT_NO_THROW(stan::prob::neg_binomial_rng(6, 2, rng));
EXPECT_NO_THROW(stan::prob::neg_binomial_rng(0.5,1,rng));
EXPECT_THROW(stan::prob::neg_binomial_rng(0, 2, rng),std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(-6, 2, rng),std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(6, -2, rng),std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(stan::math::positive_infinity(), 2,
rng),
std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(6,stan::math::positive_infinity(),
rng),
std::domain_error);
}
TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
int N = 1000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::negative_binomial_distribution<>dist (5,0.6);
boost::math::chi_squared mydist(K-1);
int loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = i - 1;
int count = 0;
double bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N * pdf(dist, i);
}
expect[K-1] = N * (1 - cdf(dist, K - 1));
while (count < N) {
int a = stan::prob::neg_binomial_rng(5, 0.6/(1-0.6), rng);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest2) {
boost::random::mt19937 rng;
int N = 1000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::negative_binomial_distribution<>dist (2.4,0.6);
boost::math::chi_squared mydist(K-1);
int loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = i - 1;
int count = 0;
double bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N * pdf(dist, i);
}
expect[K-1] = N * (1 - cdf(dist, K - 1));
while (count < N) {
int a = stan::prob::neg_binomial_rng(2.4, 0.6/(1-0.6), rng);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest3) {
boost::random::mt19937 rng;
int N = 1000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::negative_binomial_distribution<>dist (0.4,0.6);
boost::math::chi_squared mydist(K-1);
int loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = i - 1;
int count = 0;
double bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N * pdf(dist, i);
}
expect[K-1] = N * (1 - cdf(dist, K - 1));
while (count < N) {
int a = stan::prob::neg_binomial_rng(0.4, 0.6/(1-0.6), rng);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<commit_msg>fully specifying call to boost::math::pdf<commit_after>#include <stan/prob/distributions/univariate/discrete/neg_binomial.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
TEST(ProbDistributionsNegBinomial, error_check) {
boost::random::mt19937 rng;
EXPECT_NO_THROW(stan::prob::neg_binomial_rng(6, 2, rng));
EXPECT_NO_THROW(stan::prob::neg_binomial_rng(0.5,1,rng));
EXPECT_THROW(stan::prob::neg_binomial_rng(0, 2, rng),std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(-6, 2, rng),std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(6, -2, rng),std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(stan::math::positive_infinity(), 2,
rng),
std::domain_error);
EXPECT_THROW(stan::prob::neg_binomial_rng(6,stan::math::positive_infinity(),
rng),
std::domain_error);
}
TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest) {
boost::random::mt19937 rng;
int N = 1000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::negative_binomial_distribution<>dist (5,0.6);
boost::math::chi_squared mydist(K-1);
int loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = i - 1;
int count = 0;
double bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N * boost::math::pdf(dist, i);
}
expect[K-1] = N * (1 - cdf(dist, K - 1));
while (count < N) {
int a = stan::prob::neg_binomial_rng(5, 0.6/(1-0.6), rng);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest2) {
boost::random::mt19937 rng;
int N = 1000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::negative_binomial_distribution<>dist (2.4,0.6);
boost::math::chi_squared mydist(K-1);
int loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = i - 1;
int count = 0;
double bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N * pdf(dist, i);
}
expect[K-1] = N * (1 - cdf(dist, K - 1));
while (count < N) {
int a = stan::prob::neg_binomial_rng(2.4, 0.6/(1-0.6), rng);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest3) {
boost::random::mt19937 rng;
int N = 1000;
int K = boost::math::round(2 * std::pow(N, 0.4));
boost::math::negative_binomial_distribution<>dist (0.4,0.6);
boost::math::chi_squared mydist(K-1);
int loc[K - 1];
for(int i = 1; i < K; i++)
loc[i - 1] = i - 1;
int count = 0;
double bin [K];
double expect [K];
for(int i = 0 ; i < K; i++) {
bin[i] = 0;
expect[i] = N * boost::math::pdf(dist, i);
}
expect[K-1] = N * (1 - cdf(dist, K - 1));
while (count < N) {
int a = stan::prob::neg_binomial_rng(0.4, 0.6/(1-0.6), rng);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
<|endoftext|> |
<commit_before>/*
* ThreadPool.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 08.02.09.
* code under LGPL
*
*/
#include <SDL_thread.h>
#include "ThreadPool.h"
#include "Debug.h"
static const unsigned int THREADNUM = 20;
ThreadPool::ThreadPool() {
nextFunc = NULL; nextParam = NULL; nextData = NULL;
mutex = SDL_CreateMutex();
awakeThread = SDL_CreateCond();
threadStartedWork = SDL_CreateCond();
threadFinishedWork = SDL_CreateCond();
notes << "ThreadPool: creating " << THREADNUM << " threads ..." << endl;
while(availableThreads.size() < THREADNUM)
prepareNewThread();
}
ThreadPool::~ThreadPool() {
SDL_mutexP(mutex);
while(usedThreads.size() > 0) {
warnings << "ThreadPool: waiting for " << usedThreads.size() << " threads to finish:" << endl;
for(std::set<ThreadPoolItem*>::iterator i = usedThreads.begin(); i != usedThreads.end(); ++i) {
if((*i)->working && (*i)->finished) {
warnings << "thread " << (*i)->name << " is ready but was not cleaned up" << endl;
SDL_CondSignal((*i)->readyForNewWork);
}
else if((*i)->working && !(*i)->finished) {
warnings << "thread " << (*i)->name << " is still working" << endl;
}
else {
warnings << "thread " << (*i)->name << " is in an invalid state" << endl;
}
}
SDL_CondWait(threadFinishedWork, mutex);
}
SDL_mutexV(mutex);
nextFunc = NULL;
SDL_CondBroadcast(awakeThread);
for(std::set<ThreadPoolItem*>::iterator i = availableThreads.begin(); i != availableThreads.end(); ++i) {
SDL_WaitThread((*i)->thread, NULL);
SDL_DestroyCond((*i)->finishedSignal);
SDL_DestroyCond((*i)->readyForNewWork);
delete *i;
}
availableThreads.clear();
SDL_DestroyCond(threadStartedWork);
SDL_DestroyCond(threadFinishedWork);
SDL_DestroyCond(awakeThread);
SDL_DestroyMutex(mutex);
}
void ThreadPool::prepareNewThread() {
ThreadPoolItem* t = new ThreadPoolItem();
t->pool = this;
t->finishedSignal = SDL_CreateCond();
t->readyForNewWork = SDL_CreateCond();
t->finished = false;
t->working = false;
availableThreads.insert(t);
t->thread = SDL_CreateThread(threadWrapper, t);
}
int ThreadPool::threadWrapper(void* param) {
ThreadPoolItem* data = (ThreadPoolItem*)param;
SDL_mutexP(data->pool->mutex);
while(true) {
SDL_CondWait(data->pool->awakeThread, data->pool->mutex);
if(data->pool->nextFunc == NULL) break;
data->pool->usedThreads.insert(data);
data->pool->availableThreads.erase(data);
ThreadFunc func = data->pool->nextFunc; data->pool->nextFunc = NULL;
void* param = data->pool->nextParam; data->pool->nextParam = NULL;
data->name = data->pool->nextName;
data->finished = false;
data->working = true;
data->pool->nextData = data;
SDL_mutexV(data->pool->mutex);
SDL_CondSignal(data->pool->threadStartedWork);
data->ret = (*func) (param);
data->finished = true;
SDL_CondSignal(data->finishedSignal);
SDL_CondSignal(data->pool->threadFinishedWork);
SDL_mutexP(data->pool->mutex);
while(data->working) SDL_CondWait(data->readyForNewWork, data->pool->mutex);
data->pool->usedThreads.erase(data);
data->pool->availableThreads.insert(data);
}
SDL_mutexV(data->pool->mutex);
return 0;
}
ThreadPoolItem* ThreadPool::start(ThreadFunc fct, void* param, const std::string& name) {
SDL_mutexP(mutex);
if(availableThreads.size() == 0) {
warnings << "no available thread in ThreadPool for " << name << ", creating new one..." << endl;
prepareNewThread();
}
assert(nextFunc == NULL);
nextFunc = fct;
nextParam = param;
nextName = name;
assert(nextData == NULL);
SDL_mutexV(mutex);
SDL_CondSignal(awakeThread);
SDL_mutexP(mutex);
while(nextData == NULL) SDL_CondWait(threadStartedWork, mutex);
ThreadPoolItem* data = nextData; nextData = NULL;
SDL_mutexV(mutex);
return data;
}
bool ThreadPool::wait(ThreadPoolItem* thread, int* status) {
if(!thread) return false;
SDL_mutexP(mutex);
if(!thread->working) {
warnings << "given thread " << thread->name << " is not working anymore" << endl;
SDL_mutexV(mutex);
return false;
}
while(!thread->finished) SDL_CondWait(thread->finishedSignal, mutex);
if(status) *status = thread->ret;
thread->working = false;
SDL_mutexV(mutex);
SDL_CondSignal(thread->readyForNewWork);
return true;
}
ThreadPool* threadPool = NULL;
void InitThreadPool() {
threadPool = new ThreadPool();
}
void UnInitThreadPool() {
delete threadPool;
threadPool = NULL;
}
<commit_msg>fixed one possible thread block<commit_after>/*
* ThreadPool.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 08.02.09.
* code under LGPL
*
*/
#include <SDL_thread.h>
#include "ThreadPool.h"
#include "Debug.h"
static const unsigned int THREADNUM = 20;
ThreadPool::ThreadPool() {
nextFunc = NULL; nextParam = NULL; nextData = NULL;
mutex = SDL_CreateMutex();
awakeThread = SDL_CreateCond();
threadStartedWork = SDL_CreateCond();
threadFinishedWork = SDL_CreateCond();
notes << "ThreadPool: creating " << THREADNUM << " threads ..." << endl;
while(availableThreads.size() < THREADNUM)
prepareNewThread();
}
ThreadPool::~ThreadPool() {
SDL_mutexP(mutex);
while(usedThreads.size() > 0) {
warnings << "ThreadPool: waiting for " << usedThreads.size() << " threads to finish:" << endl;
for(std::set<ThreadPoolItem*>::iterator i = usedThreads.begin(); i != usedThreads.end(); ++i) {
if((*i)->working && (*i)->finished) {
warnings << "thread " << (*i)->name << " is ready but was not cleaned up" << endl;
SDL_CondSignal((*i)->readyForNewWork);
}
else if((*i)->working && !(*i)->finished) {
warnings << "thread " << (*i)->name << " is still working" << endl;
}
else {
warnings << "thread " << (*i)->name << " is in an invalid state" << endl;
}
}
SDL_CondWait(threadFinishedWork, mutex);
}
SDL_mutexV(mutex);
nextFunc = NULL;
SDL_CondBroadcast(awakeThread);
for(std::set<ThreadPoolItem*>::iterator i = availableThreads.begin(); i != availableThreads.end(); ++i) {
SDL_WaitThread((*i)->thread, NULL);
SDL_DestroyCond((*i)->finishedSignal);
SDL_DestroyCond((*i)->readyForNewWork);
delete *i;
}
availableThreads.clear();
SDL_DestroyCond(threadStartedWork);
SDL_DestroyCond(threadFinishedWork);
SDL_DestroyCond(awakeThread);
SDL_DestroyMutex(mutex);
}
void ThreadPool::prepareNewThread() {
ThreadPoolItem* t = new ThreadPoolItem();
t->pool = this;
t->finishedSignal = SDL_CreateCond();
t->readyForNewWork = SDL_CreateCond();
t->finished = false;
t->working = false;
availableThreads.insert(t);
t->thread = SDL_CreateThread(threadWrapper, t);
}
int ThreadPool::threadWrapper(void* param) {
ThreadPoolItem* data = (ThreadPoolItem*)param;
SDL_mutexP(data->pool->mutex);
while(true) {
SDL_CondWait(data->pool->awakeThread, data->pool->mutex);
if(data->pool->nextFunc == NULL) break;
data->pool->usedThreads.insert(data);
data->pool->availableThreads.erase(data);
ThreadFunc func = data->pool->nextFunc; data->pool->nextFunc = NULL;
void* param = data->pool->nextParam; data->pool->nextParam = NULL;
data->name = data->pool->nextName;
data->finished = false;
data->working = true;
data->pool->nextData = data;
SDL_mutexV(data->pool->mutex);
SDL_CondSignal(data->pool->threadStartedWork);
data->ret = (*func) (param);
SDL_mutexP(data->pool->mutex);
data->finished = true;
SDL_mutexV(data->pool->mutex);
SDL_CondSignal(data->finishedSignal);
SDL_CondSignal(data->pool->threadFinishedWork);
SDL_mutexP(data->pool->mutex);
while(data->working) SDL_CondWait(data->readyForNewWork, data->pool->mutex);
data->pool->usedThreads.erase(data);
data->pool->availableThreads.insert(data);
}
SDL_mutexV(data->pool->mutex);
return 0;
}
ThreadPoolItem* ThreadPool::start(ThreadFunc fct, void* param, const std::string& name) {
SDL_mutexP(mutex);
if(availableThreads.size() == 0) {
warnings << "no available thread in ThreadPool for " << name << ", creating new one..." << endl;
prepareNewThread();
}
assert(nextFunc == NULL);
nextFunc = fct;
nextParam = param;
nextName = name;
assert(nextData == NULL);
SDL_mutexV(mutex);
SDL_CondSignal(awakeThread);
SDL_mutexP(mutex);
while(nextData == NULL) SDL_CondWait(threadStartedWork, mutex);
ThreadPoolItem* data = nextData; nextData = NULL;
SDL_mutexV(mutex);
return data;
}
bool ThreadPool::wait(ThreadPoolItem* thread, int* status) {
if(!thread) return false;
SDL_mutexP(mutex);
if(!thread->working) {
warnings << "given thread " << thread->name << " is not working anymore" << endl;
SDL_mutexV(mutex);
return false;
}
while(!thread->finished) SDL_CondWait(thread->finishedSignal, mutex);
if(status) *status = thread->ret;
thread->working = false;
SDL_mutexV(mutex);
SDL_CondSignal(thread->readyForNewWork);
return true;
}
ThreadPool* threadPool = NULL;
void InitThreadPool() {
threadPool = new ThreadPool();
}
void UnInitThreadPool() {
delete threadPool;
threadPool = NULL;
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file PositionControl.hpp
*
* A cascaded position controller for position/velocity control only.
*/
#include <matrix/matrix/math.hpp>
#include <uORB/topics/vehicle_local_position.h>
#include <uORB/topics/vehicle_local_position_setpoint.h>
#include <parameters/param.h>
#pragma once
namespace Controller
{
/** Constraints that depends on mode and are lower
* than the global limits.
* tilt_max: Cannot exceed PI/2 radians
* vel_max_z_up: Cannot exceed maximum global velocity upwards
* @see MPC_TILTMAX_AIR
* @see MPC_Z_VEL_MAX_DN
*/
struct Constraints {
float tilt_max; /**< maximum tilt always below Pi/2 */
float vel_max_z_up; /**< maximum speed upwards always smaller than MPC_VEL_Z_MAX_UP */
};
}
/**
* Core Position-Control for MC.
* This class contains P-controller for position and
* PID-controller for velocity.
* Inputs:
* vehicle position/velocity/yaw
* desired set-point position/velocity/thrust/yaw/yaw-speed
* constraints that are stricter than global limits
* Output
* thrust vector and a yaw-setpoint
*
* If there is a position and a velocity set-point present, then
* the velocity set-point is used as feed-forward. If feed-forward is
* active, then the velocity component of the P-controller output has
* priority over the feed-forward component.
*
* A setpoint that is NAN is considered as not set.
*/
class PositionControl
{
public:
PositionControl();
~PositionControl() {};
/**
* Update the current vehicle state.
* @param state a vehicle_local_position_s structure
* @param vel_dot the derivative of the vehicle velocity
*/
void updateState(const vehicle_local_position_s &state, const matrix::Vector3f &vel_dot);
/**
* Update the desired setpoints.
* @param setpoint a vehicle_local_position_setpoint_s structure
*/
void updateSetpoint(const vehicle_local_position_setpoint_s &setpoint);
/**
* Set constraints that are stricter than the global limits.
* @param constraints a PositionControl structure with supported constraints
*/
void updateConstraints(const Controller::Constraints &constraints);
/**
* Apply P-position and PID-velocity controller that updates the member
* thrust, yaw- and yawspeed-setpoints.
* @see _thr_sp
* @see _yaw_sp
* @see _yawspeed_sp
* @param dt the delta-time
*/
void generateThrustYawSetpoint(const float &dt);
/**
* Set the integral term in xy to 0.
* @see _thr_int
*/
void resetIntegralXY() {_thr_int(0) = _thr_int(1) = 0.0f;};
/**
* Set the integral term in z to 0.
* @see _thr_int
*/
void resetIntegralZ() {_thr_int(2) = 0.0f;};
/**
* Get the
* @see _thr_sp
* @return The thrust set-point member.
*/
matrix::Vector3f getThrustSetpoint() {return _thr_sp;}
/**
* Get the
* @see _yaw_sp
* @return The yaw set-point member.
*/
float getYawSetpoint() { return _yaw_sp;}
/**
* Get the
* @see _yawspeed_sp
* @return The yawspeed set-point member.
*/
float getYawspeedSetpoint() {return _yawspeed_sp;}
/**
* Get the
* @see _vel_sp
* @return The velocity set-point member.
*/
matrix::Vector3f getVelSp() {return _vel_sp;}
/**
* Get the
* @see _pos_sp
* @return The position set-point member.
*/
matrix::Vector3f getPosSp() {return _pos_sp;}
private:
void _interfaceMapping(); /** maps set-points to internal member set-points */
void _positionController(); /** applies the P-position-controller */
void _velocityController(const float &dt); /** applies the PID-velocity-controller */
void _updateParams(); /** updates parameters */
void _setParams(); /** sets parameters to internal member */
matrix::Vector3f _pos{}; /**< MC position */
matrix::Vector3f _vel{}; /**< MC velocity */
matrix::Vector3f _vel_dot{}; /**< MC velocity derivative */
matrix::Vector3f _acc{}; /**< MC acceleration */
float _yaw{0.0f}; /**< MC yaw */
matrix::Vector3f _pos_sp{}; /**< desired position */
matrix::Vector3f _vel_sp{}; /**< desired velocity */
matrix::Vector3f _acc_sp{}; /**< desired acceleration: not supported yet */
matrix::Vector3f _thr_sp{}; /**< desired thrust */
float _yaw_sp{}; /**< desired yaw */
float _yawspeed_sp{}; /** desired yaw-speed */
matrix::Vector3f _thr_int{}; /**< thrust integral term */
Controller::Constraints _constraints{}; /**< variable constraints */
bool _skip_controller{false}; /**< skips position/velocity controller. true for stabilized mode */
/**
* Position Gains.
* Pp: P-controller gain for position-controller
* Pv: P-controller gain for velocity-controller
* Iv: I-controller gain for velocity-controller
* Dv: D-controller gain for velocity-controller
*/
matrix::Vector3f _Pp, _Pv, _Iv, _Dv = matrix::Vector3f{0.0f, 0.0f, 0.0f};
float MPC_THR_MAX{1.0f}; /**< maximum thrust */
float MPC_THR_HOVER{0.5f}; /** equilibrium point for the velocity controller */
float MPC_THR_MIN{0.0f}; /**< minimum throttle for any position controlled mode */
float MPC_MANTHR_MIN{0.0f}; /**< minimum throttle for stabilized mode */
float MPC_XY_VEL_MAX{1.0f}; /**< maximum speed in the horizontal direction */
float MPC_Z_VEL_MAX_DN{1.0f}; /**< maximum speed in downwards direction */
float MPC_Z_VEL_MAX_UP{1.0f}; /**< maximum speed in upwards direction */
float MPC_TILTMAX_AIR{1.5}; /**< maximum tilt for any position/velocity controlled mode in radians */
float MPC_MAN_TILT_MAX{3.1}; /**< maximum tilt for manual/altitude mode in radians */
// Parameter handles
int _parameter_sub { -1 };
param_t MPC_Z_P_h { PARAM_INVALID };
param_t MPC_Z_VEL_P_h { PARAM_INVALID };
param_t MPC_Z_VEL_I_h { PARAM_INVALID };
param_t MPC_Z_VEL_D_h { PARAM_INVALID };
param_t MPC_XY_P_h { PARAM_INVALID };
param_t MPC_XY_VEL_P_h { PARAM_INVALID };
param_t MPC_XY_VEL_I_h { PARAM_INVALID };
param_t MPC_XY_VEL_D_h { PARAM_INVALID };
param_t MPC_XY_VEL_MAX_h { PARAM_INVALID };
param_t MPC_Z_VEL_MAX_DN_h { PARAM_INVALID };
param_t MPC_Z_VEL_MAX_UP_h { PARAM_INVALID };
param_t MPC_THR_HOVER_h { PARAM_INVALID };
param_t MPC_THR_MAX_h { PARAM_INVALID };
param_t MPC_THR_MIN_h { PARAM_INVALID };
param_t MPC_MANTHR_MIN_h { PARAM_INVALID };
param_t MPC_TILTMAX_AIR_h { PARAM_INVALID };
param_t MPC_MAN_TILT_MAX_h { PARAM_INVALID };
};
<commit_msg>PositionControl.hpp: inherit from ModuleParams and replace params with ModuleParams type<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file PositionControl.hpp
*
* A cascaded position controller for position/velocity control only.
*/
#include <matrix/matrix/math.hpp>
#include <uORB/topics/vehicle_local_position.h>
#include <uORB/topics/vehicle_local_position_setpoint.h>
#include <px4_module_params.h>
#pragma once
namespace Controller
{
/** Constraints that depends on mode and are lower
* than the global limits.
* tilt_max: Cannot exceed PI/2 radians
* vel_max_z_up: Cannot exceed maximum global velocity upwards
* @see MPC_TILTMAX_AIR
* @see MPC_Z_VEL_MAX_DN
*/
struct Constraints {
float tilt_max; /**< maximum tilt always below Pi/2 */
float vel_max_z_up; /**< maximum speed upwards always smaller than MPC_VEL_Z_MAX_UP */
};
}
/**
* Core Position-Control for MC.
* This class contains P-controller for position and
* PID-controller for velocity.
* Inputs:
* vehicle position/velocity/yaw
* desired set-point position/velocity/thrust/yaw/yaw-speed
* constraints that are stricter than global limits
* Output
* thrust vector and a yaw-setpoint
*
* If there is a position and a velocity set-point present, then
* the velocity set-point is used as feed-forward. If feed-forward is
* active, then the velocity component of the P-controller output has
* priority over the feed-forward component.
*
* A setpoint that is NAN is considered as not set.
*/
class PositionControl : public ModuleParams
{
public:
PositionControl(ModuleParams *parent);
~PositionControl() = default;
/**
* Overwrites certain parameters.
* Overwrites are required for unit-conversion.
* This method should only be called if parameters
* have been updated.
*/
void overwriteParams();
/**
* Update the current vehicle state.
* @param state a vehicle_local_position_s structure
* @param vel_dot the derivative of the vehicle velocity
*/
void updateState(const vehicle_local_position_s &state, const matrix::Vector3f &vel_dot);
/**
* Update the desired setpoints.
* @param setpoint a vehicle_local_position_setpoint_s structure
*/
void updateSetpoint(const vehicle_local_position_setpoint_s &setpoint);
/**
* Set constraints that are stricter than the global limits.
* @param constraints a PositionControl structure with supported constraints
*/
void updateConstraints(const Controller::Constraints &constraints);
/**
* Apply P-position and PID-velocity controller that updates the member
* thrust, yaw- and yawspeed-setpoints.
* @see _thr_sp
* @see _yaw_sp
* @see _yawspeed_sp
* @param dt the delta-time
*/
void generateThrustYawSetpoint(const float &dt);
/**
* Set the integral term in xy to 0.
* @see _thr_int
*/
void resetIntegralXY() {_thr_int(0) = _thr_int(1) = 0.0f;};
/**
* Set the integral term in z to 0.
* @see _thr_int
*/
void resetIntegralZ() {_thr_int(2) = 0.0f;};
/**
* Get the
* @see _thr_sp
* @return The thrust set-point member.
*/
matrix::Vector3f getThrustSetpoint() {return _thr_sp;}
/**
* Get the
* @see _yaw_sp
* @return The yaw set-point member.
*/
float getYawSetpoint() { return _yaw_sp;}
/**
* Get the
* @see _yawspeed_sp
* @return The yawspeed set-point member.
*/
float getYawspeedSetpoint() {return _yawspeed_sp;}
/**
* Get the
* @see _vel_sp
* @return The velocity set-point member.
*/
matrix::Vector3f getVelSp() {return _vel_sp;}
/**
* Get the
* @see _pos_sp
* @return The position set-point member.
*/
matrix::Vector3f getPosSp() {return _pos_sp;}
private:
void _interfaceMapping(); /** maps set-points to internal member set-points */
void _positionController(); /** applies the P-position-controller */
void _velocityController(const float &dt); /** applies the PID-velocity-controller */
matrix::Vector3f _pos{}; /**< MC position */
matrix::Vector3f _vel{}; /**< MC velocity */
matrix::Vector3f _vel_dot{}; /**< MC velocity derivative */
matrix::Vector3f _acc{}; /**< MC acceleration */
float _yaw{0.0f}; /**< MC yaw */
matrix::Vector3f _pos_sp{}; /**< desired position */
matrix::Vector3f _vel_sp{}; /**< desired velocity */
matrix::Vector3f _acc_sp{}; /**< desired acceleration: not supported yet */
matrix::Vector3f _thr_sp{}; /**< desired thrust */
float _yaw_sp{}; /**< desired yaw */
float _yawspeed_sp{}; /** desired yaw-speed */
matrix::Vector3f _thr_int{}; /**< thrust integral term */
Controller::Constraints _constraints{}; /**< variable constraints */
bool _skip_controller{false}; /**< skips position/velocity controller. true for stabilized mode */
DEFINE_PARAMETERS(
(ParamFloat<px4::params::MPC_THR_MAX>) MPC_THR_MAX,
(ParamFloat<px4::params::MPC_THR_HOVER>) MPC_THR_HOVER,
(ParamFloat<px4::params::MPC_THR_MIN>) MPC_THR_MIN,
(ParamFloat<px4::params::MPC_MANTHR_MIN>) MPC_MANTHR_MIN,
(ParamFloat<px4::params::MPC_XY_VEL_MAX>) MPC_XY_VEL_MAX,
(ParamFloat<px4::params::MPC_Z_VEL_MAX_DN>) MPC_Z_VEL_MAX_DN,
(ParamFloat<px4::params::MPC_Z_VEL_MAX_UP>) MPC_Z_VEL_MAX_UP,
(ParamFloat<px4::params::MPC_TILTMAX_AIR>) MPC_TILTMAX_AIR,
(ParamFloat<px4::params::MPC_MAN_TILT_MAX>) MPC_MAN_TILT_MAX,
(ParamFloat<px4::params::MPC_Z_P>) MPC_Z_P,
(ParamFloat<px4::params::MPC_Z_VEL_P>) MPC_Z_VEL_P,
(ParamFloat<px4::params::MPC_Z_VEL_I>) MPC_Z_VEL_I,
(ParamFloat<px4::params::MPC_Z_VEL_D>) MPC_Z_VEL_D,
(ParamFloat<px4::params::MPC_XY_P>) MPC_XY_P,
(ParamFloat<px4::params::MPC_XY_VEL_P>) MPC_XY_VEL_P,
(ParamFloat<px4::params::MPC_XY_VEL_I>) MPC_XY_VEL_I,
(ParamFloat<px4::params::MPC_XY_VEL_D>) MPC_XY_VEL_D
)
};
<|endoftext|> |
<commit_before>#ifndef INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP
#define INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California 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 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.
File description:
GPU buffer object helper
File author(s):
Lance Putnam, 2010, [email protected]
*/
#include "allocore/graphics/al_GPUObject.hpp"
#include "allocore/graphics/al_Graphics.hpp"
namespace al{
/// Generic buffer object
/**
Vertex Buffer Objects (VBOs) create buffer memory for vertex attributes in
high-performance memory (in contrast, Vertex Arrays store buffer memory in the
client CPU, incurring the overhead of data transfer). If the buffer object is
used to store pixel data, it is called Pixel Buffer Object (PBO).
VBOs provide an interface to access these buffers in a similar fashion to vertex
arrays. Hints of 'target' and 'mode' help the implementation determine whether
to use system, AGP or video memory.
Unlike display lists, the data in vertex buffer object can be read and updated
by mapping the buffer into client's memory space.
Another important advantage of VBO is sharing the buffer objects with many
clients, like display lists and textures. Since VBO is on the server's side,
multiple clients will be able to access the same buffer with the corresponding
identifier.
*/
class BufferObject : public GPUObject {
public:
/// Buffer access mode
enum AccessMode{
READ_ONLY = GL_READ_ONLY,
WRITE_ONLY = GL_WRITE_ONLY,
READ_WRITE = GL_READ_WRITE
};
/// Array type
enum ArrayType{
VERTEX_ARRAY = GL_VERTEX_ARRAY,
NORMAL_ARRAY = GL_NORMAL_ARRAY,
COLOR_ARRAY = GL_COLOR_ARRAY,
INDEX_ARRAY = GL_INDEX_ARRAY,
TEXTURE_COORD_ARRAY = GL_TEXTURE_COORD_ARRAY,
EDGE_FLAG_ARRAY = GL_EDGE_FLAG_ARRAY
};
/// Buffer type
enum BufferType{
ARRAY_BUFFER = GL_ARRAY_BUFFER,
ELEMENT_ARRAY_BUFFER = GL_ELEMENT_ARRAY_BUFFER,
PIXEL_PACK_BUFFER = GL_PIXEL_PACK_BUFFER, /**< Transfer to PBO */
PIXEL_UNPACK_BUFFER = GL_PIXEL_UNPACK_BUFFER /**< Transfer from PBO */
};
/*
"Static" means the data in VBO will not be changed, "Dynamic" means the data
will be changed frequently, and "Stream" means the data will be changed every
frame. "Draw" means the data will be sent to the GPU from the application,
"Read" means the data will be read by the application from the GPU, and "Copy"
means the data will be copied internally on the GPU.
*/
enum BufferUsage{
STREAM_DRAW = GL_STREAM_DRAW,
// STREAM_READ = GL_STREAM_READ,
// STREAM_COPY = GL_STREAM_COPY,
STATIC_DRAW = GL_STATIC_DRAW,
// STATIC_READ = GL_STATIC_READ,
// STATIC_COPY = GL_STATIC_COPY,
DYNAMIC_DRAW = GL_DYNAMIC_DRAW,
// DYNAMIC_READ = GL_DYNAMIC_READ,
// DYNAMIC_COPY = GL_DYNAMIC_COPY
};
BufferObject(BufferType bufType, BufferUsage bufUsage)
: mMapMode(READ_WRITE), mType(bufType), mUsage(bufUsage),
mDataType(Graphics::FLOAT), mNumComps(0), mNumElems(0), mData(0)
{}
virtual ~BufferObject(){ destroy(); }
void bufferType(BufferType v){ mType=v; }
void mapMode(AccessMode v){ mMapMode=v; }
void operator()(){
//data(); onPointerFunc(); unbind();
bind(); onPointerFunc();
}
void send() { (*this)(); }
void bind(){ validate(); glBindBuffer(mType, id()); }
void unbind() const { glBindBuffer(mType, 0); }
#ifdef AL_GRAPHICS_USE_OPENGL
/* Warning: these are not supported in OpenGL ES */
/// Map data store to client address space
/// If successful, returns a valid pointer to the data, otherwise, it returns
/// NULL.
/// After using the pointer, call unmap() as soon as possible
void * map(){ bind(); return glMapBuffer(mType, mMapMode); }
/// Map data store to client address space.
/// If successful, returns true and sets argument to address of data,
/// otherwise, returns false and leaves argument unaffected.
/// After using the pointer, call unmap() as soon as possible
template <class T>
bool map(T *& buf){
if(Graphics::toDataType<T>() == mDataType){
void * r = map();
if(r){ buf=(T *)r; return true; }
}
return false;
}
/// Unmaps data store from client address
/// After unmap(), the mapped pointer is invalid
bool unmap(){ return glUnmapBuffer(mType)==GL_TRUE; }
#endif
/// Set buffer data store and copy over client data
void data(const void * src, Graphics::DataType dataType, int numElems, int numComps=1){
mData = (void *)src;
mDataType = dataType;
mNumElems = numElems;
mNumComps = numComps;
data();
}
/// Set buffer data store and copy over client data
template <class T>
void data(const T * src, int numElems, int numComps=1){
data(src, Graphics::toDataType<T>(), numElems, numComps);
}
/// Set buffer data store without copying client data
void data(Graphics::DataType dataType, int numElems, int numComps=1){
data(0, dataType, numElems, numComps);
}
/// Set buffer data store using cached values
void data(){
bind();
glBufferData(mType, Graphics::numBytes(mDataType)*mNumElems*mNumComps, mData, mUsage);
unbind();
}
protected:
AccessMode mMapMode;
BufferType mType;
BufferUsage mUsage;
Graphics::DataType mDataType;
int mNumComps;
int mNumElems;
void * mData;
virtual void onCreate(){ glGenBuffers(1, (GLuint*)&mID); }
virtual void onDestroy(){ glDeleteBuffers(1, (GLuint*)&mID); }
virtual void onPointerFunc() = 0;
};
/// Vertex buffer object
class VBO : public BufferObject {
public:
VBO(BufferUsage usage=STREAM_DRAW)
: BufferObject(ARRAY_BUFFER, usage){}
static void enable(){ glEnableClientState(VERTEX_ARRAY); }
static void disable(){ glDisableClientState(VERTEX_ARRAY); }
protected:
virtual void onPointerFunc(){ glVertexPointer(mNumComps, mDataType, 0, 0); }
};
/// Color buffer object
class CBO : public BufferObject {
public:
CBO(BufferUsage usage=STREAM_DRAW)
: BufferObject(ARRAY_BUFFER, usage){}
static void enable(){ glEnableClientState(COLOR_ARRAY); }
static void disable(){ glDisableClientState(COLOR_ARRAY); }
protected:
virtual void onPointerFunc(){ glColorPointer(mNumComps, mDataType, 0, 0); }
};
/// Pixel buffer object
class PBO : public BufferObject {
public:
PBO(bool packMode, BufferUsage usage=STREAM_DRAW)
: BufferObject(packMode ? PIXEL_PACK_BUFFER : PIXEL_UNPACK_BUFFER, usage){}
// static void enable(){ glEnableClientState(ArrayType::Vertex); }
// static void disable(){ glDisableClientState(ArrayType::Vertex); }
protected:
virtual void onPointerFunc(){ glVertexPointer(mNumComps, mDataType, 0, 0); }
};
/// Element object buffer
class EBO : public BufferObject {
public:
EBO(Graphics::Primitive prim=Graphics::POINTS, BufferUsage usage=STATIC_DRAW)
: BufferObject(ELEMENT_ARRAY_BUFFER, usage), mPrim(prim), mStart(0), mEnd(0)
{}
EBO& prim(Graphics::Primitive v){ mPrim=v; return *this; }
EBO& range(int start, int end){ mStart=start; mEnd=end; return *this; }
protected:
Graphics::Primitive mPrim;
int mStart, mEnd;
virtual void onPointerFunc(){
if(mEnd) glDrawRangeElements(mPrim, mStart, mEnd, mNumElems, mDataType, 0);
else glDrawRangeElements(mPrim, 0, mNumElems, mNumElems, mDataType, 0);
}
};
/*
class BufferObjects : public GPUObject, public Drawable {
public:
BufferObjects() {};
virtual ~BufferObjects() {};
virtual void draw(Graphics& gl);
Mesh& data() { return *mData; }
protected:
virtual void onCreate() {};
virtual void onDestroy() {};
Mesh mData;
VBO mVBO;
CBO mCBO;
EBO mEBO;
};
*/
} // al::
#endif
<commit_msg>BufferObject: add support for sub-data<commit_after>#ifndef INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP
#define INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California 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 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.
File description:
GPU buffer object helper
File author(s):
Lance Putnam, 2010, [email protected]
*/
#include "allocore/graphics/al_GPUObject.hpp"
#include "allocore/graphics/al_Graphics.hpp"
namespace al{
/// Generic buffer object
/**
Vertex Buffer Objects (VBOs) create buffer memory for vertex attributes in
high-performance memory (in contrast, Vertex Arrays store buffer memory in the
client CPU, incurring the overhead of data transfer). If the buffer object is
used to store pixel data, it is called Pixel Buffer Object (PBO).
VBOs provide an interface to access these buffers in a similar fashion to vertex
arrays. Hints of 'target' and 'mode' help the implementation determine whether
to use system, AGP or video memory.
Unlike display lists, the data in vertex buffer object can be read and updated
by mapping the buffer into client's memory space.
Another important advantage of VBO is sharing the buffer objects with many
clients, like display lists and textures. Since VBO is on the server's side,
multiple clients will be able to access the same buffer with the corresponding
identifier.
*/
class BufferObject : public GPUObject {
public:
/// Buffer access mode
enum AccessMode{
READ_ONLY = GL_READ_ONLY,
WRITE_ONLY = GL_WRITE_ONLY,
READ_WRITE = GL_READ_WRITE
};
/// Array type
enum ArrayType{
VERTEX_ARRAY = GL_VERTEX_ARRAY,
NORMAL_ARRAY = GL_NORMAL_ARRAY,
COLOR_ARRAY = GL_COLOR_ARRAY,
INDEX_ARRAY = GL_INDEX_ARRAY,
TEXTURE_COORD_ARRAY = GL_TEXTURE_COORD_ARRAY,
EDGE_FLAG_ARRAY = GL_EDGE_FLAG_ARRAY
};
/// Buffer type
enum BufferType{
ARRAY_BUFFER = GL_ARRAY_BUFFER,
ELEMENT_ARRAY_BUFFER = GL_ELEMENT_ARRAY_BUFFER,
PIXEL_PACK_BUFFER = GL_PIXEL_PACK_BUFFER, /**< Transfer to PBO */
PIXEL_UNPACK_BUFFER = GL_PIXEL_UNPACK_BUFFER /**< Transfer from PBO */
};
/*
"Static" means the data in VBO will not be changed, "Dynamic" means the data
will be changed frequently, and "Stream" means the data will be changed every
frame. "Draw" means the data will be sent to the GPU from the application,
"Read" means the data will be read by the application from the GPU, and "Copy"
means the data will be copied internally on the GPU.
*/
enum BufferUsage{
STREAM_DRAW = GL_STREAM_DRAW,
//STREAM_READ = GL_STREAM_READ,
//STREAM_COPY = GL_STREAM_COPY,
STATIC_DRAW = GL_STATIC_DRAW,
//STATIC_READ = GL_STATIC_READ,
//STATIC_COPY = GL_STATIC_COPY,
DYNAMIC_DRAW = GL_DYNAMIC_DRAW,
//DYNAMIC_READ = GL_DYNAMIC_READ,
//DYNAMIC_COPY = GL_DYNAMIC_COPY
};
BufferObject(BufferType bufType, BufferUsage bufUsage)
: mMapMode(READ_WRITE), mType(bufType), mUsage(bufUsage),
mDataType(Graphics::FLOAT), mNumComps(0), mNumElems(0), mData(0)
{}
virtual ~BufferObject(){ destroy(); }
void bufferType(BufferType v){ mType=v; }
void usage(BufferUsage v){ mUsage=v; }
void mapMode(AccessMode v){ mMapMode=v; }
void operator()(){
//data(); onPointerFunc(); unbind();
bind(); onPointerFunc();
}
void send() { (*this)(); }
void bind(){ validate(); glBindBuffer(mType, id()); }
void unbind() const { glBindBuffer(mType, 0); }
#ifdef AL_GRAPHICS_USE_OPENGL
/* Warning: these are not supported in OpenGL ES */
/// Map data store to client address space
/// If successful, returns a valid pointer to the data, otherwise, it returns
/// NULL.
/// After using the pointer, call unmap() as soon as possible
void * map(){ bind(); return glMapBuffer(mType, mMapMode); }
/// Map data store to client address space.
/// If successful, returns true and sets argument to address of data,
/// otherwise, returns false and leaves argument unaffected.
/// After using the pointer, call unmap() as soon as possible
template <class T>
bool map(T *& buf){
if(Graphics::toDataType<T>() == mDataType){
void * r = map();
if(r){ buf=(T *)r; return true; }
}
return false;
}
/// Unmaps data store from client address
/// After unmap(), the mapped pointer is invalid
bool unmap(){ return glUnmapBuffer(mType)==GL_TRUE; }
#endif
/// Set size, in bytes, of buffer without sending data
void resize(int numBytes){
mData = NULL;
mDataType = Graphics::BYTE;
mNumElems = numBytes;
mNumComps = 1;
data();
}
/// Set buffer data store and copy over client data
void data(const void * src, Graphics::DataType dataType, int numElems, int numComps=1){
mData = (void *)src;
mDataType = dataType;
mNumElems = numElems;
mNumComps = numComps;
data();
}
/// Set buffer data store and copy over client data
template <class T>
void data(const T * src, int numElems, int numComps=1){
data(src, Graphics::toDataType<T>(), numElems, numComps);
}
/// Set buffer data store without copying client data
void data(Graphics::DataType dataType, int numElems, int numComps=1){
data(0, dataType, numElems, numComps);
}
/// Set buffer data store using cached values
void data(){
bind();
glBufferData(mType, Graphics::numBytes(mDataType)*mNumElems*mNumComps, mData, mUsage);
unbind();
}
/// Set subregion of buffer store
template <class T>
int subData(const T * src, int numElems, int byteOffset=0){
if(numElems){
bind();
glBufferSubData(mType, byteOffset, numElems*sizeof(T), src);
unbind();
}
return numElems*sizeof(T) + byteOffset;
}
protected:
AccessMode mMapMode;
BufferType mType;
BufferUsage mUsage;
Graphics::DataType mDataType;
int mNumComps;
int mNumElems;
void * mData;
virtual void onCreate(){ glGenBuffers(1, (GLuint*)&mID); }
virtual void onDestroy(){ glDeleteBuffers(1, (GLuint*)&mID); }
virtual void onPointerFunc() = 0;
};
/// Vertex buffer object
class VBO : public BufferObject {
public:
VBO(BufferUsage usage=STREAM_DRAW)
: BufferObject(ARRAY_BUFFER, usage){}
static void enable(){ glEnableClientState(VERTEX_ARRAY); }
static void disable(){ glDisableClientState(VERTEX_ARRAY); }
protected:
virtual void onPointerFunc(){ glVertexPointer(mNumComps, mDataType, 0, 0); }
};
/// Color buffer object
class CBO : public BufferObject {
public:
CBO(BufferUsage usage=STREAM_DRAW)
: BufferObject(ARRAY_BUFFER, usage){}
static void enable(){ glEnableClientState(COLOR_ARRAY); }
static void disable(){ glDisableClientState(COLOR_ARRAY); }
protected:
virtual void onPointerFunc(){ glColorPointer(mNumComps, mDataType, 0, 0); }
};
/// Pixel buffer object
class PBO : public BufferObject {
public:
PBO(bool packMode, BufferUsage usage=STREAM_DRAW)
: BufferObject(packMode ? PIXEL_PACK_BUFFER : PIXEL_UNPACK_BUFFER, usage){}
// static void enable(){ glEnableClientState(ArrayType::Vertex); }
// static void disable(){ glDisableClientState(ArrayType::Vertex); }
protected:
virtual void onPointerFunc(){ glVertexPointer(mNumComps, mDataType, 0, 0); }
};
/// Element object buffer
class EBO : public BufferObject {
public:
EBO(Graphics::Primitive prim=Graphics::POINTS, BufferUsage usage=STATIC_DRAW)
: BufferObject(ELEMENT_ARRAY_BUFFER, usage), mPrim(prim), mStart(0), mEnd(0)
{}
EBO& primitive(Graphics::Primitive v){ mPrim=v; return *this; }
EBO& range(int start, int end){ mStart=start; mEnd=end; return *this; }
protected:
Graphics::Primitive mPrim;
int mStart, mEnd;
virtual void onPointerFunc(){
if(mEnd) glDrawRangeElements(mPrim, mStart, mEnd, mNumElems, mDataType, 0);
else glDrawRangeElements(mPrim, 0, mNumElems, mNumElems, mDataType, 0);
}
};
/*
class BufferObjects : public GPUObject, public Drawable {
public:
BufferObjects() {};
virtual ~BufferObjects() {};
virtual void draw(Graphics& gl);
Mesh& data() { return *mData; }
protected:
virtual void onCreate() {};
virtual void onDestroy() {};
Mesh mData;
VBO mVBO;
CBO mCBO;
EBO mEBO;
};
*/
} // al::
#endif
<|endoftext|> |
<commit_before>#include "parallel.h"
#include <iostream>
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include "cmdLineOptions.h"
#include "h5test.h"
void printVersion(const char* execName)
{
if (P.myProc == 0)
std::cerr << execName << " Version: " << H5TEST_VERSION << std::endl;
}
void printUsage(const char* execName)
{
printVersion(execName);
if (P.myProc == 0)
std::cerr << "\nUsage:\n"
<< execName << " [options]\n\n"
<< "Options:\n"
<< " -h, -? : Print Usage\n"
<< " -v : Print Version\n"
<< " -C : use h5 chunk\n"
<< " -S : use h5 slab (default)\n"
<< " -N : no T3PIO\n"
<< " -O type : output type (l: lua, t: table, b: both (default: table))\n"
<< " -n nvar : nvar (default=4)\n"
<< " -l num : local size is num (default=10)\n"
<< " -g num : global size is num\n"
<< " -f factor : number of stripes per writer (default=2)\n"
<< " -s num : maximum number of stripes\n"
<< " -z num : maximum stripe size in MB\n"
<< " -p num : maximum number of writers per node\n"
<< " -w num : Total number of writers\n"
<< std::endl;
}
CmdLineOptions::CmdLineOptions(int argc, char* argv[])
: m_state(iBAD)
{
int opt;
bool version, help, illegal;
char choice;
maxWritersPer = INT_MAX;
useT3PIO = true;
maxWriters = -1;
version = false;
help = false;
localSz = -1;
globalSz = -1;
h5chunk = false;
h5slab = false;
factor = 1;
stripes = -1;
stripeSz = -1;
h5style = "h5slab";
luaStyleOutput = false;
tableStyleOutput = true;
while ( (opt = getopt(argc, argv, "s:hCSLO:f:p:w:l:g:n:z:?v")) != -1)
{
switch (opt)
{
case 'v':
version = true;
break;
case '?':
case 'h':
help = true;
break;
case 'C':
h5chunk = true;
break;
case 'N':
useT3PIO = false;
break;
case 'f':
factor = strtol(optarg, (char **) NULL, 10);
break;
case 's':
stripes = strtol(optarg, (char **) NULL, 10);
break;
case 'z':
stripeSz = strtol(optarg, (char **) NULL, 10);
break;
case 'g':
globalSz = strtoll(optarg, (char **) NULL, 10);
break;
case 'l':
localSz = strtoll(optarg, (char **) NULL, 10);
break;
case 'n':
nvar = strtol(optarg, (char **) NULL, 10);
break;
case 'O':
choice = tolower(optarg[0]);
luaStyleOutput = ( choice == 'b' || choice == 'l')
break;
case 'p':
maxWritersPer = strtol(optarg, (char **) NULL, 10);
break;
case 'w':
maxWriters = strtol(optarg, (char **) NULL, 10);
break;
case 'S':
h5slab = true;
break;
default:
illegal = true;
;
}
}
if (version)
{
m_state = iHELP;
printVersion(argv[0]);
return;
}
if (help)
{
m_state = iHELP;
printUsage(argv[0]);
return;
}
if (! h5chunk && ! h5slab)
h5slab = true;
if ( h5chunk )
h5style = "h5chunk";
if (localSz < 0)
{
if (globalSz < 0)
localSz = 10;
else
{
int rem = globalSz % P.nProcs;
localSz = globalSz/P.nProcs + (P.myProc < rem);
}
}
if (globalSz < 0)
globalSz = localSz * P.nProcs;
m_state = iGOOD;
}
<commit_msg>better output report control with -O option<commit_after>#include "parallel.h"
#include <iostream>
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include "cmdLineOptions.h"
#include "h5test.h"
void printVersion(const char* execName)
{
if (P.myProc == 0)
std::cerr << execName << " Version: " << H5TEST_VERSION << std::endl;
}
void printUsage(const char* execName)
{
printVersion(execName);
if (P.myProc == 0)
std::cerr << "\nUsage:\n"
<< execName << " [options]\n\n"
<< "Options:\n"
<< " -h, -? : Print Usage\n"
<< " -v : Print Version\n"
<< " -C : use h5 chunk\n"
<< " -S : use h5 slab (default)\n"
<< " -N : no T3PIO\n"
<< " -O type : output type (l: lua, t: table, b: both (default: table))\n"
<< " -n nvar : nvar (default=4)\n"
<< " -l num : local size is num (default=10)\n"
<< " -g num : global size is num\n"
<< " -f factor : number of stripes per writer (default=2)\n"
<< " -s num : maximum number of stripes\n"
<< " -z num : maximum stripe size in MB\n"
<< " -p num : maximum number of writers per node\n"
<< " -w num : Total number of writers\n"
<< std::endl;
}
CmdLineOptions::CmdLineOptions(int argc, char* argv[])
: m_state(iBAD)
{
int opt;
bool version, help, illegal;
char choice;
maxWritersPer = INT_MAX;
useT3PIO = true;
maxWriters = -1;
version = false;
help = false;
localSz = -1;
globalSz = -1;
h5chunk = false;
h5slab = false;
factor = 1;
stripes = -1;
stripeSz = -1;
h5style = "h5slab";
luaStyleOutput = false;
tableStyleOutput = true;
while ( (opt = getopt(argc, argv, "s:hCSLO:f:p:w:l:g:n:z:?v")) != -1)
{
switch (opt)
{
case 'v':
version = true;
break;
case '?':
case 'h':
help = true;
break;
case 'C':
h5chunk = true;
break;
case 'N':
useT3PIO = false;
break;
case 'f':
factor = strtol(optarg, (char **) NULL, 10);
break;
case 's':
stripes = strtol(optarg, (char **) NULL, 10);
break;
case 'z':
stripeSz = strtol(optarg, (char **) NULL, 10);
break;
case 'g':
globalSz = strtoll(optarg, (char **) NULL, 10);
break;
case 'l':
localSz = strtoll(optarg, (char **) NULL, 10);
break;
case 'n':
nvar = strtol(optarg, (char **) NULL, 10);
break;
case 'O':
choice = tolower(optarg[0]);
luaStyleOutput = ( choice == 'b' || choice == 'l');
break;
case 'p':
maxWritersPer = strtol(optarg, (char **) NULL, 10);
break;
case 'w':
maxWriters = strtol(optarg, (char **) NULL, 10);
break;
case 'S':
h5slab = true;
break;
default:
illegal = true;
;
}
}
if (version)
{
m_state = iHELP;
printVersion(argv[0]);
return;
}
if (help)
{
m_state = iHELP;
printUsage(argv[0]);
return;
}
if (! h5chunk && ! h5slab)
h5slab = true;
if ( h5chunk )
h5style = "h5chunk";
if (localSz < 0)
{
if (globalSz < 0)
localSz = 10;
else
{
int rem = globalSz % P.nProcs;
localSz = globalSz/P.nProcs + (P.myProc < rem);
}
}
if (globalSz < 0)
globalSz = localSz * P.nProcs;
m_state = iGOOD;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2009 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface header
#include "TimeKeeper.h"
// system implementation headers
#include <time.h>
#include <string>
#include <string.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef __BEOS__
# include <OS.h>
#endif
#if !defined(_WIN32)
# include <sys/time.h>
# include <sys/types.h>
static int64_t lastTime = 0;
# ifdef HAVE_SCHED_H
# include <sched.h>
# endif
#else // !defined(_WIN32)
# include <mmsystem.h>
static unsigned long int lastTime = 0;
static LARGE_INTEGER qpcLastTime;
static LONGLONG qpcFrequency = 0;
static LONGLONG qpcLastCalibration;
static DWORD timeLastCalibration;
#endif // !defined(_WIN32)
// common implementation headers
#include "TextUtils.h"
#include "bzfio.h"
static TimeKeeper currentTime;
static TimeKeeper tickTime;
static TimeKeeper sunExplodeTime;
static TimeKeeper sunGenesisTime;
static TimeKeeper nullTime;
static TimeKeeper startTime = TimeKeeper::getCurrent();
#if !defined(_WIN32)
static inline int64_t getEpochMicroseconds()
{
struct timeval nowTime;
gettimeofday(&nowTime, NULL);
return (int64_t(nowTime.tv_sec) * int64_t(1000000))
+ int64_t(nowTime.tv_usec);
}
#endif
const TimeKeeper& TimeKeeper::getCurrent(void)
{
// if not first call then update current time, else use default initial time
#if !defined(_WIN32)
if (lastTime == 0) {
// time starts at 0 seconds from the first call to getCurrent()
lastTime = getEpochMicroseconds();
}
else {
const int64_t nowTime = getEpochMicroseconds();
int64_t diff = (nowTime - lastTime);
if (diff < 0) {
logDebugMessage(5, "WARNING: went back in time %li microseconds\n",
(long int)diff);
diff = 0; // eh, how'd we go back in time?
}
currentTime += double(diff) * 1.0e-6;;
lastTime = nowTime;
}
#else /* !defined(_WIN32) */
if (qpcFrequency != 0) {
// main timer is qpc
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
LONGLONG diff = now.QuadPart - qpcLastTime.QuadPart;
LONGLONG clkSpent = now.QuadPart - qpcLastCalibration;
qpcLastTime = now;
if (clkSpent > qpcFrequency) {
// Recalibrate Frequency
DWORD tgt = timeGetTime();
DWORD deltaTgt = tgt - timeLastCalibration;
timeLastCalibration = tgt;
qpcLastCalibration = now.QuadPart;
if (deltaTgt > 0) {
LONGLONG oldqpcfreq = qpcFrequency;
qpcFrequency = (clkSpent * 1000) / deltaTgt;
if (qpcFrequency != oldqpcfreq)
logDebugMessage(4, "Recalibrated QPC frequency. Old: %f ; New: %f\n",
(double)oldqpcfreq, (double)qpcFrequency);
}
}
currentTime += (double) diff / (double) qpcFrequency;
} else if (lastTime != 0) {
unsigned long int now = (unsigned long int)timeGetTime();
unsigned long int diff;
if (now < lastTime) {
// eh, how'd we go back in time?
diff = 0;
} else {
diff = now - lastTime;
}
currentTime += 1.0e-3 * (double)diff;
lastTime = now;
} else {
static bool sane = true;
// should only get into here once on app start
if (!sane) {
logDebugMessage(1,"Sanity check failure in TimeKeeper::getCurrent()\n");
}
sane = false;
// make sure we're at our best timer resolution possible
timeBeginPeriod(1);
LARGE_INTEGER freq;
if (QueryPerformanceFrequency(&freq)) {
QueryPerformanceCounter(&qpcLastTime);
qpcFrequency = freq.QuadPart;
logDebugMessage(4,"Actual reported QPC Frequency: %f\n", (double)qpcFrequency);
qpcLastCalibration = qpcLastTime.QuadPart;
timeLastCalibration = timeGetTime();
} else {
logDebugMessage(1,"QueryPerformanceFrequency failed with error %d\n", GetLastError());
lastTime = (unsigned long int)timeGetTime();
}
}
#endif /* !defined(_WIN32) */
return currentTime;
}
const TimeKeeper& TimeKeeper::getStartTime(void) // const
{
return startTime;
}
const TimeKeeper& TimeKeeper::getTick(void) // const
{
return tickTime;
}
void TimeKeeper::setTick(void)
{
tickTime = getCurrent();
}
const TimeKeeper& TimeKeeper::getSunExplodeTime(void)
{
sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60;
return sunExplodeTime;
}
const TimeKeeper& TimeKeeper::getSunGenesisTime(void)
{
sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60;
return sunGenesisTime;
}
const TimeKeeper& TimeKeeper::getNullTime(void)
{
nullTime.seconds = 0;
return nullTime;
}
const char *TimeKeeper::timestamp(void) // const
{
static char buffer[256]; // static, so that it doesn't vanish
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d",
now->tm_year, now->tm_mon, now->tm_mday,
now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256);
buffer[255] = '\0'; // safety
return buffer;
}
/** returns a short string of the local time */
//static
std::string TimeKeeper::shortTimeStamp(void) {
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
std::string result( TextUtils::format("%02d:%02d", now->tm_hour, now->tm_min) );
return result;
}
void TimeKeeper::localTime(int *year, int *month, int* day,
int* hour, int* min, int* sec, bool* dst) // const
{
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
if (year) { *year = now->tm_year; }
if (month) { *month = now->tm_mon; }
if (day) { *day = now->tm_mday; }
if (hour) { *hour = now->tm_hour; }
if (min) { *min = now->tm_min; }
if (sec) { *sec = now->tm_sec; }
if (dst) { *dst = (now->tm_isdst != 0); }
}
void TimeKeeper::localTimeDOW(int *year, int *month, int* day, int* wday,
int* hour, int* min, int* sec, bool* dst) // const
{
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
if (year) { *year = now->tm_year; }
if (month) { *month = now->tm_mon; }
if (day) { *day = now->tm_mday; }
if (wday) { *wday = now->tm_wday; }
if (hour) { *hour = now->tm_hour; }
if (min) { *min = now->tm_min; }
if (sec) { *sec = now->tm_sec; }
if (dst) { *dst = (now->tm_isdst != 0); }
}
void TimeKeeper::UTCTime(int *year, int *month, int* day, int* wday,
int* hour, int* min, int* sec, bool* dst) // const
{
time_t tnow = time(0);
struct tm *now = gmtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
if (year) { *year = now->tm_year; }
if (month) { *month = now->tm_mon; }
if (day) { *day = now->tm_mday; }
if (wday) { *wday = now->tm_wday; }
if (hour) { *hour = now->tm_hour; }
if (min) { *min = now->tm_min; }
if (sec) { *sec = now->tm_sec; }
if (dst) { *dst = (now->tm_isdst != 0); }
}
// function for converting a float time (e.g. difference of two TimeKeepers)
// into an array of ints
void TimeKeeper::convertTime(double raw, long int convertedTimes[]) // const
{
long int day, hour, min, sec, remainder;
static const int secondsInDay = 86400;
sec = (long int)raw;
day = sec / secondsInDay;
remainder = sec - (day * secondsInDay);
hour = remainder / 3600;
remainder = sec - ((hour * 3600) + (day * secondsInDay));
min = remainder / 60;
remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60));
sec = remainder;
convertedTimes[0] = day;
convertedTimes[1] = hour;
convertedTimes[2] = min;
convertedTimes[3] = sec;
return;
}
// function for printing an array of ints representing a time
// as a human-readable string
const std::string TimeKeeper::printTime(long int timeValue[])
{
std::string valueNames;
char temp[20];
if (timeValue[0] > 0) {
snprintf(temp, 20, "%ld day%s", timeValue[0], timeValue[0] == 1 ? "" : "s");
valueNames.append(temp);
}
if (timeValue[1] > 0) {
if (timeValue[0] > 0) {
valueNames.append(", ");
}
snprintf(temp, 20, "%ld hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s");
valueNames.append(temp);
}
if (timeValue[2] > 0) {
if ((timeValue[1] > 0) || (timeValue[0] > 0)) {
valueNames.append(", ");
}
snprintf(temp, 20, "%ld min%s", timeValue[2], timeValue[2] == 1 ? "" : "s");
valueNames.append(temp);
}
if (timeValue[3] > 0) {
if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) {
valueNames.append(", ");
}
snprintf(temp, 20, "%ld sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s");
valueNames.append(temp);
}
return valueNames;
}
// function for printing a float time difference as a human-readable string
const std::string TimeKeeper::printTime(double diff)
{
long int temp[4];
convertTime(diff, temp);
return printTime(temp);
}
void TimeKeeper::sleep(double seconds)
{
if (seconds <= 0.0) {
return;
}
#ifdef HAVE_USLEEP
usleep((unsigned int)(1.0e6 * seconds));
return;
#endif
#if defined(HAVE_SLEEP) && !defined(__APPLE__)
// equivalent to _sleep() on win32 (not sleep(3))
Sleep((DWORD)(seconds * 1000.0));
return;
#endif
#ifdef HAVE_SNOOZE
snooze((bigtime_t)(1.0e6 * seconds));
return;
#endif
#ifdef HAVE_SELECT
struct timeval tv;
tv.tv_sec = (long)seconds;
tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec));
select(0, NULL, NULL, NULL, &tv);
return;
#endif
#ifdef HAVE_WAITFORSINGLEOBJECT
HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WaitForSingleObject(dummyEvent, (DWORD)(1000.0 * seconds));
CloseHandle(dummyEvent);
return;
#endif
// fall-back case is fugly manual timekeeping
TimeKeeper now = TimeKeeper::getCurrent();
while ((TimeKeeper::getCurrent() - now) < seconds) {
continue;
}
return;
}
void TimeKeeper::setProcessorAffinity(int processor)
{
#ifdef HAVE_SCHED_SETAFFINITY
/* linuxy fix for time travel */
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(processor, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
#elif defined(WIN32)
/* windowsy fix for time travel */
HANDLE hThread = GetCurrentThread();
DWORD_PTR dwMask = 1 << processor;
DWORD_PTR dwProcs = 0;
GetProcessAffinityMask(NULL, NULL, &dwProcs);
if (dwMask < dwProcs) {
logDebugMessage(1, "Unable to set process affinity mask (specified processor does not exist).\n");
return;
}
SetThreadAffinityMask(hThread, dwMask);
#else
logDebugMessage(1, "Unable to set processor affinity to %d - function not implemented on this platform.\n", processor);
#endif
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>* added a mutex lock around getCurrent() to protect against the sound thread (needs to be tested on windows, should probably add the debug message there as well)<commit_after>/* bzflag
* Copyright (c) 1993 - 2009 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface header
#include "TimeKeeper.h"
// system headers
#include <time.h>
#include <string>
#include <string.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef __BEOS__
# include <OS.h>
#endif
#if !defined(_WIN32)
# include <sys/time.h>
# include <sys/types.h>
static int64_t lastTime = 0;
# ifdef HAVE_SCHED_H
# include <sched.h>
# endif
#else // !defined(_WIN32)
# include <mmsystem.h>
static unsigned long int lastTime = 0;
static LARGE_INTEGER qpcLastTime;
static LONGLONG qpcFrequency = 0;
static LONGLONG qpcLastCalibration;
static DWORD timeLastCalibration;
#endif // !defined(_WIN32)
// system threading headers
#ifndef _WIN32
# include <sys/types.h>
# include <dirent.h>
#endif
#ifdef HAVE_PTHREADS
# include <pthread.h>
#endif
// common headers
#include "TextUtils.h"
#include "bzfio.h"
//============================================================================//
#if defined(HAVE_PTHREADS)
static pthread_mutex_t timer_mutex;
# define LOCK_TIMER_MUTEX pthread_mutex_lock(&timer_mutex);
# define UNLOCK_TIMER_MUTEX pthread_mutex_unlock(&timer_mutex);
#elif defined(_WIN32)
static CRITICAL_SECTION timer_critical;
# define LOCK_TIMER_MUTEX EnterCriticalSection(&timer_critical);
# define UNLOCK_TIMER_MUTEX LeaveCriticalSection(&timer_critical);
#else
# define LOCK_TIMER_MUTEX
# define UNLOCK_TIMER_MUTEX
#endif
//============================================================================//
static TimeKeeper currentTime;
static TimeKeeper tickTime;
static TimeKeeper sunExplodeTime;
static TimeKeeper sunGenesisTime;
static TimeKeeper nullTime;
static TimeKeeper startTime = TimeKeeper::getCurrent();
//============================================================================//
#if !defined(_WIN32)
static inline int64_t getEpochMicroseconds()
{
struct timeval nowTime;
gettimeofday(&nowTime, NULL);
return (int64_t(nowTime.tv_sec) * int64_t(1000000))
+ int64_t(nowTime.tv_usec);
}
#endif
const TimeKeeper& TimeKeeper::getCurrent(void)
{
LOCK_TIMER_MUTEX
// if not first call then update current time, else use default initial time
#if !defined(_WIN32)
if (lastTime == 0) {
// time starts at 0 seconds from the first call to getCurrent()
lastTime = getEpochMicroseconds();
}
else {
const int64_t nowTime = getEpochMicroseconds();
int64_t diff = (nowTime - lastTime);
if (diff < 0) {
logDebugMessage(5, "WARNING: went back in time %li microseconds\n",
(long int)diff);
diff = 0; // eh, how'd we go back in time?
}
currentTime += double(diff) * 1.0e-6;;
lastTime = nowTime;
}
#else /* !defined(_WIN32) */
if (qpcFrequency != 0) {
// main timer is qpc
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
LONGLONG diff = now.QuadPart - qpcLastTime.QuadPart;
LONGLONG clkSpent = now.QuadPart - qpcLastCalibration;
qpcLastTime = now;
if (clkSpent > qpcFrequency) {
// Recalibrate Frequency
DWORD tgt = timeGetTime();
DWORD deltaTgt = tgt - timeLastCalibration;
timeLastCalibration = tgt;
qpcLastCalibration = now.QuadPart;
if (deltaTgt > 0) {
LONGLONG oldqpcfreq = qpcFrequency;
qpcFrequency = (clkSpent * 1000) / deltaTgt;
if (qpcFrequency != oldqpcfreq)
logDebugMessage(4, "Recalibrated QPC frequency. Old: %f ; New: %f\n",
(double)oldqpcfreq, (double)qpcFrequency);
}
}
currentTime += (double) diff / (double) qpcFrequency;
} else if (lastTime != 0) {
unsigned long int now = (unsigned long int)timeGetTime();
unsigned long int diff;
if (now < lastTime) {
// eh, how'd we go back in time?
diff = 0;
} else {
diff = now - lastTime;
}
currentTime += 1.0e-3 * (double)diff;
lastTime = now;
} else {
static bool sane = true;
// should only get into here once on app start
if (!sane) {
logDebugMessage(1,"Sanity check failure in TimeKeeper::getCurrent()\n");
}
sane = false;
// make sure we're at our best timer resolution possible
timeBeginPeriod(1);
LARGE_INTEGER freq;
if (QueryPerformanceFrequency(&freq)) {
QueryPerformanceCounter(&qpcLastTime);
qpcFrequency = freq.QuadPart;
logDebugMessage(4,"Actual reported QPC Frequency: %f\n", (double)qpcFrequency);
qpcLastCalibration = qpcLastTime.QuadPart;
timeLastCalibration = timeGetTime();
} else {
logDebugMessage(1,"QueryPerformanceFrequency failed with error %d\n", GetLastError());
lastTime = (unsigned long int)timeGetTime();
}
}
#endif /* !defined(_WIN32) */
UNLOCK_TIMER_MUTEX
return currentTime;
}
const TimeKeeper& TimeKeeper::getStartTime(void) // const
{
return startTime;
}
const TimeKeeper& TimeKeeper::getTick(void) // const
{
return tickTime;
}
void TimeKeeper::setTick(void)
{
tickTime = getCurrent();
}
const TimeKeeper& TimeKeeper::getSunExplodeTime(void)
{
sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60;
return sunExplodeTime;
}
const TimeKeeper& TimeKeeper::getSunGenesisTime(void)
{
sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60;
return sunGenesisTime;
}
const TimeKeeper& TimeKeeper::getNullTime(void)
{
nullTime.seconds = 0;
return nullTime;
}
const char *TimeKeeper::timestamp(void) // const
{
static char buffer[256]; // static, so that it doesn't vanish
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d",
now->tm_year, now->tm_mon, now->tm_mday,
now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256);
buffer[255] = '\0'; // safety
return buffer;
}
/** returns a short string of the local time */
//static
std::string TimeKeeper::shortTimeStamp(void) {
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
std::string result( TextUtils::format("%02d:%02d", now->tm_hour, now->tm_min) );
return result;
}
void TimeKeeper::localTime(int *year, int *month, int* day,
int* hour, int* min, int* sec, bool* dst) // const
{
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
if (year) { *year = now->tm_year; }
if (month) { *month = now->tm_mon; }
if (day) { *day = now->tm_mday; }
if (hour) { *hour = now->tm_hour; }
if (min) { *min = now->tm_min; }
if (sec) { *sec = now->tm_sec; }
if (dst) { *dst = (now->tm_isdst != 0); }
}
void TimeKeeper::localTimeDOW(int *year, int *month, int* day, int* wday,
int* hour, int* min, int* sec, bool* dst) // const
{
time_t tnow = time(0);
struct tm *now = localtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
if (year) { *year = now->tm_year; }
if (month) { *month = now->tm_mon; }
if (day) { *day = now->tm_mday; }
if (wday) { *wday = now->tm_wday; }
if (hour) { *hour = now->tm_hour; }
if (min) { *min = now->tm_min; }
if (sec) { *sec = now->tm_sec; }
if (dst) { *dst = (now->tm_isdst != 0); }
}
void TimeKeeper::UTCTime(int *year, int *month, int* day, int* wday,
int* hour, int* min, int* sec, bool* dst) // const
{
time_t tnow = time(0);
struct tm *now = gmtime(&tnow);
now->tm_year += 1900;
++now->tm_mon;
if (year) { *year = now->tm_year; }
if (month) { *month = now->tm_mon; }
if (day) { *day = now->tm_mday; }
if (wday) { *wday = now->tm_wday; }
if (hour) { *hour = now->tm_hour; }
if (min) { *min = now->tm_min; }
if (sec) { *sec = now->tm_sec; }
if (dst) { *dst = (now->tm_isdst != 0); }
}
// function for converting a float time (e.g. difference of two TimeKeepers)
// into an array of ints
void TimeKeeper::convertTime(double raw, long int convertedTimes[]) // const
{
long int day, hour, min, sec, remainder;
static const int secondsInDay = 86400;
sec = (long int)raw;
day = sec / secondsInDay;
remainder = sec - (day * secondsInDay);
hour = remainder / 3600;
remainder = sec - ((hour * 3600) + (day * secondsInDay));
min = remainder / 60;
remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60));
sec = remainder;
convertedTimes[0] = day;
convertedTimes[1] = hour;
convertedTimes[2] = min;
convertedTimes[3] = sec;
return;
}
// function for printing an array of ints representing a time
// as a human-readable string
const std::string TimeKeeper::printTime(long int timeValue[])
{
std::string valueNames;
char temp[20];
if (timeValue[0] > 0) {
snprintf(temp, 20, "%ld day%s", timeValue[0], timeValue[0] == 1 ? "" : "s");
valueNames.append(temp);
}
if (timeValue[1] > 0) {
if (timeValue[0] > 0) {
valueNames.append(", ");
}
snprintf(temp, 20, "%ld hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s");
valueNames.append(temp);
}
if (timeValue[2] > 0) {
if ((timeValue[1] > 0) || (timeValue[0] > 0)) {
valueNames.append(", ");
}
snprintf(temp, 20, "%ld min%s", timeValue[2], timeValue[2] == 1 ? "" : "s");
valueNames.append(temp);
}
if (timeValue[3] > 0) {
if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) {
valueNames.append(", ");
}
snprintf(temp, 20, "%ld sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s");
valueNames.append(temp);
}
return valueNames;
}
// function for printing a float time difference as a human-readable string
const std::string TimeKeeper::printTime(double diff)
{
long int temp[4];
convertTime(diff, temp);
return printTime(temp);
}
void TimeKeeper::sleep(double seconds)
{
if (seconds <= 0.0) {
return;
}
#ifdef HAVE_USLEEP
usleep((unsigned int)(1.0e6 * seconds));
return;
#endif
#if defined(HAVE_SLEEP) && !defined(__APPLE__)
// equivalent to _sleep() on win32 (not sleep(3))
Sleep((DWORD)(seconds * 1000.0));
return;
#endif
#ifdef HAVE_SNOOZE
snooze((bigtime_t)(1.0e6 * seconds));
return;
#endif
#ifdef HAVE_SELECT
struct timeval tv;
tv.tv_sec = (long)seconds;
tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec));
select(0, NULL, NULL, NULL, &tv);
return;
#endif
#ifdef HAVE_WAITFORSINGLEOBJECT
HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WaitForSingleObject(dummyEvent, (DWORD)(1000.0 * seconds));
CloseHandle(dummyEvent);
return;
#endif
// fall-back case is fugly manual timekeeping
TimeKeeper now = TimeKeeper::getCurrent();
while ((TimeKeeper::getCurrent() - now) < seconds) {
continue;
}
return;
}
void TimeKeeper::setProcessorAffinity(int processor)
{
#ifdef HAVE_SCHED_SETAFFINITY
/* linuxy fix for time travel */
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(processor, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
#elif defined(WIN32)
/* windowsy fix for time travel */
HANDLE hThread = GetCurrentThread();
DWORD_PTR dwMask = 1 << processor;
DWORD_PTR dwProcs = 0;
GetProcessAffinityMask(NULL, NULL, &dwProcs);
if (dwMask < dwProcs) {
logDebugMessage(1, "Unable to set process affinity mask (specified processor does not exist).\n");
return;
}
SetThreadAffinityMask(hThread, dwMask);
#else
logDebugMessage(1, "Unable to set processor affinity to %d - function not implemented on this platform.\n", processor);
#endif
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdQuicklookViewRenderer.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtOpenGL>
//
// System includes (sorted by alphabetic order)
// necessary for the opengl variables and methods
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdDatasetModel.h"
#include "Core/mvdTypes.h"
#include "Core/mvdVectorImageModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::QuicklookViewRenderer
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
QuicklookViewRenderer
::QuicklookViewRenderer( QObject* parent ) :
ImageViewRenderer( parent ),
m_GlRoiActor( otb::GlROIActor::New() )
{
assert( !m_GlRoiActor.IsNull() );
this->SetReferenceActorShaderMode("STANDARD");
}
/*****************************************************************************/
QuicklookViewRenderer
::~QuicklookViewRenderer()
{
}
/*****************************************************************************/
AbstractImageViewRenderer::RenderingContext*
QuicklookViewRenderer
::NewRenderingContext() const
{
RenderingContext* context = new QuicklookViewRenderer::RenderingContext();
#if USE_VIEW_SETTINGS_SIDE_EFFECT
#else
assert( !m_GlView.IsNull() );
//
// Share otb::GlViewRendering settings with manipulator using
// RenderingContext. Manipulator can then setup otb::ViewSettings
// directly by side-effect.
context->m_ViewSettings = m_GlView->GetSettings();
#endif
return context;
}
/*******************************************************************************/
void
QuicklookViewRenderer
::virtual_FinishScene()
{
assert( !m_GlView.IsNull() );
// qDebug() << this << "::virtual_FinishScene()";
otb::GlImageActor::Pointer referenceGlImageActor( GetReferenceGlImageActor() );
if( referenceGlImageActor.IsNull() )
return;
std::string key( m_GlView->AddActor( m_GlRoiActor ) );
m_GlRoiActor->SetVisible( true );
m_GlRoiActor->SetKwl( referenceGlImageActor->GetKwl() );
m_GlRoiActor->SetWkt( referenceGlImageActor->GetWkt() );
/*
ColorType color;
color.Fill( 1.0 );
m_GlRoiActor->SetColor( color );
*/
m_GlRoiActor->SetFill( true );
m_GlRoiActor->SetAlpha( 0.2 );
m_GlView->MoveActorToEndOfRenderingOrder( key, true );
}
/*****************************************************************************/
void
QuicklookViewRenderer
::UpdateActors( const AbstractImageViewRenderer::RenderingContext* c )
{
assert( c!=NULL );
ImageViewRenderer::UpdateActors( c );
assert(
c==dynamic_cast< const QuicklookViewRenderer::RenderingContext * >( c )
);
const QuicklookViewRenderer::RenderingContext * context =
dynamic_cast< const QuicklookViewRenderer::RenderingContext * >( c );
/*
qDebug()
<< "ROI-origin:"
<< context->m_RoiOrigin[ 0 ] << "," << context->m_RoiOrigin[ 1 ]
<< "ROI-extent:"
<< context->m_RoiExtent[ 0 ] << "," << context->m_RoiExtent[ 1 ];
*/
m_GlRoiActor->SetUL( context->m_RoiOrigin );
m_GlRoiActor->SetLR( context->m_RoiExtent );
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
} // end namespace 'mvd'
<commit_msg>ENH: ROI should not be filled (odd when viewing large regions)<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdQuicklookViewRenderer.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtOpenGL>
//
// System includes (sorted by alphabetic order)
// necessary for the opengl variables and methods
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdDatasetModel.h"
#include "Core/mvdTypes.h"
#include "Core/mvdVectorImageModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::QuicklookViewRenderer
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
QuicklookViewRenderer
::QuicklookViewRenderer( QObject* parent ) :
ImageViewRenderer( parent ),
m_GlRoiActor( otb::GlROIActor::New() )
{
assert( !m_GlRoiActor.IsNull() );
this->SetReferenceActorShaderMode("STANDARD");
}
/*****************************************************************************/
QuicklookViewRenderer
::~QuicklookViewRenderer()
{
}
/*****************************************************************************/
AbstractImageViewRenderer::RenderingContext*
QuicklookViewRenderer
::NewRenderingContext() const
{
RenderingContext* context = new QuicklookViewRenderer::RenderingContext();
#if USE_VIEW_SETTINGS_SIDE_EFFECT
#else
assert( !m_GlView.IsNull() );
//
// Share otb::GlViewRendering settings with manipulator using
// RenderingContext. Manipulator can then setup otb::ViewSettings
// directly by side-effect.
context->m_ViewSettings = m_GlView->GetSettings();
#endif
return context;
}
/*******************************************************************************/
void
QuicklookViewRenderer
::virtual_FinishScene()
{
assert( !m_GlView.IsNull() );
// qDebug() << this << "::virtual_FinishScene()";
otb::GlImageActor::Pointer referenceGlImageActor( GetReferenceGlImageActor() );
if( referenceGlImageActor.IsNull() )
return;
std::string key( m_GlView->AddActor( m_GlRoiActor ) );
m_GlRoiActor->SetVisible( true );
m_GlRoiActor->SetKwl( referenceGlImageActor->GetKwl() );
m_GlRoiActor->SetWkt( referenceGlImageActor->GetWkt() );
/*
ColorType color;
color.Fill( 1.0 );
m_GlRoiActor->SetColor( color );
*/
m_GlRoiActor->SetFill( false );
m_GlRoiActor->SetAlpha( 0.2 );
m_GlView->MoveActorToEndOfRenderingOrder( key, true );
}
/*****************************************************************************/
void
QuicklookViewRenderer
::UpdateActors( const AbstractImageViewRenderer::RenderingContext* c )
{
assert( c!=NULL );
ImageViewRenderer::UpdateActors( c );
assert(
c==dynamic_cast< const QuicklookViewRenderer::RenderingContext * >( c )
);
const QuicklookViewRenderer::RenderingContext * context =
dynamic_cast< const QuicklookViewRenderer::RenderingContext * >( c );
/*
qDebug()
<< "ROI-origin:"
<< context->m_RoiOrigin[ 0 ] << "," << context->m_RoiOrigin[ 1 ]
<< "ROI-extent:"
<< context->m_RoiExtent[ 0 ] << "," << context->m_RoiExtent[ 1 ];
*/
m_GlRoiActor->SetUL( context->m_RoiOrigin );
m_GlRoiActor->SetLR( context->m_RoiExtent );
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
} // end namespace 'mvd'
<|endoftext|> |
<commit_before>// Filename: INSStaggeredStokesOperator.C
// Created on 29 Apr 2008 by Boyce Griffith
//
// Copyright (c) 2002-2010, Boyce Griffith
// 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 New York University 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 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 "INSStaggeredStokesOperator.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#ifndef included_IBAMR_config
#include <IBAMR_config.h>
#define included_IBAMR_config
#endif
#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif
// IBAMR INCLUDES
#include <ibamr/INSStaggeredPressureBcCoef.h>
#include <ibamr/namespaces.h>
// IBTK INCLUDES
#include <ibtk/CellNoCornersFillPattern.h>
#include <ibtk/SideNoCornersFillPattern.h>
// C++ STDLIB INCLUDES
#include <limits>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
namespace
{
// Number of ghosts cells used for each variable quantity.
static const int CELLG = (USING_LARGE_GHOST_CELL_WIDTH ? 2 : 1);
static const int SIDEG = (USING_LARGE_GHOST_CELL_WIDTH ? 2 : 1);
// Type of coarsening to perform prior to setting coarse-fine boundary and
// physical boundary ghost cell values.
static const std::string DATA_COARSEN_TYPE = "CUBIC_COARSEN";
// Type of extrapolation to use at physical boundaries.
static const std::string BDRY_EXTRAP_TYPE = "LINEAR";
// Whether to enforce consistent interpolated values at Type 2 coarse-fine
// interface ghost cells.
static const bool CONSISTENT_TYPE_2_BDRY = false;
// Timers.
static Pointer<Timer> t_apply;
static Pointer<Timer> t_initialize_operator_state;
static Pointer<Timer> t_deallocate_operator_state;
}
/////////////////////////////// PUBLIC ///////////////////////////////////////
INSStaggeredStokesOperator::INSStaggeredStokesOperator(
const INSCoefs& problem_coefs,
const std::vector<RobinBcCoefStrategy<NDIM>*>& U_bc_coefs,
Pointer<INSStaggeredPhysicalBoundaryHelper> U_bc_helper,
RobinBcCoefStrategy<NDIM>* P_bc_coef,
Pointer<HierarchyMathOps> hier_math_ops)
: d_is_initialized(false),
d_current_time(std::numeric_limits<double>::quiet_NaN()),
d_new_time(std::numeric_limits<double>::quiet_NaN()),
d_dt(std::numeric_limits<double>::quiet_NaN()),
d_problem_coefs(problem_coefs),
d_helmholtz_spec("INSStaggeredStokesOperator::helmholtz_spec"),
d_hier_math_ops(hier_math_ops),
d_homogeneous_bc(false),
d_correcting_rhs(false),
d_U_bc_coefs(U_bc_coefs),
d_U_bc_helper(U_bc_helper),
d_P_bc_coef(P_bc_coef),
d_U_P_bdry_fill_op(Pointer<HierarchyGhostCellInterpolation>(NULL)),
d_no_fill_op(Pointer<HierarchyGhostCellInterpolation>(NULL)),
d_x_scratch(NULL)
{
// Setup Timers.
static bool timers_need_init = true;
if (timers_need_init)
{
t_apply = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredStokesOperator::apply()");
t_initialize_operator_state = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredStokesOperator::initializeOperatorState()");
t_deallocate_operator_state = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredStokesOperator::deallocateOperatorState()");
timers_need_init = false;
}
return;
}// INSStaggeredStokesOperator
INSStaggeredStokesOperator::~INSStaggeredStokesOperator()
{
deallocateOperatorState();
return;
}// ~INSStaggeredStokesOperator
void
INSStaggeredStokesOperator::setHomogeneousBc(
const bool homogeneous_bc)
{
d_homogeneous_bc = homogeneous_bc;
return;
}// setHomogeneousBc
void
INSStaggeredStokesOperator::setTimeInterval(
const double current_time,
const double new_time)
{
const double rho = d_problem_coefs.getRho();
const double mu = d_problem_coefs.getMu();
const double lambda = d_problem_coefs.getLambda();
d_current_time = current_time;
d_new_time = new_time;
d_dt = d_new_time-d_current_time;
d_helmholtz_spec.setCConstant((rho/d_dt)+0.5*lambda);
d_helmholtz_spec.setDConstant( -0.5*mu );
return;
}// setTimeInterval
void
INSStaggeredStokesOperator::modifyRhsForInhomogeneousBc(
SAMRAIVectorReal<NDIM,double>& y)
{
// Set y := y - A*0, i.e., shift the right-hand-side vector to account for
// inhomogeneous boundary conditions.
if (!d_homogeneous_bc)
{
d_correcting_rhs = true;
Pointer<SAMRAIVectorReal<NDIM,double> > x = y.cloneVector("");
x->allocateVectorData();
x->setToScalar(0.0);
Pointer<SAMRAIVectorReal<NDIM,double> > b = y.cloneVector("");
b->allocateVectorData();
b->setToScalar(0.0);
apply(*x,*b);
y.subtract(Pointer<SAMRAIVectorReal<NDIM,double> >(&y, false), b);
x->freeVectorComponents();
x.setNull();
b->freeVectorComponents();
b.setNull();
d_correcting_rhs = false;
}
return;
}// modifyRhsForInhomogeneousBc
void
INSStaggeredStokesOperator::apply(
const bool homogeneous_bc,
SAMRAIVectorReal<NDIM,double>& x,
SAMRAIVectorReal<NDIM,double>& y)
{
t_apply->start();
// Get the vector components.
// const int U_in_idx = x.getComponentDescriptorIndex(0);
// const int P_in_idx = x.getComponentDescriptorIndex(1);
const int U_out_idx = y.getComponentDescriptorIndex(0);
const int P_out_idx = y.getComponentDescriptorIndex(1);
const int U_scratch_idx = d_x_scratch->getComponentDescriptorIndex(0);
const int P_scratch_idx = d_x_scratch->getComponentDescriptorIndex(1);
const Pointer<Variable<NDIM> >& U_out_var = y.getComponentVariable(0);
const Pointer<Variable<NDIM> >& P_out_var = y.getComponentVariable(1);
Pointer<SideVariable<NDIM,double> > U_out_sc_var = U_out_var;
Pointer<CellVariable<NDIM,double> > P_out_cc_var = P_out_var;
const Pointer<Variable<NDIM> >& U_scratch_var = d_x_scratch->getComponentVariable(0);
const Pointer<Variable<NDIM> >& P_scratch_var = d_x_scratch->getComponentVariable(1);
Pointer<SideVariable<NDIM,double> > U_scratch_sc_var = U_scratch_var;
Pointer<CellVariable<NDIM,double> > P_scratch_cc_var = P_scratch_var;
d_x_scratch->copyVector(Pointer<SAMRAIVectorReal<NDIM,double> >(&x,false));
// Reset the interpolation operators and fill the data.
Pointer<VariableFillPattern<NDIM> > sc_fill_pattern = new SideNoCornersFillPattern(SIDEG, false, true);
Pointer<VariableFillPattern<NDIM> > cc_fill_pattern = new CellNoCornersFillPattern(CELLG, false, true);
typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;
InterpolationTransactionComponent U_scratch_component(U_scratch_idx, DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_U_bc_coefs, sc_fill_pattern);
InterpolationTransactionComponent P_scratch_component(P_scratch_idx, DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_P_bc_coef , cc_fill_pattern);
std::vector<InterpolationTransactionComponent> U_P_components(2);
U_P_components[0] = U_scratch_component;
U_P_components[1] = P_scratch_component;
INSStaggeredPressureBcCoef* P_bc_coef = dynamic_cast<INSStaggeredPressureBcCoef*>(d_P_bc_coef);
P_bc_coef->setVelocityNewPatchDataIndex(U_scratch_idx);
d_U_P_bdry_fill_op->setHomogeneousBc(homogeneous_bc);
d_U_P_bdry_fill_op->resetTransactionComponents(U_P_components);
d_U_P_bdry_fill_op->fillData(d_new_time);
// Compute the action of the operator:
// A*[u;p] = [((rho/dt)*I-0.5*mu*L)*u + grad p; -div u].
static const bool cf_bdry_synch = true;
d_hier_math_ops->grad(
U_out_idx, U_out_sc_var,
cf_bdry_synch,
1.0, P_scratch_idx, P_scratch_cc_var, d_no_fill_op, d_new_time);
d_hier_math_ops->laplace(
U_out_idx, U_out_sc_var,
d_helmholtz_spec,
U_scratch_idx, U_scratch_sc_var, d_no_fill_op, d_new_time,
1.0,
U_out_idx, U_out_sc_var);
d_U_bc_helper->zeroValuesAtDirichletBoundaries(U_out_idx);
d_hier_math_ops->div(
P_out_idx, P_out_cc_var,
-1.0, U_scratch_idx, U_scratch_sc_var, d_no_fill_op, d_new_time,
cf_bdry_synch);
t_apply->stop();
return;
}// apply
void
INSStaggeredStokesOperator::apply(
SAMRAIVectorReal<NDIM,double>& x,
SAMRAIVectorReal<NDIM,double>& y)
{
apply(d_correcting_rhs ? d_homogeneous_bc : true,x,y);
return;
}// apply
void
INSStaggeredStokesOperator::initializeOperatorState(
const SAMRAIVectorReal<NDIM,double>& in,
const SAMRAIVectorReal<NDIM,double>& out)
{
t_initialize_operator_state->start();
if (d_is_initialized) deallocateOperatorState();
d_x_scratch = in.cloneVector("INSStaggeredStokesOperator::x_scratch");
d_x_scratch->allocateVectorData();
Pointer<VariableFillPattern<NDIM> > sc_fill_pattern = new SideNoCornersFillPattern(SIDEG, false, true);
Pointer<VariableFillPattern<NDIM> > cc_fill_pattern = new CellNoCornersFillPattern(CELLG, false, true);
typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;
InterpolationTransactionComponent U_scratch_component(d_x_scratch->getComponentDescriptorIndex(0), DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_U_bc_coefs, sc_fill_pattern);
InterpolationTransactionComponent P_scratch_component(d_x_scratch->getComponentDescriptorIndex(1), DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_P_bc_coef , cc_fill_pattern);
std::vector<InterpolationTransactionComponent> U_P_components(2);
U_P_components[0] = U_scratch_component;
U_P_components[1] = P_scratch_component;
d_U_P_bdry_fill_op = new HierarchyGhostCellInterpolation();
d_U_P_bdry_fill_op->initializeOperatorState(U_P_components, d_x_scratch->getPatchHierarchy());
d_is_initialized = true;
t_initialize_operator_state->stop();
return;
}// initializeOperatorState
void
INSStaggeredStokesOperator::deallocateOperatorState()
{
if (!d_is_initialized) return;
t_deallocate_operator_state->start();
d_x_scratch->freeVectorComponents();
d_x_scratch.setNull();
d_is_initialized = false;
t_deallocate_operator_state->stop();
return;
}// deallocateOperatorState
void
INSStaggeredStokesOperator::enableLogging(
bool enabled)
{
// intentionally blank
return;
}// enableLogging
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
}// namespace IBAMR
/////////////////////// TEMPLATE INSTANTIATION ///////////////////////////////
#include <tbox/Pointer.C>
template class Pointer<IBAMR::INSStaggeredStokesOperator>;
//////////////////////////////////////////////////////////////////////////////
<commit_msg>updated INSStaggeredStokesOperator.C to work with NULL BC objects<commit_after>// Filename: INSStaggeredStokesOperator.C
// Created on 29 Apr 2008 by Boyce Griffith
//
// Copyright (c) 2002-2010, Boyce Griffith
// 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 New York University 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 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 "INSStaggeredStokesOperator.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#ifndef included_IBAMR_config
#include <IBAMR_config.h>
#define included_IBAMR_config
#endif
#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif
// IBAMR INCLUDES
#include <ibamr/INSStaggeredPressureBcCoef.h>
#include <ibamr/namespaces.h>
// IBTK INCLUDES
#include <ibtk/CellNoCornersFillPattern.h>
#include <ibtk/SideNoCornersFillPattern.h>
// C++ STDLIB INCLUDES
#include <limits>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
namespace
{
// Number of ghosts cells used for each variable quantity.
static const int CELLG = (USING_LARGE_GHOST_CELL_WIDTH ? 2 : 1);
static const int SIDEG = (USING_LARGE_GHOST_CELL_WIDTH ? 2 : 1);
// Type of coarsening to perform prior to setting coarse-fine boundary and
// physical boundary ghost cell values.
static const std::string DATA_COARSEN_TYPE = "CUBIC_COARSEN";
// Type of extrapolation to use at physical boundaries.
static const std::string BDRY_EXTRAP_TYPE = "LINEAR";
// Whether to enforce consistent interpolated values at Type 2 coarse-fine
// interface ghost cells.
static const bool CONSISTENT_TYPE_2_BDRY = false;
// Timers.
static Pointer<Timer> t_apply;
static Pointer<Timer> t_initialize_operator_state;
static Pointer<Timer> t_deallocate_operator_state;
}
/////////////////////////////// PUBLIC ///////////////////////////////////////
INSStaggeredStokesOperator::INSStaggeredStokesOperator(
const INSCoefs& problem_coefs,
const std::vector<RobinBcCoefStrategy<NDIM>*>& U_bc_coefs,
Pointer<INSStaggeredPhysicalBoundaryHelper> U_bc_helper,
RobinBcCoefStrategy<NDIM>* P_bc_coef,
Pointer<HierarchyMathOps> hier_math_ops)
: d_is_initialized(false),
d_current_time(std::numeric_limits<double>::quiet_NaN()),
d_new_time(std::numeric_limits<double>::quiet_NaN()),
d_dt(std::numeric_limits<double>::quiet_NaN()),
d_problem_coefs(problem_coefs),
d_helmholtz_spec("INSStaggeredStokesOperator::helmholtz_spec"),
d_hier_math_ops(hier_math_ops),
d_homogeneous_bc(false),
d_correcting_rhs(false),
d_U_bc_coefs(U_bc_coefs),
d_U_bc_helper(U_bc_helper),
d_P_bc_coef(P_bc_coef),
d_U_P_bdry_fill_op(Pointer<HierarchyGhostCellInterpolation>(NULL)),
d_no_fill_op(Pointer<HierarchyGhostCellInterpolation>(NULL)),
d_x_scratch(NULL)
{
// Setup Timers.
static bool timers_need_init = true;
if (timers_need_init)
{
t_apply = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredStokesOperator::apply()");
t_initialize_operator_state = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredStokesOperator::initializeOperatorState()");
t_deallocate_operator_state = TimerManager::getManager()->getTimer("IBAMR::INSStaggeredStokesOperator::deallocateOperatorState()");
timers_need_init = false;
}
return;
}// INSStaggeredStokesOperator
INSStaggeredStokesOperator::~INSStaggeredStokesOperator()
{
deallocateOperatorState();
return;
}// ~INSStaggeredStokesOperator
void
INSStaggeredStokesOperator::setHomogeneousBc(
const bool homogeneous_bc)
{
d_homogeneous_bc = homogeneous_bc;
return;
}// setHomogeneousBc
void
INSStaggeredStokesOperator::setTimeInterval(
const double current_time,
const double new_time)
{
const double rho = d_problem_coefs.getRho();
const double mu = d_problem_coefs.getMu();
const double lambda = d_problem_coefs.getLambda();
d_current_time = current_time;
d_new_time = new_time;
d_dt = d_new_time-d_current_time;
d_helmholtz_spec.setCConstant((rho/d_dt)+0.5*lambda);
d_helmholtz_spec.setDConstant( -0.5*mu );
return;
}// setTimeInterval
void
INSStaggeredStokesOperator::modifyRhsForInhomogeneousBc(
SAMRAIVectorReal<NDIM,double>& y)
{
// Set y := y - A*0, i.e., shift the right-hand-side vector to account for
// inhomogeneous boundary conditions.
if (!d_homogeneous_bc)
{
d_correcting_rhs = true;
Pointer<SAMRAIVectorReal<NDIM,double> > x = y.cloneVector("");
x->allocateVectorData();
x->setToScalar(0.0);
Pointer<SAMRAIVectorReal<NDIM,double> > b = y.cloneVector("");
b->allocateVectorData();
b->setToScalar(0.0);
apply(*x,*b);
y.subtract(Pointer<SAMRAIVectorReal<NDIM,double> >(&y, false), b);
x->freeVectorComponents();
x.setNull();
b->freeVectorComponents();
b.setNull();
d_correcting_rhs = false;
}
return;
}// modifyRhsForInhomogeneousBc
void
INSStaggeredStokesOperator::apply(
const bool homogeneous_bc,
SAMRAIVectorReal<NDIM,double>& x,
SAMRAIVectorReal<NDIM,double>& y)
{
t_apply->start();
// Get the vector components.
// const int U_in_idx = x.getComponentDescriptorIndex(0);
// const int P_in_idx = x.getComponentDescriptorIndex(1);
const int U_out_idx = y.getComponentDescriptorIndex(0);
const int P_out_idx = y.getComponentDescriptorIndex(1);
const int U_scratch_idx = d_x_scratch->getComponentDescriptorIndex(0);
const int P_scratch_idx = d_x_scratch->getComponentDescriptorIndex(1);
const Pointer<Variable<NDIM> >& U_out_var = y.getComponentVariable(0);
const Pointer<Variable<NDIM> >& P_out_var = y.getComponentVariable(1);
Pointer<SideVariable<NDIM,double> > U_out_sc_var = U_out_var;
Pointer<CellVariable<NDIM,double> > P_out_cc_var = P_out_var;
const Pointer<Variable<NDIM> >& U_scratch_var = d_x_scratch->getComponentVariable(0);
const Pointer<Variable<NDIM> >& P_scratch_var = d_x_scratch->getComponentVariable(1);
Pointer<SideVariable<NDIM,double> > U_scratch_sc_var = U_scratch_var;
Pointer<CellVariable<NDIM,double> > P_scratch_cc_var = P_scratch_var;
d_x_scratch->copyVector(Pointer<SAMRAIVectorReal<NDIM,double> >(&x,false));
// Reset the interpolation operators and fill the data.
Pointer<VariableFillPattern<NDIM> > sc_fill_pattern = new SideNoCornersFillPattern(SIDEG, false, true);
Pointer<VariableFillPattern<NDIM> > cc_fill_pattern = new CellNoCornersFillPattern(CELLG, false, true);
typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;
InterpolationTransactionComponent U_scratch_component(U_scratch_idx, DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_U_bc_coefs, sc_fill_pattern);
InterpolationTransactionComponent P_scratch_component(P_scratch_idx, DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_P_bc_coef , cc_fill_pattern);
std::vector<InterpolationTransactionComponent> U_P_components(2);
U_P_components[0] = U_scratch_component;
U_P_components[1] = P_scratch_component;
INSStaggeredPressureBcCoef* P_bc_coef = dynamic_cast<INSStaggeredPressureBcCoef*>(d_P_bc_coef);
if (P_bc_coef != NULL) P_bc_coef->setVelocityNewPatchDataIndex(U_scratch_idx);
d_U_P_bdry_fill_op->setHomogeneousBc(homogeneous_bc);
d_U_P_bdry_fill_op->resetTransactionComponents(U_P_components);
d_U_P_bdry_fill_op->fillData(d_new_time);
// Compute the action of the operator:
// A*[u;p] = [((rho/dt)*I-0.5*mu*L)*u + grad p; -div u].
static const bool cf_bdry_synch = true;
d_hier_math_ops->grad(
U_out_idx, U_out_sc_var,
cf_bdry_synch,
1.0, P_scratch_idx, P_scratch_cc_var, d_no_fill_op, d_new_time);
d_hier_math_ops->laplace(
U_out_idx, U_out_sc_var,
d_helmholtz_spec,
U_scratch_idx, U_scratch_sc_var, d_no_fill_op, d_new_time,
1.0,
U_out_idx, U_out_sc_var);
if (!d_U_bc_helper.isNull()) d_U_bc_helper->zeroValuesAtDirichletBoundaries(U_out_idx);
d_hier_math_ops->div(
P_out_idx, P_out_cc_var,
-1.0, U_scratch_idx, U_scratch_sc_var, d_no_fill_op, d_new_time,
cf_bdry_synch);
t_apply->stop();
return;
}// apply
void
INSStaggeredStokesOperator::apply(
SAMRAIVectorReal<NDIM,double>& x,
SAMRAIVectorReal<NDIM,double>& y)
{
apply(d_correcting_rhs ? d_homogeneous_bc : true,x,y);
return;
}// apply
void
INSStaggeredStokesOperator::initializeOperatorState(
const SAMRAIVectorReal<NDIM,double>& in,
const SAMRAIVectorReal<NDIM,double>& out)
{
t_initialize_operator_state->start();
if (d_is_initialized) deallocateOperatorState();
d_x_scratch = in.cloneVector("INSStaggeredStokesOperator::x_scratch");
d_x_scratch->allocateVectorData();
Pointer<VariableFillPattern<NDIM> > sc_fill_pattern = new SideNoCornersFillPattern(SIDEG, false, true);
Pointer<VariableFillPattern<NDIM> > cc_fill_pattern = new CellNoCornersFillPattern(CELLG, false, true);
typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;
InterpolationTransactionComponent U_scratch_component(d_x_scratch->getComponentDescriptorIndex(0), DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_U_bc_coefs, sc_fill_pattern);
InterpolationTransactionComponent P_scratch_component(d_x_scratch->getComponentDescriptorIndex(1), DATA_COARSEN_TYPE, BDRY_EXTRAP_TYPE, CONSISTENT_TYPE_2_BDRY, d_P_bc_coef , cc_fill_pattern);
std::vector<InterpolationTransactionComponent> U_P_components(2);
U_P_components[0] = U_scratch_component;
U_P_components[1] = P_scratch_component;
d_U_P_bdry_fill_op = new HierarchyGhostCellInterpolation();
d_U_P_bdry_fill_op->initializeOperatorState(U_P_components, d_x_scratch->getPatchHierarchy());
d_is_initialized = true;
t_initialize_operator_state->stop();
return;
}// initializeOperatorState
void
INSStaggeredStokesOperator::deallocateOperatorState()
{
if (!d_is_initialized) return;
t_deallocate_operator_state->start();
d_x_scratch->freeVectorComponents();
d_x_scratch.setNull();
d_is_initialized = false;
t_deallocate_operator_state->stop();
return;
}// deallocateOperatorState
void
INSStaggeredStokesOperator::enableLogging(
bool enabled)
{
// intentionally blank
return;
}// enableLogging
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
}// namespace IBAMR
/////////////////////// TEMPLATE INSTANTIATION ///////////////////////////////
#include <tbox/Pointer.C>
template class Pointer<IBAMR::INSStaggeredStokesOperator>;
//////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "NeighborCoupleable.h"
#include "FEProblem.h"
#include "MooseError.h" // mooseDeprecated
#include "MooseVariableFE.h"
#include "Problem.h"
#include "SubProblem.h"
NeighborCoupleable::NeighborCoupleable(const MooseObject * moose_object,
bool nodal,
bool neighbor_nodal,
bool is_fv)
: Coupleable(moose_object, nodal, is_fv), _neighbor_nodal(neighbor_nodal)
{
}
const VariableValue &
NeighborCoupleable::coupledNeighborValue(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return (_c_is_implicit) ? var->dofValuesNeighbor() : var->dofValuesOldNeighbor();
else
return (_c_is_implicit) ? var->slnNeighbor() : var->slnOldNeighbor();
}
std::vector<const VariableValue *>
NeighborCoupleable::coupledNeighborValues(const std::string & var_name) const
{
auto func = [this, &var_name](unsigned int comp) {
return &coupledNeighborValue(var_name, comp);
};
return coupledVectorHelper<const VariableValue *>(var_name, func);
}
const ADVariableValue &
NeighborCoupleable::adCoupledNeighborValue(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVarHelper<MooseVariableField<Real>>(var_name, comp);
if (!var)
return *getADDefaultValue(var_name);
if (_neighbor_nodal)
mooseError("adCoupledNeighborValue cannot be used for nodal compute objects at this time");
if (!_c_is_implicit)
mooseError("adCoupledNeighborValue returns a data structure with derivatives. Explicit schemes "
"use old solution data which do not have derivatives so adCoupledNeighborValue is "
"not appropriate. Please use coupledNeighborValue instead");
return var->adSlnNeighbor();
}
std::vector<const ADVariableValue *>
NeighborCoupleable::adCoupledNeighborValues(const std::string & var_name) const
{
auto func = [this, &var_name](unsigned int comp) {
return &adCoupledNeighborValue(var_name, comp);
};
return coupledVectorHelper<const ADVariableValue *>(var_name, func);
}
const ADVectorVariableValue &
NeighborCoupleable::adCoupledVectorNeighborValue(const std::string & var_name,
unsigned int comp) const
{
auto var = getVarHelper<MooseVariableField<RealVectorValue>>(var_name, comp);
if (!var)
return *getADDefaultVectorValue(var_name);
if (_neighbor_nodal)
mooseError(
"adCoupledVectorNeighborValue cannot be used for nodal compute objects at this time");
if (!_c_is_implicit)
mooseError(
"adCoupledVectorNeighborValue returns a data structure with derivatives. Explicit schemes "
"use old solution data which do not have derivatives so adCoupledVectorNeighborValue is "
"not appropriate. Please use coupledNeighborValue instead");
return var->adSlnNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueDot(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return var->dofValuesDotNeighbor();
else
return var->uDotNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueDotDu(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return var->dofValuesDuDotDuNeighbor();
else
return var->duDotDuNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueOld(const std::string & var_name, unsigned int comp) const
{
validateExecutionerType(var_name, "coupledNeighborValueOld");
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return (_c_is_implicit) ? var->dofValuesOldNeighbor() : var->dofValuesOlderNeighbor();
else
return (_c_is_implicit) ? var->slnOldNeighbor() : var->slnOlderNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueOlder(const std::string & var_name, unsigned int comp) const
{
validateExecutionerType(var_name, "coupledNeighborValueOlder");
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
{
if (_c_is_implicit)
return var->dofValuesOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
else
{
if (_c_is_implicit)
return var->slnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
}
const VariableGradient &
NeighborCoupleable::coupledNeighborGradient(const std::string & var_name, unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have gradients");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnNeighbor() : var->gradSlnOldNeighbor();
}
const VariableGradient &
NeighborCoupleable::coupledNeighborGradientOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have gradients");
validateExecutionerType(var_name, "coupledNeighborGradientOld");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnOldNeighbor() : var->gradSlnOlderNeighbor();
}
const VariableGradient &
NeighborCoupleable::coupledNeighborGradientOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have gradients");
validateExecutionerType(var_name, "coupledNeighborGradientOlder");
const auto * var = getVar(var_name, comp);
if (_c_is_implicit)
return var->gradSlnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
const VectorVariableGradient &
NeighborCoupleable::coupledVectorNeighborGradient(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
const auto * var = getVectorVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnNeighbor() : var->gradSlnOldNeighbor();
}
const VectorVariableGradient &
NeighborCoupleable::coupledVectorNeighborGradientOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledVectorNeighborGradientOld");
const auto * var = getVectorVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnOldNeighbor() : var->gradSlnOlderNeighbor();
}
const VectorVariableGradient &
NeighborCoupleable::coupledVectorNeighborGradientOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledVectorNeighborGradientOlder");
const auto * var = getVectorVar(var_name, comp);
if (_c_is_implicit)
return var->gradSlnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
const ArrayVariableValue &
NeighborCoupleable::coupledArrayNeighborValue(const std::string & var_name, unsigned int comp) const
{
const auto * var = getArrayVar(var_name, comp);
if (_neighbor_nodal)
return (_c_is_implicit) ? var->dofValuesNeighbor() : var->dofValuesOldNeighbor();
else
return (_c_is_implicit) ? var->slnNeighbor() : var->slnOldNeighbor();
}
const ArrayVariableGradient &
NeighborCoupleable::coupledArrayNeighborGradient(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
const auto * var = getArrayVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnNeighbor() : var->gradSlnOldNeighbor();
}
const ArrayVariableGradient &
NeighborCoupleable::coupledArrayNeighborGradientOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledArrayNeighborGradientOld");
const auto * var = getArrayVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnOldNeighbor() : var->gradSlnOlderNeighbor();
}
const ArrayVariableGradient &
NeighborCoupleable::coupledArrayNeighborGradientOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledArrayNeighborGradientOlder");
const auto * var = getArrayVar(var_name, comp);
if (_c_is_implicit)
return var->gradSlnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
const VariableSecond &
NeighborCoupleable::coupledNeighborSecond(const std::string & var_name, unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have second derivatives");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->secondSlnNeighbor() : var->secondSlnOldNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborDofValues(const std::string & var_name, unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("nodal objects should not call coupledDofValues");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->dofValuesNeighbor() : var->dofValuesOldNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborDofValuesOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("nodal objects should not call coupledDofValuesOld");
validateExecutionerType(var_name, "coupledNeighborDofValuesOld");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->dofValuesOldNeighbor() : var->dofValuesOlderNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborDofValuesOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("nodal objects should not call coupledDofValuesOlder");
validateExecutionerType(var_name, "coupledNeighborDofValuesOlder");
const auto * var = getVar(var_name, comp);
if (_c_is_implicit)
return var->dofValuesOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
<commit_msg>Allow use of FV variables with neighborCoupledValue/Gradient<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "NeighborCoupleable.h"
#include "FEProblem.h"
#include "MooseError.h" // mooseDeprecated
#include "MooseVariableFE.h"
#include "Problem.h"
#include "SubProblem.h"
NeighborCoupleable::NeighborCoupleable(const MooseObject * moose_object,
bool nodal,
bool neighbor_nodal,
bool is_fv)
: Coupleable(moose_object, nodal, is_fv), _neighbor_nodal(neighbor_nodal)
{
}
const VariableValue &
NeighborCoupleable::coupledNeighborValue(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVarHelper<MooseVariableField<Real>>(var_name, comp);
if (_neighbor_nodal)
return (_c_is_implicit) ? var->dofValuesNeighbor() : var->dofValuesOldNeighbor();
else
return (_c_is_implicit) ? var->slnNeighbor() : var->slnOldNeighbor();
}
std::vector<const VariableValue *>
NeighborCoupleable::coupledNeighborValues(const std::string & var_name) const
{
auto func = [this, &var_name](unsigned int comp) {
return &coupledNeighborValue(var_name, comp);
};
return coupledVectorHelper<const VariableValue *>(var_name, func);
}
const ADVariableValue &
NeighborCoupleable::adCoupledNeighborValue(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVarHelper<MooseVariableField<Real>>(var_name, comp);
if (!var)
return *getADDefaultValue(var_name);
if (_neighbor_nodal)
mooseError("adCoupledNeighborValue cannot be used for nodal compute objects at this time");
if (!_c_is_implicit)
mooseError("adCoupledNeighborValue returns a data structure with derivatives. Explicit schemes "
"use old solution data which do not have derivatives so adCoupledNeighborValue is "
"not appropriate. Please use coupledNeighborValue instead");
return var->adSlnNeighbor();
}
std::vector<const ADVariableValue *>
NeighborCoupleable::adCoupledNeighborValues(const std::string & var_name) const
{
auto func = [this, &var_name](unsigned int comp) {
return &adCoupledNeighborValue(var_name, comp);
};
return coupledVectorHelper<const ADVariableValue *>(var_name, func);
}
const ADVectorVariableValue &
NeighborCoupleable::adCoupledVectorNeighborValue(const std::string & var_name,
unsigned int comp) const
{
auto var = getVarHelper<MooseVariableField<RealVectorValue>>(var_name, comp);
if (!var)
return *getADDefaultVectorValue(var_name);
if (_neighbor_nodal)
mooseError(
"adCoupledVectorNeighborValue cannot be used for nodal compute objects at this time");
if (!_c_is_implicit)
mooseError(
"adCoupledVectorNeighborValue returns a data structure with derivatives. Explicit schemes "
"use old solution data which do not have derivatives so adCoupledVectorNeighborValue is "
"not appropriate. Please use coupledNeighborValue instead");
return var->adSlnNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueDot(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return var->dofValuesDotNeighbor();
else
return var->uDotNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueDotDu(const std::string & var_name, unsigned int comp) const
{
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return var->dofValuesDuDotDuNeighbor();
else
return var->duDotDuNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueOld(const std::string & var_name, unsigned int comp) const
{
validateExecutionerType(var_name, "coupledNeighborValueOld");
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
return (_c_is_implicit) ? var->dofValuesOldNeighbor() : var->dofValuesOlderNeighbor();
else
return (_c_is_implicit) ? var->slnOldNeighbor() : var->slnOlderNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborValueOlder(const std::string & var_name, unsigned int comp) const
{
validateExecutionerType(var_name, "coupledNeighborValueOlder");
const auto * var = getVar(var_name, comp);
if (_neighbor_nodal)
{
if (_c_is_implicit)
return var->dofValuesOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
else
{
if (_c_is_implicit)
return var->slnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
}
const VariableGradient &
NeighborCoupleable::coupledNeighborGradient(const std::string & var_name, unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have gradients");
const auto * var = getVarHelper<MooseVariableField<Real>>(var_name, comp);
return (_c_is_implicit) ? var->gradSlnNeighbor() : var->gradSlnOldNeighbor();
}
const VariableGradient &
NeighborCoupleable::coupledNeighborGradientOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have gradients");
validateExecutionerType(var_name, "coupledNeighborGradientOld");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnOldNeighbor() : var->gradSlnOlderNeighbor();
}
const VariableGradient &
NeighborCoupleable::coupledNeighborGradientOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have gradients");
validateExecutionerType(var_name, "coupledNeighborGradientOlder");
const auto * var = getVar(var_name, comp);
if (_c_is_implicit)
return var->gradSlnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
const VectorVariableGradient &
NeighborCoupleable::coupledVectorNeighborGradient(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
const auto * var = getVectorVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnNeighbor() : var->gradSlnOldNeighbor();
}
const VectorVariableGradient &
NeighborCoupleable::coupledVectorNeighborGradientOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledVectorNeighborGradientOld");
const auto * var = getVectorVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnOldNeighbor() : var->gradSlnOlderNeighbor();
}
const VectorVariableGradient &
NeighborCoupleable::coupledVectorNeighborGradientOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledVectorNeighborGradientOlder");
const auto * var = getVectorVar(var_name, comp);
if (_c_is_implicit)
return var->gradSlnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
const ArrayVariableValue &
NeighborCoupleable::coupledArrayNeighborValue(const std::string & var_name, unsigned int comp) const
{
const auto * var = getArrayVar(var_name, comp);
if (_neighbor_nodal)
return (_c_is_implicit) ? var->dofValuesNeighbor() : var->dofValuesOldNeighbor();
else
return (_c_is_implicit) ? var->slnNeighbor() : var->slnOldNeighbor();
}
const ArrayVariableGradient &
NeighborCoupleable::coupledArrayNeighborGradient(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
const auto * var = getArrayVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnNeighbor() : var->gradSlnOldNeighbor();
}
const ArrayVariableGradient &
NeighborCoupleable::coupledArrayNeighborGradientOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledArrayNeighborGradientOld");
const auto * var = getArrayVar(var_name, comp);
return (_c_is_implicit) ? var->gradSlnOldNeighbor() : var->gradSlnOlderNeighbor();
}
const ArrayVariableGradient &
NeighborCoupleable::coupledArrayNeighborGradientOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Gradients are non-sensical with nodal compute objects");
validateExecutionerType(var_name, "coupledArrayNeighborGradientOlder");
const auto * var = getArrayVar(var_name, comp);
if (_c_is_implicit)
return var->gradSlnOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
const VariableSecond &
NeighborCoupleable::coupledNeighborSecond(const std::string & var_name, unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("Nodal variables do not have second derivatives");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->secondSlnNeighbor() : var->secondSlnOldNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborDofValues(const std::string & var_name, unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("nodal objects should not call coupledDofValues");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->dofValuesNeighbor() : var->dofValuesOldNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborDofValuesOld(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("nodal objects should not call coupledDofValuesOld");
validateExecutionerType(var_name, "coupledNeighborDofValuesOld");
const auto * var = getVar(var_name, comp);
return (_c_is_implicit) ? var->dofValuesOldNeighbor() : var->dofValuesOlderNeighbor();
}
const VariableValue &
NeighborCoupleable::coupledNeighborDofValuesOlder(const std::string & var_name,
unsigned int comp) const
{
if (_neighbor_nodal)
mooseError("nodal objects should not call coupledDofValuesOlder");
validateExecutionerType(var_name, "coupledNeighborDofValuesOlder");
const auto * var = getVar(var_name, comp);
if (_c_is_implicit)
return var->dofValuesOlderNeighbor();
else
mooseError("Older values not available for explicit schemes");
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/simple_spin.h"
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
void simple_spin_lock(simple_spinlock_t *lock)
{
static uint32_t bar = 13;
static uint32_t *foo = &bar;
while(1) {
__sync_synchronize();
uint32_t oldval = *lock;
if (oldval == 0) {
if (__sync_bool_compare_and_swap(lock, 0, 1))
return;
}
// delay
for (int i = 0; i < 100000; i++) {
*foo = (*foo * 33) + 17;
}
}
}
void simple_spin_unlock(simple_spinlock_t *lock)
{
__sync_bool_compare_and_swap(lock, 1, 0);
}
<commit_msg>simple_spin: use file-scope global not function<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/simple_spin.h"
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
static uint32_t bar = 13;
static uint32_t *foo = &bar;
void simple_spin_lock(simple_spinlock_t *lock)
{
while(1) {
__sync_synchronize();
uint32_t oldval = *lock;
if (oldval == 0) {
if (__sync_bool_compare_and_swap(lock, 0, 1))
return;
}
// delay
for (int i = 0; i < 100000; i++) {
*foo = (*foo * 33) + 17;
}
}
}
void simple_spin_unlock(simple_spinlock_t *lock)
{
__sync_bool_compare_and_swap(lock, 1, 0);
}
<|endoftext|> |
<commit_before>// win32_handmade.cpp
// compiles with -doc -FC -Zi win32_handmade.cpp user32.lib gdi32.lib
// see: build.bat for switches used in compilation
/* ========================================================================
$File: $
$Date: $
$Revision: 0.1.d4.b(build#) $
$Creator: Sebastian Meier zu Biesen $
$Notice: (C) Copyright 2000-2016 by Joker Solutions, All Rights Reserved. $
======================================================================== */
#include <Windows.h>
#include <stdint.h>
#include "win32_handmade.h"
global_variable bool Running;
global_variable bool Debug = 0;
global_variable BITMAPINFO BitmapInfo;
global_variable void *BitmapMemory;
global_variable int BytesPerPixel = 4;
global_variable int BitmapWidth;
global_variable int BitmapHeight;
internal void Win32RenderGradient(int XOffset, int YOffset) {
int Pitch = BitmapWidth*BytesPerPixel;
uint8 *Row = (uint8 *)BitmapMemory;
for (int Y = 0; Y < BitmapHeight; ++Y) {
uint32 *Pixel = (uint32 *)Row;
for (int X = 0; X < BitmapWidth; ++X) {
uint8 Blue = (X + XOffset);
uint8 Green = (Y + YOffset);
uint8 Red = (X + XOffset);
*Pixel++ = ((Red << 16) | (Green << 8) | (Blue));
}
Row += Pitch;
}
}
internal void Win32ResizeDIBSection(int Width, int Height) {
if (BitmapMemory) {
VirtualFree(BitmapMemory,0,MEM_RELEASE);
}
BitmapWidth = Width;
BitmapHeight = Height;
BitmapInfo.bmiHeader.biSize = sizeof(BitmapInfo.bmiHeader);
BitmapInfo.bmiHeader.biWidth = BitmapWidth;
BitmapInfo.bmiHeader.biHeight = -BitmapHeight;
BitmapInfo.bmiHeader.biPlanes = 1;
BitmapInfo.bmiHeader.biBitCount = 32;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
int BitmapMemorySize = (BitmapWidth*BitmapHeight)*BytesPerPixel;
BitmapMemory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE);
}
internal void Win32UpdateWindow(HDC DeviceContext, RECT *WindowRect, int X, int Y, int Width, int Height) {
int WindowWidth = WindowRect->right - WindowRect->left;
int WindowHeight = WindowRect->bottom - WindowRect->top;
StretchDIBits(DeviceContext, 0, 0, BitmapWidth, BitmapHeight, 0, 0, WindowWidth, WindowHeight, BitmapMemory, &BitmapInfo, DIB_RGB_COLORS, SRCCOPY);
}
LRESULT CALLBACK Win32MainWindowCallback(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam)
{
LRESULT Result = 0;
switch (Message) {
case WM_SIZE:
{
RECT WindowRect;
GetClientRect(Window,&WindowRect);
int Width = WindowRect.right - WindowRect.left;
int Height = WindowRect.bottom - WindowRect.top;
Win32ResizeDIBSection(Width, Height);
if (Debug) { OutputDebugStringA("WM_SIZE\n"); }
} break;
case WM_DESTROY:
{
Running = false;
if (Debug) { OutputDebugStringA("WM_DESTROY\n"); }
} break;
case WM_CLOSE:
{
Running = false;
if (Debug) { OutputDebugStringA("WM_CLOSE\n"); }
} break;
case WM_QUIT:
{
if (Debug) { OutputDebugStringA("WM_QUIT\n"); }
} break;
case WM_ACTIVATEAPP:
{
if (Debug) { OutputDebugStringA("WM_ACTIVATEAPP\n"); }
} break;
case WM_PAINT:
{
PAINTSTRUCT Paint;
HDC DeviceContext = BeginPaint(Window, &Paint);
int X = Paint.rcPaint.left;
int Y = Paint.rcPaint.top;
int Width = Paint.rcPaint.right - Paint.rcPaint.left;
int Height = Paint.rcPaint.bottom - Paint.rcPaint.top;
RECT WindowRect;
GetClientRect(Window, &WindowRect);
Win32UpdateWindow(DeviceContext, &WindowRect, X, Y, Width, Height);
EndPaint(Window,&Paint);
if (Debug) { OutputDebugStringA("WM_PAINT\n"); }
} break;
default:
{
Result = DefWindowProc(Window,Message,WParam,LParam);
//OutputDebugStringA("default\n");
} break;
}
return(Result);
}
int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE hPrevInstance, LPSTR CommandLine, int ShowCode) {
WNDCLASS WindowClass = {};
WindowClass.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC;
WindowClass.lpfnWndProc = Win32MainWindowCallback;
WindowClass.hInstance = Instance;
//WindowClass.hIcon = ;
//WindowClass.hCursor = ;
WindowClass.lpszClassName = "hmhWindowClass";
if (RegisterClass(&WindowClass))
{
HWND WindowHandle = CreateWindowEx(
0,
WindowClass.lpszClassName,
"Handmade Hero v0.1",
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
0,
0,
Instance,
0);
if (WindowHandle)
{
int XOffset = 0;
int YOffset = 0;
Running = true;
while(Running)
{
MSG Message;
while (PeekMessage(&Message, 0, 0, 0, PM_REMOVE)) {
if (Message.message == WM_QUIT) {
Running = false;
}
TranslateMessage(&Message);
DispatchMessage(&Message);
}
Win32RenderGradient(XOffset, YOffset);
HDC DeviceContext = GetDC(WindowHandle);
RECT WindowRect;
GetClientRect(WindowHandle, &WindowRect);
int WindowWidth = WindowRect.right - WindowRect.left;
int WindowHeight = WindowRect.bottom - WindowRect.top;
Win32UpdateWindow(DeviceContext,&WindowRect,0,0,WindowWidth,WindowHeight);
ReleaseDC(WindowHandle, DeviceContext);
++XOffset;
}
}
else
{
//TODO(smzb): Log this event
}
}
else {
//TODO(smzb): log this event
}
if (Debug) { MessageBox(0, "This is Handmade Hero", "Handmade Hero v0.1", MB_OK | MB_ICONINFORMATION); }
return 0;
}
<commit_msg>moved Bitmap related global vars into their own struct + some code cleanup<commit_after>// win32_handmade.cpp
// compiles with -doc -FC -Zi win32_handmade.cpp user32.lib gdi32.lib
// see: build.bat for switches used in compilation
/* ========================================================================
$File: $
$Date: $
$Revision: 0.1.d4.b(build#) $
$Creator: Sebastian Meier zu Biesen $
$Notice: (C) Copyright 2000-2016 by Joker Solutions, All Rights Reserved. $
======================================================================== */
#include <Windows.h>
#include <stdint.h>
#include "win32_handmade.h"
struct win32_offscreen_buffer {
BITMAPINFO Info;
void *Memory;
int BytesPerPixel = 4;
int Width;
int Height;
int Pitch;
};
global_variable bool Running;
global_variable bool Debug = 0;
global_variable win32_offscreen_buffer GlobalBackBuffer;
internal void Win32RenderGradient(win32_offscreen_buffer Buffer, int XOffset, int YOffset) {
uint8 *Row = (uint8 *)Buffer.Memory;
for (int Y = 0; Y < Buffer.Height; ++Y) {
uint32 *Pixel = (uint32 *)Row;
for (int X = 0; X < Buffer.Width; ++X) {
uint8 Blue = (X + XOffset);
uint8 Green = (Y + YOffset);
uint8 Red = (X + XOffset);
*Pixel++ = ((Red << 16) | (Green << 8) | (Blue));
}
Row += Buffer.Pitch;
}
}
internal void Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height) {
if (Buffer->Memory) {
VirtualFree(Buffer->Memory,0,MEM_RELEASE);
}
Buffer->Width = Width;
Buffer->Height = Height;
Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
Buffer->Info.bmiHeader.biWidth = Buffer->Width;
Buffer->Info.bmiHeader.biHeight = -Buffer->Height;
Buffer->Info.bmiHeader.biPlanes = 1;
Buffer->Info.bmiHeader.biBitCount = 32;
Buffer->Info.bmiHeader.biCompression = BI_RGB;
int BitmapMemorySize = (Buffer->Width*Buffer->Height)*Buffer->BytesPerPixel;
Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE);
Buffer->Pitch = Buffer->Width*Buffer->BytesPerPixel;
}
internal void Win32DisplayBufferInWindow(HDC DeviceContext, RECT WindowRect, win32_offscreen_buffer Buffer, int X, int Y, int Width, int Height) {
int WindowWidth = WindowRect.right - WindowRect.left;
int WindowHeight = WindowRect.bottom - WindowRect.top;
StretchDIBits(DeviceContext, 0, 0, Buffer.Width, Buffer.Height, 0, 0, WindowWidth, WindowHeight, Buffer.Memory, &Buffer.Info, DIB_RGB_COLORS, SRCCOPY);
}
LRESULT CALLBACK Win32MainWindowCallback(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam)
{
LRESULT Result = 0;
switch (Message) {
case WM_SIZE:
{
RECT WindowRect;
GetClientRect(Window,&WindowRect);
int Width = WindowRect.right - WindowRect.left;
int Height = WindowRect.bottom - WindowRect.top;
Win32ResizeDIBSection(&GlobalBackBuffer, Width, Height);
if (Debug) { OutputDebugStringA("WM_SIZE\n"); }
} break;
case WM_DESTROY:
{
Running = false;
if (Debug) { OutputDebugStringA("WM_DESTROY\n"); }
} break;
case WM_CLOSE:
{
Running = false;
if (Debug) { OutputDebugStringA("WM_CLOSE\n"); }
} break;
case WM_QUIT:
{
if (Debug) { OutputDebugStringA("WM_QUIT\n"); }
} break;
case WM_ACTIVATEAPP:
{
if (Debug) { OutputDebugStringA("WM_ACTIVATEAPP\n"); }
} break;
case WM_PAINT:
{
PAINTSTRUCT Paint;
HDC DeviceContext = BeginPaint(Window, &Paint);
int X = Paint.rcPaint.left;
int Y = Paint.rcPaint.top;
int Width = Paint.rcPaint.right - Paint.rcPaint.left;
int Height = Paint.rcPaint.bottom - Paint.rcPaint.top;
RECT WindowRect;
GetClientRect(Window, &WindowRect);
Win32DisplayBufferInWindow(DeviceContext, WindowRect, GlobalBackBuffer , X, Y, Width, Height);
EndPaint(Window,&Paint);
if (Debug) { OutputDebugStringA("WM_PAINT\n"); }
} break;
default:
{
Result = DefWindowProc(Window,Message,WParam,LParam);
//OutputDebugStringA("default\n");
} break;
}
return(Result);
}
int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE hPrevInstance, LPSTR CommandLine, int ShowCode) {
WNDCLASS WindowClass = {};
WindowClass.style = CS_HREDRAW|CS_VREDRAW;
WindowClass.lpfnWndProc = Win32MainWindowCallback;
WindowClass.hInstance = Instance;
//WindowClass.hIcon = ;
//WindowClass.hCursor = ;
WindowClass.lpszClassName = "hmhWindowClass";
if (RegisterClass(&WindowClass))
{
HWND WindowHandle = CreateWindowEx(
0,
WindowClass.lpszClassName,
"Handmade Hero v0.1",
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
0,
0,
Instance,
0);
if (WindowHandle)
{
int XOffset = 0;
int YOffset = 0;
Running = true;
while(Running)
{
MSG Message;
while (PeekMessage(&Message, 0, 0, 0, PM_REMOVE)) {
if (Message.message == WM_QUIT) {
Running = false;
}
TranslateMessage(&Message);
DispatchMessage(&Message);
}
Win32RenderGradient(GlobalBackBuffer, XOffset, YOffset);
HDC DeviceContext = GetDC(WindowHandle);
RECT WindowRect;
GetClientRect(WindowHandle, &WindowRect);
int WindowWidth = WindowRect.right - WindowRect.left;
int WindowHeight = WindowRect.bottom - WindowRect.top;
Win32DisplayBufferInWindow(DeviceContext, WindowRect, GlobalBackBuffer, 0, 0, WindowWidth, WindowHeight);
ReleaseDC(WindowHandle, DeviceContext);
++XOffset;
}
}
else
{
//TODO(smzb): Log this event
}
}
else {
//TODO(smzb): log this event
}
if (Debug) { MessageBox(0, "This is Handmade Hero", "Handmade Hero v0.1", MB_OK | MB_ICONINFORMATION); }
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "cpprefactoringchanges.h"
using namespace CPlusPlus;
using namespace CppTools;
using namespace TextEditor;
CppRefactoringChanges::CppRefactoringChanges(const Snapshot &snapshot,
CppModelManagerInterface *modelManager)
: m_snapshot(snapshot)
, m_modelManager(modelManager)
, m_workingCopy(modelManager->workingCopy())
{
Q_ASSERT(modelManager);
}
QStringList CppRefactoringChanges::apply()
{
const QStringList changedFiles = TextEditor::RefactoringChanges::apply();
m_modelManager->updateSourceFiles(changedFiles);
return changedFiles;
}
Document::Ptr CppRefactoringChanges::parsedDocumentForFile(const QString &fileName) const
{
Document::Ptr doc = m_snapshot.document(fileName);
QString source;
if (m_workingCopy.contains(fileName)) {
QPair<QString, unsigned> workingCopy = m_workingCopy.get(fileName);
if (doc && doc->editorRevision() == workingCopy.second)
return doc;
else
source = workingCopy.first;
} else {
QFile file(fileName);
if (! file.open(QFile::ReadOnly))
return Document::Ptr();
source = QTextStream(&file).readAll(); // ### FIXME read bytes, and remove the convert below
file.close();
}
doc = m_snapshot.documentFromSource(source.toLatin1(), fileName);
doc->check();
return doc;
}
<commit_msg>Preprocess the source file.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "cpprefactoringchanges.h"
using namespace CPlusPlus;
using namespace CppTools;
using namespace TextEditor;
CppRefactoringChanges::CppRefactoringChanges(const Snapshot &snapshot,
CppModelManagerInterface *modelManager)
: m_snapshot(snapshot)
, m_modelManager(modelManager)
, m_workingCopy(modelManager->workingCopy())
{
Q_ASSERT(modelManager);
}
QStringList CppRefactoringChanges::apply()
{
const QStringList changedFiles = TextEditor::RefactoringChanges::apply();
m_modelManager->updateSourceFiles(changedFiles);
return changedFiles;
}
Document::Ptr CppRefactoringChanges::parsedDocumentForFile(const QString &fileName) const
{
Document::Ptr doc = m_snapshot.document(fileName);
QString source;
if (m_workingCopy.contains(fileName)) {
QPair<QString, unsigned> workingCopy = m_workingCopy.get(fileName);
if (doc && doc->editorRevision() == workingCopy.second)
return doc;
else
source = workingCopy.first;
} else {
QFile file(fileName);
if (! file.open(QFile::ReadOnly))
return Document::Ptr();
source = QTextStream(&file).readAll(); // ### FIXME read bytes, and remove the convert below
file.close();
}
const QByteArray contents = m_snapshot.preprocessedCode(source, fileName);
doc = m_snapshot.documentFromSource(contents, fileName);
doc->check();
return doc;
}
<|endoftext|> |
<commit_before>#define _POSIX_SOURCE
#include "afs.h"
#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "condor_constants.h"
#include "subproc.h"
#include <string.h>
static char *_FileName_ = __FILE__; // Used by EXCEPT (see condor_debug.h)
AFS_Info::AFS_Info()
{
char *tmp;
my_cell_name = 0;
// find out if we're running AFS here
if( (tmp=param("HAS_AFS")) == NULL ) {
has_afs = FALSE;
return;
}
if( tmp[0] == 't' || tmp[0] == 'T' ) {
has_afs = TRUE;
} else {
free( tmp ); /* BUG FIXED : Ashish */
has_afs = FALSE;
return;
}
free( tmp ); /* BUG FIXED : Ashish */
// get pathname for the "fs" program
if( (tmp=param("FS_PATHNAME")) == NULL ) {
EXCEPT( "FS_PATHNAME not defined" );
}
strcpy( fs_pathname, tmp );
free( tmp ); /* BUG FIXED : Ashish */
// get pathname for the "vos" program
if( (tmp=param("VOS_PATHNAME")) == NULL ) {
EXCEPT( "VOS_PATHNAME not defined" );
}
strcpy( vos_pathname, tmp );
free( tmp ); /* BUG FIXED : Ashish */
my_cell_name = 0;
}
AFS_Info::~AFS_Info()
{
delete [] my_cell_name;
}
void
AFS_Info::display()
{
if( !has_afs ) {
dprintf( D_ALWAYS, "This machine doesn't run AFS\n" );
return;
}
dprintf( D_ALWAYS, "fs_pathname: \"%s\"\n", fs_pathname );
dprintf( D_ALWAYS, "vos_pathname: \"%s\"\n", vos_pathname );
if( my_cell_name ) {
dprintf( D_ALWAYS, "my_cell_name: \"%s\"\n", my_cell_name );
} else {
dprintf( D_ALWAYS, "my_cell_name: \"%s\"\n", "(NULL)" );
}
}
char *
AFS_Info::my_cell()
{
char *ptr;
if( !my_cell_name ) {
// find out what AFS cell we're in
if( (ptr=find_my_cell()) == NULL ) {
return NULL;
}
my_cell_name = new char[ strlen(ptr) + 1 ];
strcpy( my_cell_name, ptr );
}
return my_cell_name;
}
/*
Use the "fs wscell" command to find the AFS cell of this host.
*/
char *
AFS_Info::find_my_cell()
{
char *answer;
char buf[_POSIX_PATH_MAX ];
FILE *fp;
char *ptr;
SubProc p( fs_pathname, "wscell", "r" );
if( !has_afs ) {
return NULL;
}
return p.parse_output( "belongs to cell", "'", "'" );
}
/*
Use the "fs whichcell" command to find the AFS cell of the given pathname.
*/
char *
AFS_Info::which_cell( const char *path )
{
char *answer;
char args[ _POSIX_PATH_MAX ];
FILE *fp;
SubProc *fs;
if( !has_afs ) {
return NULL;
}
sprintf( args, "whichcell %s", path );
fs = new SubProc( fs_pathname, args, "r" );
answer = fs->parse_output("in cell", "'", "'" );
delete fs;
return answer;
}
/*
Use the "fs examine" command to find the AFS volume of the given pathname.
*/
char *
AFS_Info::which_vol( const char *path )
{
char *answer;
char args[ _POSIX_PATH_MAX ];
FILE *fp;
char *ptr;
SubProc *fs;
if( !has_afs ) {
return NULL;
}
sprintf( args, "examine %s", path );
fs = new SubProc( fs_pathname, args, "r" );
answer = fs->parse_output( "Volume status", "named ", "\n" );
delete fs;
return answer;
}
char *
AFS_Info::which_srvr( const char *path )
{
SubProc *vos;
char *answer;
char args[ _POSIX_PATH_MAX ];
char *vol;
if( !has_afs ) {
return NULL;
}
vol = which_vol( path );
sprintf( args, "examine %s", vol );
vos = new SubProc( vos_pathname, args, "r" );
answer = vos->parse_output( " server", "server ", " partition" );
delete vos;
return answer;
}
/*
The following routines provide a simple C interface to this class.
*/
static AFS_Info *MyInfo;
extern "C" {
char *
get_host_cell()
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->my_cell();
}
char *get_file_cell( const char *pathname )
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->which_cell( pathname );
}
char *get_file_vol( const char *pathname )
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->which_vol( pathname );
}
char *get_file_srvr( const char *pathname )
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->which_srvr( pathname );
}
} /* end of extern "C" */
<commit_msg>if file doesn't exist, check to see if directory is on AFS<commit_after>#define _POSIX_SOURCE
#include "afs.h"
#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "condor_constants.h"
#include "subproc.h"
#include <string.h>
static char *_FileName_ = __FILE__; // Used by EXCEPT (see condor_debug.h)
AFS_Info::AFS_Info()
{
char *tmp;
my_cell_name = 0;
// find out if we're running AFS here
if( (tmp=param("HAS_AFS")) == NULL ) {
has_afs = FALSE;
return;
}
if( tmp[0] == 't' || tmp[0] == 'T' ) {
has_afs = TRUE;
} else {
free( tmp ); /* BUG FIXED : Ashish */
has_afs = FALSE;
return;
}
free( tmp ); /* BUG FIXED : Ashish */
// get pathname for the "fs" program
if( (tmp=param("FS_PATHNAME")) == NULL ) {
EXCEPT( "FS_PATHNAME not defined" );
}
strcpy( fs_pathname, tmp );
free( tmp ); /* BUG FIXED : Ashish */
// get pathname for the "vos" program
if( (tmp=param("VOS_PATHNAME")) == NULL ) {
EXCEPT( "VOS_PATHNAME not defined" );
}
strcpy( vos_pathname, tmp );
free( tmp ); /* BUG FIXED : Ashish */
my_cell_name = 0;
}
AFS_Info::~AFS_Info()
{
delete [] my_cell_name;
}
void
AFS_Info::display()
{
if( !has_afs ) {
dprintf( D_ALWAYS, "This machine doesn't run AFS\n" );
return;
}
dprintf( D_ALWAYS, "fs_pathname: \"%s\"\n", fs_pathname );
dprintf( D_ALWAYS, "vos_pathname: \"%s\"\n", vos_pathname );
if( my_cell_name ) {
dprintf( D_ALWAYS, "my_cell_name: \"%s\"\n", my_cell_name );
} else {
dprintf( D_ALWAYS, "my_cell_name: \"%s\"\n", "(NULL)" );
}
}
char *
AFS_Info::my_cell()
{
char *ptr;
if( !my_cell_name ) {
// find out what AFS cell we're in
if( (ptr=find_my_cell()) == NULL ) {
return NULL;
}
my_cell_name = new char[ strlen(ptr) + 1 ];
strcpy( my_cell_name, ptr );
}
return my_cell_name;
}
/*
Use the "fs wscell" command to find the AFS cell of this host.
*/
char *
AFS_Info::find_my_cell()
{
char *answer;
char buf[_POSIX_PATH_MAX ];
FILE *fp;
char *ptr;
SubProc p( fs_pathname, "wscell", "r" );
if( !has_afs ) {
return NULL;
}
return p.parse_output( "belongs to cell", "'", "'" );
}
/*
Use the "fs whichcell" command to find the AFS cell of the given pathname.
*/
char *
AFS_Info::which_cell( const char *path )
{
char *answer;
char args[ _POSIX_PATH_MAX ];
FILE *fp;
SubProc *fs;
if( !has_afs ) {
return NULL;
}
sprintf( args, "whichcell %s", path );
fs = new SubProc( fs_pathname, args, "r" );
answer = fs->parse_output("in cell", "'", "'" );
delete fs;
// file might not be created yet; if answer is NULL, try to find
// directory on AFS
if (answer == NULL) {
int i;
for (i = strlen(args); i >= 0 && args[i] != '/'; i--);
if (i >= 0) {
args[i] = '\0';
fs = new SubProc( fs_pathname, args, "r" );
answer = fs->parse_output("in cell", "'", "'" );
delete fs;
}
}
return answer;
}
/*
Use the "fs examine" command to find the AFS volume of the given pathname.
*/
char *
AFS_Info::which_vol( const char *path )
{
char *answer;
char args[ _POSIX_PATH_MAX ];
FILE *fp;
char *ptr;
SubProc *fs;
if( !has_afs ) {
return NULL;
}
sprintf( args, "examine %s", path );
fs = new SubProc( fs_pathname, args, "r" );
answer = fs->parse_output( "Volume status", "named ", "\n" );
delete fs;
// file might not be created yet; if answer is NULL, try to find
// directory on AFS
if (answer == NULL) {
int i;
for (i = strlen(args); i >= 0 && args[i] != '/'; i--);
if (i >= 0) {
args[i] = '\0';
fs = new SubProc( fs_pathname, args, "r" );
answer = fs->parse_output("in cell", "'", "'" );
delete fs;
}
}
return answer;
}
char *
AFS_Info::which_srvr( const char *path )
{
SubProc *vos;
char *answer;
char args[ _POSIX_PATH_MAX ];
char *vol;
if( !has_afs ) {
return NULL;
}
vol = which_vol( path );
sprintf( args, "examine %s", vol );
vos = new SubProc( vos_pathname, args, "r" );
answer = vos->parse_output( " server", "server ", " partition" );
delete vos;
return answer;
}
/*
The following routines provide a simple C interface to this class.
*/
static AFS_Info *MyInfo;
extern "C" {
char *
get_host_cell()
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->my_cell();
}
char *get_file_cell( const char *pathname )
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->which_cell( pathname );
}
char *get_file_vol( const char *pathname )
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->which_vol( pathname );
}
char *get_file_srvr( const char *pathname )
{
if( !MyInfo ) {
MyInfo = new AFS_Info();
}
return MyInfo->which_srvr( pathname );
}
} /* end of extern "C" */
<|endoftext|> |
<commit_before>#define LUMIX_NO_CUSTOM_CRT
#include "../model.h"
#include "../renderer.h"
#include "../render_scene.h"
#include "editor/studio_app.h"
#include "editor/world_editor.h"
#include "engine/core.h"
#include "engine/engine.h"
#include "engine/universe.h"
#include "imgui/imgui.h"
#include "spline_geometry_plugin.h"
namespace Lumix {
static const ComponentType SPLINE_GEOMETRY_TYPE = reflection::getComponentType("spline_geometry");
static const ComponentType SPLINE_TYPE = reflection::getComponentType("spline");
struct SplineIterator {
SplineIterator(Span<const Vec3> points) : points(points) {}
void move(float delta) { t += delta; }
bool isEnd() { return u32(t) >= points.length() - 2; }
Vec3 getDir() {
const u32 segment = u32(t);
float rel_t = t - segment;
Vec3 p0 = points[segment + 0];
Vec3 p1 = points[segment + 1];
Vec3 p2 = points[segment + 2];
return lerp(p1 - p0, p2 - p1, rel_t);
}
Vec3 getPosition() {
const u32 segment = u32(t);
float rel_t = t - segment;
Vec3 p0 = points[segment + 0];
Vec3 p1 = points[segment + 1];
Vec3 p2 = points[segment + 2];
p0 = (p1 + p0) * 0.5f;
p2 = (p1 + p2) * 0.5f;
return lerp(lerp(p0, p1, rel_t), lerp(p1, p2, rel_t), rel_t);
}
float t = 0;
Span<const Vec3> points;
};
SplineGeometryPlugin::SplineGeometryPlugin(StudioApp& app)
: m_app(app)
{}
void SplineGeometryPlugin::paint(const DVec3& pos, const Universe& universe, EntityRef entity, ProceduralGeometry& pg, Renderer& renderer) const {
if (pg.vertex_data.size() == 0) return;
// TODO undo/redo
const Transform tr = universe.getTransform(entity);
const Vec3 center(tr.inverted().transform(pos));
const float R2 = m_brush_size * m_brush_size;
const u8* end = pg.vertex_data.data() + pg.vertex_data.size();
const u32 stride = pg.vertex_decl.getStride();
ASSERT(stride != 0);
const u32 offset = 20 + m_brush_channel; // TODO
for (u8* iter = pg.vertex_data.getMutableData(); iter < end; iter += stride) {
Vec3 p;
memcpy(&p, iter, sizeof(p));
if (squaredLength(p - center) < R2) {
*(iter + offset) = m_brush_value;
}
}
if (pg.vertex_buffer) renderer.destroy(pg.vertex_buffer);
const Renderer::MemRef mem = renderer.copy(pg.vertex_data.data(), (u32)pg.vertex_data.size());
pg.vertex_buffer = renderer.createBuffer(mem, gpu::BufferFlags::IMMUTABLE);
}
bool SplineGeometryPlugin::paint(UniverseView& view, i32 x, i32 y) {
WorldEditor& editor = view.getEditor();
const Array<EntityRef>& selected = editor.getSelectedEntities();
if (selected.size() != 1) return false;
const Universe& universe = *editor.getUniverse();
const bool is_spline = universe.hasComponent(selected[0], SPLINE_GEOMETRY_TYPE);
if (!is_spline) return false;
RenderScene* scene = (RenderScene*)universe.getScene(SPLINE_GEOMETRY_TYPE);
DVec3 origin;
Vec3 dir;
view.getViewport().getRay({(float)x, (float)y}, origin, dir);
const RayCastModelHit hit = scene->castRayProceduralGeometry(origin, dir);
if (!hit.is_hit) return false;
if (hit.entity != selected[0]) return false;
Renderer* renderer = (Renderer*)editor.getEngine().getPluginManager().getPlugin("renderer");
ASSERT(renderer);
ProceduralGeometry& pg = scene->getProceduralGeometry(selected[0]);
paint(hit.origin + hit.t * hit.dir, universe, selected[0], pg, *renderer);
return true;
}
bool SplineGeometryPlugin::onMouseDown(UniverseView& view, int x, int y) {
return paint(view, x, y);
}
void SplineGeometryPlugin::onMouseUp(UniverseView& view, int x, int y, os::MouseButton button) {
}
void SplineGeometryPlugin::onMouseMove(UniverseView& view, int x, int y, int rel_x, int rel_y) {
paint(view, x, y);
}
void SplineGeometryPlugin::drawCursor(WorldEditor& editor, EntityRef entity) const {
const UniverseView& view = editor.getView();
const Vec2 mp = view.getMousePos();
Universe& universe = *editor.getUniverse();
RenderScene* scene = static_cast<RenderScene*>(universe.getScene(SPLINE_GEOMETRY_TYPE));
DVec3 origin;
Vec3 dir;
editor.getView().getViewport().getRay(mp, origin, dir);
const RayCastModelHit hit = scene->castRayProceduralGeometry(origin, dir);
if (hit.is_hit) {
const DVec3 center = hit.origin + hit.dir * hit.t;
drawCursor(editor, *scene, entity, center);
return;
}
}
void SplineGeometryPlugin::drawCursor(WorldEditor& editor, RenderScene& scene, EntityRef entity, const DVec3& center) const {
UniverseView& view = editor.getView();
addCircle(view, center, m_brush_size, Vec3(0, 1, 0), Color::GREEN);
const ProceduralGeometry& pg = scene.getProceduralGeometry(entity);
if (pg.vertex_data.size() == 0) return;
const u8* data = pg.vertex_data.data();
const u32 stride = pg.vertex_decl.getStride();
const float R2 = m_brush_size * m_brush_size;
const Transform tr = scene.getUniverse().getTransform(entity);
const Vec3 center_local = Vec3(tr.inverted().transform(center));
for (u32 i = 0, c = pg.getIndexCount(); i < c; ++i) {
Vec3 p;
memcpy(&p, data + stride * i, sizeof(p));
if (squaredLength(center_local - p) < R2) {
addCircle(view, tr.transform(p), 0.1f, Vec3(0, 1, 0), Color::BLUE);
}
}
}
void SplineGeometryPlugin::onGUI(PropertyGrid& grid, ComponentUID cmp, WorldEditor& editor) {
if (cmp.type != SPLINE_GEOMETRY_TYPE) return;
const EntityRef e = *cmp.entity;
Universe& universe = cmp.scene->getUniverse();
if (!universe.hasComponent(*cmp.entity, SPLINE_TYPE)) {
ImGui::TextUnformatted("There's no spline component");
if (ImGui::Button("Create spline component")) {
editor.addComponent(Span(&e, 1), SPLINE_TYPE);
}
}
else {
RenderScene* render_scene = (RenderScene*)universe.getScene(SPLINE_GEOMETRY_TYPE);
CoreScene* core_scene = (CoreScene*)universe.getScene(SPLINE_TYPE);
const Spline& spline = core_scene->getSpline(e);
const SplineGeometry& sg = render_scene->getSplineGeometry(e);
const ProceduralGeometry& pg = render_scene->getProceduralGeometry(e);
drawCursor(editor, *cmp.entity);
ImGuiEx::Label("Triangles");
ImGui::Text("%d", pg.index_data.size() / (pg.index_type == gpu::DataType::U16 ? 2 : 4) / 3);
ImGuiEx::Label("Brush size");
ImGui::DragFloat("##bs", &m_brush_size, 0.1f, 0, FLT_MAX);
if (sg.num_user_channels > 1) {
ImGuiEx::Label("Paint channel");
ImGui::SliderInt("##pc", (int*)&m_brush_channel, 0, sg.num_user_channels - 1);
}
ImGuiEx::Label("Paint value");
ImGui::SliderInt("##pv", (int*)&m_brush_value, 0, 255);
if (ImGui::Button("Generate geometry")) {
if (!spline.points.empty()) {
const float width = sg.width;
SplineIterator iterator(spline.points);
gpu::VertexDecl decl;
decl.addAttribute(0, 0, 3, gpu::AttributeType::FLOAT, 0);
OutputMemoryStream vertices(m_app.getAllocator());
OutputMemoryStream indices(m_app.getAllocator());
vertices.reserve(16 * 1024);
if (sg.flags.isSet(SplineGeometry::HAS_UVS)) {
decl.addAttribute(1, 12, 2, gpu::AttributeType::FLOAT, 0);
struct Vertex {
Vec3 position;
Vec2 uv;
};
auto write_vertex = [&](const Vertex& v){
vertices.write(v);
if (sg.num_user_channels > 0) {
u32 tmp = 0;
vertices.write(&tmp, sg.num_user_channels);
}
};
float u = 0;
u32 rows = 0;
Vec3 prev_p = spline.points[0];
const u32 u_density = sg.u_density;
while (!iterator.isEnd()) {
++rows;
const Vec3 p = iterator.getPosition();
const Vec3 dir = iterator.getDir();
const Vec3 side = normalize(cross(Vec3(0, 1, 0), dir)) * width;
u += length(p - prev_p);
const Vec3 p0 = p - side;
for (u32 i = 0; i < u_density; ++i) {
Vertex v;
v.position = p0 + 2 * side * (i / float(u_density - 1));
v.uv.x = u;
v.uv.y = i / float(u_density - 1) * width;
write_vertex(v);
}
iterator.move(sg.v_density);
prev_p = p;
}
for (u32 row = 0; row < rows - 1; ++row) {
for (u32 i = 0; i < u_density - 1; ++i) {
indices.write(u16(u_density * row + i));
indices.write(u16(u_density * row + i + 1));
indices.write(u16(u_density * (row + 1) + i));
indices.write(u16(u_density * row + i + 1));
indices.write(u16(u_density * (row + 1) + i));
indices.write(u16(u_density * (row + 1) + i + 1));
}
}
if (sg.num_user_channels > 0) {
decl.addAttribute(2, 20, sg.num_user_channels, gpu::AttributeType::U8, gpu::Attribute::NORMALIZED);
}
}
else {
while (!iterator.isEnd()) {
const Vec3 p = iterator.getPosition();
const Vec3 dir = iterator.getDir();
const Vec3 side = normalize(cross(Vec3(0, 1, 0), dir)) * width;
const Vec3 v0 = p + side;
const Vec3 v1 = p - side;
vertices.write(v0);
if (sg.num_user_channels > 0) {
u32 tmp = 0;
vertices.write(&tmp, sg.num_user_channels);
}
vertices.write(v1);
if (sg.num_user_channels > 0) {
u32 tmp = 0;
vertices.write(&tmp, sg.num_user_channels);
}
iterator.move(0.1f);
}
if (sg.num_user_channels > 0) {
decl.addAttribute(1, 12, sg.num_user_channels, gpu::AttributeType::U8, gpu::Attribute::NORMALIZED);
}
}
render_scene->setProceduralGeometry(e, vertices, decl, gpu::PrimitiveType::TRIANGLES, indices, gpu::DataType::U16);
}
}
}
}
} // namespace Lumix<commit_msg>fixed linux build<commit_after>#define LUMIX_NO_CUSTOM_CRT
#include "../model.h"
#include "../renderer.h"
#include "../render_scene.h"
#include "editor/studio_app.h"
#include "editor/world_editor.h"
#include "engine/core.h"
#include "engine/engine.h"
#include "engine/universe.h"
#include "imgui/imgui.h"
#include "spline_geometry_plugin.h"
namespace Lumix {
static const ComponentType SPLINE_GEOMETRY_TYPE = reflection::getComponentType("spline_geometry");
static const ComponentType SPLINE_TYPE = reflection::getComponentType("spline");
struct SplineIterator {
SplineIterator(Span<const Vec3> points) : points(points) {}
void move(float delta) { t += delta; }
bool isEnd() { return u32(t) >= points.length() - 2; }
Vec3 getDir() {
const u32 segment = u32(t);
float rel_t = t - segment;
Vec3 p0 = points[segment + 0];
Vec3 p1 = points[segment + 1];
Vec3 p2 = points[segment + 2];
return lerp(p1 - p0, p2 - p1, rel_t);
}
Vec3 getPosition() {
const u32 segment = u32(t);
float rel_t = t - segment;
Vec3 p0 = points[segment + 0];
Vec3 p1 = points[segment + 1];
Vec3 p2 = points[segment + 2];
p0 = (p1 + p0) * 0.5f;
p2 = (p1 + p2) * 0.5f;
return lerp(lerp(p0, p1, rel_t), lerp(p1, p2, rel_t), rel_t);
}
float t = 0;
Span<const Vec3> points;
};
SplineGeometryPlugin::SplineGeometryPlugin(StudioApp& app)
: m_app(app)
{}
void SplineGeometryPlugin::paint(const DVec3& pos, const Universe& universe, EntityRef entity, ProceduralGeometry& pg, Renderer& renderer) const {
if (pg.vertex_data.size() == 0) return;
// TODO undo/redo
const Transform tr = universe.getTransform(entity);
const Vec3 center(tr.inverted().transform(pos));
const float R2 = m_brush_size * m_brush_size;
const u8* end = pg.vertex_data.data() + pg.vertex_data.size();
const u32 stride = pg.vertex_decl.getStride();
ASSERT(stride != 0);
const u32 offset = 20 + m_brush_channel; // TODO
for (u8* iter = pg.vertex_data.getMutableData(); iter < end; iter += stride) {
Vec3 p;
memcpy(&p, iter, sizeof(p));
if (squaredLength(p - center) < R2) {
*(iter + offset) = m_brush_value;
}
}
if (pg.vertex_buffer) renderer.destroy(pg.vertex_buffer);
const Renderer::MemRef mem = renderer.copy(pg.vertex_data.data(), (u32)pg.vertex_data.size());
pg.vertex_buffer = renderer.createBuffer(mem, gpu::BufferFlags::IMMUTABLE);
}
bool SplineGeometryPlugin::paint(UniverseView& view, i32 x, i32 y) {
WorldEditor& editor = view.getEditor();
const Array<EntityRef>& selected = editor.getSelectedEntities();
if (selected.size() != 1) return false;
const Universe& universe = *editor.getUniverse();
const bool is_spline = universe.hasComponent(selected[0], SPLINE_GEOMETRY_TYPE);
if (!is_spline) return false;
RenderScene* scene = (RenderScene*)universe.getScene(SPLINE_GEOMETRY_TYPE);
DVec3 origin;
Vec3 dir;
view.getViewport().getRay({(float)x, (float)y}, origin, dir);
const RayCastModelHit hit = scene->castRayProceduralGeometry(origin, dir);
if (!hit.is_hit) return false;
if (hit.entity != selected[0]) return false;
Renderer* renderer = (Renderer*)editor.getEngine().getPluginManager().getPlugin("renderer");
ASSERT(renderer);
ProceduralGeometry& pg = scene->getProceduralGeometry(selected[0]);
paint(hit.origin + hit.t * hit.dir, universe, selected[0], pg, *renderer);
return true;
}
bool SplineGeometryPlugin::onMouseDown(UniverseView& view, int x, int y) {
return paint(view, x, y);
}
void SplineGeometryPlugin::onMouseUp(UniverseView& view, int x, int y, os::MouseButton button) {
}
void SplineGeometryPlugin::onMouseMove(UniverseView& view, int x, int y, int rel_x, int rel_y) {
paint(view, x, y);
}
void SplineGeometryPlugin::drawCursor(WorldEditor& editor, EntityRef entity) const {
const UniverseView& view = editor.getView();
const Vec2 mp = view.getMousePos();
Universe& universe = *editor.getUniverse();
RenderScene* scene = static_cast<RenderScene*>(universe.getScene(SPLINE_GEOMETRY_TYPE));
DVec3 origin;
Vec3 dir;
editor.getView().getViewport().getRay(mp, origin, dir);
const RayCastModelHit hit = scene->castRayProceduralGeometry(origin, dir);
if (hit.is_hit) {
const DVec3 center = hit.origin + hit.dir * hit.t;
drawCursor(editor, *scene, entity, center);
return;
}
}
void SplineGeometryPlugin::drawCursor(WorldEditor& editor, RenderScene& scene, EntityRef entity, const DVec3& center) const {
UniverseView& view = editor.getView();
addCircle(view, center, m_brush_size, Vec3(0, 1, 0), Color::GREEN);
const ProceduralGeometry& pg = scene.getProceduralGeometry(entity);
if (pg.vertex_data.size() == 0) return;
const u8* data = pg.vertex_data.data();
const u32 stride = pg.vertex_decl.getStride();
const float R2 = m_brush_size * m_brush_size;
const Transform tr = scene.getUniverse().getTransform(entity);
const Vec3 center_local = Vec3(tr.inverted().transform(center));
for (u32 i = 0, c = pg.getIndexCount(); i < c; ++i) {
Vec3 p;
memcpy(&p, data + stride * i, sizeof(p));
if (squaredLength(center_local - p) < R2) {
addCircle(view, tr.transform(p), 0.1f, Vec3(0, 1, 0), Color::BLUE);
}
}
}
void SplineGeometryPlugin::onGUI(PropertyGrid& grid, ComponentUID cmp, WorldEditor& editor) {
if (cmp.type != SPLINE_GEOMETRY_TYPE) return;
const EntityRef e = *cmp.entity;
Universe& universe = cmp.scene->getUniverse();
if (!universe.hasComponent(*cmp.entity, SPLINE_TYPE)) {
ImGui::TextUnformatted("There's no spline component");
if (ImGui::Button("Create spline component")) {
editor.addComponent(Span(&e, 1), SPLINE_TYPE);
}
}
else {
RenderScene* render_scene = (RenderScene*)universe.getScene(SPLINE_GEOMETRY_TYPE);
CoreScene* core_scene = (CoreScene*)universe.getScene(SPLINE_TYPE);
const Spline& spline = core_scene->getSpline(e);
const SplineGeometry& sg = render_scene->getSplineGeometry(e);
const ProceduralGeometry& pg = render_scene->getProceduralGeometry(e);
drawCursor(editor, *cmp.entity);
ImGuiEx::Label("Triangles");
ImGui::Text("%d", u32(pg.index_data.size() / (pg.index_type == gpu::DataType::U16 ? 2 : 4) / 3));
ImGuiEx::Label("Brush size");
ImGui::DragFloat("##bs", &m_brush_size, 0.1f, 0, FLT_MAX);
if (sg.num_user_channels > 1) {
ImGuiEx::Label("Paint channel");
ImGui::SliderInt("##pc", (int*)&m_brush_channel, 0, sg.num_user_channels - 1);
}
ImGuiEx::Label("Paint value");
ImGui::SliderInt("##pv", (int*)&m_brush_value, 0, 255);
if (ImGui::Button("Generate geometry")) {
if (!spline.points.empty()) {
const float width = sg.width;
SplineIterator iterator(spline.points);
gpu::VertexDecl decl;
decl.addAttribute(0, 0, 3, gpu::AttributeType::FLOAT, 0);
OutputMemoryStream vertices(m_app.getAllocator());
OutputMemoryStream indices(m_app.getAllocator());
vertices.reserve(16 * 1024);
if (sg.flags.isSet(SplineGeometry::HAS_UVS)) {
decl.addAttribute(1, 12, 2, gpu::AttributeType::FLOAT, 0);
struct Vertex {
Vec3 position;
Vec2 uv;
};
auto write_vertex = [&](const Vertex& v){
vertices.write(v);
if (sg.num_user_channels > 0) {
u32 tmp = 0;
vertices.write(&tmp, sg.num_user_channels);
}
};
float u = 0;
u32 rows = 0;
Vec3 prev_p = spline.points[0];
const u32 u_density = sg.u_density;
while (!iterator.isEnd()) {
++rows;
const Vec3 p = iterator.getPosition();
const Vec3 dir = iterator.getDir();
const Vec3 side = normalize(cross(Vec3(0, 1, 0), dir)) * width;
u += length(p - prev_p);
const Vec3 p0 = p - side;
for (u32 i = 0; i < u_density; ++i) {
Vertex v;
v.position = p0 + 2 * side * (i / float(u_density - 1));
v.uv.x = u;
v.uv.y = i / float(u_density - 1) * width;
write_vertex(v);
}
iterator.move(sg.v_density);
prev_p = p;
}
for (u32 row = 0; row < rows - 1; ++row) {
for (u32 i = 0; i < u_density - 1; ++i) {
indices.write(u16(u_density * row + i));
indices.write(u16(u_density * row + i + 1));
indices.write(u16(u_density * (row + 1) + i));
indices.write(u16(u_density * row + i + 1));
indices.write(u16(u_density * (row + 1) + i));
indices.write(u16(u_density * (row + 1) + i + 1));
}
}
if (sg.num_user_channels > 0) {
decl.addAttribute(2, 20, sg.num_user_channels, gpu::AttributeType::U8, gpu::Attribute::NORMALIZED);
}
}
else {
while (!iterator.isEnd()) {
const Vec3 p = iterator.getPosition();
const Vec3 dir = iterator.getDir();
const Vec3 side = normalize(cross(Vec3(0, 1, 0), dir)) * width;
const Vec3 v0 = p + side;
const Vec3 v1 = p - side;
vertices.write(v0);
if (sg.num_user_channels > 0) {
u32 tmp = 0;
vertices.write(&tmp, sg.num_user_channels);
}
vertices.write(v1);
if (sg.num_user_channels > 0) {
u32 tmp = 0;
vertices.write(&tmp, sg.num_user_channels);
}
iterator.move(0.1f);
}
if (sg.num_user_channels > 0) {
decl.addAttribute(1, 12, sg.num_user_channels, gpu::AttributeType::U8, gpu::Attribute::NORMALIZED);
}
}
render_scene->setProceduralGeometry(e, vertices, decl, gpu::PrimitiveType::TRIANGLES, indices, gpu::DataType::U16);
}
}
}
}
} // namespace Lumix<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/task/XInteractionHandler2.hpp>
#include <iahndl.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <cppuhelper/implbase3.hxx>
#include <cppuhelper/supportsservice.hxx>
using namespace com::sun::star;
namespace {
class UUIInteractionHandler:
public cppu::WeakImplHelper3< com::sun::star::lang::XServiceInfo,
com::sun::star::lang::XInitialization,
com::sun::star::task::XInteractionHandler2 >
{
private:
UUIInteractionHelper * m_pImpl;
UUIInteractionHandler(UUIInteractionHandler &); // not implemented
void operator =(UUIInteractionHandler); // not implemented
public:
UUIInteractionHandler(com::sun::star::uno::Reference<
com::sun::star::uno::XComponentContext >
const & rxContext)
SAL_THROW(());
virtual ~UUIInteractionHandler() SAL_THROW(());
virtual OUString SAL_CALL getImplementationName()
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL supportsService(OUString const &
rServiceName)
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual com::sun::star::uno::Sequence< OUString > SAL_CALL
getSupportedServiceNames()
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual void SAL_CALL
initialize(
com::sun::star::uno::Sequence< com::sun::star::uno::Any > const &
rArguments)
throw (com::sun::star::uno::Exception, std::exception) SAL_OVERRIDE;
virtual void SAL_CALL
handle(com::sun::star::uno::Reference<
com::sun::star::task::XInteractionRequest > const &
rRequest)
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL
handleInteractionRequest(
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& _Request
) throw ( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;
};
UUIInteractionHandler::UUIInteractionHandler(
uno::Reference< uno::XComponentContext > const &
rxContext)
SAL_THROW(())
: m_pImpl(new UUIInteractionHelper(rxContext))
{
}
UUIInteractionHandler::~UUIInteractionHandler()
{
delete m_pImpl;
}
OUString SAL_CALL UUIInteractionHandler::getImplementationName()
throw (uno::RuntimeException, std::exception)
{
return OUString("com.sun.star.comp.uui.UUIInteractionHandler");
}
sal_Bool SAL_CALL
UUIInteractionHandler::supportsService(OUString const & rServiceName)
throw (uno::RuntimeException, std::exception)
{
return cppu::supportsService(this, rServiceName);
}
uno::Sequence< OUString > SAL_CALL
UUIInteractionHandler::getSupportedServiceNames()
throw (uno::RuntimeException, std::exception)
{
uno::Sequence< OUString > aNames(3);
aNames[0] = "com.sun.star.task.InteractionHandler";
// added to indicate support for configuration.backend.MergeRecoveryRequest
aNames[1] = "com.sun.star.configuration.backend.InteractionHandler";
aNames[2] = "com.sun.star.uui.InteractionHandler";
// for backwards compatibility
return aNames;
}
void SAL_CALL
UUIInteractionHandler::initialize(
uno::Sequence< uno::Any > const & rArguments)
throw (uno::Exception, std::exception)
{
uno::Reference<uno::XComponentContext> xContext = m_pImpl->getORB();
delete m_pImpl;
// The old-style InteractionHandler service supported a sequence of
// PropertyValue, while the new-style service now uses constructors to pass
// in Parent and Context values; for backwards compatibility, keep support
// for a PropertyValue sequence, too:
uno::Reference< awt::XWindow > xWindow;
OUString aContext;
if (!((rArguments.getLength() == 1 && (rArguments[0] >>= xWindow)) ||
(rArguments.getLength() == 2 && (rArguments[0] >>= xWindow) &&
(rArguments[1] >>= aContext))))
{
::comphelper::NamedValueCollection aProperties( rArguments );
if ( aProperties.has( "Parent" ) )
{
OSL_VERIFY( aProperties.get( "Parent" ) >>= xWindow );
}
if ( aProperties.has( "Context" ) )
{
OSL_VERIFY( aProperties.get( "Context" ) >>= aContext );
}
}
m_pImpl = new UUIInteractionHelper(xContext, xWindow, aContext);
}
void SAL_CALL
UUIInteractionHandler::handle(
uno::Reference< task::XInteractionRequest > const & rRequest)
throw (uno::RuntimeException, std::exception)
{
try
{
m_pImpl->handleRequest(rRequest);
}
catch (uno::RuntimeException const & ex)
{
throw uno::RuntimeException(ex.Message, *this);
}
}
sal_Bool SAL_CALL UUIInteractionHandler::handleInteractionRequest(
const uno::Reference< task::XInteractionRequest >& _Request ) throw ( uno::RuntimeException, std::exception )
{
try
{
return m_pImpl->handleRequest( _Request );
}
catch (uno::RuntimeException const & ex)
{
throw uno::RuntimeException( ex.Message, *this );
}
}
}
extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
com_sun_star_comp_uui_UUIInteractionHandler_get_implementation(
css::uno::XComponentContext *context,
css::uno::Sequence<css::uno::Any> const &)
{
return cppu::acquire(new UUIInteractionHandler(context));
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Clean up function declarations<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sal/config.h>
#include <boost/noncopyable.hpp>
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/task/XInteractionHandler2.hpp>
#include <iahndl.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <cppuhelper/implbase3.hxx>
#include <cppuhelper/supportsservice.hxx>
using namespace com::sun::star;
namespace {
class UUIInteractionHandler:
public cppu::WeakImplHelper3< com::sun::star::lang::XServiceInfo,
com::sun::star::lang::XInitialization,
com::sun::star::task::XInteractionHandler2 >,
private boost::noncopyable
{
private:
UUIInteractionHelper * m_pImpl;
public:
UUIInteractionHandler(com::sun::star::uno::Reference<
com::sun::star::uno::XComponentContext >
const & rxContext)
SAL_THROW(());
virtual ~UUIInteractionHandler() SAL_THROW(());
virtual OUString SAL_CALL getImplementationName()
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL supportsService(OUString const &
rServiceName)
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual com::sun::star::uno::Sequence< OUString > SAL_CALL
getSupportedServiceNames()
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual void SAL_CALL
initialize(
com::sun::star::uno::Sequence< com::sun::star::uno::Any > const &
rArguments)
throw (com::sun::star::uno::Exception, std::exception) SAL_OVERRIDE;
virtual void SAL_CALL
handle(com::sun::star::uno::Reference<
com::sun::star::task::XInteractionRequest > const &
rRequest)
throw (com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL
handleInteractionRequest(
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionRequest >& _Request
) throw ( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;
};
UUIInteractionHandler::UUIInteractionHandler(
uno::Reference< uno::XComponentContext > const &
rxContext)
SAL_THROW(())
: m_pImpl(new UUIInteractionHelper(rxContext))
{
}
UUIInteractionHandler::~UUIInteractionHandler()
{
delete m_pImpl;
}
OUString SAL_CALL UUIInteractionHandler::getImplementationName()
throw (uno::RuntimeException, std::exception)
{
return OUString("com.sun.star.comp.uui.UUIInteractionHandler");
}
sal_Bool SAL_CALL
UUIInteractionHandler::supportsService(OUString const & rServiceName)
throw (uno::RuntimeException, std::exception)
{
return cppu::supportsService(this, rServiceName);
}
uno::Sequence< OUString > SAL_CALL
UUIInteractionHandler::getSupportedServiceNames()
throw (uno::RuntimeException, std::exception)
{
uno::Sequence< OUString > aNames(3);
aNames[0] = "com.sun.star.task.InteractionHandler";
// added to indicate support for configuration.backend.MergeRecoveryRequest
aNames[1] = "com.sun.star.configuration.backend.InteractionHandler";
aNames[2] = "com.sun.star.uui.InteractionHandler";
// for backwards compatibility
return aNames;
}
void SAL_CALL
UUIInteractionHandler::initialize(
uno::Sequence< uno::Any > const & rArguments)
throw (uno::Exception, std::exception)
{
uno::Reference<uno::XComponentContext> xContext = m_pImpl->getORB();
delete m_pImpl;
// The old-style InteractionHandler service supported a sequence of
// PropertyValue, while the new-style service now uses constructors to pass
// in Parent and Context values; for backwards compatibility, keep support
// for a PropertyValue sequence, too:
uno::Reference< awt::XWindow > xWindow;
OUString aContext;
if (!((rArguments.getLength() == 1 && (rArguments[0] >>= xWindow)) ||
(rArguments.getLength() == 2 && (rArguments[0] >>= xWindow) &&
(rArguments[1] >>= aContext))))
{
::comphelper::NamedValueCollection aProperties( rArguments );
if ( aProperties.has( "Parent" ) )
{
OSL_VERIFY( aProperties.get( "Parent" ) >>= xWindow );
}
if ( aProperties.has( "Context" ) )
{
OSL_VERIFY( aProperties.get( "Context" ) >>= aContext );
}
}
m_pImpl = new UUIInteractionHelper(xContext, xWindow, aContext);
}
void SAL_CALL
UUIInteractionHandler::handle(
uno::Reference< task::XInteractionRequest > const & rRequest)
throw (uno::RuntimeException, std::exception)
{
try
{
m_pImpl->handleRequest(rRequest);
}
catch (uno::RuntimeException const & ex)
{
throw uno::RuntimeException(ex.Message, *this);
}
}
sal_Bool SAL_CALL UUIInteractionHandler::handleInteractionRequest(
const uno::Reference< task::XInteractionRequest >& _Request ) throw ( uno::RuntimeException, std::exception )
{
try
{
return m_pImpl->handleRequest( _Request );
}
catch (uno::RuntimeException const & ex)
{
throw uno::RuntimeException( ex.Message, *this );
}
}
}
extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
com_sun_star_comp_uui_UUIInteractionHandler_get_implementation(
css::uno::XComponentContext *context,
css::uno::Sequence<css::uno::Any> const &)
{
return cppu::acquire(new UUIInteractionHandler(context));
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>Add TODO comment for when liblangtag gets updated<commit_after><|endoftext|> |
<commit_before>/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_GL_FILTERING_FILTER_BILATERAL_2DAS_HPP
#define PIC_GL_FILTERING_FILTER_BILATERAL_2DAS_HPP
#include "../../util/vec.hpp"
#include "../../util/std_util.hpp"
#include "../../gl/filtering/filter.hpp"
#include "../../gl/filtering/filter_sampling_map.hpp"
#include "../../gl/point_samplers/sampler_random_m.hpp"
namespace pic {
class FilterGLBilateral2DAS: public FilterGL
{
protected:
float sigma_s, sigma_r;
MRSamplersGL<2> *ms;
//Random numbers tile
ImageGL *imageRand;
//Sampling map
FilterGLSamplingMap *fGLsm;
ImageGL *imgTmp;
/**
* @brief initShaders
*/
void initShaders();
/**
* @brief FragmentShader
*/
void FragmentShader();
public:
/**
* @brief FilterGLBilateral2DAS
*/
FilterGLBilateral2DAS();
~FilterGLBilateral2DAS();
/**
* @brief releaseAux
*/
void releaseAux()
{
delete_s(ms);
delete_s(imageRand);
delete_s(fGLsm);
delete_s(imgTmp);
}
/**
* @brief FilterGLBilateral2DAS
* @param sigma_s
* @param sigma_r
*/
FilterGLBilateral2DAS(float sigma_s, float sigma_r);
/**
* @brief update
* @param sigma_s
* @param sigma_r
*/
void update(float sigma_s, float sigma_r);
/**
* @brief Process
* @param imgIn
* @param imgOut
* @return
*/
ImageGL *Process(ImageGLVec imgIn, ImageGL *imgOut);
/**
* @brief execute
* @param imgIn
* @param sigma_s
* @param sigma_r
* @return
*/
static ImageGL *execute(ImageGL *imgIn, float sigma_s, float sigma_r)
{
FilterGLBilateral2DAS *filter = new FilterGLBilateral2DAS(sigma_s, sigma_r);
ImageGL *imgOut = filter->Process(SingleGL(imgIn), NULL);
delete filter;
return imgOut;
}
};
PIC_INLINE FilterGLBilateral2DAS::FilterGLBilateral2DAS(): FilterGL()
{
ms = NULL;
imageRand = NULL;
fGLsm = NULL;
imgTmp = NULL;
}
PIC_INLINE FilterGLBilateral2DAS::~FilterGLBilateral2DAS()
{
release();
}
PIC_INLINE FilterGLBilateral2DAS::FilterGLBilateral2DAS(float sigma_s,
float sigma_r): FilterGL()
{
//protected values are assigned/computed
this->sigma_s = sigma_s;
this->sigma_r = sigma_r;
fGLsm = new FilterGLSamplingMap(sigma_s);
imgTmp = NULL;
int nRand = 32;
Image tmp_image_rand(1, 128, 128, 1);
tmp_image_rand.setRand(1);
tmp_image_rand *= float(nRand - 1);
imageRand = new ImageGL(&tmp_image_rand, true);
imageRand->generateTextureGL(GL_TEXTURE_2D, GL_INT, false);
//Precomputation of the Gaussian Kernel
int kernelSize = PrecomputedGaussian::getKernelSize(sigma_s);
int halfKernelSize = kernelSize >> 1;
//Poisson samples
#ifdef PIC_DEBUG
printf("Window: %d\n", halfKernelSize);
#endif
Vec2i window = Vec2i(halfKernelSize, halfKernelSize);
ms = new MRSamplersGL<2>(ST_BRIDSON, window, halfKernelSize, 3, nRand);
ms->generateTexture();
ms->generateLevelsRTexture();
FragmentShader();
initShaders();
}
PIC_INLINE void FilterGLBilateral2DAS::FragmentShader()
{
fragment_source = MAKE_STRING
(
uniform sampler2D u_tex;
uniform isampler2D u_poisson;
uniform sampler2D u_sample;
uniform isampler2D u_rand;
uniform isampler2D u_levelsR;
uniform float sigmas2;
uniform float sigmar2;
uniform int levelsR_Size;
out vec4 f_color;
//Calculate the number of samples
int CalculateSamples(int shifter, ivec2 tSize) {
//Fetch to the sampling map
float levelVal = dot(texture(u_sample, gl_FragCoord.xy / tSize.xy).xyz, vec3(1.0)) / 3.0;
levelVal = clamp(1.0f - levelVal, 0.0, 1.0) * float(levelsR_Size);
int levelInt = int(floor(levelVal));
int nSamples = texelFetch(u_levelsR, ivec2(levelInt, shifter), 0).x;
if(levelInt < (levelsR_Size - 1)) {
float tmp = (levelVal - float(levelInt));
if(tmp > 0.0) {
int nSamples1 = texelFetch(u_levelsR, ivec2(levelInt + 1, shifter), 0).x;
nSamples += int(float(nSamples1 - nSamples) * tmp);
}
}
return nSamples / 2;
}
void main(void) {
ivec2 coordsFrag = ivec2(gl_FragCoord.xy);
//Coordinates
int shifter = texelFetch(u_rand, coordsFrag.xy % 128, 0).x;
//Calculating the number of samples
ivec2 tSize = textureSize(u_tex, 0);
int nSamples = CalculateSamples(shifter, tSize);
//Filtering
vec3 tmpCol;
vec3 colRef = texelFetch(u_tex, coordsFrag, 0).xyz;
vec3 color = vec3(0.0);
float weight = 0.0;
for(int i = 0; i < nSamples; i++) {
ivec4 coords = texelFetch(u_poisson, ivec2(i, shifter), 0);
//Texture fetch
tmpCol = texelFetch(u_tex, coordsFrag.xy + coords.xy, 0).xyz;
vec3 tmpCol2 = tmpCol - colRef;
float dstR = dot(tmpCol2.xyz, tmpCol2.xyz);
float tmp = exp(-dstR / sigmar2 - float(coords.z) / sigmas2);
color += tmpCol * tmp;
weight += tmp;
}
color = weight > 0.0 ? color / weight : colRef;
f_color = vec4(color, 1.0);
}
);
}
PIC_INLINE void FilterGLBilateral2DAS::initShaders()
{
#ifdef PIC_DEBUG
printf("Number of samples: %d\n", ms->nSamples / 2);
#endif
technique.initStandard("330", vertex_source, fragment_source, "FilterGLBilateral2DAS");
update(-1.0f, -1.0f);
}
PIC_INLINE void FilterGLBilateral2DAS::update(float sigma_s, float sigma_r)
{
bool flag = false;
if(sigma_s > 0.0f) {
flag = (this->sigma_s == sigma_s);
this->sigma_s = sigma_s;
}
if(sigma_r > 0.0f) {
flag = flag || (this->sigma_r == sigma_r);
this->sigma_r = sigma_r;
}
if(!flag) {
}
//shader update
int kernelSize = PrecomputedGaussian::getKernelSize(this->sigma_s);
int halfKernelSize = kernelSize >> 1;
Vec2i window = Vec2i(halfKernelSize, halfKernelSize);
ms->updateGL(window, halfKernelSize);
//shader update
float sigmas2 = 2.0f * this->sigma_s * this->sigma_s;
float sigmar2 = 2.0f * this->sigma_r * this->sigma_r;
technique.bind();
technique.setUniform1i("u_tex", 0);
technique.setUniform1i("u_poisson", 1);
technique.setUniform1i("u_rand", 2);
technique.setUniform1i("u_sample", 3);
technique.setUniform1i("u_levelsR", 4);
technique.setUniform1f("sigmas2", sigmas2);
technique.setUniform1f("sigmar2", sigmar2);
technique.setUniform1i("levelsR_Size", ms->nLevels);
technique.unbind();
}
PIC_INLINE ImageGL *FilterGLBilateral2DAS::Process(ImageGLVec imgIn,
ImageGL *imgOut)
{
if(imgIn[0] == NULL) {
return imgOut;
}
int w = imgIn[0]->width;
int h = imgIn[0]->height;
if(imgOut == NULL) {
imgOut = new ImageGL(1, w, h, imgIn[0]->channels, IMG_GPU, GL_TEXTURE_2D);
}
if(fbo == NULL) {
fbo = new Fbo();
fbo->create(w, h, 1, false, imgOut->getTexture());
}
if(imgTmp == NULL) {
float scale = fGLsm->getScale();
imgTmp = new ImageGL( 1,
int(imgIn[0]->widthf * scale),
int(imgIn[0]->heightf * scale),
1, IMG_GPU, GL_TEXTURE_2D);
}
ImageGL *edge, *base;
if(imgIn.size() == 2) {
//Joint/Cross Bilateral Filtering
base = imgIn[0];
edge = imgIn[1];
} else {
base = imgIn[0];
edge = imgIn[0];
}
//Calculating the sampling map
imgTmp = fGLsm->Process(imgIn, imgTmp);
//Rendering
fbo->bind();
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
//Shaders
technique.bind();
//Textures
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, ms->getLevelsRTexture());
glActiveTexture(GL_TEXTURE3);
imgTmp->bindTexture();
glActiveTexture(GL_TEXTURE2);
imageRand->bindTexture();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, ms->getTexture());
glActiveTexture(GL_TEXTURE0);
base->bindTexture();
//Rendering aligned quad
quad->Render();
//Fbo
fbo->unbind();
//Shaders
technique.unbind();
//Textures
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE3);
imgTmp->unBindTexture();
glActiveTexture(GL_TEXTURE2);
imageRand->unBindTexture();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
base->unBindTexture();
return imgOut;
}
} // end namespace pic
#endif /* PIC_GL_FILTERING_FILTER_BILATERAL_2DAS_HPP */
<commit_msg>Update filter_bilateral_2das.hpp<commit_after>/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_GL_FILTERING_FILTER_BILATERAL_2DAS_HPP
#define PIC_GL_FILTERING_FILTER_BILATERAL_2DAS_HPP
#include "../../util/vec.hpp"
#include "../../util/std_util.hpp"
#include "../../gl/filtering/filter.hpp"
#include "../../gl/filtering/filter_sampling_map.hpp"
#include "../../gl/point_samplers/sampler_random_m.hpp"
namespace pic {
class FilterGLBilateral2DAS: public FilterGL
{
protected:
float sigma_s, sigma_r;
MRSamplersGL<2> *ms;
//Random numbers tile
ImageGL *imageRand;
//Sampling map
FilterGLSamplingMap *fGLsm;
ImageGL *imgTmp;
/**
* @brief initShaders
*/
void initShaders();
/**
* @brief FragmentShader
*/
void FragmentShader();
public:
/**
* @brief FilterGLBilateral2DAS
*/
FilterGLBilateral2DAS();
~FilterGLBilateral2DAS();
/**
* @brief releaseAux
*/
void releaseAux()
{
delete_s(ms);
delete_s(imageRand);
delete_s(fGLsm);
delete_s(imgTmp);
}
/**
* @brief FilterGLBilateral2DAS
* @param sigma_s
* @param sigma_r
*/
FilterGLBilateral2DAS(float sigma_s, float sigma_r);
/**
* @brief update
* @param sigma_s
* @param sigma_r
*/
void update(float sigma_s, float sigma_r);
/**
* @brief Process
* @param imgIn
* @param imgOut
* @return
*/
ImageGL *Process(ImageGLVec imgIn, ImageGL *imgOut);
/**
* @brief execute
* @param imgIn
* @param sigma_s
* @param sigma_r
* @return
*/
static ImageGL *execute(ImageGL *imgIn, float sigma_s, float sigma_r)
{
FilterGLBilateral2DAS *filter = new FilterGLBilateral2DAS(sigma_s, sigma_r);
ImageGL *imgOut = filter->Process(SingleGL(imgIn), NULL);
delete filter;
return imgOut;
}
};
PIC_INLINE FilterGLBilateral2DAS::FilterGLBilateral2DAS(): FilterGL()
{
ms = NULL;
imageRand = NULL;
fGLsm = NULL;
imgTmp = NULL;
}
PIC_INLINE FilterGLBilateral2DAS::~FilterGLBilateral2DAS()
{
release();
}
PIC_INLINE FilterGLBilateral2DAS::FilterGLBilateral2DAS(float sigma_s,
float sigma_r): FilterGL()
{
//protected values are assigned/computed
this->sigma_s = sigma_s;
this->sigma_r = sigma_r;
fGLsm = new FilterGLSamplingMap(sigma_s);
imgTmp = NULL;
int nRand = 32;
Image tmp_image_rand(1, 128, 128, 1);
tmp_image_rand.setRand(1);
tmp_image_rand *= float(nRand - 1);
imageRand = new ImageGL(&tmp_image_rand, true);
imageRand->generateTextureGL(GL_TEXTURE_2D, GL_INT, false);
//Precomputation of the Gaussian Kernel
int kernelSize = PrecomputedGaussian::getKernelSize(sigma_s);
int halfKernelSize = kernelSize >> 1;
//Poisson samples
#ifdef PIC_DEBUG
printf("Window: %d\n", halfKernelSize);
#endif
Vec2i window = Vec2i(halfKernelSize, halfKernelSize);
ms = new MRSamplersGL<2>(ST_BRIDSON, window, halfKernelSize, 3, nRand);
ms->generateTexture();
ms->generateLevelsRTexture();
FragmentShader();
initShaders();
}
PIC_INLINE void FilterGLBilateral2DAS::FragmentShader()
{
fragment_source = MAKE_STRING
(
uniform sampler2D u_tex;
uniform isampler2D u_poisson;
uniform sampler2D u_sample;
uniform isampler2D u_rand;
uniform isampler2D u_levelsR;
uniform float sigmas2;
uniform float sigmar2;
uniform int levelsR_Size;
out vec4 f_color;
//Calculate the number of samples
int CalculateSamples(int shifter, ivec2 tSize) {
//Fetch to the sampling map
float levelVal = dot(texture(u_sample, gl_FragCoord.xy / tSize.xy).xyz, vec3(1.0)) / 3.0;
levelVal = clamp(1.0f - levelVal, 0.0, 1.0) * float(levelsR_Size);
int levelInt = int(floor(levelVal));
int nSamples = texelFetch(u_levelsR, ivec2(levelInt, shifter), 0).x;
if(levelInt < (levelsR_Size - 1)) {
float tmp = (levelVal - float(levelInt));
if(tmp > 0.0) {
int nSamples1 = texelFetch(u_levelsR, ivec2(levelInt + 1, shifter), 0).x;
nSamples += int(float(nSamples1 - nSamples) * tmp);
}
}
return nSamples / 2;
}
void main(void) {
ivec2 coordsFrag = ivec2(gl_FragCoord.xy);
//Coordinates
int shifter = texelFetch(u_rand, coordsFrag.xy % 128, 0).x;
//Calculating the number of samples
ivec2 tSize = textureSize(u_tex, 0);
int nSamples = CalculateSamples(shifter, tSize);
//Filtering
vec3 tmpCol;
vec3 colRef = texelFetch(u_tex, coordsFrag, 0).xyz;
vec3 color = vec3(0.0);
float weight = 0.0;
for(int i = 0; i < nSamples; i++) {
ivec4 coords = texelFetch(u_poisson, ivec2(i, shifter), 0);
//Texture fetch
tmpCol = texelFetch(u_tex, coordsFrag.xy + coords.xy, 0).xyz;
vec3 tmpCol2 = tmpCol - colRef;
float dstR = dot(tmpCol2.xyz, tmpCol2.xyz);
float tmp = exp(-dstR / sigmar2 - float(coords.z) / sigmas2);
color += tmpCol * tmp;
weight += tmp;
}
color = weight > 0.0 ? color / weight : colRef;
f_color = vec4(color, 1.0);
}
);
}
PIC_INLINE void FilterGLBilateral2DAS::initShaders()
{
#ifdef PIC_DEBUG
printf("Number of samples: %d\n", ms->nSamples / 2);
#endif
technique.initStandard("330", vertex_source, fragment_source, "FilterGLBilateral2DAS");
update(-1.0f, -1.0f);
}
PIC_INLINE void FilterGLBilateral2DAS::update(float sigma_s, float sigma_r)
{
bool flag = false;
if(sigma_s > 0.0f) {
flag = (this->sigma_s == sigma_s);
this->sigma_s = sigma_s;
}
if(sigma_r > 0.0f) {
flag = flag || (this->sigma_r == sigma_r);
this->sigma_r = sigma_r;
}
if(!flag) {
}
//shader update
int kernelSize = PrecomputedGaussian::getKernelSize(this->sigma_s);
int halfKernelSize = kernelSize >> 1;
Vec2i window = Vec2i(halfKernelSize, halfKernelSize);
ms->updateGL(window, halfKernelSize);
//shader update
float sigmas2 = 2.0f * this->sigma_s * this->sigma_s;
float sigmar2 = 2.0f * this->sigma_r * this->sigma_r;
technique.bind();
technique.setUniform1i("u_tex", 0);
technique.setUniform1i("u_poisson", 1);
technique.setUniform1i("u_rand", 2);
technique.setUniform1i("u_sample", 3);
technique.setUniform1i("u_levelsR", 4);
technique.setUniform1f("sigmas2", sigmas2);
technique.setUniform1f("sigmar2", sigmar2);
technique.setUniform1i("levelsR_Size", ms->nLevels);
technique.unbind();
}
PIC_INLINE ImageGL *FilterGLBilateral2DAS::Process(ImageGLVec imgIn,
ImageGL *imgOut)
{
if(imgIn[0] == NULL) {
return imgOut;
}
int w = imgIn[0]->width;
int h = imgIn[0]->height;
if(imgOut == NULL) {
imgOut = new ImageGL(1, w, h, imgIn[0]->channels, IMG_GPU, GL_TEXTURE_2D);
}
if(fbo == NULL) {
fbo = new Fbo();
fbo->create(w, h, 1, false, imgOut->getTexture());
}
ImageGL *edge, *base;
if(imgIn.size() == 2) {
//Joint/Cross Bilateral Filtering
base = imgIn[0];
edge = imgIn[1];
} else {
base = imgIn[0];
edge = imgIn[0];
}
//Calculating the sampling map
imgTmp = fGLsm->Process(imgIn, imgTmp);
//Rendering
fbo->bind();
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
//Shaders
technique.bind();
//Textures
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, ms->getLevelsRTexture());
glActiveTexture(GL_TEXTURE3);
imgTmp->bindTexture();
glActiveTexture(GL_TEXTURE2);
imageRand->bindTexture();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, ms->getTexture());
glActiveTexture(GL_TEXTURE0);
base->bindTexture();
//Rendering aligned quad
quad->Render();
//Fbo
fbo->unbind();
//Shaders
technique.unbind();
//Textures
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE3);
imgTmp->unBindTexture();
glActiveTexture(GL_TEXTURE2);
imageRand->unBindTexture();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
base->unBindTexture();
return imgOut;
}
} // end namespace pic
#endif /* PIC_GL_FILTERING_FILTER_BILATERAL_2DAS_HPP */
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_PLATFORM_HPP
#define RJ_GAME_COMPONENTS_PLATFORM_HPP
#include <rectojump/game/entity_rect.hpp>
namespace rj
{
class platform : public entity_rect
{
protected:
void update(dur duration) override
{m_render_object.move(m_velocity * duration);}
void init() override
{ }
public:
platform(const sf::Vector2f& pos, const sf::Vector2f& size = {20.f, 20.f}) :
entity_rect{pos, size, {-0.3f, 0.f}}
{m_render_object.setOrigin(size.x / 2, size.y / 2);}
~platform() = default;
};
}
#endif // RJ_GAME_COMPONENTS_PLATFORM_HPP
<commit_msg>cleanup platform<commit_after>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_PLATFORM_HPP
#define RJ_GAME_COMPONENTS_PLATFORM_HPP
#include <rectojump/game/entity_rect.hpp>
namespace rj
{
class platform : public entity_rect
{
public:
platform(const sf::Vector2f& pos, const sf::Vector2f& size = {20.f, 20.f}) :
entity_rect{pos, size, {-0.3f, 0.f}}
{m_render_object.setOrigin(size.x / 2, size.y / 2);}
~platform() = default;
private:
void update(dur duration) override
{m_render_object.move(m_velocity * duration);}
};
}
#endif // RJ_GAME_COMPONENTS_PLATFORM_HPP
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include <rapidcheck-catch.h>
#include "rapidcheck/Gen.h"
#include "rapidcheck/shrinkable/Create.h"
#include "util/ArbitraryRandom.h"
using namespace rc;
using namespace rc::detail;
using namespace rc::newgen::detail;
struct MockGenerationHandler : public GenerationHandler
{
Any onGenerate(const Gen<Any> &gen) override
{
wasCalled = true;
passedGenerator = gen;
return returnValue;
}
bool wasCalled = false;
Gen<Any> passedGenerator = Gen<Any>(
fn::constant(shrinkable::just(Any::of(0))));
Any returnValue;
};
TEST_CASE("Gen") {
SECTION("operator()") {
prop("passes the arguments to the functor",
[](const Random &random, int size) {
bool called = false;
Random passedRandom;
int passedSize;
Gen<int> gen([&](const Random &random, int size) {
called = true;
passedRandom = random;
passedSize = size;
return shrinkable::just(0);
});
gen(random, size);
RC_ASSERT(called);
RC_ASSERT(passedRandom == random);
RC_ASSERT(passedSize == size);
});
prop("returns the value returned by the functor",
[](const Random &random, int size, int x) {
Gen<int> gen([=](const Random &random, int size) {
return shrinkable::just(x);
});
RC_ASSERT(gen(random, size) == shrinkable::just(x));
});
prop("if exception is thrown in generation function, shrinkable is"
" returned that rethrows the exception on call to value()",
[](const std::string &message) {
Gen<int> gen([=](const Random &random, int size) -> Shrinkable<int> {
throw GenerationFailure(message);
});
const auto shrinkable = gen(Random(), 0);
try {
shrinkable.value();
} catch (const GenerationFailure &e) {
RC_ASSERT(e.what() == message);
RC_SUCCEED("Threw correct exception");
}
RC_FAIL("Did not throw correct exception");
});
}
SECTION("operator*") {
ImplicitScope scope;
SECTION("by default throws exception") {
Gen<int> gen(fn::constant(shrinkable::just(0)));
REQUIRE_THROWS(*gen);
}
MockGenerationHandler handler;
handler.returnValue = Any::of(456);
ImplicitParam<rc::newgen::detail::param::CurrentHandler> letHandler(
&handler);
Gen<int> gen(fn::constant(shrinkable::just(1337)));
int x = *gen;
SECTION("passes erased self to onGenerate") {
auto result = shrinkable::map(
handler.passedGenerator(Random(), 0),
[](Any &&any) { return std::move(any.get<int>()); });
REQUIRE(result == shrinkable::just(1337));
REQUIRE(handler.wasCalled);
}
SECTION("returns what is returned by onGenerate") {
RC_ASSERT(x == 456);
}
}
}
<commit_msg>Move GenTests to new framework<commit_after>#include <catch.hpp>
#include <rapidcheck-catch.h>
#include "rapidcheck/Gen.h"
#include "rapidcheck/shrinkable/Create.h"
#include "util/ArbitraryRandom.h"
using namespace rc;
using namespace rc::detail;
using namespace rc::newgen::detail;
struct MockGenerationHandler : public GenerationHandler
{
Any onGenerate(const Gen<Any> &gen) override
{
wasCalled = true;
passedGenerator = gen;
return returnValue;
}
bool wasCalled = false;
Gen<Any> passedGenerator = Gen<Any>(
fn::constant(shrinkable::just(Any::of(0))));
Any returnValue;
};
TEST_CASE("Gen") {
SECTION("operator()") {
newprop(
"passes the arguments to the functor",
[](const Random &random, int size) {
bool called = false;
Random passedRandom;
int passedSize;
Gen<int> gen([&](const Random &random, int size) {
called = true;
passedRandom = random;
passedSize = size;
return shrinkable::just(0);
});
gen(random, size);
RC_ASSERT(called);
RC_ASSERT(passedRandom == random);
RC_ASSERT(passedSize == size);
});
newprop(
"returns the value returned by the functor",
[](const Random &random, int size, int x) {
Gen<int> gen([=](const Random &random, int size) {
return shrinkable::just(x);
});
RC_ASSERT(gen(random, size) == shrinkable::just(x));
});
newprop(
"if exception is thrown in generation function, shrinkable is"
" returned that rethrows the exception on call to value()",
[](const std::string &message) {
Gen<int> gen([=](const Random &random, int size) -> Shrinkable<int> {
throw GenerationFailure(message);
});
const auto shrinkable = gen(Random(), 0);
try {
shrinkable.value();
} catch (const GenerationFailure &e) {
RC_ASSERT(e.what() == message);
RC_SUCCEED("Threw correct exception");
}
RC_FAIL("Did not throw correct exception");
});
}
SECTION("operator*") {
ImplicitScope scope;
SECTION("by default throws exception") {
Gen<int> gen(fn::constant(shrinkable::just(0)));
REQUIRE_THROWS(*gen);
}
MockGenerationHandler handler;
handler.returnValue = Any::of(456);
ImplicitParam<rc::newgen::detail::param::CurrentHandler> letHandler(
&handler);
Gen<int> gen(fn::constant(shrinkable::just(1337)));
int x = *gen;
SECTION("passes erased self to onGenerate") {
auto result = shrinkable::map(
handler.passedGenerator(Random(), 0),
[](Any &&any) { return std::move(any.get<int>()); });
REQUIRE(result == shrinkable::just(1337));
REQUIRE(handler.wasCalled);
}
SECTION("returns what is returned by onGenerate") {
RC_ASSERT(x == 456);
}
}
}
<|endoftext|> |
<commit_before>/*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution 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(s) 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 "openma/body/inversedynamicsmatrix.h"
#include "openma/body/inversedynamicsprocessor_p.h"
#include "openma/body/anchor.h"
#include "openma/body/chain.h"
#include "openma/body/inertialparameters.h"
#include "openma/body/joint.h"
#include "openma/body/model.h"
#include "openma/body/segment.h"
#include "openma/body/utils.h"
#include "openma/base/trial.h"
#include "openma/instrument/forceplate.h"
#include "openma/math.h"
// -------------------------------------------------------------------------- //
// PRIVATE API //
// -------------------------------------------------------------------------- //
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace ma
{
namespace body
{
class InverseDynamicMatrixPrivate : public InverseDynamicProcessorPrivate
{
OPENMA_DECLARE_PINT_ACCESSOR(InverseDynamicMatrix)
public:
InverseDynamicMatrixPrivate(InverseDynamicMatrix* pint);
~InverseDynamicMatrixPrivate();
};
InverseDynamicMatrixPrivate::InverseDynamicMatrixPrivate(InverseDynamicMatrix* pint)
: InverseDynamicProcessorPrivate(pint,"InverseDynamicMatrix")
{};
InverseDynamicMatrixPrivate::~InverseDynamicMatrixPrivate() = default;
};
};
#endif
// -------------------------------------------------------------------------- //
// PUBLIC API //
// -------------------------------------------------------------------------- //
OPENMA_INSTANCE_STATIC_TYPEID(ma::body::InverseDynamicMatrix);
namespace ma
{
namespace body
{
/**
* @class InverseDynamicMatrix openma/body/matrixinversedynamics.h
* @brief Algorithm to compute joint kinetics expressed in the global frame
*
* @TODO Explain in details the required element to use this algorithm (model configure, external wrench, etc.).
*
* @ingroup openma_body
*/
/**
* Constructor
*/
InverseDynamicMatrix::InverseDynamicMatrix(Node* parent)
: InverseDynamicProcessor(*new InverseDynamicMatrixPrivate(this), parent)
{};
/**
* Destructor
*/
InverseDynamicMatrix::~InverseDynamicMatrix() _OPENMA_NOEXCEPT = default;
/**
* Internally this method is a combination of two algorithms published in the litterature [1,2].
* Both of these algorithms are known to be less sensitive to noise [3]. The reason to use this is only to reduce computation time.
* - No need to convert to quaternion
* - No need to create sparse 6x6 matrices
* - Angular velocity and angular acceleration computed directly from rotation matrices
* - All the results are express in the inertial (global) coordinate system
*
* @par References
* 1. Dumas et al., 2004, A 3D generic inverse dynamic method using wrench notation and quaternion algebra, Computer methods in Biomechanics and Biomedical Engineering, 7 (3), pp. 159-166
* 2. Doriot & Chèze, 2004, A Three-Dimensional Kinematic and Dynamic Study of the Lower Limb During the Stance Phase of Gait Using an Homogeneous Matrix Approach, IEEE Transactions on Biomedical Engineering, 51 (1), pp. 21-27
* 3. Dumas et al., 2007, Influence of the 3D Inverse Dynamic Method on the Joint Forces and Moments During Gait, Journal ofBiomechanicalEngineering, 129, pp. 786-790
*/
bool InverseDynamicMatrix::run(Node* inout)
{
#if !defined(_MSC_VER)
#warning WE NEED TO MANAGE UNITS FOR FORCES AND MOMENTS
#endif
auto models = inout->findChildren<Model*>({},{},false);
for (auto& model : models)
{
auto chains = model->chains()->findChildren<Chain*>({},{},false);
for (auto& chain : chains)
{
auto joints = chain->findChildren<Joint*>({},{},false);
if (joints.empty())
{
warning("No joint found in the chain '%s'. Inverse dynamics for this chain aborted.", chain->name().c_str());
continue;
}
// Properties check
std::vector<TimeSequence*> tss(joints.size());
unsigned inc = 0;
for (const auto& joint : joints)
tss[inc++] = joint->distalSegment()->pose();
double rate = 0.0, start = 0.0;
unsigned samples = 0;
if (!compare_timesequences_properties(tss, rate, start, samples))
{
error("At least one segment's pose does not have the same sample rate, start time or number of samples in the chain '%s'.", chain->name().c_str());
continue;
}
assert(rate > 0.);
double dt = 1. / rate;
double gres = 0.;
math::Vector Fd, Md, pd;
math::Vector g = math::Map<const math::Vector>(1, model->gravity(), &gres).replicate(samples);
// Iteration computation of joint kinetics
for (auto itJ = joints.rbegin() ; itJ != joints.rend() ; ++itJ)
{
auto jnt = *itJ;
auto seg = jnt->distalSegment();
auto bsip = seg->findChild<InertialParameters*>();
if (bsip == nullptr)
{
error("The segment '%s' does not have body segment inertial parameters. Inverse dynamics for the chain '%s' aborted.", seg->name().c_str(), chain->name().c_str());
break;
}
// Internal variables used
// -----------------------
// - Pose of the segment
auto pose = math::to_pose(seg->pose());
// - Rotation component of the pose in the Inertial Coordinate System (ICS)
auto R = pose.block<9>(0);
// - Tensor of inertia expressed in the ICS
math::Array<9> I = transform_relative_inertia(bsip, seg, pose);
// - Centre of mass expressed in the ICS
math::Position com = transform_relative_com(bsip, seg, pose);
// - Mass of the segment
double m = bsip->mass();
// - Proximal end point of the segment
auto pp = math::to_position(jnt->proximalAnchor()->position());
if (!pp.isValid())
{
error("Unexpected error in the computation of proximal anchor position for the joint '%s'. Inverse dynamics for the chain '%s' aborted.", jnt->name().c_str(), chain->name().c_str());
break;
}
// - Lever arm between the proximal end point and the centre of mass
math::Position c = com - pp;
// Derivatives computation
// -----------------------
// TODO Would it be possible to reduce the computation time by compute the angular velocity for the lower triangle only (same for the angular acceleration)
// - Angular velocity of the segment in the ICS
math::Vector omega = R.derivative<1>(dt).transform(R.transpose()).skewRedux();
// - Angular acceleration of the segment in the ICS
math::Vector alpha = R.derivative<2>(dt).transform(R.transpose()).skewRedux();
// - Linear acceleration of the CoM in the ICS
auto a = com.derivative<2>(dt);
// Forces and moments computed at the proximal end point
// -----------------------------------------------------
// - External contact (ground, etc.)
math::Vector Fext(samples); Fext.values().setZero(); Fext.residuals().setZero();
math::Vector Mext(samples); Mext.values().setZero(); Mext.residuals().setZero();
auto externals = seg->findChildren<const TimeSequence*>({}, {{"type", TimeSequence::Wrench}});
for (const auto& external : externals)
{
auto wrench = math::to_wrench(external);
if (!wrench.isValid())
{
warning("The external wrench '%s' is not valid or does not have the same sample rate, start time or number of sample than the rest of the chain '%s'.", external->name().c_str(), chain->name().c_str());
continue;
}
Fext += wrench.block<3>(0);
Mext += wrench.block<3>(3) + (wrench.block<3>(6) - pp).cross(wrench.block<3>(0));
}
// - Add the forces and moments of distal joint (if any)
// NOTE: The opposite sign (-=) is because of the use of the action forces and moments computed for the previous segment. In the current segment, they represent reaction forces and moments.
if (pd.isValid())
{
Fext -= Fd;
Mext -= Md + (pd - pp).cross(Fd);
}
// - Weight
math::Vector Fwei = m * g / 1000.0;
auto Mwei = c.cross(Fwei);
// - Dynamics
math::Vector Fdyn = m * a / 1000.0;
auto Mdyn = (I.transform(alpha) + omega.cross(I.transform(omega))) / 1000.0 + c.cross(Fdyn);
// - Proximal joint (result)
math::Vector Fp = Fdyn - Fwei - Fext;
math::Vector Mp = Mdyn - Mwei - Mext;
math::to_timesequence(Fp, jnt->name() + ".Force", rate, start, TimeSequence::Force, "N", jnt);
math::to_timesequence(Mp, jnt->name() + ".Moment", rate, start, TimeSequence::Moment, "Nmm" , jnt);
// Set the next (reaction) distal joint variables
Fd = Fp;
Md = Mp;
pd = pp;
}
}
}
return true;
};
/**
* Create a deep copy of the object and return it as another object.
*/
InverseDynamicMatrix* InverseDynamicMatrix::clone(Node* parent) const
{
auto dest = new InverseDynamicMatrix;
dest->copy(this);
dest->addParent(parent);
return dest;
};
/**
* Do a deep copy of the the given @a source. The previous content is replaced.
*/
void InverseDynamicMatrix::copy(const Node* source) _OPENMA_NOEXCEPT
{
auto src = node_cast<const InverseDynamicMatrix*>(source);
if (src == nullptr)
return;
this->InverseDynamicProcessor::copy(src);
};
};
};<commit_msg>Save segments angular velocity for later use.<commit_after>/*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution 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(s) 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 "openma/body/inversedynamicsmatrix.h"
#include "openma/body/inversedynamicsprocessor_p.h"
#include "openma/body/anchor.h"
#include "openma/body/chain.h"
#include "openma/body/inertialparameters.h"
#include "openma/body/joint.h"
#include "openma/body/model.h"
#include "openma/body/segment.h"
#include "openma/body/utils.h"
#include "openma/base/trial.h"
#include "openma/instrument/forceplate.h"
#include "openma/math.h"
// -------------------------------------------------------------------------- //
// PRIVATE API //
// -------------------------------------------------------------------------- //
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace ma
{
namespace body
{
class InverseDynamicMatrixPrivate : public InverseDynamicProcessorPrivate
{
OPENMA_DECLARE_PINT_ACCESSOR(InverseDynamicMatrix)
public:
InverseDynamicMatrixPrivate(InverseDynamicMatrix* pint);
~InverseDynamicMatrixPrivate();
};
InverseDynamicMatrixPrivate::InverseDynamicMatrixPrivate(InverseDynamicMatrix* pint)
: InverseDynamicProcessorPrivate(pint,"InverseDynamicMatrix")
{};
InverseDynamicMatrixPrivate::~InverseDynamicMatrixPrivate() = default;
};
};
#endif
// -------------------------------------------------------------------------- //
// PUBLIC API //
// -------------------------------------------------------------------------- //
OPENMA_INSTANCE_STATIC_TYPEID(ma::body::InverseDynamicMatrix);
namespace ma
{
namespace body
{
/**
* @class InverseDynamicMatrix openma/body/matrixinversedynamics.h
* @brief Algorithm to compute joint kinetics expressed in the global frame
*
* @TODO Explain in details the required element to use this algorithm (model configure, external wrench, etc.).
*
* @ingroup openma_body
*/
/**
* Constructor
*/
InverseDynamicMatrix::InverseDynamicMatrix(Node* parent)
: InverseDynamicProcessor(*new InverseDynamicMatrixPrivate(this), parent)
{};
/**
* Destructor
*/
InverseDynamicMatrix::~InverseDynamicMatrix() _OPENMA_NOEXCEPT = default;
/**
* Internally this method is a combination of two algorithms published in the litterature [1,2].
* Both of these algorithms are known to be less sensitive to noise [3]. The reason to use this is only to reduce computation time.
* - No need to convert to quaternion
* - No need to create sparse 6x6 matrices
* - Angular velocity and angular acceleration computed directly from rotation matrices
* - All the results are express in the inertial (global) coordinate system
*
* @par References
* 1. Dumas et al., 2004, A 3D generic inverse dynamic method using wrench notation and quaternion algebra, Computer methods in Biomechanics and Biomedical Engineering, 7 (3), pp. 159-166
* 2. Doriot & Chèze, 2004, A Three-Dimensional Kinematic and Dynamic Study of the Lower Limb During the Stance Phase of Gait Using an Homogeneous Matrix Approach, IEEE Transactions on Biomedical Engineering, 51 (1), pp. 21-27
* 3. Dumas et al., 2007, Influence of the 3D Inverse Dynamic Method on the Joint Forces and Moments During Gait, Journal ofBiomechanicalEngineering, 129, pp. 786-790
*/
bool InverseDynamicMatrix::run(Node* inout)
{
#if !defined(_MSC_VER)
#warning WE NEED TO MANAGE UNITS FOR FORCES AND MOMENTS
#endif
auto models = inout->findChildren<Model*>({},{},false);
for (auto& model : models)
{
auto chains = model->chains()->findChildren<Chain*>({},{},false);
for (auto& chain : chains)
{
auto joints = chain->findChildren<Joint*>({},{},false);
if (joints.empty())
{
warning("No joint found in the chain '%s'. Inverse dynamics for this chain aborted.", chain->name().c_str());
continue;
}
// Properties check
std::vector<TimeSequence*> tss(joints.size());
unsigned inc = 0;
for (const auto& joint : joints)
tss[inc++] = joint->distalSegment()->pose();
double rate = 0.0, start = 0.0;
unsigned samples = 0;
if (!compare_timesequences_properties(tss, rate, start, samples))
{
error("At least one segment's pose does not have the same sample rate, start time or number of samples in the chain '%s'.", chain->name().c_str());
continue;
}
assert(rate > 0.);
double dt = 1. / rate;
double gres = 0.;
math::Vector Fd, Md, pd;
math::Vector g = math::Map<const math::Vector>(1, model->gravity(), &gres).replicate(samples);
// Iteration computation of joint kinetics
for (auto itJ = joints.rbegin() ; itJ != joints.rend() ; ++itJ)
{
auto jnt = *itJ;
auto seg = jnt->distalSegment();
auto bsip = seg->findChild<InertialParameters*>();
if (bsip == nullptr)
{
error("The segment '%s' does not have body segment inertial parameters. Inverse dynamics for the chain '%s' aborted.", seg->name().c_str(), chain->name().c_str());
break;
}
// Internal variables used
// -----------------------
// - Pose of the segment
auto spts = seg->pose();
auto pose = math::to_pose(spts);
// - Rotation component of the pose in the Inertial Coordinate System (ICS)
auto R = pose.block<9>(0);
// - Tensor of inertia expressed in the ICS
math::Array<9> I = transform_relative_inertia(bsip, seg, pose);
// - Centre of mass expressed in the ICS
math::Position com = transform_relative_com(bsip, seg, pose);
// - Mass of the segment
double m = bsip->mass();
// - Proximal end point of the segment
auto pp = math::to_position(jnt->proximalAnchor()->position());
if (!pp.isValid())
{
error("Unexpected error in the computation of proximal anchor position for the joint '%s'. Inverse dynamics for the chain '%s' aborted.", jnt->name().c_str(), chain->name().c_str());
break;
}
// - Lever arm between the proximal end point and the centre of mass
math::Position c = com - pp;
// Derivatives computation
// -----------------------
// TODO Would it be possible to reduce the computation time by compute the angular velocity for the lower triangle only (same for the angular acceleration)
// - Angular velocity of the segment in the ICS
math::Vector omega = R.derivative<1>(dt).transform(R.transpose()).skewRedux();
// - Angular acceleration of the segment in the ICS
math::Vector alpha = R.derivative<2>(dt).transform(R.transpose()).skewRedux();
// - Linear acceleration of the CoM in the ICS
auto a = com.derivative<2>(dt);
// Forces and moments computed at the proximal end point
// -----------------------------------------------------
// - External contact (ground, etc.)
math::Vector Fext(samples); Fext.values().setZero(); Fext.residuals().setZero();
math::Vector Mext(samples); Mext.values().setZero(); Mext.residuals().setZero();
auto externals = seg->findChildren<const TimeSequence*>({}, {{"type", TimeSequence::Wrench}});
for (const auto& external : externals)
{
auto wrench = math::to_wrench(external);
if (!wrench.isValid())
{
warning("The external wrench '%s' is not valid or does not have the same sample rate, start time or number of sample than the rest of the chain '%s'.", external->name().c_str(), chain->name().c_str());
continue;
}
Fext += wrench.block<3>(0);
Mext += wrench.block<3>(3) + (wrench.block<3>(6) - pp).cross(wrench.block<3>(0));
}
// - Add the forces and moments of distal joint (if any)
// NOTE: The opposite sign (-=) is because of the use of the action forces and moments computed for the previous segment. In the current segment, they represent reaction forces and moments.
if (pd.isValid())
{
Fext -= Fd;
Mext -= Md + (pd - pp).cross(Fd);
}
// - Weight
math::Vector Fwei = m * g / 1000.0;
auto Mwei = c.cross(Fwei);
// - Dynamics
math::Vector Fdyn = m * a / 1000.0;
auto Mdyn = (I.transform(alpha) + omega.cross(I.transform(omega))) / 1000.0 + c.cross(Fdyn);
// - Proximal joint (result)
math::Vector Fp = Fdyn - Fwei - Fext;
math::Vector Mp = Mdyn - Mwei - Mext;
math::to_timesequence(Fp, jnt->name() + ".Force", rate, start, TimeSequence::Force, "N", jnt);
math::to_timesequence(Mp, jnt->name() + ".Moment", rate, start, TimeSequence::Moment, "Nmm" , jnt);
math::to_timesequence(omega, spts->name() + ".Omega", rate, start, TimeSequence::Angle | TimeSequence::Velocity | TimeSequence::Reconstructed, "rad/s" , seg);
// Set the next (reaction) distal joint variables
Fd = Fp;
Md = Mp;
pd = pp;
}
}
}
return true;
};
/**
* Create a deep copy of the object and return it as another object.
*/
InverseDynamicMatrix* InverseDynamicMatrix::clone(Node* parent) const
{
auto dest = new InverseDynamicMatrix;
dest->copy(this);
dest->addParent(parent);
return dest;
};
/**
* Do a deep copy of the the given @a source. The previous content is replaced.
*/
void InverseDynamicMatrix::copy(const Node* source) _OPENMA_NOEXCEPT
{
auto src = node_cast<const InverseDynamicMatrix*>(source);
if (src == nullptr)
return;
this->InverseDynamicProcessor::copy(src);
};
};
};<|endoftext|> |
<commit_before>/*
* Copyright 2015 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#ifdef OX_USE_STDLIB
#include <array>
#endif
#include "bstring.hpp"
#include "fmt.hpp"
#include "hashmap.hpp"
#include "string.hpp"
#include "units.hpp"
extern "C" {
void oxTraceInitHook();
void oxTraceHook(const char *file, int line, const char *ch, const char *msg);
}
namespace ox::trace {
struct TraceMsg {
static constexpr auto TypeName = "net.drinkingtea.ox.trace.TraceMsg";
static constexpr auto Fields = 5;
static constexpr auto TypeVersion = 1;
const char *file = "";
int line = 0;
uint64_t time = 0;
const char *ch = "";
BasicString<100> msg;
};
template<typename T>
constexpr Error model(T *io, TraceMsg *obj) {
io->template setTypeInfo<TraceMsg>();
oxReturnError(io->field("ch", &obj->ch));
oxReturnError(io->field("file", &obj->file));
oxReturnError(io->field("line", &obj->line));
oxReturnError(io->field("time", &obj->time));
oxReturnError(io->field("msg", &obj->msg));
return OxError(0);
}
class OutStream {
protected:
const char *m_delimiter = " ";
TraceMsg m_msg;
public:
constexpr OutStream(const char *file, int line, const char *ch, const char *msg = "") noexcept {
m_msg.file = file;
m_msg.line = line;
m_msg.ch = ch;
m_msg.msg = msg;
}
#ifdef OX_USE_STDLIB
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, std::array<detail::FmtArg, fmtSegmentCnt - 1> elements) noexcept {
//static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format.");
m_msg.file = file;
m_msg.line = line;
m_msg.ch = ch;
const auto &firstSegment = fmtSegments.segments[0];
oxIgnoreError(m_msg.msg.append(firstSegment.str, firstSegment.length));
//const detail::FmtArg elements[sizeof...(args)] = {args...};
for (auto i = 0u; i < fmtSegments.size - 1; ++i) {
m_msg.msg += elements[i].out;
const auto &s = fmtSegments.segments[i + 1];
oxIgnoreError(m_msg.msg.append(s.str, s.length));
}
}
#else
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, Args... args) noexcept {
//static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format.");
m_msg.file = file;
m_msg.line = line;
m_msg.ch = ch;
const auto &firstSegment = fmtSegments.segments[0];
oxIgnoreError(m_msg.msg.append(firstSegment.str, firstSegment.length));
const detail::FmtArg elements[sizeof...(args)] = {args...};
for (auto i = 0u; i < fmtSegments.size - 1; ++i) {
m_msg.msg += elements[i].out;
const auto &s = fmtSegments.segments[i + 1];
oxIgnoreError(m_msg.msg.append(s.str, s.length));
}
}
#endif
inline ~OutStream() noexcept {
oxTraceHook(m_msg.file, m_msg.line, m_msg.ch, m_msg.msg.c_str());
}
template<typename T>
constexpr OutStream &operator<<(const typename enable_if<is_integral_v<T>>::type &v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
if constexpr(T(-1) < 0) {
m_msg.msg += static_cast<int64_t>(v);
} else {
m_msg.msg += static_cast<uint64_t>(v);
}
return *this;
}
constexpr OutStream &operator<<(char *v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v;
return *this;
}
constexpr OutStream &operator<<(const char *v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v;
return *this;
}
template<std::size_t sz>
constexpr OutStream &operator<<(const BasicString<sz> &v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v.c_str();
return *this;
}
template<std::size_t sz>
constexpr OutStream &operator<<(const BString<sz> &v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v.c_str();
return *this;
}
constexpr OutStream &operator<<(char v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v;
return *this;
}
constexpr OutStream &operator<<(const Error &err) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += static_cast<int64_t>(err);
return *this;
}
/**
* del sets the delimiter between log segments.
*/
constexpr OutStream &del(const char *delimiter) noexcept {
m_delimiter = delimiter;
return *this;
}
};
class NullStream {
public:
constexpr NullStream(const char*, int, const char*, const char* = "") noexcept {
}
#ifdef OX_USE_STDLIB
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, std::array<detail::FmtArg, fmtSegmentCnt - 1>) noexcept {
}
#else
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, Args...) {
}
#endif
template<typename T>
constexpr NullStream &operator<<(const T&) noexcept {
return *this;
}
constexpr NullStream &del(const char*) noexcept {
return *this;
}
};
#if defined(DEBUG) && !defined(OX_BARE_METAL)
using TraceStream = OutStream;
#else
using TraceStream = NullStream;
#endif
void logError(const char *file, int line, const Error &err);
void init();
}
#define oxLogError(err) ox::trace::logError(__FILE__, __LINE__, err)
#define oxTrace(...) ox::trace::TraceStream(__FILE__, __LINE__, __VA_ARGS__)
#define oxOut(...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", __VA_ARGS__)
#define oxErr(...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", __VA_ARGS__)
#ifdef OX_USE_STDLIB
// Non-GCC compilers don't like ##__VA_ARGS__, so use initializer list, which relies on std lib
#define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__})
#define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__})
#define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__})
#else
#define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__)
#define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__)
#define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__)
#endif
#define oxInfo(...) oxTrace("info", __VA_ARGS__)
#define oxInfof(...) oxTracef("info", __VA_ARGS__)
#define oxError(...) oxTrace("error", __VA_ARGS__)
#define oxErrorf(...) oxTracef("error", __VA_ARGS__)
#ifndef OX_NODEBUG
#define oxDebug(...) oxTrace("debug", __VA_ARGS__)
#define oxDebugf(...) oxTracef("debug", __VA_ARGS__)
#else
#define oxDebug(...) static_assert(false, "Debug prints were checked in."); oxTrace("debug", __VA_ARGS__)
#define oxDebugf(...) static_assert(false, "Debug prints were checked in."); oxTracef("debug", __VA_ARGS__)
#endif
<commit_msg>[ox/std] Remove template integer operators from OutStream<commit_after>/*
* Copyright 2015 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#ifdef OX_USE_STDLIB
#include <array>
#endif
#include "bstring.hpp"
#include "fmt.hpp"
#include "hashmap.hpp"
#include "string.hpp"
#include "units.hpp"
extern "C" {
void oxTraceInitHook();
void oxTraceHook(const char *file, int line, const char *ch, const char *msg);
}
namespace ox::trace {
struct TraceMsg {
static constexpr auto TypeName = "net.drinkingtea.ox.trace.TraceMsg";
static constexpr auto Fields = 5;
static constexpr auto TypeVersion = 1;
const char *file = "";
int line = 0;
uint64_t time = 0;
const char *ch = "";
BasicString<100> msg;
};
template<typename T>
constexpr Error model(T *io, TraceMsg *obj) {
io->template setTypeInfo<TraceMsg>();
oxReturnError(io->field("ch", &obj->ch));
oxReturnError(io->field("file", &obj->file));
oxReturnError(io->field("line", &obj->line));
oxReturnError(io->field("time", &obj->time));
oxReturnError(io->field("msg", &obj->msg));
return OxError(0);
}
class OutStream {
protected:
const char *m_delimiter = " ";
TraceMsg m_msg;
public:
constexpr OutStream(const char *file, int line, const char *ch, const char *msg = "") noexcept {
m_msg.file = file;
m_msg.line = line;
m_msg.ch = ch;
m_msg.msg = msg;
}
#ifdef OX_USE_STDLIB
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, std::array<detail::FmtArg, fmtSegmentCnt - 1> elements) noexcept {
//static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format.");
m_msg.file = file;
m_msg.line = line;
m_msg.ch = ch;
const auto &firstSegment = fmtSegments.segments[0];
oxIgnoreError(m_msg.msg.append(firstSegment.str, firstSegment.length));
//const detail::FmtArg elements[sizeof...(args)] = {args...};
for (auto i = 0u; i < fmtSegments.size - 1; ++i) {
m_msg.msg += elements[i].out;
const auto &s = fmtSegments.segments[i + 1];
oxIgnoreError(m_msg.msg.append(s.str, s.length));
}
}
#else
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, Args... args) noexcept {
//static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format.");
m_msg.file = file;
m_msg.line = line;
m_msg.ch = ch;
const auto &firstSegment = fmtSegments.segments[0];
oxIgnoreError(m_msg.msg.append(firstSegment.str, firstSegment.length));
const detail::FmtArg elements[sizeof...(args)] = {args...};
for (auto i = 0u; i < fmtSegments.size - 1; ++i) {
m_msg.msg += elements[i].out;
const auto &s = fmtSegments.segments[i + 1];
oxIgnoreError(m_msg.msg.append(s.str, s.length));
}
}
#endif
inline ~OutStream() noexcept {
oxTraceHook(m_msg.file, m_msg.line, m_msg.ch, m_msg.msg.c_str());
}
constexpr OutStream &operator<<(short v) noexcept;
constexpr OutStream &operator<<(int v) noexcept;
constexpr OutStream &operator<<(long v) noexcept;
constexpr OutStream &operator<<(long long v) noexcept;
constexpr OutStream &operator<<(unsigned char v) noexcept;
constexpr OutStream &operator<<(unsigned short v) noexcept;
constexpr OutStream &operator<<(unsigned int v) noexcept;
constexpr OutStream &operator<<(unsigned long v) noexcept;
constexpr OutStream &operator<<(unsigned long long v) noexcept;
constexpr OutStream &operator<<(char v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v;
return *this;
}
constexpr OutStream &operator<<(const char *v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += v;
return *this;
}
template<std::size_t sz>
constexpr OutStream &operator<<(const BString<sz> &v) noexcept {
return operator<<(v.c_str());
}
template<std::size_t sz>
constexpr OutStream &operator<<(const BasicString<sz> &v) noexcept {
return operator<<(v.c_str());
}
constexpr OutStream &operator<<(const Error &err) noexcept {
return appendSignedInt(static_cast<int64_t>(err));
}
/**
* del sets the delimiter between log segments.
*/
constexpr OutStream &del(const char *delimiter) noexcept {
m_delimiter = delimiter;
return *this;
}
private:
constexpr OutStream &appendSignedInt(int64_t v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += static_cast<int64_t>(v);
return *this;
}
constexpr OutStream &appendUnsignedInt(uint64_t v) noexcept {
if (m_msg.msg.len()) {
m_msg.msg += m_delimiter;
}
m_msg.msg += static_cast<int64_t>(v);
return *this;
}
};
constexpr OutStream &OutStream::operator<<(short v) noexcept {
return appendSignedInt(v);
}
constexpr OutStream &OutStream::operator<<(int v) noexcept {
return appendSignedInt(v);
}
constexpr OutStream &OutStream::operator<<(long v) noexcept {
return appendSignedInt(v);
}
constexpr OutStream &OutStream::operator<<(long long v) noexcept {
return appendSignedInt(v);
}
constexpr OutStream &OutStream::operator<<(unsigned char v) noexcept {
return appendUnsignedInt(v);
}
constexpr OutStream &OutStream::operator<<(unsigned short v) noexcept {
return appendUnsignedInt(v);
}
constexpr OutStream &OutStream::operator<<(unsigned int v) noexcept {
return appendUnsignedInt(v);
}
constexpr OutStream &OutStream::operator<<(unsigned long v) noexcept {
return appendUnsignedInt(v);
}
constexpr OutStream &OutStream::operator<<(unsigned long long v) noexcept {
return appendUnsignedInt(v);
}
class NullStream {
public:
constexpr NullStream(const char*, int, const char*, const char* = "") noexcept {
}
#ifdef OX_USE_STDLIB
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, std::array<detail::FmtArg, fmtSegmentCnt - 1>) noexcept {
}
#else
template<std::size_t fmtSegmentCnt, typename ...Args>
constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, Args...) {
}
#endif
template<typename T>
constexpr NullStream &operator<<(const T&) noexcept {
return *this;
}
constexpr NullStream &del(const char*) noexcept {
return *this;
}
};
#if defined(DEBUG) && !defined(OX_BARE_METAL)
using TraceStream = OutStream;
#else
using TraceStream = NullStream;
#endif
void logError(const char *file, int line, const Error &err);
void init();
}
#define oxLogError(err) ox::trace::logError(__FILE__, __LINE__, err)
#define oxTrace(...) ox::trace::TraceStream(__FILE__, __LINE__, __VA_ARGS__)
#define oxOut(...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", __VA_ARGS__)
#define oxErr(...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", __VA_ARGS__)
#ifdef OX_USE_STDLIB
// Non-GCC compilers don't like ##__VA_ARGS__, so use initializer list, which relies on std lib
#define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__})
#define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__})
#define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__})
#else
#define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__)
#define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__)
#define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__)
#endif
#define oxInfo(...) oxTrace("info", __VA_ARGS__)
#define oxInfof(...) oxTracef("info", __VA_ARGS__)
#define oxError(...) oxTrace("error", __VA_ARGS__)
#define oxErrorf(...) oxTracef("error", __VA_ARGS__)
#ifndef OX_NODEBUG
#define oxDebug(...) oxTrace("debug", __VA_ARGS__)
#define oxDebugf(...) oxTracef("debug", __VA_ARGS__)
#else
#define oxDebug(...) static_assert(false, "Debug prints were checked in."); oxTrace("debug", __VA_ARGS__)
#define oxDebugf(...) static_assert(false, "Debug prints were checked in."); oxTracef("debug", __VA_ARGS__)
#endif
<|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 <fstream>
#include <string>
#include <vector>
#include "gflags/gflags.h"
#include "ros/include/ros/ros.h"
#include "ros/include/rosbag/bag.h"
#include "ros/include/rosbag/view.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/common/util/string_util.h"
DEFINE_string(adapter_config_filename,
"/apollo/modules/data/conf/event_collector_adapter.conf",
"Path for adapter configuration.");
DEFINE_string(events_filename, "events.txt", "File to save event list.");
DEFINE_string(events_related_bags_filename, "events_related_bags.txt",
"File to save events related bags list.");
DEFINE_double(event_time_backtrack_seconds, 20,
"Backtrack from the event time to consider bags as related.");
namespace apollo {
namespace data {
namespace {
using apollo::common::adapter::AdapterManager;
using apollo::canbus::Chassis;
void OnSigInt(int32_t signal_num) {
// only response for ctrl + c
if (signal_num != SIGINT) {
return;
}
AINFO << "EventCollector got signal: " << signal_num;
// Only stop once.
static bool is_stopping = false;
if (!is_stopping) {
is_stopping = true;
ros::shutdown();
}
}
class EventCollector {
public:
void Init(int32_t argc, char **argv) {
signal(SIGINT, OnSigInt);
ros::init(argc, argv, "EventCollector");
AdapterManager::Init(FLAGS_adapter_config_filename);
}
void Start() {
AdapterManager::AddDriveEventCallback(&EventCollector::OnDriveEvent, this);
AdapterManager::AddChassisCallback(&EventCollector::OnChassis, this);
AdapterManager::AddMonitorCallback(&EventCollector::OnMonitorMessage, this);
AINFO << "Start spining...";
ros::spin();
}
void Stop() {
// Save events_related_bags.
std::ofstream fout(FLAGS_events_related_bags_filename);
if (!fout) {
AERROR << "Failed to write " << FLAGS_events_related_bags_filename;
return;
}
AINFO << "Saving info to " << FLAGS_events_related_bags_filename << "...";
fout << std::fixed << std::setprecision(1);
sort(events_.begin(), events_.end());
for (const std::string& bag_filename :
apollo::common::util::ListSubPaths("./", DT_REG)) {
if (!apollo::common::util::EndWith(bag_filename, ".bag")) {
continue;
}
rosbag::Bag bag(bag_filename);
rosbag::View view(bag);
const double begin_time = view.getBeginTime().toSec();
const double end_time =
view.getEndTime().toSec() + FLAGS_event_time_backtrack_seconds;
bool started_line = false;
const std::tuple<double, std::string> key(begin_time, "");
for (auto iter = std::lower_bound(events_.begin(), events_.end(), key);
iter != events_.end() && std::get<0>(*iter) < end_time; ++iter) {
// event_time = std::get<0>(*iter)
// event_message = std::get<1>(*iter)
if (!started_line) {
started_line = true;
fout << bag_filename << "\n";
}
fout << " Offset = " << std::get<0>(*iter) - begin_time << ", "
<< std::get<1>(*iter) << "\n";
}
}
}
private:
// Event time and message.
std::vector<std::tuple<double, std::string>> events_;
Chassis::DrivingMode current_driving_mode_;
void OnDriveEvent(const apollo::common::DriveEvent& event) {
// The header time is the real event time.
SaveEvent(event.header().timestamp_sec(), "DriveEvent", event.event());
}
void OnChassis(const Chassis& chassis) {
// Save event when driving_mode changes from COMPLETE_AUTO_DRIVE to
// EMERGENCY_MODE which is taken as a disengagement.
if (current_driving_mode_ == Chassis::COMPLETE_AUTO_DRIVE &&
chassis.driving_mode() == Chassis::EMERGENCY_MODE) {
SaveEvent(chassis.header().timestamp_sec(), "Disengagement");
}
current_driving_mode_ = chassis.driving_mode();
}
void OnMonitorMessage(
const apollo::common::monitor::MonitorMessage& monitor_msg) {
using apollo::common::monitor::MonitorMessageItem;
// Save all ERROR and FATAL monitor logs.
const double time_sec = monitor_msg.header().timestamp_sec();
for (const auto& item : monitor_msg.item()) {
if (item.log_level() == MonitorMessageItem::ERROR ||
item.log_level() == MonitorMessageItem::FATAL) {
SaveEvent(time_sec, "MonitorErrorLog", item.msg());
}
}
}
void SaveEvent(const double timestamp_sec, const std::string type,
const std::string description = "") {
const auto msg = apollo::common::util::StrCat(
timestamp_sec, " [", type, "] ", description);
AINFO << "SaveEvent: " << msg;
events_.emplace_back(timestamp_sec, msg);
// Append new event and flush.
std::ofstream fout(FLAGS_events_filename, std::ofstream::app);
if (fout) {
fout << msg << std::endl;
} else {
AERROR << "Failed to write to " << FLAGS_events_filename;
}
}
};
} // namespace
} // namespace data
} // namespace apollo
int main(int32_t argc, char **argv) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
apollo::data::EventCollector event_collector;
event_collector.Init(argc, argv);
event_collector.Start();
event_collector.Stop();
return 0;
}
<commit_msg>Data: Rename to last_driving_mode_ to make it clear.<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 <fstream>
#include <string>
#include <vector>
#include "gflags/gflags.h"
#include "ros/include/ros/ros.h"
#include "ros/include/rosbag/bag.h"
#include "ros/include/rosbag/view.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/common/util/string_util.h"
DEFINE_string(adapter_config_filename,
"/apollo/modules/data/conf/event_collector_adapter.conf",
"Path for adapter configuration.");
DEFINE_string(events_filename, "events.txt", "File to save event list.");
DEFINE_string(events_related_bags_filename, "events_related_bags.txt",
"File to save events related bags list.");
DEFINE_double(event_time_backtrack_seconds, 20,
"Backtrack from the event time to consider bags as related.");
namespace apollo {
namespace data {
namespace {
using apollo::common::adapter::AdapterManager;
using apollo::canbus::Chassis;
void OnSigInt(int32_t signal_num) {
// only response for ctrl + c
if (signal_num != SIGINT) {
return;
}
AINFO << "EventCollector got signal: " << signal_num;
// Only stop once.
static bool is_stopping = false;
if (!is_stopping) {
is_stopping = true;
ros::shutdown();
}
}
class EventCollector {
public:
void Init(int32_t argc, char **argv) {
signal(SIGINT, OnSigInt);
ros::init(argc, argv, "EventCollector");
AdapterManager::Init(FLAGS_adapter_config_filename);
}
void Start() {
AdapterManager::AddDriveEventCallback(&EventCollector::OnDriveEvent, this);
AdapterManager::AddChassisCallback(&EventCollector::OnChassis, this);
AdapterManager::AddMonitorCallback(&EventCollector::OnMonitorMessage, this);
AINFO << "Start spining...";
ros::spin();
}
void Stop() {
// Save events_related_bags.
std::ofstream fout(FLAGS_events_related_bags_filename);
if (!fout) {
AERROR << "Failed to write " << FLAGS_events_related_bags_filename;
return;
}
AINFO << "Saving info to " << FLAGS_events_related_bags_filename << "...";
fout << std::fixed << std::setprecision(1);
sort(events_.begin(), events_.end());
for (const std::string& bag_filename :
apollo::common::util::ListSubPaths("./", DT_REG)) {
if (!apollo::common::util::EndWith(bag_filename, ".bag")) {
continue;
}
rosbag::Bag bag(bag_filename);
rosbag::View view(bag);
const double begin_time = view.getBeginTime().toSec();
const double end_time =
view.getEndTime().toSec() + FLAGS_event_time_backtrack_seconds;
bool started_line = false;
const std::tuple<double, std::string> key(begin_time, "");
for (auto iter = std::lower_bound(events_.begin(), events_.end(), key);
iter != events_.end() && std::get<0>(*iter) < end_time; ++iter) {
// event_time = std::get<0>(*iter)
// event_message = std::get<1>(*iter)
if (!started_line) {
started_line = true;
fout << bag_filename << "\n";
}
fout << " Offset = " << std::get<0>(*iter) - begin_time << ", "
<< std::get<1>(*iter) << "\n";
}
}
}
private:
// Event time and message.
std::vector<std::tuple<double, std::string>> events_;
Chassis::DrivingMode last_driving_mode_;
void OnDriveEvent(const apollo::common::DriveEvent& event) {
// The header time is the real event time.
SaveEvent(event.header().timestamp_sec(), "DriveEvent", event.event());
}
void OnChassis(const Chassis& chassis) {
// Save event when driving_mode changes from COMPLETE_AUTO_DRIVE to
// EMERGENCY_MODE which is taken as a disengagement.
if (last_driving_mode_ == Chassis::COMPLETE_AUTO_DRIVE &&
chassis.driving_mode() == Chassis::EMERGENCY_MODE) {
SaveEvent(chassis.header().timestamp_sec(), "Disengagement");
}
last_driving_mode_ = chassis.driving_mode();
}
void OnMonitorMessage(
const apollo::common::monitor::MonitorMessage& monitor_msg) {
using apollo::common::monitor::MonitorMessageItem;
// Save all ERROR and FATAL monitor logs.
const double time_sec = monitor_msg.header().timestamp_sec();
for (const auto& item : monitor_msg.item()) {
if (item.log_level() == MonitorMessageItem::ERROR ||
item.log_level() == MonitorMessageItem::FATAL) {
SaveEvent(time_sec, "MonitorErrorLog", item.msg());
}
}
}
void SaveEvent(const double timestamp_sec, const std::string type,
const std::string description = "") {
const auto msg = apollo::common::util::StrCat(
timestamp_sec, " [", type, "] ", description);
AINFO << "SaveEvent: " << msg;
events_.emplace_back(timestamp_sec, msg);
// Append new event and flush.
std::ofstream fout(FLAGS_events_filename, std::ofstream::app);
if (fout) {
fout << msg << std::endl;
} else {
AERROR << "Failed to write to " << FLAGS_events_filename;
}
}
};
} // namespace
} // namespace data
} // namespace apollo
int main(int32_t argc, char **argv) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
apollo::data::EventCollector event_collector;
event_collector.Init(argc, argv);
event_collector.Start();
event_collector.Stop();
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* ctrl_video.cpp
*****************************************************************************
* Copyright (C) 2004 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <[email protected]>
*
* 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 "ctrl_video.hpp"
#include "../src/theme.hpp"
#include "../src/vout_window.hpp"
#include "../src/os_graphics.hpp"
#include "../src/vlcproc.hpp"
#include "../src/vout_manager.hpp"
#include "../src/window_manager.hpp"
#include "../commands/async_queue.hpp"
#include "../commands/cmd_resize.hpp"
CtrlVideo::CtrlVideo( intf_thread_t *pIntf, GenericLayout &rLayout,
bool autoResize, const UString &rHelp,
VarBool *pVisible ):
CtrlGeneric( pIntf, rHelp, pVisible ), m_rLayout( rLayout ),
m_xShift( 0 ), m_yShift( 0 ), m_bAutoResize( autoResize ),
m_pVoutWindow( NULL ), m_bIsUseable( false )
{
VarBool &rFullscreen = VlcProc::instance( getIntf() )->getFullscreenVar();
rFullscreen.addObserver( this );
// if global parameter set to no resize, override skins behavior
if( !var_InheritBool( pIntf, "qt-video-autoresize" ) )
m_bAutoResize = false;
}
CtrlVideo::~CtrlVideo()
{
VarBool &rFullscreen = VlcProc::instance( getIntf() )->getFullscreenVar();
rFullscreen.delObserver( this );
}
void CtrlVideo::handleEvent( EvtGeneric &rEvent )
{
}
bool CtrlVideo::mouseOver( int x, int y ) const
{
return false;
}
void CtrlVideo::onResize()
{
const Position *pPos = getPosition();
if( pPos && m_pVoutWindow )
{
m_pVoutWindow->move( pPos->getLeft(), pPos->getTop() );
m_pVoutWindow->resize( pPos->getWidth(), pPos->getHeight() );
}
}
void CtrlVideo::onPositionChange()
{
// Compute the difference between layout size and video size
m_xShift = m_rLayout.getWidth() - getPosition()->getWidth();
m_yShift = m_rLayout.getHeight() - getPosition()->getHeight();
}
void CtrlVideo::draw( OSGraphics &rImage, int xDest, int yDest )
{
const Position *pPos = getPosition();
if( pPos )
{
// Draw a black rectangle under the video to avoid transparency
rImage.fillRect( pPos->getLeft(), pPos->getTop(), pPos->getWidth(),
pPos->getHeight(), 0 );
}
}
void CtrlVideo::setLayout( GenericLayout *pLayout,
const Position &rPosition )
{
CtrlGeneric::setLayout( pLayout, rPosition );
m_pLayout->getActiveVar().addObserver( this );
m_bIsUseable = isVisible() && m_pLayout->getActiveVar().get();
// register Video Control
VoutManager::instance( getIntf() )->registerCtrlVideo( this );
msg_Dbg( getIntf(),"New VideoControl detected(%p), useability=%s",
this, m_bIsUseable ? "true" : "false" );
}
void CtrlVideo::unsetLayout()
{
m_pLayout->getActiveVar().delObserver( this );
CtrlGeneric::unsetLayout();
}
void CtrlVideo::resizeControl( int width, int height )
{
WindowManager &rWindowManager =
getIntf()->p_sys->p_theme->getWindowManager();
const Position *pPos = getPosition();
if( width != pPos->getWidth() || height != pPos->getHeight() )
{
// new layout dimensions
int newWidth = width + m_xShift;
int newHeight = height + m_yShift;
// Resize the layout
rWindowManager.startResize( m_rLayout, WindowManager::kResizeSE );
rWindowManager.resize( m_rLayout, newWidth, newHeight );
rWindowManager.stopResize();
if( m_pVoutWindow )
{
m_pVoutWindow->resize( pPos->getWidth(), pPos->getHeight() );
m_pVoutWindow->move( pPos->getLeft(), pPos->getTop() );
}
}
}
void CtrlVideo::onUpdate( Subject<VarBool> &rVariable, void *arg )
{
// Visibility changed
if( &rVariable == m_pVisible )
{
msg_Dbg( getIntf(), "VideoCtrl : Visibility changed (visible=%d)",
isVisible() );
}
// Active Layout changed
if( &rVariable == &m_pLayout->getActiveVar() )
{
msg_Dbg( getIntf(), "VideoCtrl : Active Layout changed (isActive=%d)",
m_pLayout->getActiveVar().get() );
}
VarBool &rFullscreen = VlcProc::instance( getIntf() )->getFullscreenVar();
if( &rVariable == &rFullscreen )
{
msg_Dbg( getIntf(), "VideoCtrl : fullscreen toggled (fullscreen = %d)",
rFullscreen.get() );
}
m_bIsUseable = isVisible() &&
m_pLayout->getActiveVar().get() &&
!rFullscreen.get();
if( m_bIsUseable && !isUsed() )
{
VoutManager::instance( getIntf() )->requestVout( this );
}
else if( !m_bIsUseable && isUsed() )
{
VoutManager::instance( getIntf() )->discardVout( this );
}
}
void CtrlVideo::attachVoutWindow( VoutWindow* pVoutWindow, int width, int height )
{
width = ( width < 0 ) ? pVoutWindow->getOriginalWidth() : width;
height = ( height < 0 ) ? pVoutWindow->getOriginalHeight() : height;
WindowManager &rWindowManager =
getIntf()->p_sys->p_theme->getWindowManager();
TopWindow* pWin = getWindow();
rWindowManager.show( *pWin );
if( m_bAutoResize && width && height )
{
int newWidth = width + m_xShift;
int newHeight = height + m_yShift;
rWindowManager.startResize( m_rLayout, WindowManager::kResizeSE );
rWindowManager.resize( m_rLayout, newWidth, newHeight );
rWindowManager.stopResize();
}
pVoutWindow->setCtrlVideo( this );
m_pVoutWindow = pVoutWindow;
}
void CtrlVideo::detachVoutWindow( )
{
m_pVoutWindow->setCtrlVideo( NULL );
m_pVoutWindow = NULL;
}
<commit_msg>skins2: fix a refresh artefact (not frequent corner case)<commit_after>/*****************************************************************************
* ctrl_video.cpp
*****************************************************************************
* Copyright (C) 2004 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <[email protected]>
*
* 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 "ctrl_video.hpp"
#include "../src/theme.hpp"
#include "../src/vout_window.hpp"
#include "../src/os_graphics.hpp"
#include "../src/vlcproc.hpp"
#include "../src/vout_manager.hpp"
#include "../src/window_manager.hpp"
#include "../commands/async_queue.hpp"
#include "../commands/cmd_resize.hpp"
CtrlVideo::CtrlVideo( intf_thread_t *pIntf, GenericLayout &rLayout,
bool autoResize, const UString &rHelp,
VarBool *pVisible ):
CtrlGeneric( pIntf, rHelp, pVisible ), m_rLayout( rLayout ),
m_xShift( 0 ), m_yShift( 0 ), m_bAutoResize( autoResize ),
m_pVoutWindow( NULL ), m_bIsUseable( false )
{
VarBool &rFullscreen = VlcProc::instance( getIntf() )->getFullscreenVar();
rFullscreen.addObserver( this );
// if global parameter set to no resize, override skins behavior
if( !var_InheritBool( pIntf, "qt-video-autoresize" ) )
m_bAutoResize = false;
}
CtrlVideo::~CtrlVideo()
{
VarBool &rFullscreen = VlcProc::instance( getIntf() )->getFullscreenVar();
rFullscreen.delObserver( this );
}
void CtrlVideo::handleEvent( EvtGeneric &rEvent )
{
}
bool CtrlVideo::mouseOver( int x, int y ) const
{
return false;
}
void CtrlVideo::onResize()
{
const Position *pPos = getPosition();
if( pPos && m_pVoutWindow )
{
m_pVoutWindow->move( pPos->getLeft(), pPos->getTop() );
m_pVoutWindow->resize( pPos->getWidth(), pPos->getHeight() );
}
}
void CtrlVideo::onPositionChange()
{
// Compute the difference between layout size and video size
m_xShift = m_rLayout.getWidth() - getPosition()->getWidth();
m_yShift = m_rLayout.getHeight() - getPosition()->getHeight();
}
void CtrlVideo::draw( OSGraphics &rImage, int xDest, int yDest )
{
const Position *pPos = getPosition();
if( pPos )
{
// Draw a black rectangle under the video to avoid transparency
rImage.fillRect( pPos->getLeft(), pPos->getTop(), pPos->getWidth(),
pPos->getHeight(), 0 );
}
}
void CtrlVideo::setLayout( GenericLayout *pLayout,
const Position &rPosition )
{
CtrlGeneric::setLayout( pLayout, rPosition );
m_pLayout->getActiveVar().addObserver( this );
m_bIsUseable = isVisible() && m_pLayout->getActiveVar().get();
// register Video Control
VoutManager::instance( getIntf() )->registerCtrlVideo( this );
msg_Dbg( getIntf(),"New VideoControl detected(%p), useability=%s",
this, m_bIsUseable ? "true" : "false" );
}
void CtrlVideo::unsetLayout()
{
m_pLayout->getActiveVar().delObserver( this );
CtrlGeneric::unsetLayout();
}
void CtrlVideo::resizeControl( int width, int height )
{
WindowManager &rWindowManager =
getIntf()->p_sys->p_theme->getWindowManager();
const Position *pPos = getPosition();
if( width != pPos->getWidth() || height != pPos->getHeight() )
{
// new layout dimensions
int newWidth = width + m_xShift;
int newHeight = height + m_yShift;
// Resize the layout
rWindowManager.startResize( m_rLayout, WindowManager::kResizeSE );
rWindowManager.resize( m_rLayout, newWidth, newHeight );
rWindowManager.stopResize();
if( m_pVoutWindow )
{
m_pVoutWindow->resize( pPos->getWidth(), pPos->getHeight() );
m_pVoutWindow->move( pPos->getLeft(), pPos->getTop() );
}
}
}
void CtrlVideo::onUpdate( Subject<VarBool> &rVariable, void *arg )
{
// Visibility changed
if( &rVariable == m_pVisible )
{
msg_Dbg( getIntf(), "VideoCtrl : Visibility changed (visible=%d)",
isVisible() );
notifyLayout();
}
// Active Layout changed
if( &rVariable == &m_pLayout->getActiveVar() )
{
msg_Dbg( getIntf(), "VideoCtrl : Active Layout changed (isActive=%d)",
m_pLayout->getActiveVar().get() );
}
VarBool &rFullscreen = VlcProc::instance( getIntf() )->getFullscreenVar();
if( &rVariable == &rFullscreen )
{
msg_Dbg( getIntf(), "VideoCtrl : fullscreen toggled (fullscreen = %d)",
rFullscreen.get() );
}
m_bIsUseable = isVisible() &&
m_pLayout->getActiveVar().get() &&
!rFullscreen.get();
if( m_bIsUseable && !isUsed() )
{
VoutManager::instance( getIntf() )->requestVout( this );
}
else if( !m_bIsUseable && isUsed() )
{
VoutManager::instance( getIntf() )->discardVout( this );
}
}
void CtrlVideo::attachVoutWindow( VoutWindow* pVoutWindow, int width, int height )
{
width = ( width < 0 ) ? pVoutWindow->getOriginalWidth() : width;
height = ( height < 0 ) ? pVoutWindow->getOriginalHeight() : height;
WindowManager &rWindowManager =
getIntf()->p_sys->p_theme->getWindowManager();
TopWindow* pWin = getWindow();
rWindowManager.show( *pWin );
if( m_bAutoResize && width && height )
{
int newWidth = width + m_xShift;
int newHeight = height + m_yShift;
rWindowManager.startResize( m_rLayout, WindowManager::kResizeSE );
rWindowManager.resize( m_rLayout, newWidth, newHeight );
rWindowManager.stopResize();
}
pVoutWindow->setCtrlVideo( this );
m_pVoutWindow = pVoutWindow;
}
void CtrlVideo::detachVoutWindow( )
{
m_pVoutWindow->setCtrlVideo( NULL );
m_pVoutWindow = NULL;
}
<|endoftext|> |
<commit_before>#include "falcon/cxx/cxx.hpp"
#include "falcon/cxx/compiler_attributes.hpp"
#include "falcon/cxx/lib.hpp"
#include "falcon/cxx/lib_experimental.hpp"
#include "falcon/cxx/move_algorithm.hpp"
#include "falcon/cxx/move.hpp"
template<class... T>
void foo(T... x)
{
static_assert(noexcept(FALCON_UNPACK(x+1)), "must be noexcept");
}
int main()
{
foo(1, 2);
}
<commit_msg>constexpr test for FALCON_UNPACK<commit_after>#include "falcon/cxx/cxx.hpp"
#include "falcon/cxx/compiler_attributes.hpp"
#include "falcon/cxx/lib.hpp"
#include "falcon/cxx/lib_experimental.hpp"
#include "falcon/cxx/move_algorithm.hpp"
#include "falcon/cxx/move.hpp"
template<class... T>
constexpr int foo(T... x)
{
static_assert(noexcept(FALCON_UNPACK(x+1)), "must be noexcept");
int sum = 0;
FALCON_UNPACK(sum += x);
return sum;
}
template<int i> class i_{};
int main()
{
i_<foo(1, 2)>{};
}
<|endoftext|> |
<commit_before>#include "download.h"
#include "test-helpers.h"
using namespace podboat;
TEST_CASE("Require-view-update callback gets called when download progress or status changes",
"[Download]")
{
GIVEN("A Download object") {
bool got_called = false;
std::function<void()> callback = [&got_called]() {
got_called = true;
};
Download d(callback);
REQUIRE(d.status() == DlStatus::QUEUED);
WHEN("its progress is updated (increased)") {
d.set_progress(1.0, 1.0);
THEN("the require-view-update callback gets called") {
REQUIRE(got_called);
}
}
WHEN("its progress has not changed") {
d.set_progress(0.0, 1.0);
THEN("the require-view-update callback does not get called") {
REQUIRE_FALSE(got_called);
}
}
WHEN("its status is changed") {
d.set_status(DlStatus::DOWNLOADING);
THEN("the require-view-update callback gets called") {
REQUIRE(got_called);
}
}
WHEN("when its status is not changed") {
d.set_status(DlStatus::QUEUED);
THEN("the require-view-update callback does not get called") {
REQUIRE_FALSE(got_called);
}
}
}
}
TEST_CASE("Filename returns download's target filename", "[Download]")
{
auto emptyCallback = []() {};
Download d(emptyCallback);
SECTION("filename returns empty string by default") {
REQUIRE(d.filename().empty());
}
SECTION("filename returns same string which is set via set_filename") {
d.set_filename("abc");
REQUIRE(d.filename() == "abc");
}
SECTION("filename will return the latest configured filename") {
d.set_filename("abc");
d.set_filename("def");
REQUIRE(d.filename() == "def");
}
}
<commit_msg>Review comment: Make clear that `filename` is a function in test name<commit_after>#include "download.h"
#include "test-helpers.h"
using namespace podboat;
TEST_CASE("Require-view-update callback gets called when download progress or status changes",
"[Download]")
{
GIVEN("A Download object") {
bool got_called = false;
std::function<void()> callback = [&got_called]() {
got_called = true;
};
Download d(callback);
REQUIRE(d.status() == DlStatus::QUEUED);
WHEN("its progress is updated (increased)") {
d.set_progress(1.0, 1.0);
THEN("the require-view-update callback gets called") {
REQUIRE(got_called);
}
}
WHEN("its progress has not changed") {
d.set_progress(0.0, 1.0);
THEN("the require-view-update callback does not get called") {
REQUIRE_FALSE(got_called);
}
}
WHEN("its status is changed") {
d.set_status(DlStatus::DOWNLOADING);
THEN("the require-view-update callback gets called") {
REQUIRE(got_called);
}
}
WHEN("when its status is not changed") {
d.set_status(DlStatus::QUEUED);
THEN("the require-view-update callback does not get called") {
REQUIRE_FALSE(got_called);
}
}
}
}
TEST_CASE("filename() returns download's target filename", "[Download]")
{
auto emptyCallback = []() {};
Download d(emptyCallback);
SECTION("filename returns empty string by default") {
REQUIRE(d.filename().empty());
}
SECTION("filename returns same string which is set via set_filename") {
d.set_filename("abc");
REQUIRE(d.filename() == "abc");
}
SECTION("filename will return the latest configured filename") {
d.set_filename("abc");
d.set_filename("def");
REQUIRE(d.filename() == "def");
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <tudocomp/io.h>
#include <tudocomp/util/Generators.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include "test_util.h"
using namespace tudocomp;
typedef void (*string_test_func_t)(const std::string&);
//Check that p is a permutation of [0..n-1]
template<class T>
void ASSERT_PERMUTATION(const T& p, size_t n) {
for(size_t i = 0; i < n; ++i)
for(size_t j = 0; j < n; ++j)
{
if(i == j) continue;
ASSERT_NE(p[i],p[j]) << "at positions " << i << " and " << j;
ASSERT_LT(p[i],n);
}
}
// Simple string array dispenser
class StringArrayDispenser {
private:
static const size_t NUM_TEST_STRINGS;
static const std::string TEST_STRINGS[];
size_t m_next;
public:
StringArrayDispenser() : m_next(0) {};
bool has_next() {
return m_next < NUM_TEST_STRINGS;
}
const std::string& next() {
return TEST_STRINGS[m_next++];
}
};
const size_t StringArrayDispenser::NUM_TEST_STRINGS = 4;
const std::string StringArrayDispenser::TEST_STRINGS[] = {
"",
"0",
"aaaaaaa",
"aabaaababaaabbaabababaab",
"fjgwehfwbz43bngkwrp23fa"
};
//TODO: Markov chain generator
template<class generator_t>
void run_tests(string_test_func_t test) {
generator_t generator;
while(generator.has_next()) {
test(generator.next());
}
}
size_t lce(const std::string& text, size_t a, size_t b) {
DCHECK_NE(a,b);
size_t i = 0;
while(text[a+i] == text[b+i]) { ++i; }
return i;
}
template<class sa_t>
sdsl::int_vector<> create_lcp_naive(const std::string& text, const sa_t& sa) {
sdsl::int_vector<> lcp(sa.size());
lcp[0]=0;
for(size_t i = 1; i < sa.size(); ++i) {
lcp[i] = lce(text, sa[i],sa[i-1]);
}
return lcp;
}
template<class lcp_t, class isa_t>
sdsl::int_vector<> create_plcp_naive(const lcp_t& lcp, const isa_t& isa) {
sdsl::int_vector<> plcp(lcp.size());
for(size_t i = 0; i < lcp.size(); ++i) {
DCHECK_LT(isa[i], lcp.size());
DCHECK_GE(isa[i], 0);
plcp[i] = lcp[isa[i]];
}
for(size_t i = 1; i < lcp.size(); ++i) {
DCHECK_GE(plcp[i]+1, plcp[i-1]);
}
return plcp;
}
// === THE ACTUAL TESTS ===
template<class textds_t>
void test_TestSA(const std::string& str) {
DLOG(INFO) << "str = \"" << str << "\"" << " size: " << str.length();
size_t n = str.length();
Input input(str);
textds_t t(input.as_view());
auto& sa = t.require_sa();
ASSERT_EQ(sa.size(), n+1); //length
ASSERT_PERMUTATION(sa, n+1); //permutation
ASSERT_EQ(sa[0], n); //first element is $
//check lexicographic order
for(size_t i = 1; i < n+1; i++) {
ASSERT_GE(t[sa[i]], t[sa[i-1]]);
ASSERT_LT(str.substr(sa[i-1]), str.substr(sa[i])); //TODO: use basic_string_view to speed up!
}
auto& phi = t.require_phi();
ASSERT_EQ(phi.size(), sa.size()); //length
ASSERT_PERMUTATION(phi, phi.size()); //permutation
for(size_t i = 0; i < sa.size(); ++i) {
ASSERT_EQ(phi[sa[(i+1) % sa.size()]], sa[i]);
}
auto& isa = t.require_isa();
ASSERT_EQ(isa.size(), sa.size());
for(size_t i = 0; i < sa.size(); ++i) {
ASSERT_EQ(isa[sa[i]], i);
}
const sdsl::int_vector<> lcp_naive(create_lcp_naive(str,sa));
const auto plcp = LCP::phi_algorithm(t);
const auto plcp_naive = create_plcp_naive(lcp_naive, isa);
assert_eq_sequence(plcp, plcp_naive);
auto& lcp = t.require_lcp();
assert_eq_sequence(lcp, lcp_naive);
ASSERT_EQ(lcp.size(), sa.size()); //length
for(size_t i = 0; i < lcp.size(); ++i) {
ASSERT_EQ(lcp_naive[i], plcp_naive[sa[i]]);
ASSERT_EQ(lcp[i], plcp[sa[i]]);
ASSERT_EQ(lcp[i], plcp_naive[sa[i]]);
}
for(size_t i = 1; i < lcp.size(); ++i) {
ASSERT_EQ(lcp[i], lce(str, sa[i], sa[i-1]));
}
}
TEST(ds, TestSA) {
run_tests<StringArrayDispenser>(&test_TestSA<TextDS<>>);
for(size_t i = 0; i < 4; ++i) {
std::string s = fibonacci_word(1<<i);
test_TestSA<TextDS<>>(s);
}
// for(size_t i = 0; i < 11; ++i) {
// for(size_t j = 0; j < 2+50/(i+1); ++j) {
// std::string s = random_uniform(1<<i,Ranges::numbers,j);
// test_TestSA<TextDS<>>(s);
// }
// }
}
<commit_msg>exchanged a test with View<commit_after>#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <tudocomp/io.h>
#include <tudocomp/util/Generators.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include "test_util.h"
using namespace tudocomp;
typedef void (*string_test_func_t)(const std::string&);
//Check that p is a permutation of [0..n-1]
template<class T>
void ASSERT_PERMUTATION(const T& p, size_t n) {
for(size_t i = 0; i < n; ++i)
for(size_t j = 0; j < n; ++j)
{
if(i == j) continue;
ASSERT_NE(p[i],p[j]) << "at positions " << i << " and " << j;
ASSERT_LT(p[i],n);
}
}
// Simple string array dispenser
class StringArrayDispenser {
private:
static const size_t NUM_TEST_STRINGS;
static const std::string TEST_STRINGS[];
size_t m_next;
public:
StringArrayDispenser() : m_next(0) {};
bool has_next() {
return m_next < NUM_TEST_STRINGS;
}
const std::string& next() {
return TEST_STRINGS[m_next++];
}
};
const size_t StringArrayDispenser::NUM_TEST_STRINGS = 4;
const std::string StringArrayDispenser::TEST_STRINGS[] = {
"",
"0",
"aaaaaaa",
"aabaaababaaabbaabababaab",
"fjgwehfwbz43bngkwrp23fa"
};
//TODO: Markov chain generator
template<class generator_t>
void run_tests(string_test_func_t test) {
generator_t generator;
while(generator.has_next()) {
test(generator.next());
}
}
size_t lce(const std::string& text, size_t a, size_t b) {
DCHECK_NE(a,b);
size_t i = 0;
while(text[a+i] == text[b+i]) { ++i; }
return i;
}
template<class sa_t>
sdsl::int_vector<> create_lcp_naive(const std::string& text, const sa_t& sa) {
sdsl::int_vector<> lcp(sa.size());
lcp[0]=0;
for(size_t i = 1; i < sa.size(); ++i) {
lcp[i] = lce(text, sa[i],sa[i-1]);
}
return lcp;
}
template<class lcp_t, class isa_t>
sdsl::int_vector<> create_plcp_naive(const lcp_t& lcp, const isa_t& isa) {
sdsl::int_vector<> plcp(lcp.size());
for(size_t i = 0; i < lcp.size(); ++i) {
DCHECK_LT(isa[i], lcp.size());
DCHECK_GE(isa[i], 0);
plcp[i] = lcp[isa[i]];
}
for(size_t i = 1; i < lcp.size(); ++i) {
DCHECK_GE(plcp[i]+1, plcp[i-1]);
}
return plcp;
}
// === THE ACTUAL TESTS ===
template<class textds_t>
void test_TestSA(const std::string& str) {
DLOG(INFO) << "str = \"" << str << "\"" << " size: " << str.length();
size_t n = str.length();
Input input(str);
textds_t t(input.as_view());
auto& sa = t.require_sa();
ASSERT_EQ(sa.size(), n+1); //length
ASSERT_PERMUTATION(sa, n+1); //permutation
ASSERT_EQ(sa[0], n); //first element is $
//check lexicographic order
for(size_t i = 1; i < n+1; i++) {
ASSERT_GE(t[sa[i]], t[sa[i-1]]);
ASSERT_LT(str.substr(sa[i-1]), str.substr(sa[i])); //TODO: remove this (should be equal to below
ASSERT_LT(View(str,sa[i-1]), View(str,sa[i]));
}
auto& phi = t.require_phi();
ASSERT_EQ(phi.size(), sa.size()); //length
ASSERT_PERMUTATION(phi, phi.size()); //permutation
for(size_t i = 0; i < sa.size(); ++i) {
ASSERT_EQ(phi[sa[(i+1) % sa.size()]], sa[i]);
}
auto& isa = t.require_isa();
ASSERT_EQ(isa.size(), sa.size());
for(size_t i = 0; i < sa.size(); ++i) {
ASSERT_EQ(isa[sa[i]], i);
}
const sdsl::int_vector<> lcp_naive(create_lcp_naive(str,sa));
const auto plcp = LCP::phi_algorithm(t);
const auto plcp_naive = create_plcp_naive(lcp_naive, isa);
assert_eq_sequence(plcp, plcp_naive);
auto& lcp = t.require_lcp();
assert_eq_sequence(lcp, lcp_naive);
ASSERT_EQ(lcp.size(), sa.size()); //length
for(size_t i = 0; i < lcp.size(); ++i) {
ASSERT_EQ(lcp_naive[i], plcp_naive[sa[i]]);
ASSERT_EQ(lcp[i], plcp[sa[i]]);
ASSERT_EQ(lcp[i], plcp_naive[sa[i]]);
}
for(size_t i = 1; i < lcp.size(); ++i) {
ASSERT_EQ(lcp[i], lce(str, sa[i], sa[i-1]));
}
}
TEST(ds, TestSA) {
run_tests<StringArrayDispenser>(&test_TestSA<TextDS<>>);
for(size_t i = 0; i < 4; ++i) {
std::string s = fibonacci_word(1<<i);
test_TestSA<TextDS<>>(s);
}
// for(size_t i = 0; i < 11; ++i) {
// for(size_t j = 0; j < 2+50/(i+1); ++j) {
// std::string s = random_uniform(1<<i,Ranges::numbers,j);
// test_TestSA<TextDS<>>(s);
// }
// }
}
<|endoftext|> |
<commit_before>#include "dt_RunDrawTest.C"
#include "TClassTable.h"
#include "TDirectory.h"
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TSystem.h"
#ifndef __CINT__
#include "Event.h"
#endif
TH1F* RefClone(TH1F* orig) {
TH1F *cloned = (TH1F*)orig->Clone();
TString name = orig->GetName();
name.Prepend("ref");
cloned->SetName(name);
cloned->Reset();
return cloned;
};
TH1F* RefClone(TDirectory* from, const char* name) {
TH1F * orig = (TH1F*)from->Get(name);
if (!orig) {
cerr << "Missing " << name << " from " << from->GetName() << endl;
return 0;
}
return RefClone(orig);
}
void MakeHisto(TTree *tree, TDirectory* To) {
cout << "Generating histograms from TTree::Draw" << endl;
TDirectory* where = GenerateDrawHist(tree);
To->cd();
Event *event = new Event();
tree->SetBranchAddress("event",&event);
//We make clones of the generated histograms
//We set new names and reset the clones.
//We want to have identical histogram limits
TH1F *refNtrack = RefClone(where,"hNtrack");
TH1F *refGetNtrack = RefClone(where,"hGetNtrack");
TH1F *refNseg = RefClone(where,"hNseg");
TH1F *refTemp = RefClone(where,"hTemp");
TH1F *refHmean = RefClone(where,"hHmean");
TH1F *refHAxisMax = RefClone(where,"hHAxisMax");
TH1F *refHAxisGetMax = RefClone(where,"hHAxisGetMax");
TH1F *refHGetAxisGetMax = RefClone(where,"hHGetAxisGetMax");
TH1F *refHGetAxisMax = RefClone(where,"hHGetAxisMax");
TH1F *refGetHGetAxisMax = RefClone(where,"hGetHGetAxisMax");
TH1F *refGetRefHGetAxisMax = RefClone(where,"hGetRefHGetAxisMax");
TH1F *refPx = RefClone(where,"hPx");
TH1F *refPy = RefClone(where,"hPy");
TH1F *refPz = RefClone(where,"hPz");
TH1F *refRandom = RefClone(where,"hRandom");
TH1F *refMass2 = RefClone(where,"hMass2");
TH1F *refBx = RefClone(where,"hBx");
TH1F *refBy = RefClone(where,"hBy");
TH1F *refXfirst = RefClone(where,"hXfirst");
TH1F *refYfirst = RefClone(where,"hYfirst");
TH1F *refZfirst = RefClone(where,"hZfirst");
TH1F *refXlast = RefClone(where,"hXlast");
TH1F *refYlast = RefClone(where,"hYlast");
TH1F *refZlast = RefClone(where,"hZlast");
TH1F *refCharge = RefClone(where,"hCharge");
TH1F *refNpoint = RefClone(where,"hNpoint");
TH1F *refValid = RefClone(where,"hValid");
TH1F *refPointValue = RefClone(where,"hPointValue");
TH1F *refAlias = RefClone(where,"hAlias");
TH1F *refFullMatrix = RefClone(where,"hFullMatrix");
TH1F *refColMatrix = RefClone(where,"hColMatrix");
TH1F *refRowMatrix = RefClone(where,"hRowMatrix");
TH1F *refCellMatrix = RefClone(where,"hCellMatrix");
TH1F *refFullOper = RefClone(where,"hFullOper");
TH1F *refCellOper = RefClone(where,"hCellOper");
TH1F *refColOper = RefClone(where,"hColOper");
TH1F *refRowOper = RefClone(where,"hRowOper");
TH1F *refMatchRowOper = RefClone(where,"hMatchRowOper");
TH1F *refMatchColOper = RefClone(where,"hMatchColOper");
TH1F *refRowMatOper = RefClone(where,"hRowMatOper");
TH1F *refMatchDiffOper= RefClone(where,"hMatchDiffOper");
TH1F *refFullOper2 = RefClone(where,"hFullOper2");
TH1F *refClosestDistance = RefClone(where,"hClosestDistance");
TH1F *refClosestDistance2 = RefClone(where,"hClosestDistance2");
TH1F *refClosestDistance9 = RefClone(where,"hClosestDistance9");
TH1F *refClosestDistanceIndex = RefClone(where, "hClosestDistanceIndex");
TH2F *refPxInd = (TH2F*)RefClone(where,"hPxInd");
TH1F *refSqrtNtrack = RefClone(where,"hSqrtNtrack");
TH1F *refShiftValid = RefClone(where,"hShiftValid");
TH1F *refAndValid = RefClone(where,"hAndValid");
TH1F *refString = RefClone(where,"hString");
TH1F *refAliasStr = RefClone(where,"hAliasStr");
TH1F *refPxBx = RefClone(where,"hPxBx");
TH1F *refPxBxWeight = RefClone(where,"hPxBxWeight");
TH1F *refTriggerBits = RefClone(where,"hTriggerBits");
TH1F *refTriggerBitsFunc = RefClone(where,"hTriggerBitsFunc");
TH1F *refFiltTriggerBits = RefClone(where,"hFiltTriggerBits");
TH1F *refTrackTrigger = RefClone(where,"hTrackTrigger");
TH1F *refFiltTrackTrigger = RefClone(where,"hFiltTrackTrigger");
TH1F *refBreit = RefClone(where,"hBreit");
// Loop with user code on all events and fill the ref histograms
// The code below should produce identical results to the tree->Draw above
cout << "Recalculating the histograms with custom loop." << endl;
TClonesArray *tracks = event->GetTracks();
Int_t nev = (Int_t)tree->GetEntries();
Int_t i, ntracks, evmod,i0,i1, Nvertex;
Track *t;
EventHeader *head;
Int_t nbin = 0;
for (Int_t ev=0;ev<nev;ev++) {
nbin += tree->GetEntry(ev);
head = event->GetHeader();
evmod = head->GetEvtNum()%10;
refNtrack->Fill(event->GetNtrack());
refGetNtrack->Fill(event->GetNtrack());
refNseg->Fill(event->GetNseg());
refTemp->Fill(event->GetTemperature());
refHmean->Fill(event->GetHistogram()->GetMean());
refHAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refHAxisGetMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refHGetAxisGetMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refHGetAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refGetHGetAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refGetRefHGetAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refSqrtNtrack->Fill(sqrt(event->GetNtrack()));
if (!strcmp("type1",event->GetType()))
refString->Fill(event->GetHeader()->GetEvtNum());
if (strstr(event->GetType(),"1")) {
refString->Fill(event->GetHeader()->GetEvtNum());
}
refAliasStr->Fill(strstr(event->GetType(),"1")!=0);
Nvertex = event->GetNvertex();
for(i0=0;i0<Nvertex;i0++) {
refClosestDistance->Fill(event->GetClosestDistance(i0));
}
if (Nvertex>2) refClosestDistance2->Fill(event->GetClosestDistance(2));
if (Nvertex>9) refClosestDistance9->Fill(event->GetClosestDistance(9));
refClosestDistanceIndex->Fill(event->GetClosestDistance(Nvertex/2));
for(i0=0;i0<4;i0++) {
for(i1=0;i1<4;i1++) {
refFullMatrix->Fill(event->GetMatrix(i0,i1));
}
refColMatrix->Fill(event->GetMatrix(i0,0));
refRowMatrix->Fill(event->GetMatrix(1,i0)); // done here because the matrix is square!
}
refCellMatrix->Fill(event->GetMatrix(2,2));
TBits bits = event->GetTriggerBits();
Int_t nbits = bits.GetNbits();
Int_t ncx = refTriggerBits->GetXaxis()->GetNbins();
Int_t nextbit = -1;
while(1) {
nextbit = bits->FirstSetBit(nextbit+1);
if (nextbit >= nbits) break;
if (nextbit > ncx) refTriggerBits->Fill(ncx+1);
else refTriggerBits->Fill(nextbit);
if (nextbit > ncx) refTriggerBitsFunc->Fill(ncx+1);
else refTriggerBitsFunc->Fill(nextbit);
}
if (bits.TestBitNumber(10)) refFiltTriggerBits->Fill(nbits);
ntracks = event->GetNtrack();
if ( 5 < ntracks ) {
t = (Track*)tracks->UncheckedAt(5);
for(i0=0;i0<4;i0++) {
for(i1=0;i1<4;i1++) {
}
refColOper->Fill( event->GetMatrix(i0,1) - t->GetVertex(1) );
refRowOper->Fill( event->GetMatrix(2,i0) - t->GetVertex(2) );
}
for(i0=0;i0<3;i0++) {
refMatchRowOper->Fill( event->GetMatrix(2,i0) - t->GetVertex(i0) );
refMatchDiffOper->Fill( event->GetMatrix(i0,2) - t->GetVertex(i0) );
}
refCellOper->Fill( event->GetMatrix(2,1) - t->GetVertex(1) );
}
for (i=0;i<ntracks;i++) {
t = (Track*)tracks->UncheckedAt(i);
if (evmod == 0) refPx->Fill(t->GetPx());
if (evmod == 0) refPy->Fill(t->GetPy());
if (evmod == 0) refPz->Fill(t->GetPz());
if (evmod == 1) refRandom->Fill(t->GetRandom(),3);
if (evmod == 1) refMass2->Fill(t->GetMass2());
if (evmod == 1) refBx->Fill(t->GetBx());
if (evmod == 1) refBy->Fill(t->GetBy());
if (evmod == 2) refXfirst->Fill(t->GetXfirst());
if (evmod == 2) refYfirst->Fill(t->GetYfirst());
if (evmod == 2) refZfirst->Fill(t->GetZfirst());
if (evmod == 3) refXlast->Fill(t->GetXlast());
if (evmod == 3) refYlast->Fill(t->GetYlast());
if (evmod == 3) refZlast->Fill(t->GetZlast());
if (t->GetPx() < 0) {
refCharge->Fill(t->GetCharge());
refNpoint->Fill(t->GetNpoint());
refValid->Fill(t->GetValid());
}
Int_t valid = t->GetValid();
refShiftValid->Fill(valid << 4);
refShiftValid->Fill( (valid << 4) >> 2 );
if (event->GetNvertex()>10 && event->GetNseg()<=6000) {
refAndValid->Fill( t->GetValid() & 0x1 );
}
Track * t2 = (Track*)tracks->At(t->GetNpoint()/6);
if (t2 && t2->GetPy()>0) {
refPxInd->Fill(t2->GetPy(),t->GetPx());
}
float Bx,By;
Bx = t->GetBx();
By = t->GetBy();
if ((Bx>.15) || (By<=-.15)) refPxBx->Fill(t->GetPx());
double weight = Bx*Bx*(Bx>.15) + By*By*(By<=-.15);
if (weight) refPxBxWeight->Fill(t->GetPx(),weight);
if (i<4) {
for(i1=0;i1<3;i1++) { // 3 is the min of the 2nd dim of Matrix and Vertex
refFullOper ->Fill( event->GetMatrix(i,i1) - t->GetVertex(i1) );
refFullOper2->Fill( event->GetMatrix(i,i1) - t->GetVertex(i1) );
refRowMatOper->Fill( event->GetMatrix(i,2) - t->GetVertex(i1) );
}
refMatchColOper->Fill( event->GetMatrix(i,2) - t->GetVertex(1) );
}
for(i1=0; i1<t->GetN(); i1++) {
refPointValue->Fill( t->GetPointValue(i1) );
}
TBits bits = t->GetTriggerBits();
Int_t nbits = bits.GetNbits();
Int_t ncx = refTrackTrigger->GetXaxis()->GetNbins();
Int_t nextbit = -1;
while(1) {
nextbit = bits->FirstSetBit(nextbit+1);
if (nextbit >= nbits) break;
if (nextbit > ncx) refTrackTrigger->Fill(ncx+1);
else refTrackTrigger->Fill(nextbit);
}
if (bits.TestBitNumber(5)) refFiltTrackTrigger->Fill(t->GetPx());
refBreit->Fill(TMath::BreitWigner(t->GetPx(),3,2));
refAlias->Fill(head->GetEvtNum()*6+t->GetPx()*t->GetPy());
}
}
delete event;
Event::Reset();
}
void dt_MakeRef(const char* from, Int_t verboseLevel = 2) {
SetVerboseLevel(verboseLevel);
if (!TClassTable::GetDict("Event")) {
gSystem->Load("libEvent");
gHasLibrary = kTRUE;
}
gROOT->GetList()->Delete();
TFile *hfile = new TFile(from);
TTree *tree = (TTree*)hfile->Get("T");
TFile* f= new TFile("dt_reference.root","recreate");
MakeHisto(tree,f);
f->Write();
delete f;
delete hfile;
gROOT->cd();
cout << "Checking histograms" << endl;
Compare(gDirectory);
// gROOT->GetList()->Delete();
}
<commit_msg>Fix a CINT warning: Warning: wrong member access operator '->' FILE:dt_MakeRef.C LINE:172 Warning: wrong member access operator '->' FILE:dt_MakeRef.C LINE:250<commit_after>#include "dt_RunDrawTest.C"
#include "TClassTable.h"
#include "TDirectory.h"
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TSystem.h"
#ifndef __CINT__
#include "Event.h"
#endif
TH1F* RefClone(TH1F* orig) {
TH1F *cloned = (TH1F*)orig->Clone();
TString name = orig->GetName();
name.Prepend("ref");
cloned->SetName(name);
cloned->Reset();
return cloned;
};
TH1F* RefClone(TDirectory* from, const char* name) {
TH1F * orig = (TH1F*)from->Get(name);
if (!orig) {
cerr << "Missing " << name << " from " << from->GetName() << endl;
return 0;
}
return RefClone(orig);
}
void MakeHisto(TTree *tree, TDirectory* To) {
cout << "Generating histograms from TTree::Draw" << endl;
TDirectory* where = GenerateDrawHist(tree);
To->cd();
Event *event = new Event();
tree->SetBranchAddress("event",&event);
//We make clones of the generated histograms
//We set new names and reset the clones.
//We want to have identical histogram limits
TH1F *refNtrack = RefClone(where,"hNtrack");
TH1F *refGetNtrack = RefClone(where,"hGetNtrack");
TH1F *refNseg = RefClone(where,"hNseg");
TH1F *refTemp = RefClone(where,"hTemp");
TH1F *refHmean = RefClone(where,"hHmean");
TH1F *refHAxisMax = RefClone(where,"hHAxisMax");
TH1F *refHAxisGetMax = RefClone(where,"hHAxisGetMax");
TH1F *refHGetAxisGetMax = RefClone(where,"hHGetAxisGetMax");
TH1F *refHGetAxisMax = RefClone(where,"hHGetAxisMax");
TH1F *refGetHGetAxisMax = RefClone(where,"hGetHGetAxisMax");
TH1F *refGetRefHGetAxisMax = RefClone(where,"hGetRefHGetAxisMax");
TH1F *refPx = RefClone(where,"hPx");
TH1F *refPy = RefClone(where,"hPy");
TH1F *refPz = RefClone(where,"hPz");
TH1F *refRandom = RefClone(where,"hRandom");
TH1F *refMass2 = RefClone(where,"hMass2");
TH1F *refBx = RefClone(where,"hBx");
TH1F *refBy = RefClone(where,"hBy");
TH1F *refXfirst = RefClone(where,"hXfirst");
TH1F *refYfirst = RefClone(where,"hYfirst");
TH1F *refZfirst = RefClone(where,"hZfirst");
TH1F *refXlast = RefClone(where,"hXlast");
TH1F *refYlast = RefClone(where,"hYlast");
TH1F *refZlast = RefClone(where,"hZlast");
TH1F *refCharge = RefClone(where,"hCharge");
TH1F *refNpoint = RefClone(where,"hNpoint");
TH1F *refValid = RefClone(where,"hValid");
TH1F *refPointValue = RefClone(where,"hPointValue");
TH1F *refAlias = RefClone(where,"hAlias");
TH1F *refFullMatrix = RefClone(where,"hFullMatrix");
TH1F *refColMatrix = RefClone(where,"hColMatrix");
TH1F *refRowMatrix = RefClone(where,"hRowMatrix");
TH1F *refCellMatrix = RefClone(where,"hCellMatrix");
TH1F *refFullOper = RefClone(where,"hFullOper");
TH1F *refCellOper = RefClone(where,"hCellOper");
TH1F *refColOper = RefClone(where,"hColOper");
TH1F *refRowOper = RefClone(where,"hRowOper");
TH1F *refMatchRowOper = RefClone(where,"hMatchRowOper");
TH1F *refMatchColOper = RefClone(where,"hMatchColOper");
TH1F *refRowMatOper = RefClone(where,"hRowMatOper");
TH1F *refMatchDiffOper= RefClone(where,"hMatchDiffOper");
TH1F *refFullOper2 = RefClone(where,"hFullOper2");
TH1F *refClosestDistance = RefClone(where,"hClosestDistance");
TH1F *refClosestDistance2 = RefClone(where,"hClosestDistance2");
TH1F *refClosestDistance9 = RefClone(where,"hClosestDistance9");
TH1F *refClosestDistanceIndex = RefClone(where, "hClosestDistanceIndex");
TH2F *refPxInd = (TH2F*)RefClone(where,"hPxInd");
TH1F *refSqrtNtrack = RefClone(where,"hSqrtNtrack");
TH1F *refShiftValid = RefClone(where,"hShiftValid");
TH1F *refAndValid = RefClone(where,"hAndValid");
TH1F *refString = RefClone(where,"hString");
TH1F *refAliasStr = RefClone(where,"hAliasStr");
TH1F *refPxBx = RefClone(where,"hPxBx");
TH1F *refPxBxWeight = RefClone(where,"hPxBxWeight");
TH1F *refTriggerBits = RefClone(where,"hTriggerBits");
TH1F *refTriggerBitsFunc = RefClone(where,"hTriggerBitsFunc");
TH1F *refFiltTriggerBits = RefClone(where,"hFiltTriggerBits");
TH1F *refTrackTrigger = RefClone(where,"hTrackTrigger");
TH1F *refFiltTrackTrigger = RefClone(where,"hFiltTrackTrigger");
TH1F *refBreit = RefClone(where,"hBreit");
// Loop with user code on all events and fill the ref histograms
// The code below should produce identical results to the tree->Draw above
cout << "Recalculating the histograms with custom loop." << endl;
TClonesArray *tracks = event->GetTracks();
Int_t nev = (Int_t)tree->GetEntries();
Int_t i, ntracks, evmod,i0,i1, Nvertex;
Track *t;
EventHeader *head;
Int_t nbin = 0;
for (Int_t ev=0;ev<nev;ev++) {
nbin += tree->GetEntry(ev);
head = event->GetHeader();
evmod = head->GetEvtNum()%10;
refNtrack->Fill(event->GetNtrack());
refGetNtrack->Fill(event->GetNtrack());
refNseg->Fill(event->GetNseg());
refTemp->Fill(event->GetTemperature());
refHmean->Fill(event->GetHistogram()->GetMean());
refHAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refHAxisGetMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refHGetAxisGetMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refHGetAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refGetHGetAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refGetRefHGetAxisMax->Fill(event->GetHistogram()->GetXaxis()->GetXmax());
refSqrtNtrack->Fill(sqrt(event->GetNtrack()));
if (!strcmp("type1",event->GetType()))
refString->Fill(event->GetHeader()->GetEvtNum());
if (strstr(event->GetType(),"1")) {
refString->Fill(event->GetHeader()->GetEvtNum());
}
refAliasStr->Fill(strstr(event->GetType(),"1")!=0);
Nvertex = event->GetNvertex();
for(i0=0;i0<Nvertex;i0++) {
refClosestDistance->Fill(event->GetClosestDistance(i0));
}
if (Nvertex>2) refClosestDistance2->Fill(event->GetClosestDistance(2));
if (Nvertex>9) refClosestDistance9->Fill(event->GetClosestDistance(9));
refClosestDistanceIndex->Fill(event->GetClosestDistance(Nvertex/2));
for(i0=0;i0<4;i0++) {
for(i1=0;i1<4;i1++) {
refFullMatrix->Fill(event->GetMatrix(i0,i1));
}
refColMatrix->Fill(event->GetMatrix(i0,0));
refRowMatrix->Fill(event->GetMatrix(1,i0)); // done here because the matrix is square!
}
refCellMatrix->Fill(event->GetMatrix(2,2));
TBits bits = event->GetTriggerBits();
Int_t nbits = bits.GetNbits();
Int_t ncx = refTriggerBits->GetXaxis()->GetNbins();
Int_t nextbit = -1;
while(1) {
nextbit = bits.FirstSetBit(nextbit+1);
if (nextbit >= nbits) break;
if (nextbit > ncx) refTriggerBits->Fill(ncx+1);
else refTriggerBits->Fill(nextbit);
if (nextbit > ncx) refTriggerBitsFunc->Fill(ncx+1);
else refTriggerBitsFunc->Fill(nextbit);
}
if (bits.TestBitNumber(10)) refFiltTriggerBits->Fill(nbits);
ntracks = event->GetNtrack();
if ( 5 < ntracks ) {
t = (Track*)tracks->UncheckedAt(5);
for(i0=0;i0<4;i0++) {
for(i1=0;i1<4;i1++) {
}
refColOper->Fill( event->GetMatrix(i0,1) - t->GetVertex(1) );
refRowOper->Fill( event->GetMatrix(2,i0) - t->GetVertex(2) );
}
for(i0=0;i0<3;i0++) {
refMatchRowOper->Fill( event->GetMatrix(2,i0) - t->GetVertex(i0) );
refMatchDiffOper->Fill( event->GetMatrix(i0,2) - t->GetVertex(i0) );
}
refCellOper->Fill( event->GetMatrix(2,1) - t->GetVertex(1) );
}
for (i=0;i<ntracks;i++) {
t = (Track*)tracks->UncheckedAt(i);
if (evmod == 0) refPx->Fill(t->GetPx());
if (evmod == 0) refPy->Fill(t->GetPy());
if (evmod == 0) refPz->Fill(t->GetPz());
if (evmod == 1) refRandom->Fill(t->GetRandom(),3);
if (evmod == 1) refMass2->Fill(t->GetMass2());
if (evmod == 1) refBx->Fill(t->GetBx());
if (evmod == 1) refBy->Fill(t->GetBy());
if (evmod == 2) refXfirst->Fill(t->GetXfirst());
if (evmod == 2) refYfirst->Fill(t->GetYfirst());
if (evmod == 2) refZfirst->Fill(t->GetZfirst());
if (evmod == 3) refXlast->Fill(t->GetXlast());
if (evmod == 3) refYlast->Fill(t->GetYlast());
if (evmod == 3) refZlast->Fill(t->GetZlast());
if (t->GetPx() < 0) {
refCharge->Fill(t->GetCharge());
refNpoint->Fill(t->GetNpoint());
refValid->Fill(t->GetValid());
}
Int_t valid = t->GetValid();
refShiftValid->Fill(valid << 4);
refShiftValid->Fill( (valid << 4) >> 2 );
if (event->GetNvertex()>10 && event->GetNseg()<=6000) {
refAndValid->Fill( t->GetValid() & 0x1 );
}
Track * t2 = (Track*)tracks->At(t->GetNpoint()/6);
if (t2 && t2->GetPy()>0) {
refPxInd->Fill(t2->GetPy(),t->GetPx());
}
float Bx,By;
Bx = t->GetBx();
By = t->GetBy();
if ((Bx>.15) || (By<=-.15)) refPxBx->Fill(t->GetPx());
double weight = Bx*Bx*(Bx>.15) + By*By*(By<=-.15);
if (weight) refPxBxWeight->Fill(t->GetPx(),weight);
if (i<4) {
for(i1=0;i1<3;i1++) { // 3 is the min of the 2nd dim of Matrix and Vertex
refFullOper ->Fill( event->GetMatrix(i,i1) - t->GetVertex(i1) );
refFullOper2->Fill( event->GetMatrix(i,i1) - t->GetVertex(i1) );
refRowMatOper->Fill( event->GetMatrix(i,2) - t->GetVertex(i1) );
}
refMatchColOper->Fill( event->GetMatrix(i,2) - t->GetVertex(1) );
}
for(i1=0; i1<t->GetN(); i1++) {
refPointValue->Fill( t->GetPointValue(i1) );
}
TBits bits = t->GetTriggerBits();
Int_t nbits = bits.GetNbits();
Int_t ncx = refTrackTrigger->GetXaxis()->GetNbins();
Int_t nextbit = -1;
while(1) {
nextbit = bits.FirstSetBit(nextbit+1);
if (nextbit >= nbits) break;
if (nextbit > ncx) refTrackTrigger->Fill(ncx+1);
else refTrackTrigger->Fill(nextbit);
}
if (bits.TestBitNumber(5)) refFiltTrackTrigger->Fill(t->GetPx());
refBreit->Fill(TMath::BreitWigner(t->GetPx(),3,2));
refAlias->Fill(head->GetEvtNum()*6+t->GetPx()*t->GetPy());
}
}
delete event;
Event::Reset();
}
void dt_MakeRef(const char* from, Int_t verboseLevel = 2) {
SetVerboseLevel(verboseLevel);
if (!TClassTable::GetDict("Event")) {
gSystem->Load("libEvent");
gHasLibrary = kTRUE;
}
gROOT->GetList()->Delete();
TFile *hfile = new TFile(from);
TTree *tree = (TTree*)hfile->Get("T");
TFile* f= new TFile("dt_reference.root","recreate");
MakeHisto(tree,f);
f->Write();
delete f;
delete hfile;
gROOT->cd();
cout << "Checking histograms" << endl;
Compare(gDirectory);
// gROOT->GetList()->Delete();
}
<|endoftext|> |
<commit_before>/*
* geo_test.cpp
*
* Created on: 201487
* Author: wangqiying
*/
#include "ardb.hpp"
using namespace ardb;
void test_geo_common(Context& ctx, Ardb& db)
{
db.GetConfig().zset_max_ziplist_entries = 16;
RedisCommandFrame del;
del.SetFullCommand("del mygeo");
db.Call(ctx, del, 0);
double x = 300.3;
double y = 300.3;
double p_x = 1000.0;
double p_y = 1000.0;
uint32 raius = 1000;
uint32 total = 100000;
GeoPointArray cmp;
for (uint32 i = 0; i < total; i++)
{
char name[100];
sprintf(name, "p%u", i);
double xx = x + i * 0.1;
double yy = y + i * 0.1;
if (((xx - p_x) * (xx - p_x) + (yy - p_y) * (yy - p_y)) < raius * raius)
{
GeoPoint p;
p.x = xx;
p.y = yy;
cmp.push_back(p);
}
RedisCommandFrame geoadd;
geoadd.SetFullCommand("geoadd mygeo MERCATOR %.2f %.2f %s", xx, yy, name);
db.Call(ctx, geoadd, 0);
}
RedisCommandFrame zcard;
zcard.SetFullCommand("zcard mygeo");
db.Call(ctx, zcard, 0);
CHECK_FATAL(ctx.reply.integer != total, "geoadd failed");
RedisCommandFrame geosearch;
geosearch.SetFullCommand("geosearch mygeo MERCATOR %.2f %.2f radius %d ASC WITHCOORDINATES WITHDISTANCES", p_x, p_y,
raius);
db.Call(ctx, geosearch, 0);
CHECK_FATAL(ctx.reply.MemberSize() != cmp.size() * 4, "geosearch failed");
}
void test_geo(Ardb& db)
{
Context tmpctx;
test_geo_common(tmpctx, db);
}
<commit_msg>fix ut for geosearch<commit_after>/*
* geo_test.cpp
*
* Created on: 201487
* Author: wangqiying
*/
#include "ardb.hpp"
using namespace ardb;
void test_geo_common(Context& ctx, Ardb& db)
{
db.GetConfig().zset_max_ziplist_entries = 16;
RedisCommandFrame del;
del.SetFullCommand("del mygeo");
db.Call(ctx, del, 0);
double x = 300.3;
double y = 300.3;
double p_x = 1000.0;
double p_y = 1000.0;
uint32 raius = 1000;
uint32 total = 100000;
GeoPointArray cmp;
for (uint32 i = 0; i < total; i++)
{
char name[100];
sprintf(name, "p%u", i);
/*
* min accuracy is 0.2meters
*/
double xx = x + i * 0.3;
double yy = y + i * 0.3;
if (((xx - p_x) * (xx - p_x) + (yy - p_y) * (yy - p_y)) <= raius * raius)
{
GeoPoint p;
p.x = xx;
p.y = yy;
cmp.push_back(p);
}
RedisCommandFrame geoadd;
geoadd.SetFullCommand("geoadd mygeo MERCATOR %.2f %.2f %s", xx, yy, name);
db.Call(ctx, geoadd, 0);
}
RedisCommandFrame zcard;
zcard.SetFullCommand("zcard mygeo");
db.Call(ctx, zcard, 0);
CHECK_FATAL(ctx.reply.integer != total, "geoadd failed");
RedisCommandFrame geosearch;
geosearch.SetFullCommand("geosearch mygeo MERCATOR %.2f %.2f radius %d ASC WITHCOORDINATES WITHDISTANCES", p_x, p_y,
raius);
db.Call(ctx, geosearch, 0);
CHECK_FATAL(ctx.reply.MemberSize() != cmp.size() * 4, "geosearch failed");
}
void test_geo(Ardb& db)
{
Context tmpctx;
test_geo_common(tmpctx, db);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPNMReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkPNMReader.h"
#include <stdio.h>
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkPNMReader* vtkPNMReader::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPNMReader");
if(ret)
{
return (vtkPNMReader*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkPNMReader;
}
char vtkPNMReaderGetChar(FILE *fp)
{
char c;
int result;
if ((result = getc(fp)) == EOF )
{
return '\0';
}
c = (char)result;
if (c == '#')
{
do
{
if ((result = getc(fp)) == EOF )
{
return '\0';
}
c = (char)result;
}
while (c != '\n');
}
return c;
}
int vtkPNMReaderGetInt(FILE *fp)
{
char c;
int result = 0;
do
{
c = vtkPNMReaderGetChar(fp);
}
while ((c < '1')||(c > '9'));
do
{
result = result * 10 + (c - '0');
c = vtkPNMReaderGetChar(fp);
}
while ((c >= '0')&&(c <= '9'));
// put the CR/LF or whitespace back.....
ungetc(c, fp);
return result;
}
void vtkPNMReader::ExecuteInformation()
{
int xsize, ysize, comp;
char magic[80];
char c;
FILE *fp;
// if the user has not set the extent, but has set the VOI
// set the zaxis extent to the VOI z axis
if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
(this->DataVOI[4] || this->DataVOI[5]))
{
this->DataExtent[4] = this->DataVOI[4];
this->DataExtent[5] = this->DataVOI[5];
}
// Allocate the space for the filename
this->ComputeInternalFileName(this->DataExtent[4]);
// get the magic number by reading in a file
fp = fopen(this->InternalFileName,"rb");
if (!fp)
{
vtkErrorMacro("Unable to open file " << this->InternalFileName);
return;
}
do
{
c = vtkPNMReaderGetChar(fp);
}
while (c != 'P');
magic[0] = c;
magic[1] = vtkPNMReaderGetChar(fp);
magic[2] = '\0';
// now get the dimensions
xsize = vtkPNMReaderGetInt(fp);
ysize = vtkPNMReaderGetInt(fp);
// read max pixel value into comp for now
comp = vtkPNMReaderGetInt(fp);
// if file is ascii, any amount of whitespace may follow.
// if file is binary, a single whitespace character will follow.
// We only support binary ppm and pgm files right now. So the next
// character IS always ignored.
c = getc(fp);
// if this file was "written" on the PC, then a CR will have been
// written as a CR/LF combination. So, if this single whitespace
// character is a CR and it is followed by a LF, then swallow the
// linefeed character as well. (Not part of the PPM standard, but a
// a hard fact of life.
if ( c == 0x0d )
{
c = getc(fp);
if ( c != 0x0a )
{
ungetc( c, fp );
}
}
// Set the header size now that we have parsed it
this->SetHeaderSize(ftell(fp));
fclose(fp);
// compare magic number to determine file type
if ( ! strcmp(magic,"P5") )
{
comp = 1;
}
else if ( ! strcmp(magic,"P6") )
{
comp = 3;
}
else
{
vtkErrorMacro(<<"Unknown file type! Not a binary PGM or PPM");
return;
}
// if the user has set the VOI, just make sure its valid
if (this->DataVOI[0] || this->DataVOI[1] ||
this->DataVOI[2] || this->DataVOI[3] ||
this->DataVOI[4] || this->DataVOI[5])
{
if ((this->DataVOI[0] < 0) ||
(this->DataVOI[1] >= xsize) ||
(this->DataVOI[2] < 0) ||
(this->DataVOI[3] >= ysize))
{
vtkWarningMacro("The requested VOI is larger than the file's (" << this->InternalFileName << ") extent ");
this->DataVOI[0] = 0;
this->DataVOI[1] = xsize - 1;
this->DataVOI[2] = 0;
this->DataVOI[3] = ysize - 1;
}
}
this->DataExtent[0] = 0;
this->DataExtent[1] = xsize - 1;
this->DataExtent[2] = 0;
this->DataExtent[3] = ysize - 1;
this->SetDataScalarTypeToUnsignedChar();
this->SetNumberOfScalarComponents(comp);
vtkImageReader::UpdateInformation();
}
<commit_msg>Fixed recursive call bug<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPNMReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkPNMReader.h"
#include <stdio.h>
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkPNMReader* vtkPNMReader::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPNMReader");
if(ret)
{
return (vtkPNMReader*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkPNMReader;
}
char vtkPNMReaderGetChar(FILE *fp)
{
char c;
int result;
if ((result = getc(fp)) == EOF )
{
return '\0';
}
c = (char)result;
if (c == '#')
{
do
{
if ((result = getc(fp)) == EOF )
{
return '\0';
}
c = (char)result;
}
while (c != '\n');
}
return c;
}
int vtkPNMReaderGetInt(FILE *fp)
{
char c;
int result = 0;
do
{
c = vtkPNMReaderGetChar(fp);
}
while ((c < '1')||(c > '9'));
do
{
result = result * 10 + (c - '0');
c = vtkPNMReaderGetChar(fp);
}
while ((c >= '0')&&(c <= '9'));
// put the CR/LF or whitespace back.....
ungetc(c, fp);
return result;
}
void vtkPNMReader::ExecuteInformation()
{
int xsize, ysize, comp;
char magic[80];
char c;
FILE *fp;
// if the user has not set the extent, but has set the VOI
// set the zaxis extent to the VOI z axis
if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
(this->DataVOI[4] || this->DataVOI[5]))
{
this->DataExtent[4] = this->DataVOI[4];
this->DataExtent[5] = this->DataVOI[5];
}
// Allocate the space for the filename
this->ComputeInternalFileName(this->DataExtent[4]);
// get the magic number by reading in a file
fp = fopen(this->InternalFileName,"rb");
if (!fp)
{
vtkErrorMacro("Unable to open file " << this->InternalFileName);
return;
}
do
{
c = vtkPNMReaderGetChar(fp);
}
while (c != 'P');
magic[0] = c;
magic[1] = vtkPNMReaderGetChar(fp);
magic[2] = '\0';
// now get the dimensions
xsize = vtkPNMReaderGetInt(fp);
ysize = vtkPNMReaderGetInt(fp);
// read max pixel value into comp for now
comp = vtkPNMReaderGetInt(fp);
// if file is ascii, any amount of whitespace may follow.
// if file is binary, a single whitespace character will follow.
// We only support binary ppm and pgm files right now. So the next
// character IS always ignored.
c = getc(fp);
// if this file was "written" on the PC, then a CR will have been
// written as a CR/LF combination. So, if this single whitespace
// character is a CR and it is followed by a LF, then swallow the
// linefeed character as well. (Not part of the PPM standard, but a
// a hard fact of life.
if ( c == 0x0d )
{
c = getc(fp);
if ( c != 0x0a )
{
ungetc( c, fp );
}
}
// Set the header size now that we have parsed it
this->SetHeaderSize(ftell(fp));
fclose(fp);
// compare magic number to determine file type
if ( ! strcmp(magic,"P5") )
{
comp = 1;
}
else if ( ! strcmp(magic,"P6") )
{
comp = 3;
}
else
{
vtkErrorMacro(<<"Unknown file type! Not a binary PGM or PPM");
return;
}
// if the user has set the VOI, just make sure its valid
if (this->DataVOI[0] || this->DataVOI[1] ||
this->DataVOI[2] || this->DataVOI[3] ||
this->DataVOI[4] || this->DataVOI[5])
{
if ((this->DataVOI[0] < 0) ||
(this->DataVOI[1] >= xsize) ||
(this->DataVOI[2] < 0) ||
(this->DataVOI[3] >= ysize))
{
vtkWarningMacro("The requested VOI is larger than the file's (" << this->InternalFileName << ") extent ");
this->DataVOI[0] = 0;
this->DataVOI[1] = xsize - 1;
this->DataVOI[2] = 0;
this->DataVOI[3] = ysize - 1;
}
}
this->DataExtent[0] = 0;
this->DataExtent[1] = xsize - 1;
this->DataExtent[2] = 0;
this->DataExtent[3] = ysize - 1;
this->SetDataScalarTypeToUnsignedChar();
this->SetNumberOfScalarComponents(comp);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk, P.Marijon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef _TOOL_FindDeletion_HPP_
#define _TOOL_FindDeletion_HPP_
/*****************************************************************************/
#include <IFindObserver.hpp>
#include <FindBreakpoints.hpp>
template<size_t span>
class FindDeletion : public IFindObserver<span>
{
public :
typedef typename gatb::core::kmer::impl::Kmer<span> Kmer;
typedef typename Kmer::ModelCanonical KmerModel;
typedef typename KmerModel::Iterator KmerIterator;
public :
/** \copydoc IFindObserver<span>
*/
FindDeletion(FindBreakpoints<span> * find);
/** \copydoc IFindObserver::IFindObserver
*/
bool update();
};
template<size_t span>
FindDeletion<span>::FindDeletion(FindBreakpoints<span> * find) : IFindObserver<span>(find){}
template<size_t span>
bool FindDeletion<span>::update()
{
if((this->_find->kmer_begin().isValid() && this->_find->kmer_end().isValid()) == false)
{
return false;
}
// Test if deletion is a fuzzy deletion
std::string begin = this->_find->model().toString(this->_find->kmer_begin().forward());
std::string end = this->_find->model().toString(this->_find->kmer_end().forward());
unsigned int repeat_size = 0;
for(repeat_size = 0; begin.substr(begin.length() - 1 - repeat_size, 1) == end.substr(repeat_size, 1); repeat_size++);
// Compute del_size
unsigned int del_size = this->_find->gap_stretch_size() - this->_find->kmer_size() + repeat_size;
if(repeat_size != 0)
{
unsigned char hist_begin_pos = this->_find->position() - del_size - 1 % 256;
begin = this->_find->model().toString(this->_find->het_kmer_history(hist_begin_pos).kmer);
}
// Check gap is a deletion
std::string seq = begin + end;
KmerModel local_m(this->_find->kmer_size());
KmerIterator local_it(local_m);
Data local_d(const_cast<char*>(seq.c_str()));
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
return false;
}
}
// Write the breakpoint
this->_find->writeBreakpoint(this->_find->breakpoint_id(), this->_find->chrom_name(), this->_find->position() - del_size - 2, begin, end, repeat_size, STR_DEL_TYPE);
this->_find->breakpoint_id_iterate();
if(repeat_size != 0)
this->_find->fuzzy_deletion_iterate();
else
this->_find->clean_deletion_iterate();
return true;
}
#endif /* _TOOL_FindDeletion_HPP_ */
<commit_msg>MTG: for fuzzy deletion didn't use history just reduce size of kmer begin<commit_after>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk, P.Marijon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef _TOOL_FindDeletion_HPP_
#define _TOOL_FindDeletion_HPP_
/*****************************************************************************/
#include <IFindObserver.hpp>
#include <FindBreakpoints.hpp>
template<size_t span>
class FindDeletion : public IFindObserver<span>
{
public :
typedef typename gatb::core::kmer::impl::Kmer<span> Kmer;
typedef typename Kmer::ModelCanonical KmerModel;
typedef typename KmerModel::Iterator KmerIterator;
public :
/** \copydoc IFindObserver<span>
*/
FindDeletion(FindBreakpoints<span> * find);
/** \copydoc IFindObserver::IFindObserver
*/
bool update();
};
template<size_t span>
FindDeletion<span>::FindDeletion(FindBreakpoints<span> * find) : IFindObserver<span>(find){}
template<size_t span>
bool FindDeletion<span>::update()
{
if((this->_find->kmer_begin().isValid() && this->_find->kmer_end().isValid()) == false)
{
return false;
}
// Test if deletion is a fuzzy deletion
std::string begin = this->_find->model().toString(this->_find->kmer_begin().forward());
std::string end = this->_find->model().toString(this->_find->kmer_end().forward());
unsigned int repeat_size = 0;
for(repeat_size = 0; begin.substr(begin.length() - 1 - repeat_size, 1) == end.substr(repeat_size, 1); repeat_size++);
// Compute del_size
unsigned int del_size = this->_find->gap_stretch_size() - this->_find->kmer_size() + repeat_size + 1;
if(repeat_size != 0)
{
begin = begin.substr(0, begin.length() - repeat_size)
}
// Check gap is a deletion
std::string seq = begin + end;
KmerModel local_m(this->_find->kmer_size());
KmerIterator local_it(local_m);
Data local_d(const_cast<char*>(seq.c_str()));
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
return false;
}
}
// Write the breakpoint
this->_find->writeBreakpoint(this->_find->breakpoint_id(), this->_find->chrom_name(), this->_find->position() - del_size - 1, begin, end, repeat_size, STR_DEL_TYPE);
this->_find->breakpoint_id_iterate();
if(repeat_size != 0)
this->_find->fuzzy_deletion_iterate();
else
this->_find->clean_deletion_iterate();
return true;
}
#endif /* _TOOL_FindDeletion_HPP_ */
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Selector for the "sum" reduction implementations.
*
* The functions are responsible for selecting the most efficient
* implementation for each case, based on what is available. The selection of
* parallel versus serial is also done at this level. The implementation
* functions should never be used directly, only functions of this header can
* be used directly.
*/
#pragma once
#include "etl/config.hpp"
#include "etl/traits_lite.hpp"
//Include the implementations
#include "etl/impl/std/sum.hpp"
#include "etl/impl/sse/sum.hpp"
namespace etl {
namespace detail {
enum class sum_imple {
STD,
SSE,
AVX
};
template <typename E>
cpp14_constexpr sum_imple select_sum_impl() {
//Note: since the constexpr values will be known at compile time, the
//conditions will be a lot simplified
//Only standard access elements through the expression itself
if(!has_direct_access<E>::value){
return sum_imple::STD;
}
if(decay_traits<E>::vectorizable){
constexpr const bool sse = vectorize_impl && vector_mode == vector_mode_t::SSE3;
constexpr const bool avx = vectorize_impl && vector_mode == vector_mode_t::AVX;
if (avx) {
return sum_imple::AVX;
} else if (sse) {
return sum_imple::SSE;
}
}
return sum_imple::STD;
}
template <typename E, typename Enable = void>
struct sum_impl {
static value_t<E> apply(const E& e) {
cpp14_constexpr auto impl = select_sum_impl<E>();
if (impl == sum_imple::AVX) {
return impl::standard::sum(e);
} else if (impl == sum_imple::SSE) {
return impl::sse::sum(e);
} else {
return impl::standard::sum(e);
}
}
};
} //end of namespace detail
} //end of namespace etl
<commit_msg>Add note<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Selector for the "sum" reduction implementations.
*
* The functions are responsible for selecting the most efficient
* implementation for each case, based on what is available. The selection of
* parallel versus serial is also done at this level. The implementation
* functions should never be used directly, only functions of this header can
* be used directly.
*
* Note: In a perfect world (full constexpr function and variable templates),
* the selection should be done with a template parameter in a variable
* template full sspecialization (alias for each real functions).
*/
#pragma once
#include "etl/config.hpp"
#include "etl/traits_lite.hpp"
//Include the implementations
#include "etl/impl/std/sum.hpp"
#include "etl/impl/sse/sum.hpp"
namespace etl {
namespace detail {
enum class sum_imple {
STD,
SSE,
AVX
};
template <typename E>
cpp14_constexpr sum_imple select_sum_impl() {
//Note: since the constexpr values will be known at compile time, the
//conditions will be a lot simplified
//Only standard access elements through the expression itself
if(!has_direct_access<E>::value){
return sum_imple::STD;
}
if(decay_traits<E>::vectorizable){
constexpr const bool sse = vectorize_impl && vector_mode == vector_mode_t::SSE3;
constexpr const bool avx = vectorize_impl && vector_mode == vector_mode_t::AVX;
if (avx) {
return sum_imple::AVX;
} else if (sse) {
return sum_imple::SSE;
}
}
return sum_imple::STD;
}
template <typename E, typename Enable = void>
struct sum_impl {
static value_t<E> apply(const E& e) {
cpp14_constexpr auto impl = select_sum_impl<E>();
if (impl == sum_imple::AVX) {
return impl::standard::sum(e);
} else if (impl == sum_imple::SSE) {
return impl::sse::sum(e);
} else {
return impl::standard::sum(e);
}
}
};
} //end of namespace detail
} //end of namespace etl
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file meta.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__UTIL__META_HPP
#define FL__UTIL__META_HPP
#include <Eigen/Dense>
#include <fl/util/traits.hpp>
namespace fl
{
/**
* \ingroup meta
*
* \tparam Sizes Variadic argument containing a list of sizes. Each size
* is a result of a constexpr or a const of a signed integral
* type. Unknown sizes are represented by -1 or Eigen::Dynamic.
*
*
* Joins the sizes within the \c Sizes argument list if all sizes are
* non-dynamic. That is, all sizes are greater -1 (\c Eigen::Dynamic). If one of
* the passed sizes is \c Eigen::Dynamic, the total size collapses to
* \c Eigen::Dynamic.
*/
template <int... Sizes> struct JoinSizes;
/**
* \internal
* \ingroup meta
* \copydoc JoinSizes
*
* \tparam Head Head of the \c Sizes list of the previous recursive call
*
* Variadic counting recursion
*/
template <int Head, int... Sizes> struct JoinSizes<Head, Sizes...>
{
enum : signed int
{
Size = IsFixed<Head>() && IsFixed<JoinSizes<Sizes...>::Size>()
? Head + JoinSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of JoinSizes<...>
*/
template <> struct JoinSizes<> { enum: signed int { Size = 0 }; } ;
/**
* \ingroup meta
*
* \brief Function form of JoinSizes for two sizes
*/
inline constexpr int join_sizes(int a, int b)
{
return (a > Eigen::Dynamic && b > Eigen::Dynamic) ? a + b : Eigen::Dynamic;
}
/**
* \ingroup meta
*
* Computes the product of LocalSize times Factor. If one of the parameters is
* set to Eigen::Dynamic, the factor size will collapse to Eigen::Dynbamic as
* well.
*/
template <int ... Sizes> struct ExpandSizes;
/**
* \internal
* \ingroup meta
*/
template <int Head, int... Sizes> struct ExpandSizes<Head, Sizes...>
{
enum: signed int
{
Size = IsFixed<Head>() && IsFixed<ExpandSizes<Sizes...>::Size>()
? Head * ExpandSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of ExpandSizes<...>
*/
template <> struct ExpandSizes<> { enum: signed int { Size = 1 }; } ;
/**
* \ingroup meta
*
* Provides access to the the first type element in the specified variadic list
*/
template <typename...T> struct FirstTypeIn;
/**
* \internal
* \ingroup meta
*
* Implementation of FirstTypeIn
*/
template <typename First, typename...T> struct FirstTypeIn<First, T...>
{
typedef First Type;
};
/**
* \ingroup meta
*
* Represents a sequence of indices IndexSequence<0, 1, 2, 3, ...>
*
* This is particularly useful to expand tuples
*
* \tparam Indices List of indices starting from 0
*/
template <int ... Indices> struct IndexSequence
{
enum { Size = sizeof...(Indices) };
};
/**
* \ingroup meta
*
* Creates an IndexSequence<0, 1, 2, ...> for a specified size.
*/
template <int Size, int ... Indices>
struct CreateIndexSequence
: CreateIndexSequence<Size - 1, Size - 1, Indices...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal specialization CreateIndexSequence
*/
template <int ... Indices>
struct CreateIndexSequence<0, Indices...>
: IndexSequence<Indices...>
{ };
/**
* \ingroup meta
*
* Meta type defined in terms of a sequence of types
*/
template <typename ... T>
struct TypeSequence
{
enum : signed int { Size = sizeof...(T) };
};
/**
* \internal
* \ingroup meta
*
* Empty TypeSequence
*/
template <> struct TypeSequence<>
{
enum : signed int { Size = Eigen::Dynamic };
};
/**
* \ingroup meta
*
* Creates a \c TypeSequence<T...> by expanding the specified \c Type \c Count
* times.
*/
template <int Count, typename Type, typename...T>
struct CreateTypeSequence
: CreateTypeSequence<Count - 1, Type, Type, T...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal type of CreateTypeSequence
*/
template <typename Type, typename...T>
struct CreateTypeSequence<1, Type, T...>
: TypeSequence<Type, T...>
{ };
/**
* \ingroup meta
*
* Creates an empty \c TypeSequence<> for a \c Count = Eigen::Dynamic
*/
template <typename Type>
struct CreateTypeSequence<Eigen::Dynamic, Type>
: TypeSequence<>
{ };
/**
* \ingroup meta
*
* Same as CreateTypeSequence, however with a reversed parameter order. This is
* an attempt to make the use of \c CreateTypeSequence more natural.
*/
template <typename Type, int Count>
struct MultipleOf
: CreateTypeSequence<Count, Type>
{ };
/**
* \internal
* \ingroup meta
*
* Creates an empty TypeSequence for dynamic count
*/
template <typename Type>
struct MultipleOf<Type, Eigen::Dynamic>
: CreateTypeSequence<Eigen::Dynamic, Type>
{ };
}
#endif
<commit_msg>Implemented some "meta operators" AdaptiveModel, Join and the collapse of Join.<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file meta.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__UTIL__META_HPP
#define FL__UTIL__META_HPP
#include <Eigen/Dense>
#include <fl/util/traits.hpp>
namespace fl
{
/**
* \ingroup meta
*
* \tparam Sizes Variadic argument containing a list of sizes. Each size
* is a result of a constexpr or a const of a signed integral
* type. Unknown sizes are represented by -1 or Eigen::Dynamic.
*
*
* Joins the sizes within the \c Sizes argument list if all sizes are
* non-dynamic. That is, all sizes are greater -1 (\c Eigen::Dynamic). If one of
* the passed sizes is \c Eigen::Dynamic, the total size collapses to
* \c Eigen::Dynamic.
*/
template <int... Sizes> struct JoinSizes;
/**
* \internal
* \ingroup meta
* \copydoc JoinSizes
*
* \tparam Head Head of the \c Sizes list of the previous recursive call
*
* Variadic counting recursion
*/
template <int Head, int... Sizes> struct JoinSizes<Head, Sizes...>
{
enum : signed int
{
Size = IsFixed<Head>() && IsFixed<JoinSizes<Sizes...>::Size>()
? Head + JoinSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of JoinSizes<...>
*/
template <> struct JoinSizes<> { enum: signed int { Size = 0 }; } ;
/**
* \ingroup meta
*
* \brief Function form of JoinSizes for two sizes
*/
inline constexpr int join_sizes(int a, int b)
{
return (a > Eigen::Dynamic && b > Eigen::Dynamic) ? a + b : Eigen::Dynamic;
}
/**
* \ingroup meta
*
* Computes the product of LocalSize times Factor. If one of the parameters is
* set to Eigen::Dynamic, the factor size will collapse to Eigen::Dynbamic as
* well.
*/
template <int ... Sizes> struct ExpandSizes;
/**
* \internal
* \ingroup meta
*/
template <int Head, int... Sizes> struct ExpandSizes<Head, Sizes...>
{
enum: signed int
{
Size = IsFixed<Head>() && IsFixed<ExpandSizes<Sizes...>::Size>()
? Head * ExpandSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of ExpandSizes<...>
*/
template <> struct ExpandSizes<> { enum: signed int { Size = 1 }; } ;
/**
* \ingroup meta
*
* Provides access to the the first type element in the specified variadic list
*/
template <typename...T> struct FirstTypeIn;
/**
* \internal
* \ingroup meta
*
* Implementation of FirstTypeIn
*/
template <typename First, typename...T> struct FirstTypeIn<First, T...>
{
typedef First Type;
};
/**
* \ingroup meta
*
* Represents a sequence of indices IndexSequence<0, 1, 2, 3, ...>
*
* This is particularly useful to expand tuples
*
* \tparam Indices List of indices starting from 0
*/
template <int ... Indices> struct IndexSequence
{
enum { Size = sizeof...(Indices) };
};
/**
* \ingroup meta
*
* Creates an IndexSequence<0, 1, 2, ...> for a specified size.
*/
template <int Size, int ... Indices>
struct CreateIndexSequence
: CreateIndexSequence<Size - 1, Size - 1, Indices...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal specialization CreateIndexSequence
*/
template <int ... Indices>
struct CreateIndexSequence<0, Indices...>
: IndexSequence<Indices...>
{ };
/**
* \ingroup meta
*
* Meta type defined in terms of a sequence of types
*/
template <typename ... T>
struct TypeSequence
{
enum : signed int { Size = sizeof...(T) };
};
/**
* \internal
* \ingroup meta
*
* Empty TypeSequence
*/
template <> struct TypeSequence<>
{
enum : signed int { Size = Eigen::Dynamic };
};
/**
* \ingroup meta
*
* Creates a \c TypeSequence<T...> by expanding the specified \c Type \c Count
* times.
*/
template <int Count, typename Type, typename...T>
struct CreateTypeSequence
: CreateTypeSequence<Count - 1, Type, Type, T...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal type of CreateTypeSequence
*/
template <typename Type, typename...T>
struct CreateTypeSequence<1, Type, T...>
: TypeSequence<Type, T...>
{ };
/**
* \ingroup meta
*
* Creates an empty \c TypeSequence<> for a \c Count = Eigen::Dynamic
*/
template <typename Type>
struct CreateTypeSequence<Eigen::Dynamic, Type>
: TypeSequence<>
{ };
template <typename Model, typename ParameterModel>
struct AdaptiveModel { };
/**
* \ingroup meta
*
* Same as CreateTypeSequence, however with a reversed parameter order. This is
* an attempt to make the use of \c CreateTypeSequence more natural. It also
* allows dynamic sizes if needed.
*/
template <typename Type, int Count = Eigen::Dynamic>
struct MultipleOf
: CreateTypeSequence<Count, Type>
{ };
/**
* \internal
* \ingroup meta
*
* Creates an empty TypeSequence for dynamic count
*/
template <typename Type>
struct MultipleOf<Type, Eigen::Dynamic>
: CreateTypeSequence<Eigen::Dynamic, Type>
{ };
/**
* \c Join represents a meta operator taking an argument pack which should be
* unified in a specific way. The operator is defined by the following axioms
*
* - pack of Join<P1, P2, ...> {P1, P2, ...}
* - positive pack: sizeof...(T) of Join<T...>
* - nesting: Join<P1, Join<P2, P3>> = {P1, P2, P3}
* - Comm. Join<P1, Join<P2, P3>> = Join<Join<P1, P2>, P3>
* - MultipleOf operator: Join<MultipleOf<P, #>>
*
* \ingroup meta
*/
template <typename...T> struct Join;
/**
* \internal
* \ingroup meta
*
* Collapes the argument pack of the Join operator into Model<T...> of ay given
* Join<...> operator.
*/
template <typename...T> struct CollapseJoin;
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which expands the type sequence by the Head
* element assuming Head is neither a Join<...> nor a MultipleOf<P, #> operator.
*/
template <
typename...S,
typename Head,
typename...T,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Head, // Current non-operator pack head element
T...> // Remaining Tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<Head, S...>, // updated type sequence
T...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which unifies a Join<...> pack Head into the
* outer Join pack, i.e.
*
* Join<T1..., Join<T2...>, T3 > = Join<T1..., T2..., T3...>
*/
template <
typename...S,
typename...T,
typename...U,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Join<T...>, // Current pack head element
U...> // Remaining Tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
T..., // Extracted pack from inner Join operator
U...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which translates a MultipleOf<P,#> operator,
* at the head of the pack, into Model<MultipleOf<P, #>>, i.e
*
* Join<T1..., MultipleOf<P, 10>, T2...> =
* Join<T1..., Model<MultipleOf<P, 10>>, T2...>.
*/
template <
typename...S,
typename...T,
typename U,
int Count,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
MultipleOf<U, Count>, // Current pack head element
T...> // Remaining Join pack, the tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Model<MultipleOf<U, Count>>,// Redefine head in terms of Model<>
T...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* Terminal case of Join operator collapsing. The final result of Join<T...>
* is Model<U...> where U are all the expanded non operator types.
*/
template <
typename...S,
template <typename...> class Model
>
struct CollapseJoin<
Model<>,
TypeSequence<S...>>
{
/**
* \brief Final type outcome of the Join Operator
*/
typedef Model<S...> Type;
static_assert(sizeof...(S) > 1, "Join<A, B, ...> operator must take 2 or more"
" operands");
};
/**
* \internal
* \ingroup meta
*
* Terminal case of Join operator collapsing for a Join of the form
* Join<MultipleOf<P, #>> resulting in Model<MultipleOf<P, #>>
*/
template <
typename M,
int Count,
template <typename...> class Model
>
struct CollapseJoin<Model<>, TypeSequence<Model<MultipleOf<M, Count>>>>
{
typedef Model<MultipleOf<M, Count>> Type;
static_assert(Count > 0 || Count == -1,
"Cannot expand Join<MultipleOf<M, Count>> operator on M. "
"Count must be positive or set to -1 for the dynamic size "
"case.");
};
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2018 Global Phasing Ltd.
//
// Selections.
#ifndef GEMMI_SELECT_HPP_
#define GEMMI_SELECT_HPP_
#include <string>
#include <cstdlib> // for strtol
#include <cctype> // for isalpha
#include <climits> // for INT_MIN, INT_MAX
#include "fail.hpp" // for fail
#include "util.hpp" // for is_in_list
#include "model.hpp" // for Model, Chain, etc
#include "iterator.hpp" // for FilterProxy
namespace gemmi {
// from http://www.ccp4.ac.uk/html/pdbcur.html
// Specification of the selection sets:
// either
// /mdl/chn/s1.i1-s2.i2/at[el]:aloc
// or
// /mdl/chn/*(res).ic/at[el]:aloc
//
struct Selection {
struct List {
bool all = true;
bool inverted = false;
std::string list; // comma-separated
std::string str() const {
if (all)
return "*";
return inverted ? "!" + list : list;
}
// assumes that list.all is checked before this function is called
bool has(const std::string& name) const {
if (all)
return true;
bool found = is_in_list(name, list);
return inverted ? !found : found;
}
};
struct FlagList {
std::string pattern;
bool has(char flag) const {
if (pattern.empty())
return true;
bool invert = (pattern[0] == '!');
bool found = (pattern.find(flag, invert ? 1 : 0) != std::string::npos);
return invert ? !found : found;
}
};
struct SequenceId {
int seqnum;
char icode;
std::string str() const {
std::string s;
if (seqnum != INT_MIN && seqnum != INT_MAX)
s = std::to_string(seqnum);
if (icode != '*') {
s += '.';
if (icode != ' ')
s += icode;
}
return s;
}
int compare(const SeqId& seqid) const {
if (seqnum != *seqid.num)
return seqnum < *seqid.num ? -1 : 1;
if (icode != '*' && icode != seqid.icode)
return icode < seqid.icode ? -1 : 1;
return 0;
}
};
int mdl = 0; // 0 = all
List chain_ids;
SequenceId from_seqid = {INT_MIN, '*'};
SequenceId to_seqid = {INT_MAX, '*'};
List residue_names;
List atom_names;
List elements;
List altlocs;
FlagList residue_flags;
FlagList atom_flags;
std::string to_cid() const {
std::string cid(1, '/');
if (mdl != 0)
cid += std::to_string(mdl);
cid += '/';
cid += chain_ids.str();
cid += '/';
cid += from_seqid.str();
if (!residue_names.all) {
cid += residue_names.str();
} else {
cid += '-';
cid += to_seqid.str();
}
cid += '/';
cid += atom_names.str();
if (!elements.all)
cid += "[" + elements.str() + "]";
if (!altlocs.all)
cid += ":" + altlocs.str();
return cid;
}
bool matches(const gemmi::Model& model) const {
return mdl == 0 || std::to_string(mdl) == model.name;
}
bool matches(const gemmi::Chain& chain) const {
return chain_ids.has(chain.name);
}
bool matches(const gemmi::Residue& res) const {
return residue_names.has(res.name) &&
from_seqid.compare(res.seqid) <= 0 &&
to_seqid.compare(res.seqid) >= 0 &&
residue_flags.has(res.flag);
}
bool matches(const gemmi::Atom& a) const {
return atom_names.has(a.name) &&
elements.has(a.element.uname()) &&
altlocs.has(std::string(a.altloc ? 0 : 1, a.altloc)) &&
atom_flags.has(a.flag);
}
bool matches(const gemmi::CRA& cra) const {
return (cra.chain == nullptr || matches(*cra.chain)) &&
(cra.residue == nullptr || matches(*cra.residue)) &&
(cra.atom == nullptr || matches(*cra.atom));
}
FilterProxy<Selection, Model> models(Structure& st) const {
return {*this, st.models};
}
FilterProxy<Selection, Chain> chains(Model& model) const {
return {*this, model.chains};
}
FilterProxy<Selection, Residue> residues(Chain& chain) const {
return {*this, chain.residues};
}
FilterProxy<Selection, Atom> atoms(Residue& residue) const {
return {*this, residue.atoms};
}
CRA first_in_model(Model& model) const {
if (matches(model))
for (Chain& chain : model.chains) {
if (matches(chain))
for (Residue& res : chain.residues) {
if (matches(res))
for (Atom& atom : res.atoms) {
if (matches(atom))
return {&chain, &res, &atom};
}
}
}
return {nullptr, nullptr, nullptr};
}
std::pair<Model*, CRA> first(Structure& st) const {
for (Model& model : st.models) {
CRA cra = first_in_model(model);
if (cra.chain)
return {&model, cra};
}
return {nullptr, {nullptr, nullptr, nullptr}};
}
template<typename T>
void add_matching_children(const T& orig, T& target) {
for (const auto& orig_child : orig.children())
if (matches(orig_child)) {
target.children().push_back(orig_child.empty_copy());
add_matching_children(orig_child, target.children().back());
}
}
void add_matching_children(const Atom&, Atom&) {}
Selection& set_residue_flags(const std::string& pattern) {
residue_flags.pattern = pattern;
return *this;
}
Selection& set_atom_flags(const std::string& pattern) {
atom_flags.pattern = pattern;
return *this;
}
template<typename T>
T copy_selection(const T& orig) {
T copied = orig.empty_copy();
add_matching_children(orig, copied);
return copied;
}
};
namespace impl {
int determine_omitted_cid_fields(const std::string& cid) {
if (cid[0] == '/')
return 0; // model
if (std::isdigit(cid[0]) || cid[0] == '.' || cid[0] == '(' || cid[0] == '-')
return 2; // residue
size_t sep = cid.find_first_of("/(:[");
if (sep == std::string::npos || cid[sep] == '/')
return 1; // chain
if (cid[sep] == '(')
return 2; // residue
return 3; // atom
}
Selection::List make_cid_list(const std::string& cid, size_t pos, size_t end) {
Selection::List list;
list.all = (cid[pos] == '*');
if (cid[pos] == '!') {
list.inverted = true;
++pos;
}
list.list = cid.substr(pos, end - pos);
return list;
}
Selection::SequenceId parse_cid_seqid(const std::string& cid, size_t& pos,
int default_seqnum) {
size_t initial_pos = pos;
int seqnum = default_seqnum;
char icode = ' ';
if (cid[pos] == '*') {
++pos;
icode = '*';
} else if (std::isdigit(cid[pos])) {
char* endptr;
seqnum = std::strtol(&cid[pos], &endptr, 10);
pos = endptr - &cid[0];
}
if (cid[pos] == '.')
++pos;
if (initial_pos != pos && (std::isalpha(cid[pos]) || cid[pos] == '*'))
icode = cid[pos++];
return {seqnum, icode};
}
} // namespace impl
inline Selection parse_cid(const std::string& cid) {
Selection sel;
if (cid.empty() || (cid.size() == 1 && cid[0] == '*'))
return sel;
int omit = impl::determine_omitted_cid_fields(cid);
size_t sep = 0;
// model
if (omit == 0) {
sep = cid.find('/', 1);
if (sep != 1 && cid[1] != '*') {
char* endptr;
sel.mdl = std::strtol(&cid[1], &endptr, 10);
size_t end_pos = endptr - &cid[0];
if (end_pos != sep && end_pos != cid.length())
fail("Expected model number first: " + cid);
}
}
// chain
if (omit <= 1 && sep != std::string::npos) {
size_t pos = (sep == 0 ? 0 : sep + 1);
sep = cid.find('/', pos);
sel.chain_ids = impl::make_cid_list(cid, pos, sep);
}
// residue; MMDB CID syntax: s1.i1-s2.i2 or *(res).ic
// In gemmi both 14.a and 14a are accepted.
// *(ALA). and *(ALA) and (ALA). can be used instead of (ALA) for
// compatibility with MMDB.
if (omit <= 2 && sep != std::string::npos) {
size_t pos = (sep == 0 ? 0 : sep + 1);
if (cid[pos] != '(')
sel.from_seqid = impl::parse_cid_seqid(cid, pos, INT_MIN);
if (cid[pos] == '(') {
++pos;
size_t right_br = cid.find(')', pos);
sel.residue_names = impl::make_cid_list(cid, pos, right_br);
pos = right_br + 1;
}
// allow "(RES)." and "(RES).*" and "(RES)*"
if (cid[pos] == '.')
++pos;
if (cid[pos] == '*')
++pos;
if (cid[pos] == '-') {
++pos;
sel.to_seqid = impl::parse_cid_seqid(cid, pos, INT_MAX);
}
sep = pos;
}
// atom; at[el]:aloc
if (sep < cid.size()) {
if (sep != 0 && cid[sep] != '/')
fail("Invalid selection syntax: " + cid);
size_t pos = (sep == 0 ? 0 : sep + 1);
size_t end = cid.find_first_of("[:", pos);
if (end != pos)
sel.atom_names = impl::make_cid_list(cid, pos, end);
if (end != std::string::npos) {
if (cid[end] == '[') {
pos = end + 1;
end = cid.find(']', pos);
sel.elements = impl::make_cid_list(cid, pos, end);
sel.elements.list = to_upper(sel.elements.list);
++end;
}
if (cid[end] == ':')
sel.altlocs = impl::make_cid_list(cid, end + 1, std::string::npos);
else if (end < cid.length())
fail("Invalid selection syntax (after ']'): " + cid);
}
}
return sel;
}
} // namespace gemmi
#endif
<commit_msg>optimization<commit_after>// Copyright 2018 Global Phasing Ltd.
//
// Selections.
#ifndef GEMMI_SELECT_HPP_
#define GEMMI_SELECT_HPP_
#include <string>
#include <cstdlib> // for strtol
#include <cctype> // for isalpha
#include <climits> // for INT_MIN, INT_MAX
#include "fail.hpp" // for fail
#include "util.hpp" // for is_in_list
#include "model.hpp" // for Model, Chain, etc
#include "iterator.hpp" // for FilterProxy
namespace gemmi {
// from http://www.ccp4.ac.uk/html/pdbcur.html
// Specification of the selection sets:
// either
// /mdl/chn/s1.i1-s2.i2/at[el]:aloc
// or
// /mdl/chn/*(res).ic/at[el]:aloc
//
struct Selection {
struct List {
bool all = true;
bool inverted = false;
std::string list; // comma-separated
std::string str() const {
if (all)
return "*";
return inverted ? "!" + list : list;
}
bool has(const std::string& name) const {
if (all)
return true;
bool found = is_in_list(name, list);
return inverted ? !found : found;
}
};
struct FlagList {
std::string pattern;
bool has(char flag) const {
if (pattern.empty())
return true;
bool invert = (pattern[0] == '!');
bool found = (pattern.find(flag, invert ? 1 : 0) != std::string::npos);
return invert ? !found : found;
}
};
struct SequenceId {
int seqnum;
char icode;
std::string str() const {
std::string s;
if (seqnum != INT_MIN && seqnum != INT_MAX)
s = std::to_string(seqnum);
if (icode != '*') {
s += '.';
if (icode != ' ')
s += icode;
}
return s;
}
int compare(const SeqId& seqid) const {
if (seqnum != *seqid.num)
return seqnum < *seqid.num ? -1 : 1;
if (icode != '*' && icode != seqid.icode)
return icode < seqid.icode ? -1 : 1;
return 0;
}
};
int mdl = 0; // 0 = all
List chain_ids;
SequenceId from_seqid = {INT_MIN, '*'};
SequenceId to_seqid = {INT_MAX, '*'};
List residue_names;
List atom_names;
List elements;
List altlocs;
FlagList residue_flags;
FlagList atom_flags;
std::string to_cid() const {
std::string cid(1, '/');
if (mdl != 0)
cid += std::to_string(mdl);
cid += '/';
cid += chain_ids.str();
cid += '/';
cid += from_seqid.str();
if (!residue_names.all) {
cid += residue_names.str();
} else {
cid += '-';
cid += to_seqid.str();
}
cid += '/';
cid += atom_names.str();
if (!elements.all)
cid += "[" + elements.str() + "]";
if (!altlocs.all)
cid += ":" + altlocs.str();
return cid;
}
bool matches(const gemmi::Model& model) const {
return mdl == 0 || std::to_string(mdl) == model.name;
}
bool matches(const gemmi::Chain& chain) const {
return chain_ids.has(chain.name);
}
bool matches(const gemmi::Residue& res) const {
return residue_names.has(res.name) &&
from_seqid.compare(res.seqid) <= 0 &&
to_seqid.compare(res.seqid) >= 0 &&
residue_flags.has(res.flag);
}
bool matches(const gemmi::Atom& a) const {
return atom_names.has(a.name) &&
(elements.all || elements.has(a.element.uname())) &&
(altlocs.all || altlocs.has(std::string(a.altloc ? 1 : 0, a.altloc))) &&
atom_flags.has(a.flag);
}
bool matches(const gemmi::CRA& cra) const {
return (cra.chain == nullptr || matches(*cra.chain)) &&
(cra.residue == nullptr || matches(*cra.residue)) &&
(cra.atom == nullptr || matches(*cra.atom));
}
FilterProxy<Selection, Model> models(Structure& st) const {
return {*this, st.models};
}
FilterProxy<Selection, Chain> chains(Model& model) const {
return {*this, model.chains};
}
FilterProxy<Selection, Residue> residues(Chain& chain) const {
return {*this, chain.residues};
}
FilterProxy<Selection, Atom> atoms(Residue& residue) const {
return {*this, residue.atoms};
}
CRA first_in_model(Model& model) const {
if (matches(model))
for (Chain& chain : model.chains) {
if (matches(chain))
for (Residue& res : chain.residues) {
if (matches(res))
for (Atom& atom : res.atoms) {
if (matches(atom))
return {&chain, &res, &atom};
}
}
}
return {nullptr, nullptr, nullptr};
}
std::pair<Model*, CRA> first(Structure& st) const {
for (Model& model : st.models) {
CRA cra = first_in_model(model);
if (cra.chain)
return {&model, cra};
}
return {nullptr, {nullptr, nullptr, nullptr}};
}
template<typename T>
void add_matching_children(const T& orig, T& target) {
for (const auto& orig_child : orig.children())
if (matches(orig_child)) {
target.children().push_back(orig_child.empty_copy());
add_matching_children(orig_child, target.children().back());
}
}
void add_matching_children(const Atom&, Atom&) {}
Selection& set_residue_flags(const std::string& pattern) {
residue_flags.pattern = pattern;
return *this;
}
Selection& set_atom_flags(const std::string& pattern) {
atom_flags.pattern = pattern;
return *this;
}
template<typename T>
T copy_selection(const T& orig) {
T copied = orig.empty_copy();
add_matching_children(orig, copied);
return copied;
}
};
namespace impl {
int determine_omitted_cid_fields(const std::string& cid) {
if (cid[0] == '/')
return 0; // model
if (std::isdigit(cid[0]) || cid[0] == '.' || cid[0] == '(' || cid[0] == '-')
return 2; // residue
size_t sep = cid.find_first_of("/(:[");
if (sep == std::string::npos || cid[sep] == '/')
return 1; // chain
if (cid[sep] == '(')
return 2; // residue
return 3; // atom
}
Selection::List make_cid_list(const std::string& cid, size_t pos, size_t end) {
Selection::List list;
list.all = (cid[pos] == '*');
if (cid[pos] == '!') {
list.inverted = true;
++pos;
}
list.list = cid.substr(pos, end - pos);
return list;
}
Selection::SequenceId parse_cid_seqid(const std::string& cid, size_t& pos,
int default_seqnum) {
size_t initial_pos = pos;
int seqnum = default_seqnum;
char icode = ' ';
if (cid[pos] == '*') {
++pos;
icode = '*';
} else if (std::isdigit(cid[pos])) {
char* endptr;
seqnum = std::strtol(&cid[pos], &endptr, 10);
pos = endptr - &cid[0];
}
if (cid[pos] == '.')
++pos;
if (initial_pos != pos && (std::isalpha(cid[pos]) || cid[pos] == '*'))
icode = cid[pos++];
return {seqnum, icode};
}
} // namespace impl
inline Selection parse_cid(const std::string& cid) {
Selection sel;
if (cid.empty() || (cid.size() == 1 && cid[0] == '*'))
return sel;
int omit = impl::determine_omitted_cid_fields(cid);
size_t sep = 0;
// model
if (omit == 0) {
sep = cid.find('/', 1);
if (sep != 1 && cid[1] != '*') {
char* endptr;
sel.mdl = std::strtol(&cid[1], &endptr, 10);
size_t end_pos = endptr - &cid[0];
if (end_pos != sep && end_pos != cid.length())
fail("Expected model number first: " + cid);
}
}
// chain
if (omit <= 1 && sep != std::string::npos) {
size_t pos = (sep == 0 ? 0 : sep + 1);
sep = cid.find('/', pos);
sel.chain_ids = impl::make_cid_list(cid, pos, sep);
}
// residue; MMDB CID syntax: s1.i1-s2.i2 or *(res).ic
// In gemmi both 14.a and 14a are accepted.
// *(ALA). and *(ALA) and (ALA). can be used instead of (ALA) for
// compatibility with MMDB.
if (omit <= 2 && sep != std::string::npos) {
size_t pos = (sep == 0 ? 0 : sep + 1);
if (cid[pos] != '(')
sel.from_seqid = impl::parse_cid_seqid(cid, pos, INT_MIN);
if (cid[pos] == '(') {
++pos;
size_t right_br = cid.find(')', pos);
sel.residue_names = impl::make_cid_list(cid, pos, right_br);
pos = right_br + 1;
}
// allow "(RES)." and "(RES).*" and "(RES)*"
if (cid[pos] == '.')
++pos;
if (cid[pos] == '*')
++pos;
if (cid[pos] == '-') {
++pos;
sel.to_seqid = impl::parse_cid_seqid(cid, pos, INT_MAX);
}
sep = pos;
}
// atom; at[el]:aloc
if (sep < cid.size()) {
if (sep != 0 && cid[sep] != '/')
fail("Invalid selection syntax: " + cid);
size_t pos = (sep == 0 ? 0 : sep + 1);
size_t end = cid.find_first_of("[:", pos);
if (end != pos)
sel.atom_names = impl::make_cid_list(cid, pos, end);
if (end != std::string::npos) {
if (cid[end] == '[') {
pos = end + 1;
end = cid.find(']', pos);
sel.elements = impl::make_cid_list(cid, pos, end);
sel.elements.list = to_upper(sel.elements.list);
++end;
}
if (cid[end] == ':')
sel.altlocs = impl::make_cid_list(cid, end + 1, std::string::npos);
else if (end < cid.length())
fail("Invalid selection syntax (after ']'): " + cid);
}
}
return sel;
}
} // namespace gemmi
#endif
<|endoftext|> |
<commit_before>#ifndef __LLVM_IKOS_HPP_
#define __LLVM_IKOS_HPP_
/*
* Compute invariants for each basic block using a numerical abstract
* domain.
*/
#include "llvm/Pass.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseMap.h"
#include "boost/optional.hpp"
#include "ikos/CfgBuilder.hh"
namespace llvm_ikos
{
using namespace llvm;
using namespace cfg_impl;
enum IkosDomain { INTERVALS, CONGRUENCES, INTERVALS_CONGRUENCES, ZONES, OCTAGONS};
class LlvmIkos : public llvm::ModulePass
{
typedef llvm::DenseMap< const llvm::BasicBlock *, ZLinearConstraintSystem > invariants_map_t;
invariants_map_t m_inv_map;
IkosDomain m_absdom;
bool m_runlive;
public:
typedef invariants_map_t::iterator iterator;
typedef invariants_map_t::const_iterator const_iterator;
static char ID;
LlvmIkos (IkosDomain absdom = INTERVALS, bool runLive = false);
~LlvmIkos (){ m_inv_map.clear(); }
virtual void getAnalysisUsage (llvm::AnalysisUsage &AU) const
{
AU.setPreservesCFG();
}
virtual bool runOnModule (llvm::Module& M);
virtual bool runOnFunction (llvm::Function &F);
iterator begin () { return m_inv_map.begin(); }
iterator end () { return m_inv_map.end(); }
const_iterator begin () const { return m_inv_map.begin(); }
const_iterator end () const { return m_inv_map.end(); }
ZLinearConstraintSystem operator[] (const llvm::BasicBlock *BB) const
{
const_iterator it = m_inv_map.find (BB);
if (it == m_inv_map.end())
{
ZLinearConstraintSystem tt;
tt += mkTRUE ();
return tt;
}
else return it->second;
}
void dump (llvm::Module &M) const;
private:
ZLinearConstraint mkTRUE() const
{
return ZLinearConstraint ( ZLinearExpression (1) == ZLinearExpression (1));
}
ZLinearConstraint mkFALSE() const
{
return ZLinearConstraint ( ZLinearExpression (1) == ZLinearExpression (0));
}
template<typename AbsDomain>
bool runOnCfg (cfg_t& cfg, llvm::Function &F, VariableFactory &vfac);
};
ModulePass * createLlvmIkosPass (IkosDomain absdomain, bool runLive);
} // end namespace llvm_ikos
#endif
<commit_msg>[FIX] LlvmIkos preserves all passes. Not just CFG.<commit_after>#ifndef __LLVM_IKOS_HPP_
#define __LLVM_IKOS_HPP_
/*
* Compute invariants for each basic block using a numerical abstract
* domain.
*/
#include "llvm/Pass.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseMap.h"
#include "boost/optional.hpp"
#include "ikos/CfgBuilder.hh"
namespace llvm_ikos
{
using namespace llvm;
using namespace cfg_impl;
enum IkosDomain { INTERVALS, CONGRUENCES, INTERVALS_CONGRUENCES, ZONES, OCTAGONS};
class LlvmIkos : public llvm::ModulePass
{
typedef llvm::DenseMap< const llvm::BasicBlock *, ZLinearConstraintSystem > invariants_map_t;
invariants_map_t m_inv_map;
IkosDomain m_absdom;
bool m_runlive;
public:
typedef invariants_map_t::iterator iterator;
typedef invariants_map_t::const_iterator const_iterator;
static char ID;
LlvmIkos (IkosDomain absdom = INTERVALS, bool runLive = false);
~LlvmIkos (){ m_inv_map.clear(); }
virtual void getAnalysisUsage (llvm::AnalysisUsage &AU) const
{AU.setPreservesAll ();}
virtual bool runOnModule (llvm::Module& M);
virtual bool runOnFunction (llvm::Function &F);
iterator begin () { return m_inv_map.begin(); }
iterator end () { return m_inv_map.end(); }
const_iterator begin () const { return m_inv_map.begin(); }
const_iterator end () const { return m_inv_map.end(); }
ZLinearConstraintSystem operator[] (const llvm::BasicBlock *BB) const
{
const_iterator it = m_inv_map.find (BB);
if (it == m_inv_map.end())
{
ZLinearConstraintSystem tt;
tt += mkTRUE ();
return tt;
}
else return it->second;
}
void dump (llvm::Module &M) const;
private:
ZLinearConstraint mkTRUE() const
{
return ZLinearConstraint ( ZLinearExpression (1) == ZLinearExpression (1));
}
ZLinearConstraint mkFALSE() const
{
return ZLinearConstraint ( ZLinearExpression (1) == ZLinearExpression (0));
}
template<typename AbsDomain>
bool runOnCfg (cfg_t& cfg, llvm::Function &F, VariableFactory &vfac);
};
ModulePass * createLlvmIkosPass (IkosDomain absdomain, bool runLive);
} // end namespace llvm_ikos
#endif
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Jikken - 3D Abstract High Performance Graphics API
// Copyright(c) 2017 Jeff Hutchinson
// Copyright(c) 2017 Tim Barnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _JIKKEN_ENUMS_HPP_
#define _JIKKEN_ENUMS_HPP_
#include <cstdint>
namespace Jikken
{
enum class API : uint8_t
{
eNull,
eOpenGL,
eVulkan
};
enum class BlendState : uint8_t
{
eSrcAlpha = 0,
eOneMinusSrcAlpha
};
enum class DepthFunc : uint8_t
{
eNever = 0,
eAlways,
eLess,
eEqual,
eNotEqual,
eGreater,
eLessEqual,
eGreaterEqual
};
enum class CullFaceState : uint8_t
{
eFront = 0,
eBack
};
enum class WindingOrderState : uint8_t
{
eCW = 0,
eCCW
};
enum class PrimitiveType : uint8_t
{
eTriangles = 0,
eTriangleStrip,
eLines,
eLineStrip
};
enum class ShaderStage : uint8_t
{
eVertex = 0,
eFragment,
eGeometry,
eCompute
};
enum ClearBufferFlags : uint32_t
{
eColor = 1,
eDepth = 2,
eStencil = 4
};
enum class BufferType : uint8_t
{
eVertexBuffer = 0,
eIndexBuffer,
eConstantBuffer
};
enum class BufferUsageHint : uint8_t
{
eStaticDraw = 0,
eDynamicDraw,
eStreamDraw
};
enum VertexAttributeName : int32_t
{
ePOSITION = 0
};
enum VertexAttributeType : int32_t
{
eFLOAT = 0
};
}
#endif<commit_msg>BlendState enum update<commit_after>//-----------------------------------------------------------------------------
// Jikken - 3D Abstract High Performance Graphics API
// Copyright(c) 2017 Jeff Hutchinson
// Copyright(c) 2017 Tim Barnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _JIKKEN_ENUMS_HPP_
#define _JIKKEN_ENUMS_HPP_
#include <cstdint>
namespace Jikken
{
enum class API : uint8_t
{
eNull,
eOpenGL,
eVulkan
};
enum class BlendState : uint8_t
{
eZero = 0,
eOne,
eSrcColor,
eOneMinusSrcColor,
eSrcAlpha,
eOneMinusSrcAlpha,
eDstAlpha,
eOneMinusDstAlpha,
eDstColor,
eOneMinusDstColor
};
enum class DepthFunc : uint8_t
{
eNever = 0,
eAlways,
eLess,
eEqual,
eNotEqual,
eGreater,
eLessEqual,
eGreaterEqual
};
enum class CullFaceState : uint8_t
{
eFront = 0,
eBack
};
enum class WindingOrderState : uint8_t
{
eCW = 0,
eCCW
};
enum class PrimitiveType : uint8_t
{
eTriangles = 0,
eTriangleStrip,
eLines,
eLineStrip
};
enum class ShaderStage : uint8_t
{
eVertex = 0,
eFragment,
eGeometry,
eCompute
};
enum ClearBufferFlags : uint32_t
{
eColor = 1,
eDepth = 2,
eStencil = 4
};
enum class BufferType : uint8_t
{
eVertexBuffer = 0,
eIndexBuffer,
eConstantBuffer
};
enum class BufferUsageHint : uint8_t
{
eStaticDraw = 0,
eDynamicDraw,
eStreamDraw
};
enum VertexAttributeName : int32_t
{
ePOSITION = 0
};
enum VertexAttributeType : int32_t
{
eFLOAT = 0
};
}
#endif<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: utils.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef UTILS_HPP
#define UTILS_HPP
#ifdef MAPNIK_THREADSAFE
#include <boost/thread/mutex.hpp>
#endif
// stl
#include <stdexcept>
#include <cstdlib>
#include <limits>
#include <ctime>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <cmath>
namespace mapnik
{
#ifdef MAPNIK_THREADSAFE
using boost::mutex;
#endif
template <typename T>
class CreateUsingNew
{
public:
static T* create()
{
return new T;
}
static void destroy(T* obj)
{
delete obj;
}
};
template <typename T>
class CreateStatic
{
private:
union MaxAlign
{
char t_[sizeof(T)];
short int shortInt_;
int int_;
long int longInt_;
float float_;
double double_;
long double longDouble_;
struct Test;
int Test::* pMember_;
int (Test::*pMemberFn_)(int);
};
public:
static T* create()
{
static MaxAlign staticMemory;
return new(&staticMemory) T;
}
#ifdef __SUNPRO_CC
// Sun C++ Compiler doesn't handle `volatile` keyword same as GCC.
static void destroy(T* obj)
#else
static void destroy(volatile T* obj)
#endif
{
obj->~T();
}
};
template <typename T,
template <typename T> class CreatePolicy=CreateStatic> class singleton
{
#ifdef __SUNPRO_CC
/* Sun's C++ compiler will issue the following errors if CreatePolicy<T> is used:
Error: A class template name was expected instead of mapnik::CreatePolicy<mapnik::T>
Error: A "friend" declaration must specify a class or function.
*/
friend class CreatePolicy;
#else
friend class CreatePolicy<T>;
#endif
static T* pInstance_;
static bool destroyed_;
singleton(const singleton &rhs);
singleton& operator=(const singleton&);
static void onDeadReference()
{
throw std::runtime_error("dead reference!");
}
static void DestroySingleton()
{
CreatePolicy<T>::destroy(pInstance_);
pInstance_ = 0;
destroyed_=true;
#ifdef MAPNIK_DEBUG
std::clog << " destroyed singleton \n";
#endif
}
protected:
#ifdef MAPNIK_THREADSAFE
static mutex mutex_;
#endif
singleton() {}
public:
static T* instance()
{
if (!pInstance_)
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
if (!pInstance_)
{
if (destroyed_)
{
onDeadReference();
}
else
{
pInstance_=CreatePolicy<T>::create();
// register destruction
std::atexit(&DestroySingleton);
}
}
}
return pInstance_;
}
};
#ifdef MAPNIK_THREADSAFE
template <typename T,
template <typename T> class CreatePolicy> mutex singleton<T,CreatePolicy>::mutex_;
#endif
template <typename T,
template <typename T> class CreatePolicy> T* singleton<T,CreatePolicy>::pInstance_=0;
template <typename T,
template <typename T> class CreatePolicy> bool singleton<T,CreatePolicy>::destroyed_=false;
}
#endif //UTILS_HPP
<commit_msg>+ fixed template parameter shadowing (clang++)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: utils.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef UTILS_HPP
#define UTILS_HPP
#ifdef MAPNIK_THREADSAFE
#include <boost/thread/mutex.hpp>
#endif
// stl
#include <stdexcept>
#include <cstdlib>
#include <limits>
#include <ctime>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <cmath>
namespace mapnik
{
#ifdef MAPNIK_THREADSAFE
using boost::mutex;
#endif
template <typename T>
class CreateUsingNew
{
public:
static T* create()
{
return new T;
}
static void destroy(T* obj)
{
delete obj;
}
};
template <typename T>
class CreateStatic
{
private:
union MaxAlign
{
char t_[sizeof(T)];
short int shortInt_;
int int_;
long int longInt_;
float float_;
double double_;
long double longDouble_;
struct Test;
int Test::* pMember_;
int (Test::*pMemberFn_)(int);
};
public:
static T* create()
{
static MaxAlign staticMemory;
return new(&staticMemory) T;
}
#ifdef __SUNPRO_CC
// Sun C++ Compiler doesn't handle `volatile` keyword same as GCC.
static void destroy(T* obj)
#else
static void destroy(volatile T* obj)
#endif
{
obj->~T();
}
};
template <typename T,
template <typename U> class CreatePolicy=CreateStatic> class singleton
{
#ifdef __SUNPRO_CC
/* Sun's C++ compiler will issue the following errors if CreatePolicy<T> is used:
Error: A class template name was expected instead of mapnik::CreatePolicy<mapnik::T>
Error: A "friend" declaration must specify a class or function.
*/
friend class CreatePolicy;
#else
friend class CreatePolicy<T>;
#endif
static T* pInstance_;
static bool destroyed_;
singleton(const singleton &rhs);
singleton& operator=(const singleton&);
static void onDeadReference()
{
throw std::runtime_error("dead reference!");
}
static void DestroySingleton()
{
CreatePolicy<T>::destroy(pInstance_);
pInstance_ = 0;
destroyed_=true;
#ifdef MAPNIK_DEBUG
std::clog << " destroyed singleton \n";
#endif
}
protected:
#ifdef MAPNIK_THREADSAFE
static mutex mutex_;
#endif
singleton() {}
public:
static T* instance()
{
if (!pInstance_)
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
if (!pInstance_)
{
if (destroyed_)
{
onDeadReference();
}
else
{
pInstance_=CreatePolicy<T>::create();
// register destruction
std::atexit(&DestroySingleton);
}
}
}
return pInstance_;
}
};
#ifdef MAPNIK_THREADSAFE
template <typename T,
template <typename U> class CreatePolicy> mutex singleton<T,CreatePolicy>::mutex_;
#endif
template <typename T,
template <typename U> class CreatePolicy> T* singleton<T,CreatePolicy>::pInstance_=0;
template <typename T,
template <typename U> class CreatePolicy> bool singleton<T,CreatePolicy>::destroyed_=false;
}
#endif //UTILS_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#pragma once
#include <pdal/third/nanoflann.hpp>
#include <pdal/PointBuffer.hpp>
namespace pdal
{
class PDAL_DLL KDIndex
{
public:
KDIndex(PointBuffer& buf) : m_buf(buf), m_index(0)
{ m_3d = buf.context().hasDim(Dimension::Id::Z); }
~KDIndex()
{ delete m_index; }
size_t kdtree_get_point_count() const
{ return m_buf.size(); }
double kdtree_get_pt(const size_t idx, int dim) const
{
Dimension::Id::Enum id = Dimension::Id::Unknown;
switch (dim)
{
case 0:
id = Dimension::Id::X;
break;
case 1:
id = Dimension::Id::Y;
break;
case 3:
id = Dimension::Id::Z;
break;
}
return m_buf.getFieldAs<double>(id, idx);
}
double kdtree_distance(const double *p1, const size_t idx_p2,
size_t size) const
{
double d0 = m_buf.getFieldAs<double>(Dimension::Id::X, idx_p2) -
m_buf.getFieldAs<double>(Dimension::Id::X, size - 1);
double d1 = m_buf.getFieldAs<double>(Dimension::Id::Y, idx_p2) -
m_buf.getFieldAs<double>(Dimension::Id::Y, size - 1);
double output(d0 * d0 + d1 * d1);
if (m_3d)
{
double d2 = m_buf.getFieldAs<double>(Dimension::Id::Z, idx_p2) -
m_buf.getFieldAs<double>(Dimension::Id::Z, size - 1);
output += d2 * d2;
}
return output;
}
template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const
{
pdal::Bounds<double> bounds = m_buf.calculateBounds();
if (bounds.empty())
return false;
size_t nDims = m_3d ? 3 : 2;
for (size_t i = 0; i < nDims; ++i)
{
bb[i].low = bounds.getMinimum(i);
bb[i].high = bounds.getMaximum(i);
}
return true;
}
std::vector<size_t> radius(
double const& x,
double const& y,
double const& z,
double const& r) const;
std::vector<size_t> neighbors(
double const& x,
double const& y,
double const& z,
double distance,
boost::uint32_t count = 1) const;
void build(PointContext ctx, bool b3d = true);
private:
const PointBuffer& m_buf;
bool m_3d;
typedef nanoflann::KDTreeSingleIndexAdaptor<
nanoflann::L2_Adaptor<double, KDIndex>, KDIndex> my_kd_tree_t;
my_kd_tree_t* m_index;
};
} // namespace pdal
<commit_msg>Fix KD index typo.<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#pragma once
#include <pdal/third/nanoflann.hpp>
#include <pdal/PointBuffer.hpp>
namespace pdal
{
class PDAL_DLL KDIndex
{
public:
KDIndex(PointBuffer& buf) : m_buf(buf), m_index(0)
{ m_3d = buf.context().hasDim(Dimension::Id::Z); }
~KDIndex()
{ delete m_index; }
size_t kdtree_get_point_count() const
{ return m_buf.size(); }
double kdtree_get_pt(const size_t idx, int dim) const
{
Dimension::Id::Enum id = Dimension::Id::Unknown;
switch (dim)
{
case 0:
id = Dimension::Id::X;
break;
case 1:
id = Dimension::Id::Y;
break;
case 2:
id = Dimension::Id::Z;
break;
}
return m_buf.getFieldAs<double>(id, idx);
}
double kdtree_distance(const double *p1, const size_t idx_p2,
size_t size) const
{
double d0 = m_buf.getFieldAs<double>(Dimension::Id::X, idx_p2) -
m_buf.getFieldAs<double>(Dimension::Id::X, size - 1);
double d1 = m_buf.getFieldAs<double>(Dimension::Id::Y, idx_p2) -
m_buf.getFieldAs<double>(Dimension::Id::Y, size - 1);
double output(d0 * d0 + d1 * d1);
if (m_3d)
{
double d2 = m_buf.getFieldAs<double>(Dimension::Id::Z, idx_p2) -
m_buf.getFieldAs<double>(Dimension::Id::Z, size - 1);
output += d2 * d2;
}
return output;
}
template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const
{
pdal::Bounds<double> bounds = m_buf.calculateBounds();
if (bounds.empty())
return false;
size_t nDims = m_3d ? 3 : 2;
for (size_t i = 0; i < nDims; ++i)
{
bb[i].low = bounds.getMinimum(i);
bb[i].high = bounds.getMaximum(i);
}
return true;
}
std::vector<size_t> radius(
double const& x,
double const& y,
double const& z,
double const& r) const;
std::vector<size_t> neighbors(
double const& x,
double const& y,
double const& z,
double distance,
boost::uint32_t count = 1) const;
void build(PointContext ctx, bool b3d = true);
private:
const PointBuffer& m_buf;
bool m_3d;
typedef nanoflann::KDTreeSingleIndexAdaptor<
nanoflann::L2_Adaptor<double, KDIndex>, KDIndex> my_kd_tree_t;
my_kd_tree_t* m_index;
};
} // namespace pdal
<|endoftext|> |
<commit_before>
#pragma once
#include <proxc/version.hpp>
////////////////////////////////////////////////////////////////////////////////
// Detect the compiler
////////////////////////////////////////////////////////////////////////////////
#if defined(_MSC_VER) && !defined(__clang__) // MSVC
# pragma message("Warning: the native Microsoft compiler is not supported due to lack of proper C++14 support.")
#elif defined(__clang__) && defined(_MSC_VER) // Clang-cl (Clang for Windows)
# define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
__clang_major__, __clang_minor__, __clang_patchlevel__)
# if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
# warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
# endif
#elif defined(__clang__) && defined(__apple_build_version__) // Apple's Clang
# if __apple_build_version__ >= 6000051
# define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION(3, 6, 0)
# else
# warning "Versions of Apple's Clang prior to the one shipped with XCode is not supported."
# endif
#elif defined(__clang__) // Genuine Clang
# define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
__clang_major__, __clang_minor__, __clang_patchlevel__)
# if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
# warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
# endif
#elif defined(__GNUC__) // GCC
# define PROXC_CONFIC_GCC PROXC_CONFIG_VERSION(\
__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
# if PROXC_CONFIC_GCC < PROXC_CONFIG_VERSION(5, 0, 0)
# warning "Versions of GCC prior to 5.0.0 are not supported for lack of proper C++14 support."
# endif
#else
# warning "Your compiler was not detected properly and might not work for ProXC."
#endif
////////////////////////////////////////////////////////////////////////////////
// Detect the compiler for general C++14 capabilities
////////////////////////////////////////////////////////////////////////////////
#if (__cplusplus < 201400)
# if defined(_MSC_VER)
# pragma message("Warning: Your compiler doesn't provide C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or '-std=c++1y'.")
# else
# warning "Your compiler doesn't provde C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or 'std=c++1y'"
# endif
#endif
////////////////////////////////////////////////////////////////////////////////
// Detect the standard library
////////////////////////////////////////////////////////////////////////////////
#include <cstddef>
#if defined(_LIBCPP_VERSION)
# define PROXC_CONFIG_LIBCPP PROXC_CONFIG_VERSION( \
((_LIBCPP_VERSION) / 1000) % 10, 0, (_LIBCPP_VERSION) % 1000)
# if PROXC_CONFIG_LIBCPP < PROXC_CONFIG_VERSION(1, 0, 101)
# warning "Versions of libc++ prior to the one shipped with Clang 3.5.0 are not supported for lack of full C++14 support."
# endif
#elif defined(__GLIBCXX__)
# if __GLIBCXX__ < 20150422 // --> the libstdc++ shipped with GCC 5.1.0
# warning "Versions of libstdc++ prior to the one shipped with GCC 5.1.0 are not supported for lack of full C++14 support."
# endif
# define PROXC_CONFIG_LIBSTDCXX
#elif defined(_MSC_VER)
# define PROXC_CONFIG_LIBMSVCCXX
#else
# warning "Your standard library was not detected properly and might not work for ProXC."
#endif
////////////////////////////////////////////////////////////////////////////////
// Detect 32- or 64-bit architecture
////////////////////////////////////////////////////////////////////////////////
#ifndef PROXC_ARCH
#if defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) /* PowerPC */
# if defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
defined(__64BIT__) || defined(_LP64) || defined(__LP64__) /* PowerPC 64-bit */
# define PROXC_ARCH 64
# else /* PowerPC 32-bit */
# define PROXC_ARCH 32
# endif
#elif defined(__x86_64__) || defined(_M_X64) /* x86 64-bit */
# define PROXC_ARCH 64
#elif defined(__i386) || defined(_M_IX86) /* x86 32-bit */
# define PROXC_ARCH 32
#elif defined(_WIN32) || defined(_WIN64) /* Windows */
# if defined(_WIN64) /* Windows 64-bit */
# define PROXC_ARCH 64
# else /* Windows 32-bit */
# define PROXC_ARCH 32
# endif
#else /* Unknown architecture */
# define PROXC_ARCH 64
# warning "Architecture was neither correctly determined nor specified. Defaults to 64-bit. This can be set with -DPROXC_ARCH={32/64}, for 32-bit or 64-bit respectively."
#endif
#else
static_assert(((PROXC_ARCH) == 32) || ((PROXC_ARCH) == 64), "Architecture specified by PROXC_ARCH only supports 32 or 64 value.");
#endif // PROXC_ARCH
////////////////////////////////////////////////////////////////////////////////
// Namespace macros
////////////////////////////////////////////////////////////////////////////////
#define PROXC_NAMESPACE_BEGIN namespace proxc {
#define PROXC_NAMESPACE_END }
<commit_msg>Added configuration for cache alignment and cacheline length.<commit_after>
#pragma once
#include <proxc/version.hpp>
////////////////////////////////////////////////////////////////////////////////
// Detect the compiler
////////////////////////////////////////////////////////////////////////////////
#if defined(_MSC_VER) && !defined(__clang__) // MSVC
# pragma message("Warning: the native Microsoft compiler is not supported due to lack of proper C++14 support.")
#elif defined(__clang__) && defined(_MSC_VER) // Clang-cl (Clang for Windows)
# define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
__clang_major__, __clang_minor__, __clang_patchlevel__)
# if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
# warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
# endif
#elif defined(__clang__) && defined(__apple_build_version__) // Apple's Clang
# if __apple_build_version__ >= 6000051
# define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION(3, 6, 0)
# else
# warning "Versions of Apple's Clang prior to the one shipped with XCode is not supported."
# endif
#elif defined(__clang__) // Genuine Clang
# define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
__clang_major__, __clang_minor__, __clang_patchlevel__)
# if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
# warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
# endif
#elif defined(__GNUC__) // GCC
# define PROXC_CONFIC_GCC PROXC_CONFIG_VERSION(\
__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
# if PROXC_CONFIC_GCC < PROXC_CONFIG_VERSION(5, 0, 0)
# warning "Versions of GCC prior to 5.0.0 are not supported for lack of proper C++14 support."
# endif
#else
# warning "Your compiler was not detected properly and might not work for ProXC."
#endif
////////////////////////////////////////////////////////////////////////////////
// Detect the compiler for general C++14 capabilities
////////////////////////////////////////////////////////////////////////////////
#if (__cplusplus < 201400)
# if defined(_MSC_VER)
# pragma message("Warning: Your compiler doesn't provide C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or '-std=c++1y'.")
# else
# warning "Your compiler doesn't provde C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or 'std=c++1y'"
# endif
#endif
////////////////////////////////////////////////////////////////////////////////
// Detect the standard library
////////////////////////////////////////////////////////////////////////////////
#include <cstddef>
#if defined(_LIBCPP_VERSION)
# define PROXC_CONFIG_LIBCPP PROXC_CONFIG_VERSION( \
((_LIBCPP_VERSION) / 1000) % 10, 0, (_LIBCPP_VERSION) % 1000)
# if PROXC_CONFIG_LIBCPP < PROXC_CONFIG_VERSION(1, 0, 101)
# warning "Versions of libc++ prior to the one shipped with Clang 3.5.0 are not supported for lack of full C++14 support."
# endif
#elif defined(__GLIBCXX__)
# if __GLIBCXX__ < 20150422 // --> the libstdc++ shipped with GCC 5.1.0
# warning "Versions of libstdc++ prior to the one shipped with GCC 5.1.0 are not supported for lack of full C++14 support."
# endif
# define PROXC_CONFIG_LIBSTDCXX
#elif defined(_MSC_VER)
# define PROXC_CONFIG_LIBMSVCCXX
#else
# warning "Your standard library was not detected properly and might not work for ProXC."
#endif
////////////////////////////////////////////////////////////////////////////////
// Detect 32- or 64-bit architecture
////////////////////////////////////////////////////////////////////////////////
#ifndef PROXC_ARCH
#if defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) /* PowerPC */
# if defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
defined(__64BIT__) || defined(_LP64) || defined(__LP64__) /* PowerPC 64-bit */
# define PROXC_ARCH 64
# else /* PowerPC 32-bit */
# define PROXC_ARCH 32
# endif
#elif defined(__x86_64__) || defined(_M_X64) /* x86 64-bit */
# define PROXC_ARCH 64
#elif defined(__i386) || defined(_M_IX86) /* x86 32-bit */
# define PROXC_ARCH 32
#elif defined(_WIN32) || defined(_WIN64) /* Windows */
# if defined(_WIN64) /* Windows 64-bit */
# define PROXC_ARCH 64
# else /* Windows 32-bit */
# define PROXC_ARCH 32
# endif
#else /* Unknown architecture */
# define PROXC_ARCH 64
# warning "Architecture was neither correctly determined nor specified. Defaults to 64-bit. This can be set with -DPROXC_ARCH={32/64}, for 32-bit or 64-bit respectively."
#endif
#endif // PROXC_ARCH
static_assert(((PROXC_ARCH) == 32) || ((PROXC_ARCH) == 64), "Architecture specified by PROXC_ARCH only supports 32 or 64 value.");
// cache alignment and cachelines
static constexpr std::size_t cache_alignment{ PROXC_ARCH };
static constexpr std::size_t cacheline_length{ PROXC_ARCH };
////////////////////////////////////////////////////////////////////////////////
// Namespace macros
////////////////////////////////////////////////////////////////////////////////
#define PROXC_NAMESPACE_BEGIN namespace proxc {
#define PROXC_NAMESPACE_END }
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file pidfile.hpp
//----------------------------------------------------------------------------
/// \brief Creates and manages a file containing a process identifier.
/// This file is necessary for ease of administration of daemon processes.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <[email protected]>
// Created: 2011-02-18
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_PIDFILE_HPP_
#define _UTXX_PIDFILE_HPP_
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utxx/error.hpp>
#include <utxx/convert.hpp>
namespace utxx {
/**
* PID file manager
* Used to crete a file containing process identifier of currently
* running process. This file is used by administration scripts in
* order to be able to kill the process by pid.
*/
struct pid_file {
explicit pid_file(const char* a_filename, mode_t a_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
throw (io_error)
: m_filename(a_filename)
{
m_fd = open(a_filename, O_CREAT | O_RDWR | O_TRUNC, a_mode);
if (m_fd < 0)
throw io_error(errno, "Cannot open file:", a_filename);
pid_t pid = ::getpid();
std::string s = int_to_string(pid);
if (::write(m_fd, s.c_str(), s.size()) < 0)
throw io_error(errno, "Cannot write to file:", a_filename);
}
~pid_file() {
if (m_fd >= 0)
::close(m_fd);
::unlink(m_filename.c_str());
}
private:
std::string m_filename;
int m_fd;
};
} // namespace utxx
#endif // _UTXX_PIDFILE_HPP_
<commit_msg>Update pidfile.hpp<commit_after>//----------------------------------------------------------------------------
/// \file pidfile.hpp
//----------------------------------------------------------------------------
/// \brief Creates and manages a file containing a process identifier.
/// This file is necessary for ease of administration of daemon processes.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <[email protected]>
// Created: 2011-02-18
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#pragma once
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utxx/error.hpp>
#include <utxx/convert.hpp>
namespace utxx {
/**
* PID file manager
* Used to crete a file containing process identifier of currently
* running process. This file is used by administration scripts in
* order to be able to kill the process by pid.
*/
struct pid_file {
explicit pid_file(const char* a_filename, mode_t a_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
throw (io_error)
: m_filename(a_filename)
{
m_fd = open(a_filename, O_CREAT | O_RDWR | O_TRUNC, a_mode);
if (m_fd < 0)
throw io_error(errno, "Cannot open file:", a_filename);
pid_t pid = ::getpid();
std::string s = int_to_string(pid);
if (::write(m_fd, s.c_str(), s.size()) < 0)
throw io_error(errno, "Cannot write to file:", a_filename);
}
~pid_file() {
if (m_fd >= 0)
::close(m_fd);
::unlink(m_filename.c_str());
}
private:
std::string m_filename;
int m_fd;
};
} // namespace utxx
<|endoftext|> |
<commit_before>#include "indexer/feature_data.hpp"
#include "indexer/feature_impl.hpp"
#include "indexer/classificator.hpp"
#include "indexer/feature.hpp"
#include "base/assert.hpp"
#include "base/stl_add.hpp"
#include "std/algorithm.hpp"
#include "std/bind.hpp"
#include "std/vector.hpp"
using namespace feature;
////////////////////////////////////////////////////////////////////////////////////
// TypesHolder implementation
////////////////////////////////////////////////////////////////////////////////////
TypesHolder::TypesHolder(FeatureBase const & f)
: m_size(0), m_geoType(f.GetFeatureType())
{
f.ForEachType([this](uint32_t type)
{
this->operator()(type);
});
}
string TypesHolder::DebugPrint() const
{
Classificator const & c = classif();
string s;
for (uint32_t t : *this)
s += c.GetFullObjectName(t) + " ";
return s;
}
void TypesHolder::Remove(uint32_t t)
{
(void) RemoveIf(EqualFunctor<uint32_t>(t));
}
bool TypesHolder::Equals(TypesHolder const & other) const
{
vector<uint32_t> my(this->begin(), this->end());
vector<uint32_t> his(other.begin(), other.end());
sort(::begin(my), ::end(my));
sort(::begin(his), ::end(his));
return my == his;
}
namespace
{
class UselessTypesChecker
{
vector<uint32_t> m_types;
size_t m_count1;
template <size_t N, size_t M>
void AddTypes(char const * (&arr)[N][M])
{
Classificator const & c = classif();
for (size_t i = 0; i < N; ++i)
m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + M)));
}
public:
UselessTypesChecker()
{
// Fill types that will be taken into account last,
// when we have many types for POI.
// 1-arity
char const * arr1[][1] = {
{ "building" },
{ "hwtag" },
{ "internet_access" },
};
AddTypes(arr1);
m_count1 = m_types.size();
// 2-arity
char const * arr2[][2] = {
{ "amenity", "atm" }
};
AddTypes(arr2);
}
bool operator() (uint32_t t) const
{
auto const end1 = m_types.begin() + m_count1;
// check 2-arity types
ftype::TruncValue(t, 2);
if (find(end1, m_types.end(), t) != m_types.end())
return true;
// check 1-arity types
ftype::TruncValue(t, 1);
if (find(m_types.begin(), end1, t) != end1)
return true;
return false;
}
};
} // namespace
namespace feature
{
uint8_t CalculateHeader(uint32_t const typesCount, uint8_t const headerGeomType,
FeatureParamsBase const & params)
{
ASSERT(typesCount != 0, ("Feature should have at least one type."));
uint8_t header = static_cast<uint8_t>(typesCount - 1);
if (!params.name.IsEmpty())
header |= HEADER_HAS_NAME;
if (params.layer != 0)
header |= HEADER_HAS_LAYER;
header |= headerGeomType;
// Geometry type for additional info is only one.
switch (headerGeomType)
{
case HEADER_GEOM_POINT:
if (params.rank != 0)
header |= HEADER_HAS_ADDINFO;
break;
case HEADER_GEOM_LINE:
if (!params.ref.empty())
header |= HEADER_HAS_ADDINFO;
break;
case HEADER_GEOM_AREA:
case HEADER_GEOM_POINT_EX:
if (!params.house.IsEmpty())
header |= HEADER_HAS_ADDINFO;
break;
}
return header;
}
} // namespace feature
void TypesHolder::SortBySpec()
{
if (m_size < 2)
return;
// Put "very common" types to the end of possible PP-description types.
static UselessTypesChecker checker;
(void) RemoveIfKeepValid(m_types, m_types + m_size, bind<bool>(cref(checker), _1));
}
////////////////////////////////////////////////////////////////////////////////////
// FeatureParamsBase implementation
////////////////////////////////////////////////////////////////////////////////////
void FeatureParamsBase::MakeZero()
{
layer = 0;
rank = 0;
ref.clear();
house.Clear();
name.Clear();
}
bool FeatureParamsBase::operator == (FeatureParamsBase const & rhs) const
{
return (name == rhs.name && house == rhs.house && ref == rhs.ref &&
layer == rhs.layer && rank == rhs.rank);
}
bool FeatureParamsBase::CheckValid() const
{
CHECK(layer > LAYER_LOW && layer < LAYER_HIGH, ());
return true;
}
string FeatureParamsBase::DebugString() const
{
string const utf8name = DebugPrint(name);
return ((!utf8name.empty() ? "Name:" + utf8name : "") +
(rank != 0 ? " Rank:" + DebugPrint(rank) : "") +
(!house.IsEmpty() ? " House:" + house.Get() : "") +
(!ref.empty() ? " Ref:" + ref : ""));
}
bool FeatureParamsBase::IsEmptyNames() const
{
return name.IsEmpty() && house.IsEmpty() && ref.empty();
}
namespace
{
// Most used dummy values are taken from
// http://taginfo.openstreetmap.org/keys/addr%3Ahousename#values
bool IsDummyName(string const & s)
{
return (s.empty() ||
s == "Bloc" || s == "bloc" ||
s == "жилой дом" ||
s == "Edificio" || s == "edificio");
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// FeatureParams implementation
/////////////////////////////////////////////////////////////////////////////////////////
bool FeatureParams::AddName(string const & lang, string const & s)
{
if (IsDummyName(s))
return false;
// The "default" new name will replace the old one if any (e.g. from AddHouseName call).
name.AddString(lang, s);
return true;
}
bool FeatureParams::AddHouseName(string const & s)
{
if (IsDummyName(s) || name.FindString(s) != StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE)
return false;
// Most names are house numbers by statistics.
if (house.IsEmpty() && AddHouseNumber(s))
return true;
// Add as a default name if we don't have it yet.
string dummy;
if (!name.GetString(StringUtf8Multilang::DEFAULT_CODE, dummy))
{
name.AddString(StringUtf8Multilang::DEFAULT_CODE, s);
return true;
}
return false;
}
bool FeatureParams::AddHouseNumber(string const & ss)
{
if (!feature::IsHouseNumber(ss))
return false;
// Remove trailing zero's from house numbers.
// It's important for debug checks of serialized-deserialized feature.
string s(ss);
uint64_t n;
if (strings::to_uint64(s, n))
s = strings::to_string(n);
house.Set(s);
return true;
}
void FeatureParams::AddStreet(string s)
{
// Replace \n with spaces because we write addresses to txt file.
replace(s.begin(), s.end(), '\n', ' ');
m_addrTags.Add(AddressData::STREET, s);
}
void FeatureParams::AddAddress(string const & s)
{
size_t i = s.find_first_of("\t ");
if (i != string::npos)
{
string const house = s.substr(0, i);
if (feature::IsHouseNumber(house))
{
AddHouseNumber(house);
i = s.find_first_not_of("\t ", i);
}
else
{
i = 0;
}
}
else
{
i = 0;
}
AddStreet(s.substr(i));
}
void FeatureParams::AddPlace(string const & s)
{
m_addrTags.Add(AddressData::PLACE, s);
}
void FeatureParams::AddPostcode(string const & s)
{
m_addrTags.Add(AddressData::POSTCODE, s);
}
bool FeatureParams::FormatFullAddress(m2::PointD const & pt, string & res) const
{
string const street = GetStreet();
if (!street.empty() && !house.IsEmpty())
{
res = street + "|" + house.Get() + "|"
+ strings::to_string_dac(MercatorBounds::YToLat(pt.y), 8) + "|"
+ strings::to_string_dac(MercatorBounds::XToLon(pt.x), 8) + '\n';
return true;
}
return false;
}
string FeatureParams::GetStreet() const
{
return m_addrTags.Get(AddressData::STREET);
}
void FeatureParams::SetGeomType(feature::EGeomType t)
{
switch (t)
{
case GEOM_POINT: m_geomType = HEADER_GEOM_POINT; break;
case GEOM_LINE: m_geomType = HEADER_GEOM_LINE; break;
case GEOM_AREA: m_geomType = HEADER_GEOM_AREA; break;
default: ASSERT(false, ());
}
}
void FeatureParams::SetGeomTypePointEx()
{
ASSERT(m_geomType == HEADER_GEOM_POINT || m_geomType == HEADER_GEOM_POINT_EX, ());
ASSERT(!house.IsEmpty(), ());
m_geomType = HEADER_GEOM_POINT_EX;
}
feature::EGeomType FeatureParams::GetGeomType() const
{
CHECK_NOT_EQUAL(m_geomType, 0xFF, ());
switch (m_geomType)
{
case HEADER_GEOM_LINE: return GEOM_LINE;
case HEADER_GEOM_AREA: return GEOM_AREA;
default: return GEOM_POINT;
}
}
uint8_t FeatureParams::GetTypeMask() const
{
CHECK_NOT_EQUAL(m_geomType, 0xFF, ());
return m_geomType;
}
void FeatureParams::SetRwSubwayType(char const * cityName)
{
Classificator const & c = classif();
static uint32_t const src = c.GetTypeByPath({"railway", "station"});
uint32_t const dest = c.GetTypeByPath({"railway", "station", "subway", cityName});
for (size_t i = 0; i < m_Types.size(); ++i)
{
uint32_t t = m_Types[i];
ftype::TruncValue(t, 2);
if (t == src)
{
m_Types[i] = dest;
break;
}
}
}
void FeatureParams::AddTypes(FeatureParams const & rhs, uint32_t skipType2)
{
if (skipType2 == 0)
{
m_Types.insert(m_Types.end(), rhs.m_Types.begin(), rhs.m_Types.end());
}
else
{
for (size_t i = 0; i < rhs.m_Types.size(); ++i)
{
uint32_t t = rhs.m_Types[i];
ftype::TruncValue(t, 2);
if (t != skipType2)
m_Types.push_back(rhs.m_Types[i]);
}
}
}
bool FeatureParams::FinishAddingTypes()
{
static uint32_t const boundary = classif().GetTypeByPath({ "boundary", "administrative" });
vector<uint32_t> newTypes;
newTypes.reserve(m_Types.size());
for (size_t i = 0; i < m_Types.size(); ++i)
{
uint32_t candidate = m_Types[i];
// Assume that classificator types are equal if they are equal for 2-arity dimension
// (e.g. "place-city-capital" is equal to "place-city" and we leave the longest one "place-city-capital").
// The only exception is "boundary-administrative" type.
uint32_t type = m_Types[i];
ftype::TruncValue(type, 2);
if (type != boundary)
{
// Find all equal types (2-arity).
auto j = RemoveIfKeepValid(m_Types.begin() + i + 1, m_Types.end(), [type] (uint32_t t)
{
ftype::TruncValue(t, 2);
return (type == t);
});
// Choose the best type from equals by arity level.
for (auto k = j; k != m_Types.end(); ++k)
if (ftype::GetLevel(*k) > ftype::GetLevel(candidate))
candidate = *k;
// Delete equal types.
m_Types.erase(j, m_Types.end());
}
newTypes.push_back(candidate);
}
// Remove duplicated types.
sort(newTypes.begin(), newTypes.end());
newTypes.erase(unique(newTypes.begin(), newTypes.end()), newTypes.end());
m_Types.swap(newTypes);
if (m_Types.size() > max_types_count)
m_Types.resize(max_types_count);
return !m_Types.empty();
}
void FeatureParams::SetType(uint32_t t)
{
m_Types.clear();
m_Types.push_back(t);
}
bool FeatureParams::PopAnyType(uint32_t & t)
{
CHECK(!m_Types.empty(), ());
t = m_Types.back();
m_Types.pop_back();
return m_Types.empty();
}
bool FeatureParams::PopExactType(uint32_t t)
{
m_Types.erase(remove(m_Types.begin(), m_Types.end(), t), m_Types.end());
return m_Types.empty();
}
bool FeatureParams::IsTypeExist(uint32_t t) const
{
return (find(m_Types.begin(), m_Types.end(), t) != m_Types.end());
}
uint32_t FeatureParams::FindType(uint32_t comp, uint8_t level) const
{
for (uint32_t const type : m_Types)
{
uint32_t t = type;
ftype::TruncValue(t, level);
if (t == comp)
return type;
}
return ftype::GetEmptyValue();
}
bool FeatureParams::CheckValid() const
{
CHECK(!m_Types.empty() && m_Types.size() <= max_types_count, ());
CHECK_NOT_EQUAL(m_geomType, 0xFF, ());
return FeatureParamsBase::CheckValid();
}
uint8_t FeatureParams::GetHeader() const
{
return CalculateHeader(m_Types.size(), GetTypeMask(), *this);
}
uint32_t FeatureParams::GetIndexForType(uint32_t t)
{
return classif().GetIndexForType(t);
}
uint32_t FeatureParams::GetTypeForIndex(uint32_t i)
{
return classif().GetTypeForIndex(i);
}
string DebugPrint(FeatureParams const & p)
{
Classificator const & c = classif();
string res = "Types";
for (size_t i = 0; i < p.m_Types.size(); ++i)
res += (" : " + c.GetReadableObjectName(p.m_Types[i]));
return (res + p.DebugString());
}
<commit_msg>Added more building “useless” types.<commit_after>#include "indexer/feature_data.hpp"
#include "indexer/feature_impl.hpp"
#include "indexer/classificator.hpp"
#include "indexer/feature.hpp"
#include "base/assert.hpp"
#include "base/stl_add.hpp"
#include "std/algorithm.hpp"
#include "std/bind.hpp"
#include "std/vector.hpp"
using namespace feature;
////////////////////////////////////////////////////////////////////////////////////
// TypesHolder implementation
////////////////////////////////////////////////////////////////////////////////////
TypesHolder::TypesHolder(FeatureBase const & f)
: m_size(0), m_geoType(f.GetFeatureType())
{
f.ForEachType([this](uint32_t type)
{
this->operator()(type);
});
}
string TypesHolder::DebugPrint() const
{
Classificator const & c = classif();
string s;
for (uint32_t t : *this)
s += c.GetFullObjectName(t) + " ";
return s;
}
void TypesHolder::Remove(uint32_t t)
{
(void) RemoveIf(EqualFunctor<uint32_t>(t));
}
bool TypesHolder::Equals(TypesHolder const & other) const
{
vector<uint32_t> my(this->begin(), this->end());
vector<uint32_t> his(other.begin(), other.end());
sort(::begin(my), ::end(my));
sort(::begin(his), ::end(his));
return my == his;
}
namespace
{
class UselessTypesChecker
{
vector<uint32_t> m_types;
size_t m_count1;
template <size_t N, size_t M>
void AddTypes(char const * (&arr)[N][M])
{
Classificator const & c = classif();
for (size_t i = 0; i < N; ++i)
m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + M)));
}
public:
UselessTypesChecker()
{
// Fill types that will be taken into account last,
// when we have many types for POI.
// 1-arity
char const * arr1[][1] = {
{ "building" },
{ "building:part" },
{ "hwtag" },
{ "internet_access" },
};
AddTypes(arr1);
m_count1 = m_types.size();
// 2-arity
char const * arr2[][2] = {
{ "amenity", "atm" },
{ "building", "address" },
};
AddTypes(arr2);
}
bool operator() (uint32_t t) const
{
auto const end1 = m_types.begin() + m_count1;
// check 2-arity types
ftype::TruncValue(t, 2);
if (find(end1, m_types.end(), t) != m_types.end())
return true;
// check 1-arity types
ftype::TruncValue(t, 1);
if (find(m_types.begin(), end1, t) != end1)
return true;
return false;
}
};
} // namespace
namespace feature
{
uint8_t CalculateHeader(uint32_t const typesCount, uint8_t const headerGeomType,
FeatureParamsBase const & params)
{
ASSERT(typesCount != 0, ("Feature should have at least one type."));
uint8_t header = static_cast<uint8_t>(typesCount - 1);
if (!params.name.IsEmpty())
header |= HEADER_HAS_NAME;
if (params.layer != 0)
header |= HEADER_HAS_LAYER;
header |= headerGeomType;
// Geometry type for additional info is only one.
switch (headerGeomType)
{
case HEADER_GEOM_POINT:
if (params.rank != 0)
header |= HEADER_HAS_ADDINFO;
break;
case HEADER_GEOM_LINE:
if (!params.ref.empty())
header |= HEADER_HAS_ADDINFO;
break;
case HEADER_GEOM_AREA:
case HEADER_GEOM_POINT_EX:
if (!params.house.IsEmpty())
header |= HEADER_HAS_ADDINFO;
break;
}
return header;
}
} // namespace feature
void TypesHolder::SortBySpec()
{
if (m_size < 2)
return;
// Put "very common" types to the end of possible PP-description types.
static UselessTypesChecker checker;
(void) RemoveIfKeepValid(m_types, m_types + m_size, bind<bool>(cref(checker), _1));
}
////////////////////////////////////////////////////////////////////////////////////
// FeatureParamsBase implementation
////////////////////////////////////////////////////////////////////////////////////
void FeatureParamsBase::MakeZero()
{
layer = 0;
rank = 0;
ref.clear();
house.Clear();
name.Clear();
}
bool FeatureParamsBase::operator == (FeatureParamsBase const & rhs) const
{
return (name == rhs.name && house == rhs.house && ref == rhs.ref &&
layer == rhs.layer && rank == rhs.rank);
}
bool FeatureParamsBase::CheckValid() const
{
CHECK(layer > LAYER_LOW && layer < LAYER_HIGH, ());
return true;
}
string FeatureParamsBase::DebugString() const
{
string const utf8name = DebugPrint(name);
return ((!utf8name.empty() ? "Name:" + utf8name : "") +
(rank != 0 ? " Rank:" + DebugPrint(rank) : "") +
(!house.IsEmpty() ? " House:" + house.Get() : "") +
(!ref.empty() ? " Ref:" + ref : ""));
}
bool FeatureParamsBase::IsEmptyNames() const
{
return name.IsEmpty() && house.IsEmpty() && ref.empty();
}
namespace
{
// Most used dummy values are taken from
// http://taginfo.openstreetmap.org/keys/addr%3Ahousename#values
bool IsDummyName(string const & s)
{
return (s.empty() ||
s == "Bloc" || s == "bloc" ||
s == "жилой дом" ||
s == "Edificio" || s == "edificio");
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// FeatureParams implementation
/////////////////////////////////////////////////////////////////////////////////////////
bool FeatureParams::AddName(string const & lang, string const & s)
{
if (IsDummyName(s))
return false;
// The "default" new name will replace the old one if any (e.g. from AddHouseName call).
name.AddString(lang, s);
return true;
}
bool FeatureParams::AddHouseName(string const & s)
{
if (IsDummyName(s) || name.FindString(s) != StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE)
return false;
// Most names are house numbers by statistics.
if (house.IsEmpty() && AddHouseNumber(s))
return true;
// Add as a default name if we don't have it yet.
string dummy;
if (!name.GetString(StringUtf8Multilang::DEFAULT_CODE, dummy))
{
name.AddString(StringUtf8Multilang::DEFAULT_CODE, s);
return true;
}
return false;
}
bool FeatureParams::AddHouseNumber(string const & ss)
{
if (!feature::IsHouseNumber(ss))
return false;
// Remove trailing zero's from house numbers.
// It's important for debug checks of serialized-deserialized feature.
string s(ss);
uint64_t n;
if (strings::to_uint64(s, n))
s = strings::to_string(n);
house.Set(s);
return true;
}
void FeatureParams::AddStreet(string s)
{
// Replace \n with spaces because we write addresses to txt file.
replace(s.begin(), s.end(), '\n', ' ');
m_addrTags.Add(AddressData::STREET, s);
}
void FeatureParams::AddAddress(string const & s)
{
size_t i = s.find_first_of("\t ");
if (i != string::npos)
{
string const house = s.substr(0, i);
if (feature::IsHouseNumber(house))
{
AddHouseNumber(house);
i = s.find_first_not_of("\t ", i);
}
else
{
i = 0;
}
}
else
{
i = 0;
}
AddStreet(s.substr(i));
}
void FeatureParams::AddPlace(string const & s)
{
m_addrTags.Add(AddressData::PLACE, s);
}
void FeatureParams::AddPostcode(string const & s)
{
m_addrTags.Add(AddressData::POSTCODE, s);
}
bool FeatureParams::FormatFullAddress(m2::PointD const & pt, string & res) const
{
string const street = GetStreet();
if (!street.empty() && !house.IsEmpty())
{
res = street + "|" + house.Get() + "|"
+ strings::to_string_dac(MercatorBounds::YToLat(pt.y), 8) + "|"
+ strings::to_string_dac(MercatorBounds::XToLon(pt.x), 8) + '\n';
return true;
}
return false;
}
string FeatureParams::GetStreet() const
{
return m_addrTags.Get(AddressData::STREET);
}
void FeatureParams::SetGeomType(feature::EGeomType t)
{
switch (t)
{
case GEOM_POINT: m_geomType = HEADER_GEOM_POINT; break;
case GEOM_LINE: m_geomType = HEADER_GEOM_LINE; break;
case GEOM_AREA: m_geomType = HEADER_GEOM_AREA; break;
default: ASSERT(false, ());
}
}
void FeatureParams::SetGeomTypePointEx()
{
ASSERT(m_geomType == HEADER_GEOM_POINT || m_geomType == HEADER_GEOM_POINT_EX, ());
ASSERT(!house.IsEmpty(), ());
m_geomType = HEADER_GEOM_POINT_EX;
}
feature::EGeomType FeatureParams::GetGeomType() const
{
CHECK_NOT_EQUAL(m_geomType, 0xFF, ());
switch (m_geomType)
{
case HEADER_GEOM_LINE: return GEOM_LINE;
case HEADER_GEOM_AREA: return GEOM_AREA;
default: return GEOM_POINT;
}
}
uint8_t FeatureParams::GetTypeMask() const
{
CHECK_NOT_EQUAL(m_geomType, 0xFF, ());
return m_geomType;
}
void FeatureParams::SetRwSubwayType(char const * cityName)
{
Classificator const & c = classif();
static uint32_t const src = c.GetTypeByPath({"railway", "station"});
uint32_t const dest = c.GetTypeByPath({"railway", "station", "subway", cityName});
for (size_t i = 0; i < m_Types.size(); ++i)
{
uint32_t t = m_Types[i];
ftype::TruncValue(t, 2);
if (t == src)
{
m_Types[i] = dest;
break;
}
}
}
void FeatureParams::AddTypes(FeatureParams const & rhs, uint32_t skipType2)
{
if (skipType2 == 0)
{
m_Types.insert(m_Types.end(), rhs.m_Types.begin(), rhs.m_Types.end());
}
else
{
for (size_t i = 0; i < rhs.m_Types.size(); ++i)
{
uint32_t t = rhs.m_Types[i];
ftype::TruncValue(t, 2);
if (t != skipType2)
m_Types.push_back(rhs.m_Types[i]);
}
}
}
bool FeatureParams::FinishAddingTypes()
{
static uint32_t const boundary = classif().GetTypeByPath({ "boundary", "administrative" });
vector<uint32_t> newTypes;
newTypes.reserve(m_Types.size());
for (size_t i = 0; i < m_Types.size(); ++i)
{
uint32_t candidate = m_Types[i];
// Assume that classificator types are equal if they are equal for 2-arity dimension
// (e.g. "place-city-capital" is equal to "place-city" and we leave the longest one "place-city-capital").
// The only exception is "boundary-administrative" type.
uint32_t type = m_Types[i];
ftype::TruncValue(type, 2);
if (type != boundary)
{
// Find all equal types (2-arity).
auto j = RemoveIfKeepValid(m_Types.begin() + i + 1, m_Types.end(), [type] (uint32_t t)
{
ftype::TruncValue(t, 2);
return (type == t);
});
// Choose the best type from equals by arity level.
for (auto k = j; k != m_Types.end(); ++k)
if (ftype::GetLevel(*k) > ftype::GetLevel(candidate))
candidate = *k;
// Delete equal types.
m_Types.erase(j, m_Types.end());
}
newTypes.push_back(candidate);
}
// Remove duplicated types.
sort(newTypes.begin(), newTypes.end());
newTypes.erase(unique(newTypes.begin(), newTypes.end()), newTypes.end());
m_Types.swap(newTypes);
if (m_Types.size() > max_types_count)
m_Types.resize(max_types_count);
return !m_Types.empty();
}
void FeatureParams::SetType(uint32_t t)
{
m_Types.clear();
m_Types.push_back(t);
}
bool FeatureParams::PopAnyType(uint32_t & t)
{
CHECK(!m_Types.empty(), ());
t = m_Types.back();
m_Types.pop_back();
return m_Types.empty();
}
bool FeatureParams::PopExactType(uint32_t t)
{
m_Types.erase(remove(m_Types.begin(), m_Types.end(), t), m_Types.end());
return m_Types.empty();
}
bool FeatureParams::IsTypeExist(uint32_t t) const
{
return (find(m_Types.begin(), m_Types.end(), t) != m_Types.end());
}
uint32_t FeatureParams::FindType(uint32_t comp, uint8_t level) const
{
for (uint32_t const type : m_Types)
{
uint32_t t = type;
ftype::TruncValue(t, level);
if (t == comp)
return type;
}
return ftype::GetEmptyValue();
}
bool FeatureParams::CheckValid() const
{
CHECK(!m_Types.empty() && m_Types.size() <= max_types_count, ());
CHECK_NOT_EQUAL(m_geomType, 0xFF, ());
return FeatureParamsBase::CheckValid();
}
uint8_t FeatureParams::GetHeader() const
{
return CalculateHeader(m_Types.size(), GetTypeMask(), *this);
}
uint32_t FeatureParams::GetIndexForType(uint32_t t)
{
return classif().GetIndexForType(t);
}
uint32_t FeatureParams::GetTypeForIndex(uint32_t i)
{
return classif().GetTypeForIndex(i);
}
string DebugPrint(FeatureParams const & p)
{
Classificator const & c = classif();
string res = "Types";
for (size_t i = 0; i < p.m_Types.size(); ++i)
res += (" : " + c.GetReadableObjectName(p.m_Types[i]));
return (res + p.DebugString());
}
<|endoftext|> |
<commit_before>#include "decrypt.h"
Tag5::Ptr find_decrypting_key(const PGP & k, const std::string &keyid){
if (k.get_ASCII_Armor() == 2){
std::vector <Packet::Ptr> packets = k.get_packets();
for(Packet::Ptr const & p : packets){
if ((p -> get_tag() == 5) || (p -> get_tag() == 7)){
std::string data = p -> raw();
Tag5::Ptr key = std::make_shared<Tag5>(data);
if ( key->get_public_ptr()->get_keyid() != keyid ){
continue;
}
// make sure key has signing material
if ((key -> get_pka() == 1) || // RSA
(key -> get_pka() == 2) || // RSA
(key -> get_pka() == 16)){ // ElGamal
return key;
}
}
}
}
return Tag5::Ptr();
}
std::string pka_decrypt(const uint8_t pka, std::vector <PGPMPI> & data, const std::vector <PGPMPI> & pri, const std::vector <PGPMPI> & pub){
if (pka < 3){ // RSA
return mpitoraw(RSA_decrypt(data[0], pri, pub));
}
if (pka == 16){ // ElGamal
return ElGamal_decrypt(data, pri, pub);
}
else{
std::stringstream s; s << static_cast <int> (pka);
throw std::runtime_error("Error: PKA number " + s.str() + " not allowed or unknown.");
}
return ""; // should never reach here; mainly just to remove compiler warnings
}
std::vector <PGPMPI> decrypt_secret_key(const Tag5::Ptr & pri, const std::string & passphrase){
std::vector <PGPMPI> out;
S2K::Ptr s2k = pri -> get_s2k();
// calculate key used in encryption algorithm
std::string key = s2k -> run(passphrase, Symmetric_Algorithm_Key_Length.at(Symmetric_Algorithms.at(pri -> get_sym())) >> 3);
// decrypt secret key
std::string secret_key = use_normal_CFB_decrypt(pri -> get_sym(), pri -> get_secret(), key, pri -> get_IV());
// get checksum and remove it from the string
const unsigned int hash_size = (pri -> get_s2k_con() == 254)?20:2;
std::string checksum = secret_key.substr(secret_key.size() - hash_size, hash_size);
secret_key = secret_key.substr(0, secret_key.size() - hash_size);
// calculate and check checksum
if(pri -> get_s2k_con() == 254){
if (use_hash(s2k -> get_hash(), secret_key) != checksum){
throw std::runtime_error("Error: Secret key checksum and calculated checksum do not match.");
}
}
else{ // all other values; **UNTESTED**
uint16_t sum = 0;
for(char & c : secret_key){
sum += static_cast <unsigned char> (c);
}
if (unhexlify(makehex(sum, 4)) != checksum){
if (use_hash(s2k -> get_hash(), secret_key) != checksum){
throw std::runtime_error("Error: Secret key checksum and calculated checksum do not match.");
}
}
}
// extract MPI values
while (secret_key.size()){
out.push_back(read_MPI(secret_key));
}
return out;
}
std::string decrypt_message(PGP & m, PGP& pri, const std::string & passphrase){
if ((m.get_ASCII_Armor() != 0)/* && (m.get_ASCII_Armor() != 3) && (m.get_ASCII_Armor() != 4)*/){
throw std::runtime_error("Error: No encrypted message found.");
}
if (pri.get_ASCII_Armor() != 2){
throw std::runtime_error("Error: No Private Key found.");
}
// reused variables
uint8_t packet;
std::string data;
std::string checksum;
std::string session_key; // session key
uint8_t sym; // symmetric key algorithm used to encrypt original data
unsigned int BS; // blocksize of symmetric key algorithm
// find session key
std::vector <Packet::Ptr> message_packets = m.get_packets();
for(Packet::Ptr const & p : message_packets){
if ((p -> get_tag() == 1) || (p -> get_tag() == 3)){
data = p -> raw();
packet = p -> get_tag();
break;
}
}
if (packet == 1){ // Public-Key Encrypted Session Key Packet (Tag 1)
Tag1 tag1(data);
uint8_t pka = tag1.get_pka();
std::vector <PGPMPI> session_key_mpi = tag1.get_mpi();
// find corresponding secret key
Tag5::Ptr sec = find_decrypting_key(pri, tag1.get_keyid());
if (!sec){
throw std::runtime_error("Error: Correct Private Key not found.");
}
std::vector <PGPMPI> pub = sec -> get_mpi();
std::vector <PGPMPI> pri = decrypt_secret_key(sec, passphrase);
// get session key
session_key = zero + pka_decrypt(pka, session_key_mpi, pri, pub); // symmetric algorithm, session key, 2 octet checksum wrapped in EME_PKCS1_ENCODE
session_key = EME_PKCS1v1_5_DECODE(session_key); // remove EME_PKCS1 encoding
sym = session_key[0]; // get symmetric algorithm
checksum = session_key.substr(session_key.size() - 2, 2); // get 2 octet checksum
session_key = session_key.substr(1, session_key.size() - 3); // remove both from session key
uint16_t sum = 0;
for(char & c : session_key){ // calculate session key checksum
sum += static_cast <uint8_t> (c);
}
if (unhexlify(makehex(sum, 4)) != checksum){ // check session key checksums
throw std::runtime_error("Error: Calculated session key checksum does not match given checksum.");
}
}
else if (packet == 3){ //Symmetric-Key Encrypted Session Key Packet (Tag 3)
/* untested */
Tag3 tag3(data);
data = tag3.get_key(passphrase);
sym = data[0];
session_key = data.substr(1, data.size() - 1);
}
else{
throw std::runtime_error("Error: No session key packet found.");
}
BS = Symmetric_Algorithm_Block_Length.at(Symmetric_Algorithms.at(sym)) >> 3; // get blocksize
// Find encrypted data
data = "";
for(Packet::Ptr const & p : message_packets){
if (p -> get_tag() == 9){
data = p -> raw();
Tag9 tag9(data);
data = tag9.get_encrypted_data();
packet = 9;
break;
}
else if (p -> get_tag() == 18){
data = p -> raw();
Tag18 tag18(data);
data = tag18.get_protected_data();
packet = 18;
break;
}
}
if (!data.size()){
throw std::runtime_error("Error: No encrypted data packets found.");
}
if (sym == 2){ // Triple DES
data = use_OpenPGP_CFB_decrypt(sym, packet, data, session_key.substr(0, 8), session_key.substr(8, 8), session_key.substr(16, 8)); // decrypt encrypted data
}
else{
data = use_OpenPGP_CFB_decrypt(sym, packet, data, session_key); // decrypt encrypted data
}
if (packet == 18){ // Symmetrically Encrypted Integrity Protected Data Packet (Tag 18)
checksum = data.substr(data.size() - 20, 20); // get given SHA1 checksum
data = data.substr(0, data.size() - 20); // remove SHA1 checksum
if (use_hash(2, data) != checksum){ // check SHA1 checksum
throw std::runtime_error("Error: Given checksum and calculated checksum do not match.");
}
data = data.substr(0, data.size() - 2); // get rid of \xd3\x14
}
data = data.substr(BS + 2, data.size() - BS - 2); // get rid of prefix
if (packet == 9){ // Symmetrically Encrypted Data Packet (Tag 9)
// figure out which compression algorithm was used
// uncompressed literal data packet
if ((data[0] == 'b') || (data[0] == 't') || (data[0] == 'u')){
data = Tag11(data).write(); // add in Tag11 headers to be removed later
}
// BZIP2
else if (data.substr(0, 2) == "BZ"){
data = PGP_decompress(3, data);
}
// ZLIB
else if ((data.substr(0, 2) == "\x78\x01") || (data.substr(0, 2) == "\x78\x9c") || (data.substr(0, 2) == "\x78\xda")){
data = PGP_decompress(2, data);
}
// DEFLATE
else{
data = PGP_decompress(1, data);
}
}
// get rid of header and figure out what type of packet data it is
bool format;
data = read_packet_header(data, packet, format);
// output data
switch (packet){
case 8: // Compressed Data Packet
{
data = Tag8(data).get_data(); // compressed packets
std::vector <Packet::Ptr> compressed_packets;
while (data.size()){ // extract packets
compressed_packets.push_back(read_packet(data) -> clone());
}
// extract all packet data; probably needs better formatting
for(const Packet::Ptr & p : compressed_packets){
if (p -> get_tag() == 11){
Tag11 tag11(data);
if (tag11.get_filename() == ""){
data = tag11.get_literal();
}
else{
tag11.write();
data = "Data written to file '" + Tag11(data).get_filename() + "'";
}
}
// else{
// data += p -> show() + "\n";
// }
}
}
break;
case 11: // Literal Data Packet
{
Tag11 tag11(data);
if (tag11.get_filename() == ""){
data = tag11.get_literal();
}
else{
tag11.write();
data = "Data written to file '" + Tag11(data).get_filename() + "'";
}
}
break;
default:
{
std::stringstream s; s << packet;
throw std::runtime_error("Error: No action defined for packet type " + s.str());
}
break;
}
return data;
}
<commit_msg>Debug time<commit_after>#include "decrypt.h"
Tag5::Ptr find_decrypting_key(const PGP & k, const std::string &keyid){
if (k.get_ASCII_Armor() == 2){
std::vector <Packet::Ptr> packets = k.get_packets();
for(Packet::Ptr const & p : packets){
if ((p -> get_tag() == 5) || (p -> get_tag() == 7)){
std::string data = p -> raw();
Tag5::Ptr key = std::make_shared<Tag5>(data);
if ( key->get_public_ptr()->get_keyid() != keyid ){
continue;
}
// make sure key has signing material
if ((key -> get_pka() == 1) || // RSA
(key -> get_pka() == 2) || // RSA
(key -> get_pka() == 16)){ // ElGamal
return key;
}
}
}
}
return Tag5::Ptr();
}
std::string pka_decrypt(const uint8_t pka, std::vector <PGPMPI> & data, const std::vector <PGPMPI> & pri, const std::vector <PGPMPI> & pub){
if (pka < 3){ // RSA
return mpitoraw(RSA_decrypt(data[0], pri, pub));
}
if (pka == 16){ // ElGamal
return ElGamal_decrypt(data, pri, pub);
}
else{
std::stringstream s; s << static_cast <int> (pka);
throw std::runtime_error("Error: PKA number " + s.str() + " not allowed or unknown.");
}
return ""; // should never reach here; mainly just to remove compiler warnings
}
std::vector <PGPMPI> decrypt_secret_key(const Tag5::Ptr & pri, const std::string & passphrase){
std::vector <PGPMPI> out;
S2K::Ptr s2k = pri -> get_s2k();
// calculate key used in encryption algorithm
std::string key = s2k -> run(passphrase, Symmetric_Algorithm_Key_Length.at(Symmetric_Algorithms.at(pri -> get_sym())) >> 3);
// decrypt secret key
std::string secret_key = use_normal_CFB_decrypt(pri -> get_sym(), pri -> get_secret(), key, pri -> get_IV());
// get checksum and remove it from the string
const unsigned int hash_size = (pri -> get_s2k_con() == 254)?20:2;
std::string checksum = secret_key.substr(secret_key.size() - hash_size, hash_size);
secret_key = secret_key.substr(0, secret_key.size() - hash_size);
// calculate and check checksum
if(pri -> get_s2k_con() == 254){
if (use_hash(s2k -> get_hash(), secret_key) != checksum){
throw std::runtime_error("Error: Secret key checksum and calculated checksum do not match.");
}
}
else{ // all other values; **UNTESTED**
uint16_t sum = 0;
for(char & c : secret_key){
sum += static_cast <unsigned char> (c);
}
if (unhexlify(makehex(sum, 4)) != checksum){
if (use_hash(s2k -> get_hash(), secret_key) != checksum){
throw std::runtime_error("Error: Secret key checksum and calculated checksum do not match.");
}
}
}
// extract MPI values
while (secret_key.size()){
out.push_back(read_MPI(secret_key));
}
return out;
}
std::string decrypt_message(PGP & m, PGP& pri, const std::string & passphrase){
if ((m.get_ASCII_Armor() != 0)/* && (m.get_ASCII_Armor() != 3) && (m.get_ASCII_Armor() != 4)*/){
throw std::runtime_error("Error: No encrypted message found.");
}
if (pri.get_ASCII_Armor() != 2){
throw std::runtime_error("Error: No Private Key found.");
}
// reused variables
uint8_t packet;
std::string data;
std::string checksum;
std::string session_key; // session key
uint8_t sym; // symmetric key algorithm used to encrypt original data
unsigned int BS; // blocksize of symmetric key algorithm
// find session key
std::vector <Packet::Ptr> message_packets = m.get_packets();
for(Packet::Ptr const & p : message_packets){
if ((p -> get_tag() == 1) || (p -> get_tag() == 3)){
data = p -> raw();
packet = p -> get_tag();
break;
}
}
if (packet == 1){ // Public-Key Encrypted Session Key Packet (Tag 1)
Tag1 tag1(data);
uint8_t pka = tag1.get_pka();
std::vector <PGPMPI> session_key_mpi = tag1.get_mpi();
// find corresponding secret key
Tag5::Ptr sec = find_decrypting_key(pri, tag1.get_keyid());
if (!sec){
throw std::runtime_error("Error: Correct Private Key not found.");
}
std::vector <PGPMPI> pub = sec -> get_mpi();
std::vector <PGPMPI> pri = decrypt_secret_key(sec, passphrase);
// get session key
session_key = zero + pka_decrypt(pka, session_key_mpi, pri, pub); // symmetric algorithm, session key, 2 octet checksum wrapped in EME_PKCS1_ENCODE
session_key = EME_PKCS1v1_5_DECODE(session_key); // remove EME_PKCS1 encoding
sym = session_key[0]; // get symmetric algorithm
checksum = session_key.substr(session_key.size() - 2, 2); // get 2 octet checksum
session_key = session_key.substr(1, session_key.size() - 3); // remove both from session key
uint16_t sum = 0;
for(char & c : session_key){ // calculate session key checksum
sum += static_cast <uint8_t> (c);
}
if (unhexlify(makehex(sum, 4)) != checksum){ // check session key checksums
throw std::runtime_error("Error: Calculated session key checksum does not match given checksum.");
}
}
else if (packet == 3){ //Symmetric-Key Encrypted Session Key Packet (Tag 3)
/* untested */
Tag3 tag3(data);
data = tag3.get_key(passphrase);
sym = data[0];
session_key = data.substr(1, data.size() - 1);
}
else{
throw std::runtime_error("Error: No session key packet found.");
}
BS = Symmetric_Algorithm_Block_Length.at(Symmetric_Algorithms.at(sym)) >> 3; // get blocksize
// Find encrypted data
data = "";
for(Packet::Ptr const & p : message_packets){
if (p -> get_tag() == 9){
data = p -> raw();
Tag9 tag9(data);
data = tag9.get_encrypted_data();
packet = 9;
break;
}
else if (p -> get_tag() == 18){
data = p -> raw();
Tag18 tag18(data);
data = tag18.get_protected_data();
packet = 18;
break;
}
}
if (!data.size()){
throw std::runtime_error("Error: No encrypted data packets found.");
}
if (sym == 2){ // Triple DES
data = use_OpenPGP_CFB_decrypt(sym, packet, data, session_key.substr(0, 8), session_key.substr(8, 8), session_key.substr(16, 8)); // decrypt encrypted data
}
else{
data = use_OpenPGP_CFB_decrypt(sym, packet, data, session_key); // decrypt encrypted data
}
if (packet == 18){ // Symmetrically Encrypted Integrity Protected Data Packet (Tag 18)
checksum = data.substr(data.size() - 20, 20); // get given SHA1 checksum
data = data.substr(0, data.size() - 20); // remove SHA1 checksum
if (use_hash(2, data) != checksum){ // check SHA1 checksum
throw std::runtime_error("Error: Given checksum and calculated checksum do not match.");
}
data = data.substr(0, data.size() - 2); // get rid of \xd3\x14
}
data = data.substr(BS + 2, data.size() - BS - 2); // get rid of prefix
if (packet == 9){ // Symmetrically Encrypted Data Packet (Tag 9)
// figure out which compression algorithm was used
// uncompressed literal data packet
if ((data[0] == 'b') || (data[0] == 't') || (data[0] == 'u')){
data = Tag11(data).write(); // add in Tag11 headers to be removed later
}
// BZIP2
else if (data.substr(0, 2) == "BZ"){
data = PGP_decompress(3, data);
}
// ZLIB
else if ((data.substr(0, 2) == "\x78\x01") || (data.substr(0, 2) == "\x78\x9c") || (data.substr(0, 2) == "\x78\xda")){
data = PGP_decompress(2, data);
}
// DEFLATE
else{
data = PGP_decompress(1, data);
}
}
// get rid of header and figure out what type of packet data it is
bool format;
data = read_packet_header(data, packet, format);
// output data
switch (packet){
case 8: // Compressed Data Packet
{
data = Tag8(data).get_data(); // compressed packets
std::vector <Packet::Ptr> compressed_packets;
while (data.size()){ // extract packets
compressed_packets.push_back(read_packet(data) -> clone());
}
// extract all packet data; probably needs better formatting
for(const Packet::Ptr & p : compressed_packets){
if (p -> get_tag() == 11){
Tag11 tag11(data);
if (tag11.get_filename() == ""){
data = tag11.get_literal();
}
else{
tag11.write();
data = "Data written to file '" + Tag11(data).get_filename() + "'";
}
std::cout << data << std::endl;
}
// else{
// data += p -> show() + "\n";
// }
}
}
break;
case 11: // Literal Data Packet
{
Tag11 tag11(data);
if (tag11.get_filename() == ""){
data = tag11.get_literal();
}
else{
tag11.write();
data = "Data written to file '" + Tag11(data).get_filename() + "'";
}
}
break;
default:
{
std::stringstream s; s << packet;
throw std::runtime_error("Error: No action defined for packet type " + s.str());
}
break;
}
return data;
}
<|endoftext|> |
<commit_before>/* JCHOR - random-wait chorus instrument based on Paul Lansky's chor
and Doug Scott's trans code
p0 = output start time
p1 = input start time
p2 = output duration
p3 = input duration (not input end time)
p4 = maintain input duration, regardless of transposition (1: yes, 0: no)
p5 = transposition (8ve.pc)
p6 = number of voices (minimum of 1)
p7 = minimum grain amplitude
p8 = maximum grain amplitude
p9 = minimum grain wait (seconds)
p10 = maximum grain wait (seconds)
p11 = seed (0 - 1)
p12 = input channel [optional; if missing and input has > 1 chan, input
channels averaged]
p13 = overall amplitude multiplier [optional; if missing, must use gen 1 *]
p14 = reference to grain envelope table [optional; if missing, must use
gen 2 **]
p7 (min amp), p8 (max amp), p9 (min wait), p10 (max wait) and p13 (amp mult)
can receive dynamic updates from a table or real-time control source.
Output can be either mono or stereo. If it's stereo, the program randomly
distributes the voices across the stereo field.
Notes on p4 (maintain input duration):
Because the transposition method doesn't try to maintain duration -- it
works like the speed control on a tape deck -- you have an option about
the way to handle the duration of the input read:
- If p4 is 1, the grain length after transposition will be the same as
that given by p3 (input duration). This means that the amount actually
read from the input file will be shorter or longer than p3, depending
on the transposition.
- If p4 is 0, the segment of sound specified by p3 will be read, and the
grain length will be shorter or longer than p3, depending on the
transposition.
----
Notes about backward compatibility with pre-v4 scores:
* If an old-style gen table 1 is present, its values will be multiplied
by p13 (amplitude multiplier), even if the latter is dynamic.
** If p14 is missing, you must use an old-style gen table 2 for the
grain envelope.
----
Differences between JCHOR and chor (besides RT ability):
- No limit on input duration or number of voices
- Transpose the input signal
- Specify the input channel to use (or an average of them)
- Specify overall amplitude curve and grain window function
John Gibson ([email protected]), 9/20/98, RT'd 6/24/99; rev for v4, 7/24/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <Instrument.h>
#include <PField.h>
#include "JCHOR.h"
#include <rt.h>
#include <rtdefs.h>
extern "C" {
extern double m_DUR(float [], int); /* in sys/minc_info.c */
}
//#define DEBUG
#define ENVELOPE_TABLE_SLOT 1
#define WINDOW_FUNC_SLOT 2
#define AVERAGE_CHANS -1 // average input chans flag value
#define WINDOW_CONTROL_RATE 22050.0 // don't skimp on this
// local functions
static double interp(double, double, double, double);
JCHOR::JCHOR() : Instrument()
{
in = NULL;
winarray = NULL;
winarraylen = 0;
voices = NULL;
grain = NULL;
grain_done = false;
branch = 0;
}
JCHOR::~JCHOR()
{
delete [] in;
delete [] voices;
delete [] grain;
}
int JCHOR::init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
inskip = p[1];
float outdur = p[2];
indur = p[3];
maintain_indur = (bool) p[4];
transpose = p[5];
nvoices = (int) p[6];
minamp = p[7];
float maxamp = p[8];
minwait = p[9];
float maxwait = p[10];
seed = p[11];
inchan = (n_args > 12) ? (int) p[12] : AVERAGE_CHANS;
if (n_args < 12)
return die("JCHOR", "Not enough pfields.");
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
if (rtsetoutput(outskip, outdur, this) == -1)
return DONT_SCHEDULE;
if (outputChannels() > 2)
return die("JCHOR", "Output must have no more than two channels.");
if (nvoices < 1)
return die("JCHOR", "Must have at least one voice.");
if (minamp < 0.0 || maxamp < 0.0 || minamp > maxamp)
return die("JCHOR", "Grain amplitude range confused.");
ampdiff = maxamp - minamp;
if (minwait < 0.0 || maxwait < 0.0 || minwait > maxwait)
return die("JCHOR", "Grain wait range confused.");
waitdiff = (maxwait - minwait) * SR;
minwait *= SR;
if (seed < 0.0 || seed > 1.0)
return die("JCHOR", "Seed must be between 0 and 1 inclusive.");
amparray = floc(ENVELOPE_TABLE_SLOT);
if (amparray) {
int len = fsize(ENVELOPE_TABLE_SLOT);
tableset(SR, outdur, len, amptabs);
}
if (n_args > 14) { // handle table coming in as optional p14 TablePField
winarray = (double *) getPFieldTable(14, &winarraylen);
}
if (winarray == NULL) {
// MUST do this here, rather than in grain_input_and_transpose,
// because by the time that is called, the makegen for this slot
// may have changed.
winarray = floc(WINDOW_FUNC_SLOT);
if (winarray == NULL)
return die("JCHOR", "Either use the grain envelope pfield (p14) "
"or make an old-style gen function in slot %d.",
WINDOW_FUNC_SLOT);
winarraylen = fsize(WINDOW_FUNC_SLOT);
}
skip = (int) (SR / (float) resetval);
return nSamps();
}
void JCHOR::doupdate()
{
double p[14];
update(p, 14, kMinAmp | kMaxAmp | kMinWait | kMaxWait | kAmp);
minamp = p[7];
float maxamp = p[8];
if (minamp < 0.0)
minamp = 0.0;
if (maxamp < 0.0)
maxamp = 0.0;
if (maxamp < minamp)
maxamp = minamp;
ampdiff = maxamp - minamp;
minwait = p[9];
float maxwait = p[10];
if (minwait < 0.0)
minwait = 0.0;
if (maxwait < 0.0)
maxwait = 0.0;
if (maxwait < minwait)
maxwait = minwait;
waitdiff = (maxwait - minwait) * SR;
minwait *= SR;
if (nargs > 13)
amp = p[13];
else
amp = 1.0;
if (amparray)
amp *= tablei(currentFrame(), amparray, amptabs);
}
int JCHOR::configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
int JCHOR::run()
{
if (!grain_done) {
grain_input_and_transpose();
setup_voices();
}
for (int i = 0; i < framesToRun(); i++) {
if (--branch <= 0) {
doupdate();
branch = skip;
}
float out[2];
out[0] = out[1] = 0.0;
Voice *v = voices;
for (int j = 0; j < nvoices; j++, v++) {
if (v->index++ < 0)
continue;
if (v->index >= grainsamps) {
seed = crandom(seed);
v->index = (int) -(minwait + (seed * waitdiff));
if (outputChannels() > 1) {
seed = crandom(seed);
v->left_amp = seed;
v->right_amp = 1.0 - v->left_amp;
}
seed = crandom(seed);
v->overall_amp = minamp + (seed * ampdiff);
}
else {
float sig = grain[v->index] * v->overall_amp;
if (outputChannels() > 1) {
out[0] += sig * v->left_amp;
out[1] += sig * v->right_amp;
}
else
out[0] += sig;
}
}
out[0] *= amp;
out[1] *= amp;
rtaddout(out);
increment();
}
return framesToRun();
}
/* --------------------------------------------------------------- interp --- */
/* Cubic spline interpolation.
Nabbed from Doug Scott's trans.
*/
static double
interp(double y0, double y1, double y2, double t)
{
register double hy2, hy0, a, b, c;
a = y0;
hy0 = y0 / 2.0;
hy2 = y2 / 2.0;
b = (-3.0 * hy0) + (2.0 * y1) - hy2;
c = hy0 - y1 + hy2;
return (a + b*t + c*t*t);
}
/* --------------------------------------------------------- setup_voices --- */
int JCHOR::setup_voices()
{
voices = new Voice[nvoices];
Voice *v = voices;
for (int i = 0; i < nvoices; i++, v++) {
seed = crandom(seed);
v->index = (int) (-seed * (grainsamps - 1));
if (outputChannels() > 1) {
seed = crandom(seed);
v->left_amp = seed;
v->right_amp = 1.0 - v->left_amp;
}
seed = crandom(seed);
v->overall_amp = minamp + (seed * ampdiff);
}
#ifdef DEBUG
printf("\n%d grainsamps\n", grainsamps);
printf("Voices:\n");
for (int i = 0, v = voices; i < nvoices; i++, v++)
printf("%6d: index=%d, left=%g, right=%g, amp=%g\n",
i, v->index, v->left_amp, v->right_amp, v->overall_amp);
#endif
return 0;
}
/* -------------------------------------------- grain_input_and_transpose --- */
/* Reads part of a soundfile into a newly allocated array <grain>, transposing
the signal as it's read, and shaping its amplitude with a window function.
The method of transposition (adapted from the trans instrument) doesn't
try to preserve duration. So we have a potential discrepancy between the
input duration <indur> and the duration of that segment of sound after
transposition. (For example, if transposition is down an octave, the
length of the input segment after transposition will be <indur> * 2.)
There are two ways to handle the discrepancy. Since both ways are useful,
the caller can choose between them:
- If <maintain_indur> is true, the grain length after transposition
will be the same as that given by <indur>. This means that the amount
actually read from the input file will be shorter or longer than
<indur>, depending on the transposition.
- If <maintain_indur> is false, the segment of sound specified by
<indur> will be read, and the grain length will be shorter or longer
than <indur>, depending on the transposition.
<inchan> gives the input channel number to read, or if it's -1, specifies
that all input channels will be averaged when read into the 1-channel array
returned by the function. If the input file is mono, <inchan> is ignored.
<WINDOW_FUNC_SLOT> is the makegen slot of a function used as an amplitude
curve for the grain. Use gen 25 for a Hanning or Hamming window, or try
gens 5 or 7 to make other envelope shapes.
*/
int JCHOR::grain_input_and_transpose()
{
int i, j, k, n, reset_count, inframes, bufframes;
int getflag, incount;
float read_indur, store_indur, total_indur, interval, grainamp = 0.0;
double increment, newsig, oldsig, oldersig, frac, counter;
if (inputChannels() == 1)
inchan = 0;
interval = octpch(transpose);
increment = cpsoct(10.0 + interval) / cpsoct(10.0);
if (maintain_indur) {
read_indur = (double)indur / increment;
store_indur = indur;
}
else {
read_indur = indur;
store_indur = (double)indur / increment;
}
#ifdef DEBUG
printf("increment=%g, read_indur=%g, store_indur=%g\n",
increment, read_indur, store_indur);
#endif
#ifdef NOT_YET
total_indur = (float)m_DUR(NULL, 0);
if (inskip < 0.0 || read_indur <= 0.0 || inskip + read_indur > total_indur)
return die("JCHOR", "Input file segment out of range.");
#endif
grainsamps = (int)(store_indur * SR + 0.5);
grain = new float[grainsamps];
tableset(SR, store_indur, winarraylen, wintabs);
inframes = (int)(SR / read_indur);
bufframes = RTBUFSAMPS;
reset_count = (int) (SR / WINDOW_CONTROL_RATE);
getflag = 1;
incount = 0; /* frames */
counter = 0.0;
oldersig = oldsig = newsig = 0.0;
k = bufframes;
for (i = j = 0; i < grainsamps; i++) {
if (--j < 0) {
grainamp = tablei(i, winarray, wintabs);
j = reset_count;
}
while (getflag) {
int index;
if (k == bufframes) { /* time for an input buffer */
rtgetin(in, this, inputChannels() * bufframes);
k = 0;
}
index = k * inputChannels();
oldersig = oldsig;
oldsig = newsig;
if (inchan == AVERAGE_CHANS) {
newsig = 0.0;
for (n = 0; n < inputChannels(); n++)
newsig += (double)in[index + n];
newsig /= (double)inputChannels();
}
else
newsig = (double)in[index + inchan];
incount++;
k++;
if (counter - (float)incount < 0.5)
getflag = 0;
}
frac = counter - (double)incount + 2.0;
grain[i] = (float)interp(oldersig, oldsig, newsig, frac) * grainamp;
counter += increment;
if (counter - (float)incount >= -0.5)
getflag = 1;
}
grain_done = true;
return 0;
}
Instrument *makeJCHOR()
{
JCHOR *inst;
inst = new JCHOR();
inst->set_bus_config("JCHOR");
return inst;
}
void rtprofile()
{
RT_INTRO("JCHOR", makeJCHOR);
}
<commit_msg>Fix a few casts.<commit_after>/* JCHOR - random-wait chorus instrument based on Paul Lansky's chor
and Doug Scott's trans code
p0 = output start time
p1 = input start time
p2 = output duration
p3 = input duration (not input end time)
p4 = maintain input duration, regardless of transposition (1: yes, 0: no)
p5 = transposition (8ve.pc)
p6 = number of voices (minimum of 1)
p7 = minimum grain amplitude
p8 = maximum grain amplitude
p9 = minimum grain wait (seconds)
p10 = maximum grain wait (seconds)
p11 = seed (0 - 1)
p12 = input channel [optional; if missing and input has > 1 chan, input
channels averaged]
p13 = overall amplitude multiplier [optional; if missing, must use gen 1 *]
p14 = reference to grain envelope table [optional; if missing, must use
gen 2 **]
p7 (min amp), p8 (max amp), p9 (min wait), p10 (max wait) and p13 (amp mult)
can receive dynamic updates from a table or real-time control source.
Output can be either mono or stereo. If it's stereo, the program randomly
distributes the voices across the stereo field.
Notes on p4 (maintain input duration):
Because the transposition method doesn't try to maintain duration -- it
works like the speed control on a tape deck -- you have an option about
the way to handle the duration of the input read:
- If p4 is 1, the grain length after transposition will be the same as
that given by p3 (input duration). This means that the amount actually
read from the input file will be shorter or longer than p3, depending
on the transposition.
- If p4 is 0, the segment of sound specified by p3 will be read, and the
grain length will be shorter or longer than p3, depending on the
transposition.
----
Notes about backward compatibility with pre-v4 scores:
* If an old-style gen table 1 is present, its values will be multiplied
by p13 (amplitude multiplier), even if the latter is dynamic.
** If p14 is missing, you must use an old-style gen table 2 for the
grain envelope.
----
Differences between JCHOR and chor (besides RT ability):
- No limit on input duration or number of voices
- Transpose the input signal
- Specify the input channel to use (or an average of them)
- Specify overall amplitude curve and grain window function
John Gibson ([email protected]), 9/20/98, RT'd 6/24/99; rev for v4, 7/24/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <Instrument.h>
#include <PField.h>
#include "JCHOR.h"
#include <rt.h>
#include <rtdefs.h>
extern "C" {
extern double m_DUR(float [], int); /* in sys/minc_info.c */
}
//#define DEBUG
#define ENVELOPE_TABLE_SLOT 1
#define WINDOW_FUNC_SLOT 2
#define AVERAGE_CHANS -1 // average input chans flag value
#define WINDOW_CONTROL_RATE 22050.0 // don't skimp on this
// local functions
static double interp(double, double, double, double);
JCHOR::JCHOR() : Instrument()
{
in = NULL;
winarray = NULL;
winarraylen = 0;
voices = NULL;
grain = NULL;
grain_done = false;
branch = 0;
}
JCHOR::~JCHOR()
{
delete [] in;
delete [] voices;
delete [] grain;
}
int JCHOR::init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
inskip = p[1];
float outdur = p[2];
indur = p[3];
maintain_indur = (bool) p[4];
transpose = p[5];
nvoices = (int) p[6];
minamp = p[7];
float maxamp = p[8];
minwait = p[9];
float maxwait = p[10];
seed = p[11];
inchan = (n_args > 12) ? (int) p[12] : AVERAGE_CHANS;
if (n_args < 12)
return die("JCHOR", "Not enough pfields.");
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
if (rtsetoutput(outskip, outdur, this) == -1)
return DONT_SCHEDULE;
if (outputChannels() > 2)
return die("JCHOR", "Output must have no more than two channels.");
if (nvoices < 1)
return die("JCHOR", "Must have at least one voice.");
if (minamp < 0.0 || maxamp < 0.0 || minamp > maxamp)
return die("JCHOR", "Grain amplitude range confused.");
ampdiff = maxamp - minamp;
if (minwait < 0.0 || maxwait < 0.0 || minwait > maxwait)
return die("JCHOR", "Grain wait range confused.");
waitdiff = (maxwait - minwait) * SR;
minwait *= SR;
if (seed < 0.0 || seed > 1.0)
return die("JCHOR", "Seed must be between 0 and 1 inclusive.");
amparray = floc(ENVELOPE_TABLE_SLOT);
if (amparray) {
int len = fsize(ENVELOPE_TABLE_SLOT);
tableset(SR, outdur, len, amptabs);
}
if (n_args > 14) { // handle table coming in as optional p14 TablePField
winarray = (double *) getPFieldTable(14, &winarraylen);
}
if (winarray == NULL) {
// MUST do this here, rather than in grain_input_and_transpose,
// because by the time that is called, the makegen for this slot
// may have changed.
winarray = floc(WINDOW_FUNC_SLOT);
if (winarray == NULL)
return die("JCHOR", "Either use the grain envelope pfield (p14) "
"or make an old-style gen function in slot %d.",
WINDOW_FUNC_SLOT);
winarraylen = fsize(WINDOW_FUNC_SLOT);
}
skip = (int) (SR / (float) resetval);
return nSamps();
}
void JCHOR::doupdate()
{
double p[14];
update(p, 14, kMinAmp | kMaxAmp | kMinWait | kMaxWait | kAmp);
minamp = p[7];
float maxamp = p[8];
if (minamp < 0.0)
minamp = 0.0;
if (maxamp < 0.0)
maxamp = 0.0;
if (maxamp < minamp)
maxamp = minamp;
ampdiff = maxamp - minamp;
minwait = p[9];
float maxwait = p[10];
if (minwait < 0.0)
minwait = 0.0;
if (maxwait < 0.0)
maxwait = 0.0;
if (maxwait < minwait)
maxwait = minwait;
waitdiff = (maxwait - minwait) * SR;
minwait *= SR;
if (nargs > 13)
amp = p[13];
else
amp = 1.0;
if (amparray)
amp *= tablei(currentFrame(), amparray, amptabs);
}
int JCHOR::configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
int JCHOR::run()
{
if (!grain_done) {
grain_input_and_transpose();
setup_voices();
}
for (int i = 0; i < framesToRun(); i++) {
if (--branch <= 0) {
doupdate();
branch = skip;
}
float out[2];
out[0] = out[1] = 0.0;
Voice *v = voices;
for (int j = 0; j < nvoices; j++, v++) {
if (v->index++ < 0)
continue;
if (v->index >= grainsamps) {
seed = crandom(seed);
v->index = (int) -(minwait + (seed * waitdiff));
if (outputChannels() > 1) {
seed = crandom(seed);
v->left_amp = seed;
v->right_amp = 1.0 - v->left_amp;
}
seed = crandom(seed);
v->overall_amp = minamp + (seed * ampdiff);
}
else {
float sig = grain[v->index] * v->overall_amp;
if (outputChannels() > 1) {
out[0] += sig * v->left_amp;
out[1] += sig * v->right_amp;
}
else
out[0] += sig;
}
}
out[0] *= amp;
out[1] *= amp;
rtaddout(out);
increment();
}
return framesToRun();
}
/* --------------------------------------------------------------- interp --- */
/* Cubic spline interpolation.
Nabbed from Doug Scott's trans.
*/
static double
interp(double y0, double y1, double y2, double t)
{
register double hy2, hy0, a, b, c;
a = y0;
hy0 = y0 / 2.0;
hy2 = y2 / 2.0;
b = (-3.0 * hy0) + (2.0 * y1) - hy2;
c = hy0 - y1 + hy2;
return (a + b*t + c*t*t);
}
/* --------------------------------------------------------- setup_voices --- */
int JCHOR::setup_voices()
{
voices = new Voice[nvoices];
Voice *v = voices;
for (int i = 0; i < nvoices; i++, v++) {
seed = crandom(seed);
v->index = (int) (-seed * (grainsamps - 1));
if (outputChannels() > 1) {
seed = crandom(seed);
v->left_amp = seed;
v->right_amp = 1.0 - v->left_amp;
}
seed = crandom(seed);
v->overall_amp = minamp + (seed * ampdiff);
}
#ifdef DEBUG
printf("\n%d grainsamps\n", grainsamps);
printf("Voices:\n");
for (int i = 0, v = voices; i < nvoices; i++, v++)
printf("%6d: index=%d, left=%g, right=%g, amp=%g\n",
i, v->index, v->left_amp, v->right_amp, v->overall_amp);
#endif
return 0;
}
/* -------------------------------------------- grain_input_and_transpose --- */
/* Reads part of a soundfile into a newly allocated array <grain>, transposing
the signal as it's read, and shaping its amplitude with a window function.
The method of transposition (adapted from the trans instrument) doesn't
try to preserve duration. So we have a potential discrepancy between the
input duration <indur> and the duration of that segment of sound after
transposition. (For example, if transposition is down an octave, the
length of the input segment after transposition will be <indur> * 2.)
There are two ways to handle the discrepancy. Since both ways are useful,
the caller can choose between them:
- If <maintain_indur> is true, the grain length after transposition
will be the same as that given by <indur>. This means that the amount
actually read from the input file will be shorter or longer than
<indur>, depending on the transposition.
- If <maintain_indur> is false, the segment of sound specified by
<indur> will be read, and the grain length will be shorter or longer
than <indur>, depending on the transposition.
<inchan> gives the input channel number to read, or if it's -1, specifies
that all input channels will be averaged when read into the 1-channel array
returned by the function. If the input file is mono, <inchan> is ignored.
<WINDOW_FUNC_SLOT> is the makegen slot of a function used as an amplitude
curve for the grain. Use gen 25 for a Hanning or Hamming window, or try
gens 5 or 7 to make other envelope shapes.
*/
int JCHOR::grain_input_and_transpose()
{
int i, j, k, n, reset_count, inframes, bufframes;
int getflag, incount;
float read_indur, store_indur, total_indur, interval, grainamp = 0.0;
double increment, newsig, oldsig, oldersig, frac, counter;
if (inputChannels() == 1)
inchan = 0;
interval = octpch(transpose);
increment = cpsoct(10.0 + interval) / cpsoct(10.0);
if (maintain_indur) {
read_indur = (double)indur / increment;
store_indur = indur;
}
else {
read_indur = indur;
store_indur = (double)indur / increment;
}
#ifdef DEBUG
printf("increment=%g, read_indur=%g, store_indur=%g\n",
increment, read_indur, store_indur);
#endif
#ifdef NOT_YET
total_indur = (float)m_DUR(NULL, 0);
if (inskip < 0.0 || read_indur <= 0.0 || inskip + read_indur > total_indur)
return die("JCHOR", "Input file segment out of range.");
#endif
grainsamps = (int)(store_indur * SR + 0.5);
grain = new float[grainsamps];
tableset(SR, store_indur, winarraylen, wintabs);
inframes = (int)(SR / read_indur);
bufframes = RTBUFSAMPS;
reset_count = (int) (SR / WINDOW_CONTROL_RATE);
getflag = 1;
incount = 0; /* frames */
counter = 0.0;
oldersig = oldsig = newsig = 0.0;
k = bufframes;
for (i = j = 0; i < grainsamps; i++) {
if (--j < 0) {
grainamp = tablei(i, winarray, wintabs);
j = reset_count;
}
while (getflag) {
int index;
if (k == bufframes) { /* time for an input buffer */
rtgetin(in, this, inputChannels() * bufframes);
k = 0;
}
index = k * inputChannels();
oldersig = oldsig;
oldsig = newsig;
if (inchan == AVERAGE_CHANS) {
newsig = 0.0;
for (n = 0; n < inputChannels(); n++)
newsig += (double)in[index + n];
newsig /= (double)inputChannels();
}
else
newsig = (double)in[index + inchan];
incount++;
k++;
if (counter - (double)incount < 0.5)
getflag = 0;
}
frac = counter - (double)incount + 2.0;
grain[i] = (float)interp(oldersig, oldsig, newsig, frac) * grainamp;
counter += increment;
if (counter - (double)incount >= -0.5)
getflag = 1;
}
grain_done = true;
return 0;
}
Instrument *makeJCHOR()
{
JCHOR *inst;
inst = new JCHOR();
inst->set_bus_config("JCHOR");
return inst;
}
void rtprofile()
{
RT_INTRO("JCHOR", makeJCHOR);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/captcha_view.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/image_downloader.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/widget/widget_gtk.h"
#include "views/window/window.h"
using views::Label;
using views::Textfield;
using views::WidgetGtk;
namespace chromeos {
CaptchaView::CaptchaView(const GURL& captcha_url)
: delegate_(NULL),
captcha_url_(captcha_url),
captcha_image_(NULL),
captcha_textfield_(NULL) {
}
bool CaptchaView::Accept() {
if (delegate_)
delegate_->OnCaptchaEntered(UTF16ToUTF8(captcha_textfield_->text()));
return true;
}
std::wstring CaptchaView::GetWindowTitle() const {
return l10n_util::GetString(IDS_LOGIN_CAPTCHA_DIALOG_TITLE);
}
gfx::Size CaptchaView::GetPreferredSize() {
// TODO(nkostylev): Once UI is finalized, create locale settings.
return gfx::Size(views::Window::GetLocalizedContentsSize(
IDS_CAPTCHA_INPUT_DIALOG_WIDTH_CHARS,
IDS_CAPTCHA_INPUT_DIALOG_HEIGHT_LINES));
}
void CaptchaView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
// Can't init before we're inserted into a Container, because we require
// a HWND to parent native child controls to.
if (is_add && child == this)
Init();
}
bool CaptchaView::HandleKeystroke(views::Textfield* sender,
const views::Textfield::Keystroke& keystroke) {
return false;
}
void CaptchaView::OnImageDecoded(const SkBitmap& decoded_image) {
captcha_image_->SetImage(decoded_image);
SchedulePaint();
Layout();
}
void CaptchaView::Init() {
views::GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
int column_view_set_id = 0;
views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, column_view_set_id);
Label* label =
new views::Label(l10n_util::GetString(IDS_LOGIN_CAPTCHA_INSTRUCTIONS));
label->SetMultiLine(true);
layout->AddView(label);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
captcha_image_ = new views::ImageView();
layout->AddView(captcha_image_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
captcha_textfield_ = new views::Textfield(
views::Textfield::STYLE_DEFAULT);
captcha_textfield_->SetController(this);
layout->AddView(captcha_textfield_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
label = new views::Label(
l10n_util::GetString(IDS_SYNC_GAIA_CAPTCHA_CASE_INSENSITIVE_TIP));
label->SetMultiLine(true);
layout->AddView(label);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
captcha_textfield_->RequestFocus();
// ImageDownloader will disable itself once URL is fetched.
new ImageDownloader(this, GURL(captcha_url_), std::string());
}
} // namespace chromeos
<commit_msg>chromeos: Make Enter key works on the Captcha dialog.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/captcha_view.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/image_downloader.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/widget/widget_gtk.h"
#include "views/window/window.h"
using views::Label;
using views::Textfield;
using views::WidgetGtk;
namespace chromeos {
CaptchaView::CaptchaView(const GURL& captcha_url)
: delegate_(NULL),
captcha_url_(captcha_url),
captcha_image_(NULL),
captcha_textfield_(NULL) {
}
bool CaptchaView::Accept() {
if (delegate_)
delegate_->OnCaptchaEntered(UTF16ToUTF8(captcha_textfield_->text()));
return true;
}
std::wstring CaptchaView::GetWindowTitle() const {
return l10n_util::GetString(IDS_LOGIN_CAPTCHA_DIALOG_TITLE);
}
gfx::Size CaptchaView::GetPreferredSize() {
// TODO(nkostylev): Once UI is finalized, create locale settings.
return gfx::Size(views::Window::GetLocalizedContentsSize(
IDS_CAPTCHA_INPUT_DIALOG_WIDTH_CHARS,
IDS_CAPTCHA_INPUT_DIALOG_HEIGHT_LINES));
}
void CaptchaView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
// Can't init before we're inserted into a Container, because we require
// a HWND to parent native child controls to.
if (is_add && child == this)
Init();
}
bool CaptchaView::HandleKeystroke(views::Textfield* sender,
const views::Textfield::Keystroke& keystroke) {
if (sender == captcha_textfield_ &&
keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
GetDialogClientView()->AcceptWindow();
}
return false;
}
void CaptchaView::OnImageDecoded(const SkBitmap& decoded_image) {
captcha_image_->SetImage(decoded_image);
SchedulePaint();
Layout();
}
void CaptchaView::Init() {
views::GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
int column_view_set_id = 0;
views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, column_view_set_id);
Label* label =
new views::Label(l10n_util::GetString(IDS_LOGIN_CAPTCHA_INSTRUCTIONS));
label->SetMultiLine(true);
layout->AddView(label);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
captcha_image_ = new views::ImageView();
layout->AddView(captcha_image_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
captcha_textfield_ = new views::Textfield(
views::Textfield::STYLE_DEFAULT);
captcha_textfield_->SetController(this);
layout->AddView(captcha_textfield_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
label = new views::Label(
l10n_util::GetString(IDS_SYNC_GAIA_CAPTCHA_CASE_INSENSITIVE_TIP));
label->SetMultiLine(true);
layout->AddView(label);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
captcha_textfield_->RequestFocus();
// ImageDownloader will disable itself once URL is fetched.
new ImageDownloader(this, GURL(captcha_url_), std::string());
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/user_manager.h"
#include "app/resource_bundle.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/nss_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/input_method_library.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "gfx/codec/png_codec.h"
#include "grit/theme_resources.h"
namespace chromeos {
namespace {
// A vector pref of the users who have logged into the device.
const char kLoggedInUsers[] = "LoggedInUsers";
// A dictionary that maps usernames to file paths to their images.
const char kUserImages[] = "UserImages";
// Incognito user is represented by an empty string (since some code already
// depends on that and it's hard to figure out what).
const char kIncognitoUser[] = "";
// Special pathes to default user images.
const char* kDefaultImageNames[] = {
"default:blue",
"default:green",
"default:yellow",
"default:red",
};
// Resource IDs of default user images.
const int kDefaultImageResources[] = {
IDR_LOGIN_DEFAULT_USER_1,
IDR_LOGIN_DEFAULT_USER_2,
IDR_LOGIN_DEFAULT_USER_3,
IDR_LOGIN_DEFAULT_USER_4
};
// The one true UserManager.
static UserManager* user_manager_ = NULL;
// Stores path to the image in local state. Runs on UI thread.
void SavePathToLocalState(const std::string& username,
const std::string& image_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PrefService* local_state = g_browser_process->local_state();
DictionaryValue* images =
local_state->GetMutableDictionary(kUserImages);
images->SetWithoutPathExpansion(username, new StringValue(image_path));
DLOG(INFO) << "Saving path to user image in Local State.";
local_state->SavePersistentPrefs();
}
// Saves image to file with specified path. Runs on FILE thread.
// Posts task for saving image path to local state on UI thread.
void SaveImageToFile(const SkBitmap& image,
const FilePath& image_path,
const std::string& username) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
std::vector<unsigned char> encoded_image;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, true, &encoded_image)) {
LOG(ERROR) << "Failed to PNG encode the image.";
return;
}
if (file_util::WriteFile(image_path,
reinterpret_cast<char*>(&encoded_image[0]),
encoded_image.size()) == -1) {
LOG(ERROR) << "Failed to save image to file.";
return;
}
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableFunction(&SavePathToLocalState,
username, image_path.value()));
}
// Checks if given path is one of the default ones. If it is, returns true
// and its index in kDefaultImageNames through |image_id|. If not, returns
// false.
bool IsDefaultImagePath(const std::string& path, size_t* image_id) {
DCHECK(image_id);
for (size_t i = 0; i < arraysize(kDefaultImageNames); ++i) {
if (path == kDefaultImageNames[i]) {
*image_id = i;
return true;
}
}
return false;
}
// Checks current user's ownership on file thread.
void CheckOwnership() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
UserManager::Get()->set_current_user_is_owner(
OwnershipService::GetSharedInstance()->CurrentUserIsOwner());
}
} // namespace
UserManager::User::User() {
image_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_LOGIN_DEFAULT_USER);
}
std::string UserManager::User::GetDisplayName() const {
size_t i = email_.find('@');
if (i == 0 || i == std::string::npos) {
return email_;
}
return email_.substr(0, i);
}
// static
UserManager* UserManager::Get() {
if (!user_manager_)
user_manager_ = new UserManager();
return user_manager_;
}
// static
void UserManager::RegisterPrefs(PrefService* local_state) {
local_state->RegisterListPref(kLoggedInUsers);
local_state->RegisterDictionaryPref(kUserImages);
}
std::vector<UserManager::User> UserManager::GetUsers() const {
std::vector<User> users;
if (!g_browser_process)
return users;
PrefService* local_state = g_browser_process->local_state();
const ListValue* prefs_users = local_state->GetList(kLoggedInUsers);
const DictionaryValue* prefs_images =
local_state->GetDictionary(kUserImages);
if (prefs_users) {
for (ListValue::const_iterator it = prefs_users->begin();
it != prefs_users->end();
++it) {
std::string email;
if ((*it)->GetAsString(&email)) {
User user;
user.set_email(email);
UserImages::const_iterator image_it = user_images_.find(email);
std::string image_path;
if (image_it == user_images_.end()) {
if (prefs_images &&
prefs_images->GetStringWithoutPathExpansion(email, &image_path)) {
size_t default_image_id = arraysize(kDefaultImageNames);
if (IsDefaultImagePath(image_path, &default_image_id)) {
DCHECK(default_image_id < arraysize(kDefaultImageNames));
int resource_id = kDefaultImageResources[default_image_id];
user.set_image(
*ResourceBundle::GetSharedInstance().GetBitmapNamed(
resource_id));
user_images_[email] = user.image();
} else {
// Insert the default image so we don't send another request if
// GetUsers is called twice.
user_images_[email] = user.image();
image_loader_->Start(email, image_path);
}
}
} else {
user.set_image(image_it->second);
}
users.push_back(user);
}
}
}
return users;
}
void UserManager::OffTheRecordUserLoggedIn() {
logged_in_user_ = User();
logged_in_user_.set_email(kIncognitoUser);
NotifyOnLogin();
}
void UserManager::UserLoggedIn(const std::string& email) {
if (email == kIncognitoUser) {
OffTheRecordUserLoggedIn();
return;
}
// Get a copy of the current users.
std::vector<User> users = GetUsers();
// Clear the prefs view of the users.
PrefService* prefs = g_browser_process->local_state();
ListValue* prefs_users = prefs->GetMutableList(kLoggedInUsers);
prefs_users->Clear();
logged_in_user_.set_email(email);
// Make sure this user is first.
prefs_users->Append(Value::CreateStringValue(email));
for (std::vector<User>::iterator it = users.begin();
it != users.end();
++it) {
std::string user_email = it->email();
// Skip the most recent user.
if (email != user_email) {
prefs_users->Append(Value::CreateStringValue(user_email));
} else {
logged_in_user_ = *it;
}
}
prefs->SavePersistentPrefs();
NotifyOnLogin();
}
void UserManager::RemoveUser(const std::string& email) {
// Get a copy of the current users.
std::vector<User> users = GetUsers();
// Clear the prefs view of the users.
PrefService* prefs = g_browser_process->local_state();
ListValue* prefs_users = prefs->GetMutableList(kLoggedInUsers);
prefs_users->Clear();
for (std::vector<User>::iterator it = users.begin();
it != users.end();
++it) {
std::string user_email = it->email();
// Skip user that we would like to delete.
if (email != user_email)
prefs_users->Append(Value::CreateStringValue(user_email));
}
prefs->SavePersistentPrefs();
}
bool UserManager::IsKnownUser(const std::string& email) {
std::vector<User> users = GetUsers();
for (std::vector<User>::iterator it = users.begin();
it < users.end();
++it) {
if (it->email() == email)
return true;
}
return false;
}
void UserManager::SetLoggedInUserImage(const SkBitmap& image) {
if (logged_in_user_.email().empty())
return;
logged_in_user_.set_image(image);
OnImageLoaded(logged_in_user_.email(), image);
}
void UserManager::SaveUserImage(const std::string& username,
const SkBitmap& image) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::string filename = username + ".png";
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
FilePath image_path = user_data_dir.AppendASCII(filename);
DLOG(INFO) << "Saving user image to " << image_path.value();
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
NewRunnableFunction(&SaveImageToFile,
image, image_path, username));
}
void UserManager::SetDefaultUserImage(const std::string& username) {
if (!g_browser_process)
return;
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
const ListValue* prefs_users = local_state->GetList(kLoggedInUsers);
DCHECK(prefs_users);
const DictionaryValue* prefs_images =
local_state->GetDictionary(kUserImages);
DCHECK(prefs_images);
// We want to distribute default images between users uniformly so that if
// there're more users with red image, we won't add red one for sure.
// Thus we count how many default images of each color are used and choose
// the first color with minimal usage.
std::vector<int> colors_count(arraysize(kDefaultImageNames), 0);
for (ListValue::const_iterator it = prefs_users->begin();
it != prefs_users->end();
++it) {
std::string email;
if ((*it)->GetAsString(&email)) {
std::string image_path;
size_t default_image_id = arraysize(kDefaultImageNames);
if (prefs_images->GetStringWithoutPathExpansion(email, &image_path) &&
IsDefaultImagePath(image_path, &default_image_id)) {
DCHECK(default_image_id < arraysize(kDefaultImageNames));
++colors_count[default_image_id];
}
}
}
std::vector<int>::const_iterator min_it =
std::min_element(colors_count.begin(), colors_count.end());
int selected_id = min_it - colors_count.begin();
std::string user_image_path = kDefaultImageNames[selected_id];
int resource_id = kDefaultImageResources[selected_id];
SkBitmap user_image = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
resource_id);
SavePathToLocalState(username, user_image_path);
SetLoggedInUserImage(user_image);
}
void UserManager::OnImageLoaded(const std::string& username,
const SkBitmap& image) {
DLOG(INFO) << "Loaded image for " << username;
user_images_[username] = image;
User user;
user.set_email(username);
user.set_image(image);
NotificationService::current()->Notify(
NotificationType::LOGIN_USER_IMAGE_CHANGED,
Source<UserManager>(this),
Details<const User>(&user));
}
// Private constructor and destructor. Do nothing.
UserManager::UserManager()
: ALLOW_THIS_IN_INITIALIZER_LIST(image_loader_(new UserImageLoader(this))),
current_user_is_owner_(false) {
registrar_.Add(this, NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED,
NotificationService::AllSources());
}
UserManager::~UserManager() {
image_loader_->set_delegate(NULL);
}
void UserManager::NotifyOnLogin() {
NotificationService::current()->Notify(
NotificationType::LOGIN_USER_CHANGED,
Source<UserManager>(this),
Details<const User>(&logged_in_user_));
chromeos::CrosLibrary::Get()->GetInputMethodLibrary()->
SetDeferImeStartup(false);
// Shut down the IME so that it will reload the user's settings.
chromeos::CrosLibrary::Get()->GetInputMethodLibrary()->
StopInputMethodProcesses();
// Let the window manager know that we're logged in now.
WmIpc::instance()->SetLoggedInProperty(true);
// Ensure we've opened the real user's key/certificate database.
base::OpenPersistentNSSDB();
// Schedules current user ownership check on file thread.
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableFunction(&CheckOwnership));
}
void UserManager::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED) {
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableFunction(&CheckOwnership));
}
}
} // namespace chromeos
<commit_msg>Correct call to create dictionary in Local State if it doesn't exist.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/user_manager.h"
#include "app/resource_bundle.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/nss_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/input_method_library.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "gfx/codec/png_codec.h"
#include "grit/theme_resources.h"
namespace chromeos {
namespace {
// A vector pref of the users who have logged into the device.
const char kLoggedInUsers[] = "LoggedInUsers";
// A dictionary that maps usernames to file paths to their images.
const char kUserImages[] = "UserImages";
// Incognito user is represented by an empty string (since some code already
// depends on that and it's hard to figure out what).
const char kIncognitoUser[] = "";
// Special pathes to default user images.
const char* kDefaultImageNames[] = {
"default:blue",
"default:green",
"default:yellow",
"default:red",
};
// Resource IDs of default user images.
const int kDefaultImageResources[] = {
IDR_LOGIN_DEFAULT_USER_1,
IDR_LOGIN_DEFAULT_USER_2,
IDR_LOGIN_DEFAULT_USER_3,
IDR_LOGIN_DEFAULT_USER_4
};
// The one true UserManager.
static UserManager* user_manager_ = NULL;
// Stores path to the image in local state. Runs on UI thread.
void SavePathToLocalState(const std::string& username,
const std::string& image_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
PrefService* local_state = g_browser_process->local_state();
DictionaryValue* images =
local_state->GetMutableDictionary(kUserImages);
images->SetWithoutPathExpansion(username, new StringValue(image_path));
DLOG(INFO) << "Saving path to user image in Local State.";
local_state->SavePersistentPrefs();
}
// Saves image to file with specified path. Runs on FILE thread.
// Posts task for saving image path to local state on UI thread.
void SaveImageToFile(const SkBitmap& image,
const FilePath& image_path,
const std::string& username) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
std::vector<unsigned char> encoded_image;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, true, &encoded_image)) {
LOG(ERROR) << "Failed to PNG encode the image.";
return;
}
if (file_util::WriteFile(image_path,
reinterpret_cast<char*>(&encoded_image[0]),
encoded_image.size()) == -1) {
LOG(ERROR) << "Failed to save image to file.";
return;
}
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableFunction(&SavePathToLocalState,
username, image_path.value()));
}
// Checks if given path is one of the default ones. If it is, returns true
// and its index in kDefaultImageNames through |image_id|. If not, returns
// false.
bool IsDefaultImagePath(const std::string& path, size_t* image_id) {
DCHECK(image_id);
for (size_t i = 0; i < arraysize(kDefaultImageNames); ++i) {
if (path == kDefaultImageNames[i]) {
*image_id = i;
return true;
}
}
return false;
}
// Checks current user's ownership on file thread.
void CheckOwnership() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
UserManager::Get()->set_current_user_is_owner(
OwnershipService::GetSharedInstance()->CurrentUserIsOwner());
}
} // namespace
UserManager::User::User() {
image_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_LOGIN_DEFAULT_USER);
}
std::string UserManager::User::GetDisplayName() const {
size_t i = email_.find('@');
if (i == 0 || i == std::string::npos) {
return email_;
}
return email_.substr(0, i);
}
// static
UserManager* UserManager::Get() {
if (!user_manager_)
user_manager_ = new UserManager();
return user_manager_;
}
// static
void UserManager::RegisterPrefs(PrefService* local_state) {
local_state->RegisterListPref(kLoggedInUsers);
local_state->RegisterDictionaryPref(kUserImages);
}
std::vector<UserManager::User> UserManager::GetUsers() const {
std::vector<User> users;
if (!g_browser_process)
return users;
PrefService* local_state = g_browser_process->local_state();
const ListValue* prefs_users = local_state->GetList(kLoggedInUsers);
const DictionaryValue* prefs_images =
local_state->GetDictionary(kUserImages);
if (prefs_users) {
for (ListValue::const_iterator it = prefs_users->begin();
it != prefs_users->end();
++it) {
std::string email;
if ((*it)->GetAsString(&email)) {
User user;
user.set_email(email);
UserImages::const_iterator image_it = user_images_.find(email);
std::string image_path;
if (image_it == user_images_.end()) {
if (prefs_images &&
prefs_images->GetStringWithoutPathExpansion(email, &image_path)) {
size_t default_image_id = arraysize(kDefaultImageNames);
if (IsDefaultImagePath(image_path, &default_image_id)) {
DCHECK(default_image_id < arraysize(kDefaultImageNames));
int resource_id = kDefaultImageResources[default_image_id];
user.set_image(
*ResourceBundle::GetSharedInstance().GetBitmapNamed(
resource_id));
user_images_[email] = user.image();
} else {
// Insert the default image so we don't send another request if
// GetUsers is called twice.
user_images_[email] = user.image();
image_loader_->Start(email, image_path);
}
}
} else {
user.set_image(image_it->second);
}
users.push_back(user);
}
}
}
return users;
}
void UserManager::OffTheRecordUserLoggedIn() {
logged_in_user_ = User();
logged_in_user_.set_email(kIncognitoUser);
NotifyOnLogin();
}
void UserManager::UserLoggedIn(const std::string& email) {
if (email == kIncognitoUser) {
OffTheRecordUserLoggedIn();
return;
}
// Get a copy of the current users.
std::vector<User> users = GetUsers();
// Clear the prefs view of the users.
PrefService* prefs = g_browser_process->local_state();
ListValue* prefs_users = prefs->GetMutableList(kLoggedInUsers);
prefs_users->Clear();
logged_in_user_.set_email(email);
// Make sure this user is first.
prefs_users->Append(Value::CreateStringValue(email));
for (std::vector<User>::iterator it = users.begin();
it != users.end();
++it) {
std::string user_email = it->email();
// Skip the most recent user.
if (email != user_email) {
prefs_users->Append(Value::CreateStringValue(user_email));
} else {
logged_in_user_ = *it;
}
}
prefs->SavePersistentPrefs();
NotifyOnLogin();
}
void UserManager::RemoveUser(const std::string& email) {
// Get a copy of the current users.
std::vector<User> users = GetUsers();
// Clear the prefs view of the users.
PrefService* prefs = g_browser_process->local_state();
ListValue* prefs_users = prefs->GetMutableList(kLoggedInUsers);
prefs_users->Clear();
for (std::vector<User>::iterator it = users.begin();
it != users.end();
++it) {
std::string user_email = it->email();
// Skip user that we would like to delete.
if (email != user_email)
prefs_users->Append(Value::CreateStringValue(user_email));
}
prefs->SavePersistentPrefs();
}
bool UserManager::IsKnownUser(const std::string& email) {
std::vector<User> users = GetUsers();
for (std::vector<User>::iterator it = users.begin();
it < users.end();
++it) {
if (it->email() == email)
return true;
}
return false;
}
void UserManager::SetLoggedInUserImage(const SkBitmap& image) {
if (logged_in_user_.email().empty())
return;
logged_in_user_.set_image(image);
OnImageLoaded(logged_in_user_.email(), image);
}
void UserManager::SaveUserImage(const std::string& username,
const SkBitmap& image) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::string filename = username + ".png";
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
FilePath image_path = user_data_dir.AppendASCII(filename);
DLOG(INFO) << "Saving user image to " << image_path.value();
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
NewRunnableFunction(&SaveImageToFile,
image, image_path, username));
}
void UserManager::SetDefaultUserImage(const std::string& username) {
if (!g_browser_process)
return;
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
const ListValue* prefs_users = local_state->GetList(kLoggedInUsers);
DCHECK(prefs_users);
const DictionaryValue* prefs_images =
local_state->GetMutableDictionary(kUserImages);
DCHECK(prefs_images);
// We want to distribute default images between users uniformly so that if
// there're more users with red image, we won't add red one for sure.
// Thus we count how many default images of each color are used and choose
// the first color with minimal usage.
std::vector<int> colors_count(arraysize(kDefaultImageNames), 0);
for (ListValue::const_iterator it = prefs_users->begin();
it != prefs_users->end();
++it) {
std::string email;
if ((*it)->GetAsString(&email)) {
std::string image_path;
size_t default_image_id = arraysize(kDefaultImageNames);
if (prefs_images->GetStringWithoutPathExpansion(email, &image_path) &&
IsDefaultImagePath(image_path, &default_image_id)) {
DCHECK(default_image_id < arraysize(kDefaultImageNames));
++colors_count[default_image_id];
}
}
}
std::vector<int>::const_iterator min_it =
std::min_element(colors_count.begin(), colors_count.end());
int selected_id = min_it - colors_count.begin();
std::string user_image_path = kDefaultImageNames[selected_id];
int resource_id = kDefaultImageResources[selected_id];
SkBitmap user_image = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
resource_id);
SavePathToLocalState(username, user_image_path);
SetLoggedInUserImage(user_image);
}
void UserManager::OnImageLoaded(const std::string& username,
const SkBitmap& image) {
DLOG(INFO) << "Loaded image for " << username;
user_images_[username] = image;
User user;
user.set_email(username);
user.set_image(image);
NotificationService::current()->Notify(
NotificationType::LOGIN_USER_IMAGE_CHANGED,
Source<UserManager>(this),
Details<const User>(&user));
}
// Private constructor and destructor. Do nothing.
UserManager::UserManager()
: ALLOW_THIS_IN_INITIALIZER_LIST(image_loader_(new UserImageLoader(this))),
current_user_is_owner_(false) {
registrar_.Add(this, NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED,
NotificationService::AllSources());
}
UserManager::~UserManager() {
image_loader_->set_delegate(NULL);
}
void UserManager::NotifyOnLogin() {
NotificationService::current()->Notify(
NotificationType::LOGIN_USER_CHANGED,
Source<UserManager>(this),
Details<const User>(&logged_in_user_));
chromeos::CrosLibrary::Get()->GetInputMethodLibrary()->
SetDeferImeStartup(false);
// Shut down the IME so that it will reload the user's settings.
chromeos::CrosLibrary::Get()->GetInputMethodLibrary()->
StopInputMethodProcesses();
// Let the window manager know that we're logged in now.
WmIpc::instance()->SetLoggedInProperty(true);
// Ensure we've opened the real user's key/certificate database.
base::OpenPersistentNSSDB();
// Schedules current user ownership check on file thread.
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableFunction(&CheckOwnership));
}
void UserManager::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::OWNER_KEY_FETCH_ATTEMPT_SUCCEEDED) {
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableFunction(&CheckOwnership));
}
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/media/media_player.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chromeos/extensions/media_player_event_router.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/extensions/file_manager_util.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/user_metrics.h"
#include "content/common/url_fetcher.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_job.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/frame/panel_browser_view.h"
#endif
static const char* kMediaPlayerAppName = "mediaplayer";
static const int kPopupLeft = 0;
static const int kPopupTop = 0;
static const int kPopupWidth = 350;
static const int kPopupHeight = 300;
const MediaPlayer::UrlVector& MediaPlayer::GetPlaylist() const {
return current_playlist_;
}
int MediaPlayer::GetPlaylistPosition() const {
return current_position_;
}
////////////////////////////////////////////////////////////////////////////////
//
// Mediaplayer
//
////////////////////////////////////////////////////////////////////////////////
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(MediaPlayer);
MediaPlayer::~MediaPlayer() {
}
// static
MediaPlayer* MediaPlayer::GetInstance() {
return Singleton<MediaPlayer>::get();
}
void MediaPlayer::EnqueueMediaFile(Profile* profile, const FilePath& file_path,
Browser* creator) {
GURL url;
if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
GetOriginUrl(), &url)) {
}
EnqueueMediaFileUrl(url, creator);
}
void MediaPlayer::EnqueueMediaFileUrl(const GURL& url, Browser* creator) {
if (mediaplayer_browser_ == NULL) {
PopupMediaPlayer(creator);
}
EnqueueMediaFileUrl(url);
}
void MediaPlayer::EnqueueMediaFileUrl(const GURL& url) {
current_playlist_.push_back(MediaUrl(url));
NotifyPlaylistChanged();
}
void MediaPlayer::ForcePlayMediaFile(Profile* profile,
const FilePath& file_path,
Browser* creator) {
GURL url;
if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
GetOriginUrl(), &url)) {
return;
}
ForcePlayMediaURL(url, creator);
}
void MediaPlayer::ForcePlayMediaURL(const GURL& url, Browser* creator) {
if (mediaplayer_browser_ == NULL) {
PopupMediaPlayer(creator);
}
current_playlist_.clear();
current_playlist_.push_back(MediaUrl(url));
current_position_ = current_playlist_.size() - 1;
pending_playback_request_ = true;
NotifyPlaylistChanged();
}
void MediaPlayer::TogglePlaylistWindowVisible() {
if (playlist_browser_) {
ClosePlaylistWindow();
} else {
ShowPlaylistWindow();
}
}
void MediaPlayer::ShowPlaylistWindow() {
if (playlist_browser_ == NULL) {
PopupPlaylist(NULL);
}
}
void MediaPlayer::ClosePlaylistWindow() {
if (playlist_browser_ != NULL) {
playlist_browser_->window()->Close();
}
}
void MediaPlayer::SetPlaylistPosition(int position) {
const int playlist_size = current_playlist_.size();
if (current_position_ < 0 || current_position_ > playlist_size)
position = current_playlist_.size();
if (current_position_ != position) {
current_position_ = position;
NotifyPlaylistChanged();
}
}
void MediaPlayer::SetPlaybackError(GURL const& url) {
for (size_t x = 0; x < current_playlist_.size(); x++) {
if (current_playlist_[x].url == url) {
current_playlist_[x].haderror = true;
}
}
NotifyPlaylistChanged();
}
void MediaPlayer::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == chrome::NOTIFICATION_BROWSER_CLOSING);
registrar_.Remove(this,
chrome::NOTIFICATION_BROWSER_CLOSING,
source);
if (Source<Browser>(source).ptr() == mediaplayer_browser_) {
mediaplayer_browser_ = NULL;
} else if (Source<Browser>(source).ptr() == playlist_browser_) {
playlist_browser_ = NULL;
}
}
void MediaPlayer::NotifyPlaylistChanged() {
ExtensionMediaPlayerEventRouter::GetInstance()->NotifyPlaylistChanged();
}
bool MediaPlayer::GetPendingPlayRequestAndReset() {
bool result = pending_playback_request_;
pending_playback_request_ = false;
return result;
}
void MediaPlayer::SetPlaybackRequest() {
pending_playback_request_ = true;
}
void MediaPlayer::ToggleFullscreen() {
if (mediaplayer_browser_) {
mediaplayer_browser_->ToggleFullscreenMode();
}
}
void MediaPlayer::PopupPlaylist(Browser* creator) {
Profile* profile = BrowserList::GetLastActive()->profile();
playlist_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
kMediaPlayerAppName,
gfx::Rect(),
profile);
registrar_.Add(this,
chrome::NOTIFICATION_BROWSER_CLOSING,
Source<Browser>(playlist_browser_));
playlist_browser_->AddSelectedTabWithURL(GetMediaplayerPlaylistUrl(),
PageTransition::LINK);
playlist_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
kPopupTop,
kPopupWidth,
kPopupHeight));
playlist_browser_->window()->Show();
}
void MediaPlayer::PopupMediaPlayer(Browser* creator) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &MediaPlayer::PopupMediaPlayer,
static_cast<Browser*>(NULL)));
return;
}
Profile* profile = BrowserList::GetLastActive()->profile();
mediaplayer_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
kMediaPlayerAppName,
gfx::Rect(),
profile);
registrar_.Add(this,
chrome::NOTIFICATION_BROWSER_CLOSING,
Source<Browser>(mediaplayer_browser_));
#if defined(OS_CHROMEOS)
// Since we are on chromeos, popups should be a PanelBrowserView,
// so we can just cast it.
if (creator) {
chromeos::PanelBrowserView* creatorview =
static_cast<chromeos::PanelBrowserView*>(creator->window());
chromeos::PanelBrowserView* view =
static_cast<chromeos::PanelBrowserView*>(
mediaplayer_browser_->window());
view->SetCreatorView(creatorview);
}
#endif
mediaplayer_browser_->AddSelectedTabWithURL(GetMediaPlayerUrl(),
PageTransition::LINK);
mediaplayer_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
kPopupTop,
kPopupWidth,
kPopupHeight));
mediaplayer_browser_->window()->Show();
}
net::URLRequestJob* MediaPlayer::MaybeIntercept(net::URLRequest* request) {
// Don't attempt to intercept here as we want to wait until the mime
// type is fully determined.
return NULL;
}
// This is the list of mime types currently supported by the Google
// Document Viewer.
static const char* const supported_mime_type_list[] = {
"audio/mpeg",
"video/mp4",
"audio/mp3"
};
net::URLRequestJob* MediaPlayer::MaybeInterceptResponse(
net::URLRequest* request) {
// Do not intercept this request if it is a download.
if (request->load_flags() & net::LOAD_IS_DOWNLOAD) {
return NULL;
}
std::string mime_type;
request->GetMimeType(&mime_type);
// If it is in our list of known URLs, enqueue the url then
// Cancel the request so the mediaplayer can handle it when
// it hits it in the playlist.
if (supported_mime_types_.find(mime_type) != supported_mime_types_.end()) {
if (request->referrer() != chrome::kChromeUIMediaplayerURL &&
!request->referrer().empty()) {
EnqueueMediaFileUrl(request->url(), NULL);
request->Cancel();
}
}
return NULL;
}
GURL MediaPlayer::GetOriginUrl() const {
return FileManagerUtil::GetMediaPlayerUrl().GetOrigin();
}
GURL MediaPlayer::GetMediaplayerPlaylistUrl() const {
return FileManagerUtil::GetMediaPlayerPlaylistUrl();
}
GURL MediaPlayer::GetMediaPlayerUrl() const {
return FileManagerUtil::GetMediaPlayerUrl();
}
MediaPlayer::MediaPlayer()
: current_position_(0),
pending_playback_request_(false),
playlist_browser_(NULL),
mediaplayer_browser_(NULL) {
for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) {
supported_mime_types_.insert(supported_mime_type_list[i]);
}
};
<commit_msg>Fixing: Media file doesn't play after closing the media player using ctrl + w<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/media/media_player.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chromeos/extensions/media_player_event_router.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/extensions/file_manager_util.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/user_metrics.h"
#include "content/common/url_fetcher.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_job.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/frame/panel_browser_view.h"
#endif
static const char* kMediaPlayerAppName = "mediaplayer";
static const int kPopupLeft = 0;
static const int kPopupTop = 0;
static const int kPopupWidth = 350;
static const int kPopupHeight = 300;
const MediaPlayer::UrlVector& MediaPlayer::GetPlaylist() const {
return current_playlist_;
}
int MediaPlayer::GetPlaylistPosition() const {
return current_position_;
}
////////////////////////////////////////////////////////////////////////////////
//
// Mediaplayer
//
////////////////////////////////////////////////////////////////////////////////
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(MediaPlayer);
MediaPlayer::~MediaPlayer() {
}
// static
MediaPlayer* MediaPlayer::GetInstance() {
return Singleton<MediaPlayer>::get();
}
void MediaPlayer::EnqueueMediaFile(Profile* profile, const FilePath& file_path,
Browser* creator) {
GURL url;
if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
GetOriginUrl(), &url)) {
}
EnqueueMediaFileUrl(url, creator);
}
void MediaPlayer::EnqueueMediaFileUrl(const GURL& url, Browser* creator) {
if (mediaplayer_browser_ == NULL) {
PopupMediaPlayer(creator);
}
EnqueueMediaFileUrl(url);
}
void MediaPlayer::EnqueueMediaFileUrl(const GURL& url) {
current_playlist_.push_back(MediaUrl(url));
NotifyPlaylistChanged();
}
void MediaPlayer::ForcePlayMediaFile(Profile* profile,
const FilePath& file_path,
Browser* creator) {
GURL url;
if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
GetOriginUrl(), &url)) {
return;
}
ForcePlayMediaURL(url, creator);
}
void MediaPlayer::ForcePlayMediaURL(const GURL& url, Browser* creator) {
if (mediaplayer_browser_ == NULL) {
PopupMediaPlayer(creator);
}
current_playlist_.clear();
current_playlist_.push_back(MediaUrl(url));
current_position_ = current_playlist_.size() - 1;
pending_playback_request_ = true;
NotifyPlaylistChanged();
}
void MediaPlayer::TogglePlaylistWindowVisible() {
if (playlist_browser_) {
ClosePlaylistWindow();
} else {
ShowPlaylistWindow();
}
}
void MediaPlayer::ShowPlaylistWindow() {
if (playlist_browser_ == NULL) {
PopupPlaylist(NULL);
}
}
void MediaPlayer::ClosePlaylistWindow() {
if (playlist_browser_ != NULL) {
playlist_browser_->window()->Close();
}
}
void MediaPlayer::SetPlaylistPosition(int position) {
const int playlist_size = current_playlist_.size();
if (current_position_ < 0 || current_position_ > playlist_size)
position = current_playlist_.size();
if (current_position_ != position) {
current_position_ = position;
NotifyPlaylistChanged();
}
}
void MediaPlayer::SetPlaybackError(GURL const& url) {
for (size_t x = 0; x < current_playlist_.size(); x++) {
if (current_playlist_[x].url == url) {
current_playlist_[x].haderror = true;
}
}
NotifyPlaylistChanged();
}
void MediaPlayer::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == chrome::NOTIFICATION_BROWSER_CLOSED);
registrar_.Remove(this,
chrome::NOTIFICATION_BROWSER_CLOSED,
source);
if (Source<Browser>(source).ptr() == mediaplayer_browser_) {
mediaplayer_browser_ = NULL;
} else if (Source<Browser>(source).ptr() == playlist_browser_) {
playlist_browser_ = NULL;
}
}
void MediaPlayer::NotifyPlaylistChanged() {
ExtensionMediaPlayerEventRouter::GetInstance()->NotifyPlaylistChanged();
}
bool MediaPlayer::GetPendingPlayRequestAndReset() {
bool result = pending_playback_request_;
pending_playback_request_ = false;
return result;
}
void MediaPlayer::SetPlaybackRequest() {
pending_playback_request_ = true;
}
void MediaPlayer::ToggleFullscreen() {
if (mediaplayer_browser_) {
mediaplayer_browser_->ToggleFullscreenMode();
}
}
void MediaPlayer::PopupPlaylist(Browser* creator) {
Profile* profile = BrowserList::GetLastActive()->profile();
playlist_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
kMediaPlayerAppName,
gfx::Rect(),
profile);
registrar_.Add(this,
chrome::NOTIFICATION_BROWSER_CLOSED,
Source<Browser>(playlist_browser_));
playlist_browser_->AddSelectedTabWithURL(GetMediaplayerPlaylistUrl(),
PageTransition::LINK);
playlist_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
kPopupTop,
kPopupWidth,
kPopupHeight));
playlist_browser_->window()->Show();
}
void MediaPlayer::PopupMediaPlayer(Browser* creator) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &MediaPlayer::PopupMediaPlayer,
static_cast<Browser*>(NULL)));
return;
}
Profile* profile = BrowserList::GetLastActive()->profile();
mediaplayer_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
kMediaPlayerAppName,
gfx::Rect(),
profile);
registrar_.Add(this,
chrome::NOTIFICATION_BROWSER_CLOSED,
Source<Browser>(mediaplayer_browser_));
#if defined(OS_CHROMEOS)
// Since we are on chromeos, popups should be a PanelBrowserView,
// so we can just cast it.
if (creator) {
chromeos::PanelBrowserView* creatorview =
static_cast<chromeos::PanelBrowserView*>(creator->window());
chromeos::PanelBrowserView* view =
static_cast<chromeos::PanelBrowserView*>(
mediaplayer_browser_->window());
view->SetCreatorView(creatorview);
}
#endif
mediaplayer_browser_->AddSelectedTabWithURL(GetMediaPlayerUrl(),
PageTransition::LINK);
mediaplayer_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
kPopupTop,
kPopupWidth,
kPopupHeight));
mediaplayer_browser_->window()->Show();
}
net::URLRequestJob* MediaPlayer::MaybeIntercept(net::URLRequest* request) {
// Don't attempt to intercept here as we want to wait until the mime
// type is fully determined.
return NULL;
}
// This is the list of mime types currently supported by the Google
// Document Viewer.
static const char* const supported_mime_type_list[] = {
"audio/mpeg",
"video/mp4",
"audio/mp3"
};
net::URLRequestJob* MediaPlayer::MaybeInterceptResponse(
net::URLRequest* request) {
// Do not intercept this request if it is a download.
if (request->load_flags() & net::LOAD_IS_DOWNLOAD) {
return NULL;
}
std::string mime_type;
request->GetMimeType(&mime_type);
// If it is in our list of known URLs, enqueue the url then
// Cancel the request so the mediaplayer can handle it when
// it hits it in the playlist.
if (supported_mime_types_.find(mime_type) != supported_mime_types_.end()) {
if (request->referrer() != chrome::kChromeUIMediaplayerURL &&
!request->referrer().empty()) {
EnqueueMediaFileUrl(request->url(), NULL);
request->Cancel();
}
}
return NULL;
}
GURL MediaPlayer::GetOriginUrl() const {
return FileManagerUtil::GetMediaPlayerUrl().GetOrigin();
}
GURL MediaPlayer::GetMediaplayerPlaylistUrl() const {
return FileManagerUtil::GetMediaPlayerPlaylistUrl();
}
GURL MediaPlayer::GetMediaPlayerUrl() const {
return FileManagerUtil::GetMediaPlayerUrl();
}
MediaPlayer::MediaPlayer()
: current_position_(0),
pending_playback_request_(false),
playlist_browser_(NULL),
mediaplayer_browser_(NULL) {
for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) {
supported_mime_types_.insert(supported_mime_type_list[i]);
}
};
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_bookmark_manager_api.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
namespace {
const wchar_t kExtensionURLOverrides[] = L"extensions.chrome_url_overrides";
}
ExtensionDOMUI::ExtensionDOMUI(TabContents* tab_contents)
: DOMUI(tab_contents) {
// TODO(aa): It would be cool to show the extension's icon in here.
hide_favicon_ = true;
should_hide_url_ = true;
bindings_ = BindingsPolicy::EXTENSION;
// For chrome:// overrides, some of the defaults are a little different.
GURL url = tab_contents->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme)) {
if (url.host() == chrome::kChromeUINewTabHost) {
focus_location_bar_by_default_ = true;
} else {
// Current behavior of other chrome:// pages is to display the URL.
should_hide_url_ = false;
}
}
}
void ExtensionDOMUI::ResetExtensionFunctionDispatcher(
RenderViewHost* render_view_host) {
// Use the NavigationController to get the URL rather than the TabContents
// since this is the real underlying URL (see HandleChromeURLOverride).
NavigationController& controller = tab_contents()->controller();
const GURL& url = controller.GetActiveEntry()->url();
extension_function_dispatcher_.reset(
new ExtensionFunctionDispatcher(render_view_host, this, url));
}
void ExtensionDOMUI::ResetExtensionBookmarkManagerEventRouter() {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTabbedBookmarkManager)) {
extension_bookmark_manager_event_router_.reset(
new ExtensionBookmarkManagerEventRouter(GetProfile(), tab_contents()));
}
}
void ExtensionDOMUI::RenderViewCreated(RenderViewHost* render_view_host) {
ResetExtensionFunctionDispatcher(render_view_host);
ResetExtensionBookmarkManagerEventRouter();
}
void ExtensionDOMUI::RenderViewReused(RenderViewHost* render_view_host) {
ResetExtensionFunctionDispatcher(render_view_host);
ResetExtensionBookmarkManagerEventRouter();
}
void ExtensionDOMUI::ProcessDOMUIMessage(const std::string& message,
const Value* content,
int request_id,
bool has_callback) {
extension_function_dispatcher_->HandleRequest(message, content, request_id,
has_callback);
}
Browser* ExtensionDOMUI::GetBrowser(bool include_incognito) const {
Browser* browser = NULL;
TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
if (tab_contents_delegate) {
browser = tab_contents_delegate->GetBrowser();
if (browser && browser->profile()->IsOffTheRecord() && !include_incognito) {
// Fall back to the toplevel regular browser if we don't want to include
// incognito browsers.
browser = BrowserList::GetLastActiveWithProfile(
browser->profile()->GetOriginalProfile());
}
}
return browser;
}
Profile* ExtensionDOMUI::GetProfile() {
return DOMUI::GetProfile();
}
gfx::NativeWindow ExtensionDOMUI::GetFrameNativeWindow() {
gfx::NativeWindow native_window =
ExtensionFunctionDispatcher::Delegate::GetFrameNativeWindow();
// If there was no window associated with the function dispatcher delegate,
// then this DOMUI may be hosted in an ExternalTabContainer, and a framing
// window will be accessible through the tab_contents.
if (!native_window) {
TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
if (tab_contents_delegate)
native_window = tab_contents_delegate->GetFrameNativeWindow();
}
return native_window;
}
gfx::NativeView ExtensionDOMUI::GetNativeViewOfHost() {
return tab_contents()->GetRenderWidgetHostView()->GetNativeView();
}
////////////////////////////////////////////////////////////////////////////////
// chrome:// URL overrides
// static
void ExtensionDOMUI::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(kExtensionURLOverrides);
}
// static
bool ExtensionDOMUI::HandleChromeURLOverride(GURL* url, Profile* profile) {
if (!url->SchemeIs(chrome::kChromeUIScheme))
return false;
// Even when the extensions service is enabled by default, it's still
// disabled in incognito mode.
ExtensionsService* service = profile->GetExtensionsService();
if (!service)
return false;
const DictionaryValue* overrides =
profile->GetPrefs()->GetDictionary(kExtensionURLOverrides);
std::string page = url->host();
ListValue* url_list;
if (!overrides || !overrides->GetList(UTF8ToWide(page), &url_list))
return false;
if (!service->is_ready()) {
// TODO(erikkay) So far, it looks like extensions load before the new tab
// page. I don't know if we have anything that enforces this, so add this
// check for safety.
NOTREACHED() << "Chrome URL override requested before extensions loaded";
return false;
}
while (url_list->GetSize()) {
Value* val;
url_list->Get(0, &val);
// Verify that the override value is good. If not, unregister it and find
// the next one.
std::string override;
if (!val->GetAsString(&override)) {
NOTREACHED();
UnregisterChromeURLOverride(page, profile, val);
continue;
}
GURL extension_url(override);
if (!extension_url.is_valid()) {
NOTREACHED();
UnregisterChromeURLOverride(page, profile, val);
continue;
}
// Verify that the extension that's being referred to actually exists.
Extension* extension = service->GetExtensionByURL(extension_url);
if (!extension) {
// This can currently happen if you use --load-extension one run, and
// then don't use it the next. It could also happen if an extension
// were deleted directly from the filesystem, etc.
LOG(WARNING) << "chrome URL override present for non-existant extension";
UnregisterChromeURLOverride(page, profile, val);
continue;
}
*url = extension_url;
return true;
}
return false;
}
// static
void ExtensionDOMUI::RegisterChromeURLOverrides(
Profile* profile, const Extension::URLOverrideMap& overrides) {
if (overrides.empty())
return;
PrefService* prefs = profile->GetPrefs();
DictionaryValue* all_overrides =
prefs->GetMutableDictionary(kExtensionURLOverrides);
// For each override provided by the extension, add it to the front of
// the override list if it's not already in the list.
Extension::URLOverrideMap::const_iterator iter = overrides.begin();
for (;iter != overrides.end(); ++iter) {
const std::wstring key = UTF8ToWide((*iter).first);
ListValue* page_overrides;
if (!all_overrides->GetList(key, &page_overrides)) {
page_overrides = new ListValue();
all_overrides->Set(key, page_overrides);
} else {
// Verify that the override isn't already in the list.
ListValue::iterator i = page_overrides->begin();
for (; i != page_overrides->end(); ++i) {
std::string override_val;
if (!(*i)->GetAsString(&override_val)) {
NOTREACHED();
continue;
}
if (override_val == (*iter).first)
break;
}
// This value is already in the list, leave it alone.
if (i != page_overrides->end())
continue;
}
// Insert the override at the front of the list. Last registered override
// wins.
page_overrides->Insert(0, new StringValue((*iter).second.spec()));
}
}
// static
void ExtensionDOMUI::UnregisterAndReplaceOverride(const std::string& page,
Profile* profile, ListValue* list, Value* override) {
int index = list->Remove(*override);
if (index == 0) {
// This is the active override, so we need to find all existing
// tabs for this override and get them to reload the original URL.
for (TabContentsIterator iterator; !iterator.done(); ++iterator) {
TabContents* tab = *iterator;
if (tab->profile() != profile)
continue;
GURL url = tab->GetURL();
if (!url.SchemeIs(chrome::kChromeUIScheme) || url.host() != page)
continue;
// Don't use Reload() since |url| isn't the same as the internal URL
// that NavigationController has.
tab->controller().LoadURL(url, url, PageTransition::RELOAD);
}
}
}
// static
void ExtensionDOMUI::UnregisterChromeURLOverride(const std::string& page,
Profile* profile, Value* override) {
if (!override)
return;
PrefService* prefs = profile->GetPrefs();
DictionaryValue* all_overrides =
prefs->GetMutableDictionary(kExtensionURLOverrides);
ListValue* page_overrides;
if (!all_overrides->GetList(UTF8ToWide(page), &page_overrides)) {
// If it's being unregistered, it should already be in the list.
NOTREACHED();
return;
} else {
UnregisterAndReplaceOverride(page, profile, page_overrides, override);
}
}
RenderViewHost* ExtensionDOMUI::GetRenderViewHost() {
return tab_contents() ? tab_contents()->render_view_host() : NULL;
}
// static
void ExtensionDOMUI::UnregisterChromeURLOverrides(
Profile* profile, const Extension::URLOverrideMap& overrides) {
if (overrides.empty())
return;
PrefService* prefs = profile->GetPrefs();
DictionaryValue* all_overrides =
prefs->GetMutableDictionary(kExtensionURLOverrides);
Extension::URLOverrideMap::const_iterator iter = overrides.begin();
for (;iter != overrides.end(); ++iter) {
std::wstring page = UTF8ToWide((*iter).first);
ListValue* page_overrides;
if (!all_overrides->GetList(page, &page_overrides)) {
// If it's being unregistered, it should already be in the list.
NOTREACHED();
continue;
} else {
StringValue override((*iter).second.spec());
UnregisterAndReplaceOverride((*iter).first, profile,
page_overrides, &override);
}
}
}
<commit_msg>Hide the URL for all chrome_url_overrides.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_bookmark_manager_api.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
namespace {
const wchar_t kExtensionURLOverrides[] = L"extensions.chrome_url_overrides";
}
ExtensionDOMUI::ExtensionDOMUI(TabContents* tab_contents)
: DOMUI(tab_contents) {
// TODO(aa): It would be cool to show the extension's icon in here.
hide_favicon_ = true;
should_hide_url_ = true;
bindings_ = BindingsPolicy::EXTENSION;
// For chrome:// overrides, some of the defaults are a little different.
GURL url = tab_contents->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUINewTabHost) {
focus_location_bar_by_default_ = true;
}
}
void ExtensionDOMUI::ResetExtensionFunctionDispatcher(
RenderViewHost* render_view_host) {
// Use the NavigationController to get the URL rather than the TabContents
// since this is the real underlying URL (see HandleChromeURLOverride).
NavigationController& controller = tab_contents()->controller();
const GURL& url = controller.GetActiveEntry()->url();
extension_function_dispatcher_.reset(
new ExtensionFunctionDispatcher(render_view_host, this, url));
}
void ExtensionDOMUI::ResetExtensionBookmarkManagerEventRouter() {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTabbedBookmarkManager)) {
extension_bookmark_manager_event_router_.reset(
new ExtensionBookmarkManagerEventRouter(GetProfile(), tab_contents()));
}
}
void ExtensionDOMUI::RenderViewCreated(RenderViewHost* render_view_host) {
ResetExtensionFunctionDispatcher(render_view_host);
ResetExtensionBookmarkManagerEventRouter();
}
void ExtensionDOMUI::RenderViewReused(RenderViewHost* render_view_host) {
ResetExtensionFunctionDispatcher(render_view_host);
ResetExtensionBookmarkManagerEventRouter();
}
void ExtensionDOMUI::ProcessDOMUIMessage(const std::string& message,
const Value* content,
int request_id,
bool has_callback) {
extension_function_dispatcher_->HandleRequest(message, content, request_id,
has_callback);
}
Browser* ExtensionDOMUI::GetBrowser(bool include_incognito) const {
Browser* browser = NULL;
TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
if (tab_contents_delegate) {
browser = tab_contents_delegate->GetBrowser();
if (browser && browser->profile()->IsOffTheRecord() && !include_incognito) {
// Fall back to the toplevel regular browser if we don't want to include
// incognito browsers.
browser = BrowserList::GetLastActiveWithProfile(
browser->profile()->GetOriginalProfile());
}
}
return browser;
}
Profile* ExtensionDOMUI::GetProfile() {
return DOMUI::GetProfile();
}
gfx::NativeWindow ExtensionDOMUI::GetFrameNativeWindow() {
gfx::NativeWindow native_window =
ExtensionFunctionDispatcher::Delegate::GetFrameNativeWindow();
// If there was no window associated with the function dispatcher delegate,
// then this DOMUI may be hosted in an ExternalTabContainer, and a framing
// window will be accessible through the tab_contents.
if (!native_window) {
TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
if (tab_contents_delegate)
native_window = tab_contents_delegate->GetFrameNativeWindow();
}
return native_window;
}
gfx::NativeView ExtensionDOMUI::GetNativeViewOfHost() {
return tab_contents()->GetRenderWidgetHostView()->GetNativeView();
}
////////////////////////////////////////////////////////////////////////////////
// chrome:// URL overrides
// static
void ExtensionDOMUI::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(kExtensionURLOverrides);
}
// static
bool ExtensionDOMUI::HandleChromeURLOverride(GURL* url, Profile* profile) {
if (!url->SchemeIs(chrome::kChromeUIScheme))
return false;
// Even when the extensions service is enabled by default, it's still
// disabled in incognito mode.
ExtensionsService* service = profile->GetExtensionsService();
if (!service)
return false;
const DictionaryValue* overrides =
profile->GetPrefs()->GetDictionary(kExtensionURLOverrides);
std::string page = url->host();
ListValue* url_list;
if (!overrides || !overrides->GetList(UTF8ToWide(page), &url_list))
return false;
if (!service->is_ready()) {
// TODO(erikkay) So far, it looks like extensions load before the new tab
// page. I don't know if we have anything that enforces this, so add this
// check for safety.
NOTREACHED() << "Chrome URL override requested before extensions loaded";
return false;
}
while (url_list->GetSize()) {
Value* val;
url_list->Get(0, &val);
// Verify that the override value is good. If not, unregister it and find
// the next one.
std::string override;
if (!val->GetAsString(&override)) {
NOTREACHED();
UnregisterChromeURLOverride(page, profile, val);
continue;
}
GURL extension_url(override);
if (!extension_url.is_valid()) {
NOTREACHED();
UnregisterChromeURLOverride(page, profile, val);
continue;
}
// Verify that the extension that's being referred to actually exists.
Extension* extension = service->GetExtensionByURL(extension_url);
if (!extension) {
// This can currently happen if you use --load-extension one run, and
// then don't use it the next. It could also happen if an extension
// were deleted directly from the filesystem, etc.
LOG(WARNING) << "chrome URL override present for non-existant extension";
UnregisterChromeURLOverride(page, profile, val);
continue;
}
*url = extension_url;
return true;
}
return false;
}
// static
void ExtensionDOMUI::RegisterChromeURLOverrides(
Profile* profile, const Extension::URLOverrideMap& overrides) {
if (overrides.empty())
return;
PrefService* prefs = profile->GetPrefs();
DictionaryValue* all_overrides =
prefs->GetMutableDictionary(kExtensionURLOverrides);
// For each override provided by the extension, add it to the front of
// the override list if it's not already in the list.
Extension::URLOverrideMap::const_iterator iter = overrides.begin();
for (;iter != overrides.end(); ++iter) {
const std::wstring key = UTF8ToWide((*iter).first);
ListValue* page_overrides;
if (!all_overrides->GetList(key, &page_overrides)) {
page_overrides = new ListValue();
all_overrides->Set(key, page_overrides);
} else {
// Verify that the override isn't already in the list.
ListValue::iterator i = page_overrides->begin();
for (; i != page_overrides->end(); ++i) {
std::string override_val;
if (!(*i)->GetAsString(&override_val)) {
NOTREACHED();
continue;
}
if (override_val == (*iter).first)
break;
}
// This value is already in the list, leave it alone.
if (i != page_overrides->end())
continue;
}
// Insert the override at the front of the list. Last registered override
// wins.
page_overrides->Insert(0, new StringValue((*iter).second.spec()));
}
}
// static
void ExtensionDOMUI::UnregisterAndReplaceOverride(const std::string& page,
Profile* profile, ListValue* list, Value* override) {
int index = list->Remove(*override);
if (index == 0) {
// This is the active override, so we need to find all existing
// tabs for this override and get them to reload the original URL.
for (TabContentsIterator iterator; !iterator.done(); ++iterator) {
TabContents* tab = *iterator;
if (tab->profile() != profile)
continue;
GURL url = tab->GetURL();
if (!url.SchemeIs(chrome::kChromeUIScheme) || url.host() != page)
continue;
// Don't use Reload() since |url| isn't the same as the internal URL
// that NavigationController has.
tab->controller().LoadURL(url, url, PageTransition::RELOAD);
}
}
}
// static
void ExtensionDOMUI::UnregisterChromeURLOverride(const std::string& page,
Profile* profile, Value* override) {
if (!override)
return;
PrefService* prefs = profile->GetPrefs();
DictionaryValue* all_overrides =
prefs->GetMutableDictionary(kExtensionURLOverrides);
ListValue* page_overrides;
if (!all_overrides->GetList(UTF8ToWide(page), &page_overrides)) {
// If it's being unregistered, it should already be in the list.
NOTREACHED();
return;
} else {
UnregisterAndReplaceOverride(page, profile, page_overrides, override);
}
}
RenderViewHost* ExtensionDOMUI::GetRenderViewHost() {
return tab_contents() ? tab_contents()->render_view_host() : NULL;
}
// static
void ExtensionDOMUI::UnregisterChromeURLOverrides(
Profile* profile, const Extension::URLOverrideMap& overrides) {
if (overrides.empty())
return;
PrefService* prefs = profile->GetPrefs();
DictionaryValue* all_overrides =
prefs->GetMutableDictionary(kExtensionURLOverrides);
Extension::URLOverrideMap::const_iterator iter = overrides.begin();
for (;iter != overrides.end(); ++iter) {
std::wstring page = UTF8ToWide((*iter).first);
ListValue* page_overrides;
if (!all_overrides->GetList(page, &page_overrides)) {
// If it's being unregistered, it should already be in the list.
NOTREACHED();
continue;
} else {
StringValue override((*iter).second.spec());
UnregisterAndReplaceOverride((*iter).first, profile,
page_overrides, &override);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_manager.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_manager.h"
#include "chrome/common/render_messages.h"
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
PRERENDER_MODE_ENABLED;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::GetMode() {
return mode_;
}
// static
void PrerenderManager::SetMode(PrerenderManagerMode mode) {
mode_ = mode;
}
struct PrerenderManager::PrerenderContentsData {
PrerenderContents* contents_;
base::Time start_time_;
GURL url_;
PrerenderContentsData(PrerenderContents* contents,
base::Time start_time,
GURL url)
: contents_(contents),
start_time_(start_time),
url_(url) {
}
};
PrerenderManager::PrerenderManager(Profile* profile)
: profile_(profile),
max_prerender_age_(base::TimeDelta::FromSeconds(
kDefaultMaxPrerenderAgeSeconds)),
max_elements_(kDefaultMaxPrerenderElements),
prerender_contents_factory_(PrerenderContents::CreateFactory()) {
}
PrerenderManager::~PrerenderManager() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(
PrerenderContents::FINAL_STATUS_MANAGER_SHUTDOWN);
delete data.contents_;
}
}
void PrerenderManager::SetPrerenderContentsFactory(
PrerenderContents::Factory* prerender_contents_factory) {
prerender_contents_factory_.reset(prerender_contents_factory);
}
void PrerenderManager::AddPreload(const GURL& url,
const std::vector<GURL>& alias_urls) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeleteOldEntries();
// If the URL already exists in the set of preloaded URLs, don't do anything.
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->url_ == url)
return;
}
PrerenderContentsData data(CreatePrerenderContents(url, alias_urls),
GetCurrentTime(), url);
prerender_list_.push_back(data);
data.contents_->StartPrerendering();
while (prerender_list_.size() > max_elements_) {
data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_EVICTED);
delete data.contents_;
}
}
void PrerenderManager::DeleteOldEntries() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
if (IsPrerenderElementFresh(data.start_time_))
return;
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_TIMED_OUT);
delete data.contents_;
}
}
PrerenderContents* PrerenderManager::GetEntry(const GURL& url) {
DeleteOldEntries();
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
PrerenderContents* pc = it->contents_;
if (pc->MatchesURL(url)) {
PrerenderContents* pc = it->contents_;
prerender_list_.erase(it);
return pc;
}
}
// Entry not found.
return NULL;
}
bool PrerenderManager::MaybeUsePreloadedPage(TabContents* tc, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
scoped_ptr<PrerenderContents> pc(GetEntry(url));
if (pc.get() == NULL)
return false;
if (!pc->load_start_time().is_null())
RecordTimeUntilUsed(base::TimeTicks::Now() - pc->load_start_time());
pc->set_final_status(PrerenderContents::FINAL_STATUS_USED);
RenderViewHost* rvh = pc->render_view_host();
pc->set_render_view_host(NULL);
rvh->Send(new ViewMsg_DisplayPrerenderedPage(rvh->routing_id()));
tc->SwapInRenderViewHost(rvh);
ViewHostMsg_FrameNavigate_Params* p = pc->navigate_params();
if (p != NULL)
tc->DidNavigate(rvh, *p);
string16 title = pc->title();
if (!title.empty())
tc->UpdateTitle(rvh, pc->page_id(), UTF16ToWideHack(title));
if (pc->has_stopped_loading())
tc->DidStopLoading();
return true;
}
void PrerenderManager::RemoveEntry(PrerenderContents* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_ == entry) {
prerender_list_.erase(it);
break;
}
}
DeleteOldEntries();
}
base::Time PrerenderManager::GetCurrentTime() const {
return base::Time::Now();
}
bool PrerenderManager::IsPrerenderElementFresh(const base::Time start) const {
base::Time now = GetCurrentTime();
return (now - start < max_prerender_age_);
}
PrerenderContents* PrerenderManager::CreatePrerenderContents(
const GURL& url,
const std::vector<GURL>& alias_urls) {
return prerender_contents_factory_->CreatePrerenderContents(
this, profile_, url, alias_urls);
}
void PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta pplt) {
bool record_windowed_pplt = ShouldRecordWindowedPPLT();
switch (mode_) {
case PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderControl", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderControl", pplt);
}
break;
case PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderTreatment", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderTreatment", pplt);
}
break;
default:
break;
}
}
void PrerenderManager::RecordTimeUntilUsed(base::TimeDelta time_until_used) {
if (mode_ == PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP) {
UMA_HISTOGRAM_TIMES("PLT.TimeUntilUsed_PrerenderTreatment",
time_until_used);
}
}
PrerenderContents* PrerenderManager::FindEntry(const GURL& url) {
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_->MatchesURL(url))
return it->contents_;
}
// Entry not found.
return NULL;
}
void PrerenderManager::RecordPrefetchTagObserved() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// If we observe multiple tags within the 30 second window, we will still
// reset the window to begin at the most recent occurrence, so that we will
// always be in a window in the 30 seconds from each occurrence.
last_prefetch_seen_time_ = base::TimeTicks::Now();
}
bool PrerenderManager::ShouldRecordWindowedPPLT() const {
if (last_prefetch_seen_time_.is_null())
return false;
base::TimeDelta elapsed_time =
base::TimeTicks::Now() - last_prefetch_seen_time_;
return elapsed_time <= base::TimeDelta::FromSeconds(kWindowedPPLTSeconds);
}
<commit_msg>fix for build break BUG=none TEST=none Review URL: http://codereview.chromium.org/6334063<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_manager.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_manager.h"
#include "chrome/common/render_messages.h"
// static
base::TimeTicks PrerenderManager::last_prefetch_seen_time_;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
PRERENDER_MODE_ENABLED;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::GetMode() {
return mode_;
}
// static
void PrerenderManager::SetMode(PrerenderManagerMode mode) {
mode_ = mode;
}
struct PrerenderManager::PrerenderContentsData {
PrerenderContents* contents_;
base::Time start_time_;
GURL url_;
PrerenderContentsData(PrerenderContents* contents,
base::Time start_time,
GURL url)
: contents_(contents),
start_time_(start_time),
url_(url) {
}
};
PrerenderManager::PrerenderManager(Profile* profile)
: profile_(profile),
max_prerender_age_(base::TimeDelta::FromSeconds(
kDefaultMaxPrerenderAgeSeconds)),
max_elements_(kDefaultMaxPrerenderElements),
prerender_contents_factory_(PrerenderContents::CreateFactory()) {
}
PrerenderManager::~PrerenderManager() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(
PrerenderContents::FINAL_STATUS_MANAGER_SHUTDOWN);
delete data.contents_;
}
}
void PrerenderManager::SetPrerenderContentsFactory(
PrerenderContents::Factory* prerender_contents_factory) {
prerender_contents_factory_.reset(prerender_contents_factory);
}
void PrerenderManager::AddPreload(const GURL& url,
const std::vector<GURL>& alias_urls) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeleteOldEntries();
// If the URL already exists in the set of preloaded URLs, don't do anything.
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->url_ == url)
return;
}
PrerenderContentsData data(CreatePrerenderContents(url, alias_urls),
GetCurrentTime(), url);
prerender_list_.push_back(data);
data.contents_->StartPrerendering();
while (prerender_list_.size() > max_elements_) {
data = prerender_list_.front();
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_EVICTED);
delete data.contents_;
}
}
void PrerenderManager::DeleteOldEntries() {
while (prerender_list_.size() > 0) {
PrerenderContentsData data = prerender_list_.front();
if (IsPrerenderElementFresh(data.start_time_))
return;
prerender_list_.pop_front();
data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_TIMED_OUT);
delete data.contents_;
}
}
PrerenderContents* PrerenderManager::GetEntry(const GURL& url) {
DeleteOldEntries();
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
PrerenderContents* pc = it->contents_;
if (pc->MatchesURL(url)) {
PrerenderContents* pc = it->contents_;
prerender_list_.erase(it);
return pc;
}
}
// Entry not found.
return NULL;
}
bool PrerenderManager::MaybeUsePreloadedPage(TabContents* tc, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
scoped_ptr<PrerenderContents> pc(GetEntry(url));
if (pc.get() == NULL)
return false;
if (!pc->load_start_time().is_null())
RecordTimeUntilUsed(base::TimeTicks::Now() - pc->load_start_time());
pc->set_final_status(PrerenderContents::FINAL_STATUS_USED);
RenderViewHost* rvh = pc->render_view_host();
pc->set_render_view_host(NULL);
rvh->Send(new ViewMsg_DisplayPrerenderedPage(rvh->routing_id()));
tc->SwapInRenderViewHost(rvh);
ViewHostMsg_FrameNavigate_Params* p = pc->navigate_params();
if (p != NULL)
tc->DidNavigate(rvh, *p);
string16 title = pc->title();
if (!title.empty())
tc->UpdateTitle(rvh, pc->page_id(), UTF16ToWideHack(title));
if (pc->has_stopped_loading())
tc->DidStopLoading();
return true;
}
void PrerenderManager::RemoveEntry(PrerenderContents* entry) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_ == entry) {
prerender_list_.erase(it);
break;
}
}
DeleteOldEntries();
}
base::Time PrerenderManager::GetCurrentTime() const {
return base::Time::Now();
}
bool PrerenderManager::IsPrerenderElementFresh(const base::Time start) const {
base::Time now = GetCurrentTime();
return (now - start < max_prerender_age_);
}
PrerenderContents* PrerenderManager::CreatePrerenderContents(
const GURL& url,
const std::vector<GURL>& alias_urls) {
return prerender_contents_factory_->CreatePrerenderContents(
this, profile_, url, alias_urls);
}
void PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta pplt) {
bool record_windowed_pplt = ShouldRecordWindowedPPLT();
switch (mode_) {
case PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderControl", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderControl", pplt);
}
break;
case PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP:
UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderTreatment", pplt);
if (record_windowed_pplt) {
UMA_HISTOGRAM_TIMES(
"PLT.PerceivedPageLoadTime_WindowPrerenderTreatment", pplt);
}
break;
default:
break;
}
}
void PrerenderManager::RecordTimeUntilUsed(base::TimeDelta time_until_used) {
if (mode_ == PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP) {
UMA_HISTOGRAM_TIMES("PLT.TimeUntilUsed_PrerenderTreatment",
time_until_used);
}
}
PrerenderContents* PrerenderManager::FindEntry(const GURL& url) {
for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
it != prerender_list_.end();
++it) {
if (it->contents_->MatchesURL(url))
return it->contents_;
}
// Entry not found.
return NULL;
}
void PrerenderManager::RecordPrefetchTagObserved() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// If we observe multiple tags within the 30 second window, we will still
// reset the window to begin at the most recent occurrence, so that we will
// always be in a window in the 30 seconds from each occurrence.
last_prefetch_seen_time_ = base::TimeTicks::Now();
}
bool PrerenderManager::ShouldRecordWindowedPPLT() const {
if (last_prefetch_seen_time_.is_null())
return false;
base::TimeDelta elapsed_time =
base::TimeTicks::Now() - last_prefetch_seen_time_;
return elapsed_time <= base::TimeDelta::FromSeconds(kWindowedPPLTSeconds);
}
<|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/common/extensions/manifest.h"
#include <algorithm>
#include <set>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/extensions/features/feature.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
namespace extensions {
class ManifestTest : public testing::Test {
public:
ManifestTest() : default_value_("test") {}
protected:
void AssertType(Manifest* manifest, Extension::Type type) {
EXPECT_EQ(type, manifest->type());
EXPECT_EQ(type == Extension::TYPE_THEME, manifest->is_theme());
EXPECT_EQ(type == Extension::TYPE_PLATFORM_APP,
manifest->is_platform_app());
EXPECT_EQ(type == Extension::TYPE_PACKAGED_APP,
manifest->is_packaged_app());
EXPECT_EQ(type == Extension::TYPE_HOSTED_APP, manifest->is_hosted_app());
}
// Helper function that replaces the Manifest held by |manifest| with a copy
// with its |key| changed to |value|. If |value| is NULL, then |key| will
// instead be deleted.
void MutateManifest(
scoped_ptr<Manifest>* manifest, const std::string& key, Value* value) {
scoped_ptr<DictionaryValue> manifest_value(
manifest->get()->value()->DeepCopy());
if (value)
manifest_value->Set(key, value);
else
manifest_value->Remove(key, NULL);
manifest->reset(new Manifest(Extension::INTERNAL, manifest_value.Pass()));
}
std::string default_value_;
};
// Verifies that extensions can access the correct keys.
TEST_F(ManifestTest, Extension) {
scoped_ptr<DictionaryValue> manifest_value(new DictionaryValue());
manifest_value->SetString(keys::kName, "extension");
manifest_value->SetString(keys::kVersion, "1");
// Only supported in manifest_version=1.
manifest_value->SetString(keys::kBackgroundPageLegacy, "bg.html");
manifest_value->SetString("unknown_key", "foo");
scoped_ptr<Manifest> manifest(
new Manifest(Extension::INTERNAL, manifest_value.Pass()));
std::string error;
Extension::InstallWarningVector warnings;
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
ASSERT_EQ(1u, warnings.size());
AssertType(manifest.get(), Extension::TYPE_EXTENSION);
// The known key 'background_page' should be accessible.
std::string value;
EXPECT_TRUE(manifest->GetString(keys::kBackgroundPageLegacy, &value));
EXPECT_EQ("bg.html", value);
// The unknown key 'unknown_key' should be accesible.
value.clear();
EXPECT_TRUE(manifest->GetString("unknown_key", &value));
EXPECT_EQ("foo", value);
// Set the manifest_version to 2; background_page should stop working.
value.clear();
MutateManifest(
&manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
EXPECT_FALSE(manifest->GetString("background_page", &value));
EXPECT_EQ("", value);
// Validate should also give a warning.
warnings.clear();
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
ASSERT_EQ(2u, warnings.size());
{
Feature feature;
feature.set_name("background_page");
feature.set_max_manifest_version(1);
EXPECT_EQ(
"'background_page' requires manifest version of 1 or lower.",
warnings[0].message);
}
// Test DeepCopy and Equals.
scoped_ptr<Manifest> manifest2(manifest->DeepCopy());
EXPECT_TRUE(manifest->Equals(manifest2.get()));
EXPECT_TRUE(manifest2->Equals(manifest.get()));
MutateManifest(
&manifest, "foo", Value::CreateStringValue("blah"));
EXPECT_FALSE(manifest->Equals(manifest2.get()));
}
// Verifies that key restriction based on type works.
TEST_F(ManifestTest, ExtensionTypes) {
scoped_ptr<DictionaryValue> value(new DictionaryValue());
value->SetString(keys::kName, "extension");
value->SetString(keys::kVersion, "1");
scoped_ptr<Manifest> manifest(
new Manifest(Extension::INTERNAL, value.Pass()));
std::string error;
Extension::InstallWarningVector warnings;
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
EXPECT_TRUE(warnings.empty());
// By default, the type is Extension.
AssertType(manifest.get(), Extension::TYPE_EXTENSION);
// Theme.
MutateManifest(
&manifest, keys::kTheme, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_THEME);
MutateManifest(
&manifest, keys::kTheme, NULL);
// Packaged app.
MutateManifest(
&manifest, keys::kApp, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_PACKAGED_APP);
// Platform app.
MutateManifest(
&manifest, keys::kPlatformAppBackground, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
MutateManifest(
&manifest, keys::kPlatformAppBackground, NULL);
// Hosted app.
MutateManifest(
&manifest, keys::kWebURLs, new ListValue());
AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
MutateManifest(
&manifest, keys::kWebURLs, NULL);
MutateManifest(
&manifest, keys::kLaunchWebURL, Value::CreateStringValue("foo"));
AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
MutateManifest(
&manifest, keys::kLaunchWebURL, NULL);
};
// Verifies that the getters filter restricted keys.
TEST_F(ManifestTest, RestrictedKeys) {
scoped_ptr<DictionaryValue> value(new DictionaryValue());
value->SetString(keys::kName, "extension");
value->SetString(keys::kVersion, "1");
scoped_ptr<Manifest> manifest(
new Manifest(Extension::INTERNAL, value.Pass()));
std::string error;
Extension::InstallWarningVector warnings;
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
EXPECT_TRUE(warnings.empty());
// Platform apps cannot have a "page_action" key.
MutateManifest(
&manifest, keys::kPageAction, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_EXTENSION);
base::Value* output = NULL;
EXPECT_TRUE(manifest->HasKey(keys::kPageAction));
EXPECT_TRUE(manifest->Get(keys::kPageAction, &output));
MutateManifest(
&manifest, keys::kPlatformAppBackground, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
EXPECT_FALSE(manifest->HasKey(keys::kPageAction));
EXPECT_FALSE(manifest->Get(keys::kPageAction, &output));
MutateManifest(
&manifest, keys::kPlatformAppBackground, NULL);
// "commands" is restricted to manifest_version >= 2.
MutateManifest(
&manifest, keys::kCommands, new DictionaryValue());
EXPECT_FALSE(manifest->HasKey(keys::kCommands));
EXPECT_FALSE(manifest->Get(keys::kCommands, &output));
MutateManifest(
&manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
EXPECT_TRUE(manifest->HasKey(keys::kCommands));
EXPECT_TRUE(manifest->Get(keys::kCommands, &output));
};
} // namespace extensions
<commit_msg>Scope ManifestTest.RestrictedKeys to DEV channel for the commands API.<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/common/extensions/manifest.h"
#include <algorithm>
#include <set>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/extensions/features/feature.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
namespace extensions {
class ManifestTest : public testing::Test {
public:
ManifestTest() : default_value_("test") {}
protected:
void AssertType(Manifest* manifest, Extension::Type type) {
EXPECT_EQ(type, manifest->type());
EXPECT_EQ(type == Extension::TYPE_THEME, manifest->is_theme());
EXPECT_EQ(type == Extension::TYPE_PLATFORM_APP,
manifest->is_platform_app());
EXPECT_EQ(type == Extension::TYPE_PACKAGED_APP,
manifest->is_packaged_app());
EXPECT_EQ(type == Extension::TYPE_HOSTED_APP, manifest->is_hosted_app());
}
// Helper function that replaces the Manifest held by |manifest| with a copy
// with its |key| changed to |value|. If |value| is NULL, then |key| will
// instead be deleted.
void MutateManifest(
scoped_ptr<Manifest>* manifest, const std::string& key, Value* value) {
scoped_ptr<DictionaryValue> manifest_value(
manifest->get()->value()->DeepCopy());
if (value)
manifest_value->Set(key, value);
else
manifest_value->Remove(key, NULL);
manifest->reset(new Manifest(Extension::INTERNAL, manifest_value.Pass()));
}
std::string default_value_;
};
// Verifies that extensions can access the correct keys.
TEST_F(ManifestTest, Extension) {
scoped_ptr<DictionaryValue> manifest_value(new DictionaryValue());
manifest_value->SetString(keys::kName, "extension");
manifest_value->SetString(keys::kVersion, "1");
// Only supported in manifest_version=1.
manifest_value->SetString(keys::kBackgroundPageLegacy, "bg.html");
manifest_value->SetString("unknown_key", "foo");
scoped_ptr<Manifest> manifest(
new Manifest(Extension::INTERNAL, manifest_value.Pass()));
std::string error;
Extension::InstallWarningVector warnings;
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
ASSERT_EQ(1u, warnings.size());
AssertType(manifest.get(), Extension::TYPE_EXTENSION);
// The known key 'background_page' should be accessible.
std::string value;
EXPECT_TRUE(manifest->GetString(keys::kBackgroundPageLegacy, &value));
EXPECT_EQ("bg.html", value);
// The unknown key 'unknown_key' should be accesible.
value.clear();
EXPECT_TRUE(manifest->GetString("unknown_key", &value));
EXPECT_EQ("foo", value);
// Set the manifest_version to 2; background_page should stop working.
value.clear();
MutateManifest(
&manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
EXPECT_FALSE(manifest->GetString("background_page", &value));
EXPECT_EQ("", value);
// Validate should also give a warning.
warnings.clear();
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
ASSERT_EQ(2u, warnings.size());
{
Feature feature;
feature.set_name("background_page");
feature.set_max_manifest_version(1);
EXPECT_EQ(
"'background_page' requires manifest version of 1 or lower.",
warnings[0].message);
}
// Test DeepCopy and Equals.
scoped_ptr<Manifest> manifest2(manifest->DeepCopy());
EXPECT_TRUE(manifest->Equals(manifest2.get()));
EXPECT_TRUE(manifest2->Equals(manifest.get()));
MutateManifest(
&manifest, "foo", Value::CreateStringValue("blah"));
EXPECT_FALSE(manifest->Equals(manifest2.get()));
}
// Verifies that key restriction based on type works.
TEST_F(ManifestTest, ExtensionTypes) {
scoped_ptr<DictionaryValue> value(new DictionaryValue());
value->SetString(keys::kName, "extension");
value->SetString(keys::kVersion, "1");
scoped_ptr<Manifest> manifest(
new Manifest(Extension::INTERNAL, value.Pass()));
std::string error;
Extension::InstallWarningVector warnings;
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
EXPECT_TRUE(warnings.empty());
// By default, the type is Extension.
AssertType(manifest.get(), Extension::TYPE_EXTENSION);
// Theme.
MutateManifest(
&manifest, keys::kTheme, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_THEME);
MutateManifest(
&manifest, keys::kTheme, NULL);
// Packaged app.
MutateManifest(
&manifest, keys::kApp, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_PACKAGED_APP);
// Platform app.
MutateManifest(
&manifest, keys::kPlatformAppBackground, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
MutateManifest(
&manifest, keys::kPlatformAppBackground, NULL);
// Hosted app.
MutateManifest(
&manifest, keys::kWebURLs, new ListValue());
AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
MutateManifest(
&manifest, keys::kWebURLs, NULL);
MutateManifest(
&manifest, keys::kLaunchWebURL, Value::CreateStringValue("foo"));
AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
MutateManifest(
&manifest, keys::kLaunchWebURL, NULL);
};
// Verifies that the getters filter restricted keys.
TEST_F(ManifestTest, RestrictedKeys) {
scoped_ptr<DictionaryValue> value(new DictionaryValue());
value->SetString(keys::kName, "extension");
value->SetString(keys::kVersion, "1");
scoped_ptr<Manifest> manifest(
new Manifest(Extension::INTERNAL, value.Pass()));
std::string error;
Extension::InstallWarningVector warnings;
manifest->ValidateManifest(&error, &warnings);
EXPECT_TRUE(error.empty());
EXPECT_TRUE(warnings.empty());
// Platform apps cannot have a "page_action" key.
MutateManifest(
&manifest, keys::kPageAction, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_EXTENSION);
base::Value* output = NULL;
EXPECT_TRUE(manifest->HasKey(keys::kPageAction));
EXPECT_TRUE(manifest->Get(keys::kPageAction, &output));
MutateManifest(
&manifest, keys::kPlatformAppBackground, new DictionaryValue());
AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
EXPECT_FALSE(manifest->HasKey(keys::kPageAction));
EXPECT_FALSE(manifest->Get(keys::kPageAction, &output));
MutateManifest(
&manifest, keys::kPlatformAppBackground, NULL);
// "commands" is restricted to manifest_version >= 2.
{
// ... and dev channel, for now.
Feature::ScopedCurrentChannel dev_channel_scope(
chrome::VersionInfo::CHANNEL_DEV);
MutateManifest(
&manifest, keys::kCommands, new DictionaryValue());
EXPECT_FALSE(manifest->HasKey(keys::kCommands));
EXPECT_FALSE(manifest->Get(keys::kCommands, &output));
MutateManifest(
&manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
EXPECT_TRUE(manifest->HasKey(keys::kCommands));
EXPECT_TRUE(manifest->Get(keys::kCommands, &output));
}
};
} // namespace extensions
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <fstream>
#include <libxml/xmlmemory.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "retriever.h"
#include "../node.h"
#include "../node_util.h"
#include "../string_util.h"
#include "../tree.hh"
using std::ifstream;
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::cout;
using std::endl;
using std::vector;
using string_util::starts_with;
typedef vector<string> StringVec;
static string get_type(const string &location){
static const string CHAR("CHAR");
if(starts_with(location,CHAR))
return "NX_CHAR";
static const string INT8("INT8");
if(starts_with(location,INT8))
return "NX_INT8";
static const string INT16("INT16");
if(starts_with(location,INT16))
return "NX_INT16";
static const string INT32("INT32");
if(starts_with(location,INT32))
return "NX_INT32";
static const string UINT8("UINT8");
if(starts_with(location,UINT8))
return "NX_UINT8";
static const string UINT16("UINT16");
if(starts_with(location,UINT16))
return "NX_UINT16";
static const string UINT32("UINT32");
if(starts_with(location,UINT32))
return "NX_UINT32";
static const string FLOAT32("FLOAT32");
if(starts_with(location,FLOAT32))
return "NX_FLOAT32";
static const string FLOAT64("FLOAT64");
if(starts_with(location,FLOAT64))
return "NX_FLOAT64";
throw invalid_argument("Cannot determine type in location: "+location);
}
static string xmlChar_to_str(const xmlChar *ch, int len){
string result((char *)ch);
if( (len>0) && ((unsigned int)len<result.size()) )
result.erase(result.begin()+len,result.end());
return string_util::trim(result);
}
static bool is_right_square_bracket(const char c){
static const string RIGHT="]";
return find(RIGHT.begin(),RIGHT.end(),c)!=RIGHT.end();
}
static string get_dims(const string &location){
using std::find;
static const string LEFT("[");
if(!starts_with(location,LEFT))
return "";
string result="";
for(string::const_iterator it=location.begin() ; it!=location.end() ; it++ ){
result+=(*it);
if(is_right_square_bracket(*it))
break;
}
if(result.size()==location.size())
return "";
else
return result;
}
static xmlNode* find_element(xmlNode *a_node, const string &name){
xmlNode *cur_node=NULL;
string nodeName;
for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
nodeName=xmlChar_to_str(cur_node->name,-1);
if(nodeName==name)
return cur_node->xmlChildrenNode;
}
return NULL;
}
static void print_element_names(xmlNode * a_node){
xmlNode *cur_node = NULL;
for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
if(cur_node->type == XML_ELEMENT_NODE){
cout << "node type: Element, name: " << cur_node->name << endl;
}
//print_element_names(cur_node->children);
}
}
static xmlNode* open_path(xmlNode *node,StringVec::iterator begin, StringVec::iterator end){
// error check input
if(begin==end)
return NULL;
// locate the next part of the path
node=find_element(node,*begin);
// if it returned poorly then get out now
if(node==NULL)
return NULL;
// go to next step
begin++;
if(begin==end)
return node;
// recursively call self
return open_path(node,begin,end);
}
static string getStrValue(const xmlDocPtr &doc, const xmlNodePtr &node){
xmlChar *char_value=xmlNodeListGetString(doc,node,1);
if(char_value==NULL)
throw runtime_error("blah");
string value=xmlChar_to_str(char_value,-1);
xmlFree(char_value);
return value;
}
/**
* The factory will call the constructor with a string. The string
* specifies where to locate the data (e.g. a filename), but
* interpreting the string is left up to the implementing code.
*/
TextXmlRetriever::TextXmlRetriever(const string &str): source(str) /*,current_line(0)*/{
cout << "****************************************"
<< "****************************************" << endl; // REMOVE
cout << "TextXmlRetriever(" << source << ")" << endl; // REMOVE
// open the file
doc=xmlParseFile(source.c_str());
// check that open was successful
if(doc==NULL){
xmlFreeDoc(doc);
xmlCleanupParser();
throw runtime_error("Parsing "+source+" was not successful");
}
// check that the document is not empty
xmlNode *xml_node = NULL;
xml_node = xmlDocGetRootElement(doc);
if(xml_node==NULL)
throw runtime_error("Empty document ["+source+"]");
}
TextXmlRetriever::~TextXmlRetriever(){
//cout << "~TextXmlRetriever()" << endl;
if(doc==NULL) return;
// close the file
xmlFreeDoc(doc);
xmlCleanupParser();
}
/**
* This is the method for retrieving data from a file. The whole
* tree will be written to the new file immediately after being
* called. Interpreting the string is left up to the implementing
* code.
*/
void TextXmlRetriever::getData(const string &location, tree<Node> &tr){
cout << "TextXmlRetriever::getData(" << location << ",tree)" << endl; // REMOVE
// check that the argument is not an empty string
if(location.size()<=0)
throw invalid_argument("cannot parse empty string");
// variables for the divided string version of the location
string str_path;
string type;
string str_dims;
// convert the location to a type and (string) path
if(starts_with(location,"/")){
str_path=location;
type="NX_CHAR";
str_dims="";
}else{
// get the type and remove it from the location
type=get_type(location);
str_path=location.substr(type.size()-3,location.size());
// get the dimensions and remove it from the location
str_dims=get_dims(str_path);
str_path=str_path.substr(str_dims.size(),str_path.size());
// remove the separating colon
str_path=str_path.substr(1,str_path.size());
}
std::cout << "TYPE=" << type << " DIMS=" << str_dims << " PATH=" << str_path << std::endl; // REMOVE
StringVec path=string_util::string_to_path(str_path);
Node::NXtype int_type=node_type(type);
// get the root
xmlNode *xml_node = NULL;
xml_node = xmlDocGetRootElement(doc);
// open the path
xml_node=open_path(xml_node,path.begin(),path.end());
if(xml_node==NULL)
throw invalid_argument("path ["+location+"] does not exist in file");
// get the value
string value=getStrValue(doc, xml_node);
if(value.size()<=0)
throw runtime_error("Encountered empty value ["+source+","+location+"]");
// create an empty node
Node node(*(path.rbegin()),"empty");
// put the data in the node
vector<int> dims;
if(int_type==Node::CHAR){
dims.push_back(value.size());
}else{
dims=string_util::str_to_intVec(str_dims);
}
update_node_from_string(node,value,dims,int_type);
tr.insert(tr.begin(),node);
}
static void openPath( xmlNode *root_element, const std::vector<std::string> &path, int &num_group, int &num_data){
}
static void closePath( xmlNode *root_element, int &num_group, int &num_data){
}
const string TextXmlRetriever::MIME_TYPE("text/xml");
string TextXmlRetriever::toString() const{
return "["+MIME_TYPE+"] "+source;
}
<commit_msg>Removed ^M characters from the file. No other changes from previous version.<commit_after>#include <algorithm>
#include <iostream>
#include <fstream>
#include <libxml/xmlmemory.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "retriever.h"
#include "../node.h"
#include "../node_util.h"
#include "../string_util.h"
#include "../tree.hh"
using std::ifstream;
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::cout;
using std::endl;
using std::vector;
using string_util::starts_with;
typedef vector<string> StringVec;
static string get_type(const string &location){
static const string CHAR("CHAR");
if(starts_with(location,CHAR))
return "NX_CHAR";
static const string INT8("INT8");
if(starts_with(location,INT8))
return "NX_INT8";
static const string INT16("INT16");
if(starts_with(location,INT16))
return "NX_INT16";
static const string INT32("INT32");
if(starts_with(location,INT32))
return "NX_INT32";
static const string UINT8("UINT8");
if(starts_with(location,UINT8))
return "NX_UINT8";
static const string UINT16("UINT16");
if(starts_with(location,UINT16))
return "NX_UINT16";
static const string UINT32("UINT32");
if(starts_with(location,UINT32))
return "NX_UINT32";
static const string FLOAT32("FLOAT32");
if(starts_with(location,FLOAT32))
return "NX_FLOAT32";
static const string FLOAT64("FLOAT64");
if(starts_with(location,FLOAT64))
return "NX_FLOAT64";
throw invalid_argument("Cannot determine type in location: "+location);
}
static string xmlChar_to_str(const xmlChar *ch, int len){
string result((char *)ch);
if( (len>0) && ((unsigned int)len<result.size()) )
result.erase(result.begin()+len,result.end());
return string_util::trim(result);
}
static bool is_right_square_bracket(const char c){
static const string RIGHT="]";
return find(RIGHT.begin(),RIGHT.end(),c)!=RIGHT.end();
}
static string get_dims(const string &location){
using std::find;
static const string LEFT("[");
if(!starts_with(location,LEFT))
return "";
string result="";
for(string::const_iterator it=location.begin() ; it!=location.end() ; it++ ){
result+=(*it);
if(is_right_square_bracket(*it))
break;
}
if(result.size()==location.size())
return "";
else
return result;
}
static xmlNode* find_element(xmlNode *a_node, const string &name){
xmlNode *cur_node=NULL;
string nodeName;
for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
nodeName=xmlChar_to_str(cur_node->name,-1);
if(nodeName==name)
return cur_node->xmlChildrenNode;
}
return NULL;
}
static void print_element_names(xmlNode * a_node){
xmlNode *cur_node = NULL;
for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
if(cur_node->type == XML_ELEMENT_NODE){
cout << "node type: Element, name: " << cur_node->name << endl;
}
//print_element_names(cur_node->children);
}
}
static xmlNode* open_path(xmlNode *node,StringVec::iterator begin, StringVec::iterator end){
// error check input
if(begin==end)
return NULL;
// locate the next part of the path
node=find_element(node,*begin);
// if it returned poorly then get out now
if(node==NULL)
return NULL;
// go to next step
begin++;
if(begin==end)
return node;
// recursively call self
return open_path(node,begin,end);
}
static string getStrValue(const xmlDocPtr &doc, const xmlNodePtr &node){
xmlChar *char_value=xmlNodeListGetString(doc,node,1);
if(char_value==NULL)
throw runtime_error("blah");
string value=xmlChar_to_str(char_value,-1);
xmlFree(char_value);
return value;
}
/**
* The factory will call the constructor with a string. The string
* specifies where to locate the data (e.g. a filename), but
* interpreting the string is left up to the implementing code.
*/
TextXmlRetriever::TextXmlRetriever(const string &str): source(str) /*,current_line(0)*/{
cout << "****************************************"
<< "****************************************" << endl; // REMOVE
cout << "TextXmlRetriever(" << source << ")" << endl; // REMOVE
// open the file
doc=xmlParseFile(source.c_str());
// check that open was successful
if(doc==NULL){
xmlFreeDoc(doc);
xmlCleanupParser();
throw runtime_error("Parsing "+source+" was not successful");
}
// check that the document is not empty
xmlNode *xml_node = NULL;
xml_node = xmlDocGetRootElement(doc);
if(xml_node==NULL)
throw runtime_error("Empty document ["+source+"]");
}
TextXmlRetriever::~TextXmlRetriever(){
//cout << "~TextXmlRetriever()" << endl;
if(doc==NULL) return;
// close the file
xmlFreeDoc(doc);
xmlCleanupParser();
}
/**
* This is the method for retrieving data from a file. The whole
* tree will be written to the new file immediately after being
* called. Interpreting the string is left up to the implementing
* code.
*/
void TextXmlRetriever::getData(const string &location, tree<Node> &tr){
cout << "TextXmlRetriever::getData(" << location << ",tree)" << endl; // REMOVE
// check that the argument is not an empty string
if(location.size()<=0)
throw invalid_argument("cannot parse empty string");
// variables for the divided string version of the location
string str_path;
string type;
string str_dims;
// convert the location to a type and (string) path
if(starts_with(location,"/")){
str_path=location;
type="NX_CHAR";
str_dims="";
}else{
// get the type and remove it from the location
type=get_type(location);
str_path=location.substr(type.size()-3,location.size());
// get the dimensions and remove it from the location
str_dims=get_dims(str_path);
str_path=str_path.substr(str_dims.size(),str_path.size());
// remove the separating colon
str_path=str_path.substr(1,str_path.size());
}
std::cout << "TYPE=" << type << " DIMS=" << str_dims << " PATH=" << str_path << std::endl; // REMOVE
StringVec path=string_util::string_to_path(str_path);
Node::NXtype int_type=node_type(type);
// get the root
xmlNode *xml_node = NULL;
xml_node = xmlDocGetRootElement(doc);
// open the path
xml_node=open_path(xml_node,path.begin(),path.end());
if(xml_node==NULL)
throw invalid_argument("path ["+location+"] does not exist in file");
// get the value
string value=getStrValue(doc, xml_node);
if(value.size()<=0)
throw runtime_error("Encountered empty value ["+source+","+location+"]");
// create an empty node
Node node(*(path.rbegin()),"empty");
// put the data in the node
vector<int> dims;
if(int_type==Node::CHAR){
dims.push_back(value.size());
}else{
dims=string_util::str_to_intVec(str_dims);
}
update_node_from_string(node,value,dims,int_type);
tr.insert(tr.begin(),node);
}
static void openPath( xmlNode *root_element, const std::vector<std::string> &path, int &num_group, int &num_data){
}
static void closePath( xmlNode *root_element, int &num_group, int &num_data){
}
const string TextXmlRetriever::MIME_TYPE("text/xml");
string TextXmlRetriever::toString() const{
return "["+MIME_TYPE+"] "+source;
}
<|endoftext|> |
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <[email protected]>
Vc 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 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "cpuid.h"
#include <cstdlib>
using namespace Vc;
template<typename Vector> struct Helper
{
typedef typename Vector::Mask Mask;
typedef typename Vector::EntryType Scalar;
static Vector *blackHole;
static void setBlackHole();
static void run(const int Repetitions)
{
const int Factor = CpuId::L1Data() / sizeof(Vector);
const int opPerSecondFactor = Factor * Vector::Size;
setBlackHole();
Vector *data = new Vector[Factor];
for (int i = 0; i < Factor; ++i) {
data[i] = PseudoRandom<Vector>::next();
}
{
Benchmark timer("round", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = round(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("sqrt", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = sqrt(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("log", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = log(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("sin", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = sin(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("cos", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = cos(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("asin", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = asin(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("atan", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = atan(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("atan2", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor - 1; ++i) {
*blackHole = atan2(data[i], data[i + 1]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("rsqrt", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = rsqrt(data[i]);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("recip", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
*blackHole = reciprocal(data[i]);
}
timer.Stop();
}
timer.Print();
}
delete[] data;
}
};
template<typename Vec> Vec *Helper<Vec>::blackHole = 0;
// global (not file-static!) variable keeps the compiler from identifying the benchmark as dead code
float_v blackHoleFloat;
template<> inline void Helper<float_v>::setBlackHole() { blackHole = &blackHoleFloat; }
#if VC_IMPL_SSE
sfloat_v blackHoleSFloat;
template<> inline void Helper<sfloat_v>::setBlackHole() { blackHole = &blackHoleSFloat; }
#endif
int bmain(Benchmark::OutputMode out)
{
const int Repetitions = out == Benchmark::Stdout ? 4 : (g_Repetitions > 0 ? g_Repetitions : 100);
Benchmark::addColumn("datatype");
Benchmark::setColumnData("datatype", "float_v");
Helper<float_v>::run(Repetitions);
#if VC_IMPL_SSE
Benchmark::setColumnData("datatype", "sfloat_v");
Helper<sfloat_v>::run(Repetitions);
#endif
return 0;
}
<commit_msg>benchmark double_v, too; use forceToRegisters instead of black hole<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <[email protected]>
Vc 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 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "cpuid.h"
#include <cstdlib>
using namespace Vc;
template<typename Vector> struct Helper
{
typedef typename Vector::Mask Mask;
typedef typename Vector::EntryType Scalar;
static void run(const int Repetitions)
{
const int Factor = CpuId::L1Data() / sizeof(Vector);
const int opPerSecondFactor = Factor * Vector::Size;
Vector *data = new Vector[Factor];
for (int i = 0; i < Factor; ++i) {
data[i] = PseudoRandom<Vector>::next();
}
{
Benchmark timer("round", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = round(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("sqrt", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = sqrt(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("log", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = log(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("sin", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = sin(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("cos", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = cos(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("asin", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = asin(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("atan", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = atan(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("atan2", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor - 1; ++i) {
Vector tmp = atan2(data[i], data[i + 1]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("rsqrt", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = rsqrt(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("recip", opPerSecondFactor, "Op");
for (int rep = 0; rep < Repetitions; ++rep) {
timer.Start();
for (int i = 0; i < Factor; ++i) {
Vector tmp = reciprocal(data[i]);
Vc::forceToRegisters(tmp);
}
timer.Stop();
}
timer.Print();
}
delete[] data;
}
};
int bmain(Benchmark::OutputMode out)
{
const int Repetitions = out == Benchmark::Stdout ? 4 : (g_Repetitions > 0 ? g_Repetitions : 100);
Benchmark::addColumn("datatype");
Benchmark::setColumnData("datatype", "float_v");
Helper<float_v>::run(Repetitions);
Benchmark::setColumnData("datatype", "sfloat_v");
Helper<sfloat_v>::run(Repetitions);
Benchmark::setColumnData("datatype", "double_v");
Helper<double_v>::run(Repetitions);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Create code.cpp<commit_after><|endoftext|> |
<commit_before>#include "Process.hpp"
#include "log.hpp"
#include "Filesystem.hpp"
#include <boost/algorithm/string/join.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <cassert>
#include <stdexcept>
#include <sys/wait.h>
#include <unistd.h>
#if defined(__APPLE__) && defined(__DYNAMIC__)
#include <crt_externs.h>
#endif
namespace io = boost::iostreams;
namespace configure {
namespace {
char** get_environ()
{
#if defined(__APPLE__) && defined(__DYNAMIC__)
return *_NSGetEnviron();
#else
return environ;
#endif
}
struct Pipe
{
private:
io::file_descriptor_source _source;
io::file_descriptor_sink _sink;
public:
Pipe()
{
int fds[2];
if (::pipe(fds) == -1)
throw std::runtime_error("pipe error");
_source = io::file_descriptor_source(fds[0], io::file_descriptor_flags::close_handle);
_sink = io::file_descriptor_sink(fds[1], io::file_descriptor_flags::close_handle);
}
public:
io::file_descriptor_sink& sink() { return _sink; }
io::file_descriptor_source& source() { return _source; }
public:
void close()
{
_sink.close();
_source.close();
}
};
} // !anonymous
struct Process::Impl
{
Command const command;
Options const options;
boost::optional<ExitCode> exit_code;
io::file_descriptor_source stdout_source;
pid_t child;
Impl(Command cmd, Options options)
: command(_prepare_command(std::move(cmd)))
, options(std::move(options))
, exit_code(boost::none)
, child(_create_child())
{}
pid_t _create_child()
{
char** env = nullptr;
// Working directory
if (this->options.working_directory)
{
throw "not there";
}
if (this->options.inherit_env)
{
env = get_environ();
}
std::unique_ptr<Pipe> stdin_pipe;
std::unique_ptr<Pipe> stdout_pipe;
std::unique_ptr<Pipe> stderr_pipe;
std::tuple<bool, Stream, std::unique_ptr<Pipe>&, int> channels[] = {
std::make_tuple(false,
this->options.stdin_,
std::ref(stdin_pipe),
STDIN_FILENO),
std::make_tuple(true,
this->options.stdout_,
std::ref(stdout_pipe),
STDOUT_FILENO),
std::make_tuple(true,
this->options.stderr_,
std::ref(stderr_pipe),
STDERR_FILENO),
};
for (auto& channel: channels)
if (std::get<1>(channel) == Stream::PIPE)
std::get<2>(channel).reset(new Pipe);
log::debug("Spawning process:", boost::join(this->command, " "));
pid_t child = ::fork();
if (child < 0)
{
throw std::runtime_error("fork()");
}
else if (child == 0) // Child
{
for (auto& channel: channels)
{
Stream kind = std::get<1>(channel);
bool is_sink = std::get<0>(channel);
int old_fd = std::get<3>(channel);
if (kind == Stream::PIPE)
{
int new_fd = (is_sink ?
std::get<2>(channel)->sink().handle() :
std::get<2>(channel)->source().handle());
retry_dup2:
int ret = ::dup2(new_fd, old_fd);
if (ret == -1) {
if (errno == EINTR) goto retry_dup2;
::exit(EXIT_FAILURE);
}
}
else if (kind == Stream::DEVNULL)
{
::close(old_fd);
}
}
stdin_pipe.reset();
stdout_pipe.reset();
stderr_pipe.reset();
std::vector<char const*> args;
for (auto& arg: this->command)
args.push_back(arg.c_str());
args.push_back(nullptr);
::execve(args[0], (char**) &args[0], env);
::exit(EXIT_FAILURE);
}
else // Parent
{
if (this->options.stdout_ == Stream::PIPE)
this->stdout_source = stdout_pipe->source();
}
return child;
}
Command _prepare_command(Command cmd)
{
cmd[0] = Filesystem::which(cmd[0]).get().string();
return std::move(cmd);
}
};
Process::Process(Command cmd, Options options)
: _this(new Impl(std::move(cmd), std::move(options)))
{}
Process::~Process()
{ this->wait(); }
Process::Options const& Process::options() const
{ return _this->options; }
boost::optional<Process::ExitCode> Process::exit_code()
{
if (!_this->exit_code)
{
pid_t ret;
int status;
do
{
log::debug("Checking exit status of child", _this->child);
ret = ::waitpid(_this->child, &status, WNOHANG);
} while (ret == -1 && errno == EINTR);
if (ret == -1)
throw std::runtime_error("Waitpid failed");
if (ret != 0)
{
log::debug("The child", _this->child,
"exited with status code", WEXITSTATUS(status));
_this->exit_code = WEXITSTATUS(status);
}
else
log::debug("The child", _this->child, "is still alive");
}
return _this->exit_code;
}
Process::ExitCode Process::wait()
{
while (!this->exit_code())
log::debug("Waiting for child", _this->child, "to terminate");
return _this->exit_code.get();
}
Process::ExitCode Process::call(Command cmd, Options options)
{
Process p(std::move(cmd), std::move(options));
return p.wait();
}
std::string Process::check_output(Command cmd, Options options)
{
options.stdout_ = Stream::PIPE;
options.stderr_ = Stream::DEVNULL;
Process p(std::move(cmd), std::move(options));
char buf[4096];
std::string res;
ssize_t size;
auto& src = p._this->stdout_source;
while (true)
{
size = ::read(src.handle(), buf, sizeof(buf));
log::debug("Read from", p._this->child, "returned", size);
if (size < 0)
{
if (errno == EINTR)
{
log::debug("Read interrupted by a signal, let's retry");
continue;
}
throw std::runtime_error("read(): " + std::string(strerror(errno)));
}
if (size > 0)
{
log::debug("read", size, "bytes from child", p._this->child, "stdout");
res.append(buf, size);
}
if (size == 0)
break;
}
if (p.wait() != 0)
throw std::runtime_error("Program failed");
return res;
}
}
<commit_msg>First shot a windows process compat.<commit_after>#include "Process.hpp"
#include "log.hpp"
#include "Filesystem.hpp"
#include <boost/config.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <cassert>
#include <stdexcept>
#if defined(BOOST_POSIX_API)
# include <sys/wait.h>
# include <unistd.h>
# if defined(__APPLE__) && defined(__DYNAMIC__)
# include <crt_externs.h> // For _NSGetEnviron()
# endif
#elif defined(BOOST_WINDOWS_API)
# include <Windows.h>
#else
# error "Unsupported platform"
#endif
namespace io = boost::iostreams;
namespace configure {
namespace {
char** get_environ()
{
#if defined(__APPLE__) && defined(__DYNAMIC__)
return *_NSGetEnviron();
#else
return environ;
#endif
}
#ifdef BOOST_WINDOWS_API
typedef HANDLE file_descriptor_t;
#else
typedef int file_descriptor_t;
#endif
struct Pipe
{
private:
io::file_descriptor_source _source;
io::file_descriptor_sink _sink;
public:
Pipe()
{
file_descriptor_t fds[2];
#ifdef BOOST_WINDOWS_API
if (!::CreatePipe(&fds[0], &fds[1], NULL, 0))
#else
if (::pipe(fds) == -1)
#endif
throw std::runtime_error("pipe error");
_source = io::file_descriptor_source(
fds[0], io::file_descriptor_flags::close_handle);
_sink = io::file_descriptor_sink(
fds[1], io::file_descriptor_flags::close_handle);
}
public:
io::file_descriptor_sink& sink() { return _sink; }
io::file_descriptor_source& source() { return _source; }
public:
void close()
{
_sink.close();
_source.close();
}
};
#ifdef BOOST_WINDOWS_API
struct Child
{
private:
PROCESS_INFORMATION _proc_info;
public:
explicit Child(PROCESS_INFORMATION const& proc_info)
: _proc_info(proc_info)
{}
Child(Child&& other)
: _proc_info(other._proc_info)
{
other._proc_info.hProcess = INVALID_HANDLE_VALUE;
other._proc_info.hThread = INVALID_HANDLE_VALUE;
}
~Child()
{
::CloseHandle(proc_info.hProcess);
::CloseHandle(proc_info.hThread);
}
HANDLE process_handle() const { return proc_info.hProcess; }
};
#else
struct Child
{
private:
pid_t _pid;
public:
explicit Child(pid_t pid) : _pid(pid) {}
pid_t process_handle() const { return _pid; }
};
#endif
std::ostream& operator <<(std::ostream& out, Child const& child)
{
return out << "<Process " << child.process_handle() << ">";
}
} // !anonymous
struct Process::Impl
{
Command const command;
Options const options;
boost::optional<ExitCode> exit_code;
io::file_descriptor_sink stdin_sink;
io::file_descriptor_source stdout_source;
io::file_descriptor_source stderr_source;
Child child;
Impl(Command cmd, Options options)
: command(_prepare_command(std::move(cmd)))
, options(std::move(options))
, exit_code(boost::none)
, child(_create_child())
{}
#ifdef BOOST_POSIX_API
pid_t _create_child()
{
char** env = nullptr;
// Working directory
if (this->options.working_directory)
{
throw "not there";
}
if (this->options.inherit_env)
{
env = get_environ();
}
std::unique_ptr<Pipe> stdin_pipe;
std::unique_ptr<Pipe> stdout_pipe;
std::unique_ptr<Pipe> stderr_pipe;
std::tuple<bool, Stream, std::unique_ptr<Pipe>&, int> channels[] = {
std::make_tuple(false,
this->options.stdin_,
std::ref(stdin_pipe),
STDIN_FILENO),
std::make_tuple(true,
this->options.stdout_,
std::ref(stdout_pipe),
STDOUT_FILENO),
std::make_tuple(true,
this->options.stderr_,
std::ref(stderr_pipe),
STDERR_FILENO),
};
for (auto& channel: channels)
if (std::get<1>(channel) == Stream::PIPE)
std::get<2>(channel).reset(new Pipe);
log::debug("Spawning process:", boost::join(this->command, " "));
pid_t child = ::fork();
if (child < 0)
{
throw std::runtime_error("fork()");
}
else if (child == 0) // Child
{
for (auto& channel: channels)
{
Stream kind = std::get<1>(channel);
bool is_sink = std::get<0>(channel);
int old_fd = std::get<3>(channel);
if (kind == Stream::PIPE)
{
int new_fd = (is_sink ?
std::get<2>(channel)->sink().handle() :
std::get<2>(channel)->source().handle());
retry_dup2:
int ret = ::dup2(new_fd, old_fd);
if (ret == -1) {
if (errno == EINTR) goto retry_dup2;
::exit(EXIT_FAILURE);
}
}
else if (kind == Stream::DEVNULL)
{
::close(old_fd);
}
}
stdin_pipe.reset();
stdout_pipe.reset();
stderr_pipe.reset();
std::vector<char const*> args;
for (auto& arg: this->command)
args.push_back(arg.c_str());
args.push_back(nullptr);
::execve(args[0], (char**) &args[0], env);
::exit(EXIT_FAILURE);
}
else // Parent
{
if (this->options.stdin_ == Stream::PIPE)
this->stdin_sink = stdin_pipe->sink();
if (this->options.stdout_ == Stream::PIPE)
this->stdout_source = stdout_pipe->source();
if (this->options.stderr_ == Stream::PIPE)
this->stderr_source = stderr_pipe->source();
}
return child;
}
#elif defined(BOOST_WINDOWS_API)
PROCESS_INFORMATION _create_child()
{
LPCTSTR exe = cmd[0].c_str();
LPTSTR cmd_line;
LPSECURITY_ATTRIBUTES proc_attrs = 0
LPSECURITY_ATTRIBUTES thread_attrs = 0;
BOOL inherit_handles = false;
LPVOID env = nullptr;
LPCTSTR work_dir = nullptr;
#if (_WIN32_WINNT >= 0x0600)
DWORD creation_flags = EXTENDED_STARTUPINFO_PRESENT;
STARTUPINFOEX startup_info_ex;
ZeroMemory(&startup_info_ex, sizeof(STARTUPINFOEX));
STARTUPINFO& startup_info = startup_info_ex.StartupInfo;
startup_info.cb = sizeof(STARTUPINFOEX);
#else
DWORD creation_flags = 0;
STARTUPINFO startup_info;
ZeroMemory(&startup_info, sizeof(STARTUPINFO));
startup_info.cb = sizeof(STARTUPINFO);
#endif
std::unique_ptr<Pipe> stdin_pipe;
if (this->options.stdin_ == Stream::PIPE)
{
stdin_pipe.reset(new Pipe);
::SetHandleInformation(stdin_pipe->source().handle(),
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT);
startup_info.hStdInput = stdin_pipe->source().handle();
startup_info.dwFlags |= STARTF_USESTDHANDLES;
inherit_handles = true;
this->stdin_sink = stdin_pipe->sink();
}
else if (this->options.stdin_ == Stream::DEVNULL)
{
startup_info.hStdInput = INVALID_HANDLE_VALUE;
startup_info.dwFlags |= STARTF_USESTDHANDLES;
}
std::unique_ptr<Pipe> stdout_pipe;
if (this->options.stdout_ == Stream::PIPE)
{
stdout_pipe.reset(new Pipe);
::SetHandleInformation(stdout_pipe->sink().handle(),
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT);
startup_info.hStdOutput = stdout_pipe->sink().handle();
startup_info.dwFlags |= STARTF_USESTDHANDLES;
inherit_handles = true;
this->stdout_source = stdout_pipe->source();
}
else if (this->options.stdout_ == Stream::DEVNULL)
{
startup_info.hStdOutput = INVALID_HANDLE_VALUE;
startup_info.dwFlags |= STARTF_USESTDHANDLES;
}
std::unique_ptr<Pipe> stderr_pipe;
if (this->options.stderr_ == Stream::PIPE)
{
stderr_pipe.reset(new Pipe);
::SetHandleInformation(stderr_pipe->sink().handle(),
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT);
startup_info.hStdError = stderr_pipe->sink().handle();
startup_info.dwFlags |= STARTF_USESTDHANDLES;
inherit_handles = true;
this->stderr_source = stderr_pipe->source();
}
else if (this->options.stderr_ == Stream::DEVNULL)
{
startup_info.hStdError = INVALID_HANDLE_VALUE;
startup_info.dwFlags |= STARTF_USESTDHANDLES;
}
PROCESS_INFORMATION proc_info;
auto ret = ::CreateProcess(
cmd[0].c_str(), quote<CommandParser::windows_shell>(cmd).c_str(),
proc_attrs, thread_attrs, inherit_handles, creation_flags, env,
work_dir, &startup_info, &proc_info);
if (!ret)
throw std::runtime_error("CreateProcess() error");
return Child(proc_info);
}
#endif // !BOOST_WINDOWS_API
Command _prepare_command(Command cmd)
{
cmd[0] = Filesystem::which(cmd[0]).get().string();
return std::move(cmd);
}
};
Process::Process(Command cmd, Options options)
: _this(new Impl(std::move(cmd), std::move(options)))
{}
Process::~Process()
{ this->wait(); }
Process::Options const& Process::options() const
{ return _this->options; }
boost::optional<Process::ExitCode> Process::exit_code()
{
if (!_this->exit_code)
{
#ifdef BOOST_WINDOWS_API
int ret = ::WaitForSingleObject(_this->child.process_handle(), 0);
switch (ret)
{
case WAIT_FAILED:
throw std::runtime_error("WaitForSingleObject() failed");
case WAIT_ABANDONED:
log::warning(
"Wait on child", _this->child, "has been abandoned");
break;
case WAIT_TIMEOUT:
log::debug("The child", _this->child, "is still alive");
break;
case WAIT_OBJECT_0:
{
DWORD exit_code;
if (!::GetExitCodeProcess(
_this->child.process_handle(), &exit_code))
throw std::runtime_error("GetExitCodeProcess() failed");
log::debug("The child", _this->child,
"exited with status code", exit_code);
_this->exit_code = exit_code;
}
}
#else
pid_t ret;
int status;
do
{
log::debug("Checking exit status of child", _this->child);
ret =
::waitpid(_this->child.process_handle(), &status, WNOHANG);
} while (ret == -1 && errno == EINTR);
if (ret == -1)
throw std::runtime_error("Waitpid failed");
if (ret != 0)
{
log::debug("The child", _this->child,
"exited with status code", WEXITSTATUS(status));
_this->exit_code = WEXITSTATUS(status);
}
else
log::debug("The child", _this->child, "is still alive");
#endif
}
return _this->exit_code;
}
Process::ExitCode Process::wait()
{
while (!this->exit_code())
log::debug("Waiting for child", _this->child, "to terminate");
return _this->exit_code.get();
}
Process::ExitCode Process::call(Command cmd, Options options)
{
Process p(std::move(cmd), std::move(options));
return p.wait();
}
std::string Process::check_output(Command cmd, Options options)
{
options.stdout_ = Stream::PIPE;
options.stderr_ = Stream::DEVNULL;
Process p(std::move(cmd), std::move(options));
char buf[4096];
std::string res;
ssize_t size;
auto& src = p._this->stdout_source;
while (true)
{
size = ::read(src.handle(), buf, sizeof(buf));
log::debug("Read from", p._this->child, "returned", size);
if (size < 0)
{
if (errno == EINTR)
{
log::debug("Read interrupted by a signal, let's retry");
continue;
}
throw std::runtime_error("read(): " + std::string(strerror(errno)));
}
if (size > 0)
{
log::debug("read", size, "bytes from child", p._this->child, "stdout");
res.append(buf, size);
}
if (size == 0)
break;
}
if (p.wait() != 0)
throw std::runtime_error("Program failed");
return res;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
// #include "qsparql_tracker.h"
#include "qsparql_tracker_p.h"
#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlqueryoptions.h>
#include <qsparqlresultrow.h>
#include <qcoreapplication.h>
#include <qvariant.h>
#include <qstringlist.h>
#include <qvector.h>
#include <qstring.h>
#include <qregexp.h>
#include <qdebug.h>
Q_DECLARE_METATYPE(QVector<QStringList>)
/*
Allows a metatype to be declared for a type containing commas.
For example:
Q_DECLARE_METATYPE_COMMA(QList<QPair<QByteArray,QByteArray> >)
*/
#define Q_DECLARE_METATYPE_COMMA(...) \
QT_BEGIN_NAMESPACE \
template <> \
struct QMetaTypeId< __VA_ARGS__ > \
{ \
enum { Defined = 1 }; \
static int qt_metatype_id() \
{ \
static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
if (!metatype_id) \
metatype_id = qRegisterMetaType< __VA_ARGS__ >( #__VA_ARGS__, \
reinterpret_cast< __VA_ARGS__ *>(quintptr(-1))); \
return metatype_id; \
} \
}; \
QT_END_NAMESPACE
Q_DECLARE_METATYPE_COMMA(QMap<QString, QString>)
Q_DECLARE_METATYPE_COMMA(QVector<QMap<QString, QString> >)
Q_DECLARE_METATYPE_COMMA(QVector<QVector<QMap<QString, QString> > >)
class QTrackerDriver;
QT_BEGIN_NAMESPACE
// This enum is defined in tracker-sparql.h, but copy it here for now
// to avoid a dependency on that header.
typedef enum {
TRACKER_SPARQL_ERROR_PARSE,
TRACKER_SPARQL_ERROR_UNKNOWN_CLASS,
TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY,
TRACKER_SPARQL_ERROR_TYPE,
TRACKER_SPARQL_ERROR_CONSTRAINT,
TRACKER_SPARQL_ERROR_NO_SPACE,
TRACKER_SPARQL_ERROR_INTERNAL,
TRACKER_SPARQL_ERROR_UNSUPPORTED
} TrackerSparqlError;
class QTrackerDriverPrivate {
public:
QTrackerDriverPrivate();
~QTrackerDriverPrivate();
QDBusInterface* iface;
bool doBatch; // true: call BatchSparqlUpdate on Tracker instead of
// SparqlUpdateBlank
};
class QTrackerResultPrivate : public QObject {
Q_OBJECT
public:
QTrackerResultPrivate(QTrackerResult* res,
QSparqlQuery::StatementType tp);
~QTrackerResultPrivate();
QDBusPendingCallWatcher* watcher;
QVector<QStringList> data;
QSparqlQuery::StatementType type;
void setCall(QDBusPendingCall& call);
static TrackerSparqlError errorNameToCode(const QString& name);
static QSparqlError::ErrorType errorCodeToType(TrackerSparqlError code);
private Q_SLOTS:
void onDBusCallFinished();
private:
QTrackerResult* q; // public part
};
namespace {
// How to recognize tracker
QLatin1String service("org.freedesktop.Tracker1");
QLatin1String basePath("/org/freedesktop/Tracker1");
QLatin1String resourcesInterface("org.freedesktop.Tracker1.Resources");
QLatin1String resourcesPath("/org/freedesktop/Tracker1/Resources");
} // end of unnamed namespace
QTrackerResultPrivate::QTrackerResultPrivate(QTrackerResult* res,
QSparqlQuery::StatementType tp)
: watcher(0), type(tp), q(res)
{
}
void QTrackerResultPrivate::setCall(QDBusPendingCall& call)
{
// This function should be called only once
watcher = new QDBusPendingCallWatcher(call);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
this, SLOT(onDBusCallFinished()));
}
QTrackerResultPrivate::~QTrackerResultPrivate()
{
delete watcher;
}
TrackerSparqlError QTrackerResultPrivate::errorNameToCode(const QString& name)
{
if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Parse")) {
return TRACKER_SPARQL_ERROR_PARSE;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.UnknownClass")) {
return TRACKER_SPARQL_ERROR_UNKNOWN_CLASS;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.UnknownProperty")) {
return TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Type")) {
return TRACKER_SPARQL_ERROR_TYPE;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Constraint")) {
return TRACKER_SPARQL_ERROR_CONSTRAINT;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.NoSpace")) {
return TRACKER_SPARQL_ERROR_NO_SPACE;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Internal")) {
return TRACKER_SPARQL_ERROR_INTERNAL;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Unsupported")) {
return TRACKER_SPARQL_ERROR_UNSUPPORTED;
} else {
return static_cast<TrackerSparqlError>(-1);
}
}
QSparqlError::ErrorType QTrackerResultPrivate::errorCodeToType(TrackerSparqlError code)
{
switch (code) {
case TRACKER_SPARQL_ERROR_PARSE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_CLASS:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_TYPE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_CONSTRAINT:
return QSparqlError::ConnectionError;
case TRACKER_SPARQL_ERROR_NO_SPACE:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_INTERNAL:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_UNSUPPORTED:
return QSparqlError::BackendError;
default:
return QSparqlError::BackendError;
}
}
void QTrackerResultPrivate::onDBusCallFinished()
{
if (watcher->isError()) {
QSparqlError error(watcher->error().message());
if (watcher->error().type() == QDBusError::Other) {
TrackerSparqlError code = errorNameToCode(watcher->error().name());
error.setNumber(code);
error.setType(errorCodeToType(code));
} else {
// Error from D-Bus
error.setNumber((int)watcher->error().type());
error.setType(QSparqlError::ConnectionError);
}
q->setLastError(error);
emit q->finished();
qWarning() << "QTrackerResult:" << q->lastError() << q->query();
return;
}
switch (type) {
case QSparqlQuery::AskStatement:
case QSparqlQuery::SelectStatement:
{
QDBusPendingReply<QVector<QStringList> > reply = *watcher;
data = reply.argumentAt<0>();
if (type == QSparqlQuery::AskStatement && data.count() == 1 && data[0].count() == 1)
{
QVariant boolValue = data[0][0];
q->setBoolValue(boolValue.toBool());
}
emit q->dataReady(data.size());
break;
}
default:
// TODO: handle update results here
break;
}
Q_EMIT q->finished();
}
QTrackerResult::QTrackerResult(QSparqlQuery::StatementType tp)
{
d = new QTrackerResultPrivate(this, tp);
}
QTrackerResult::~QTrackerResult()
{
delete d;
}
QTrackerResult* QTrackerDriver::exec(const QString& query,
QSparqlQuery::StatementType type,
const QSparqlQueryOptions& options)
{
if (options.executionMethod() == QSparqlQueryOptions::SyncExec)
return 0;
QTrackerResult* res = new QTrackerResult(type);
res->setQuery(query);
QString funcToCall;
switch (type) {
case QSparqlQuery::AskStatement:
case QSparqlQuery::SelectStatement:
{
funcToCall = QString::fromLatin1("SparqlQuery");
break;
}
case QSparqlQuery::InsertStatement: // fall-through
case QSparqlQuery::DeleteStatement:
{
if (d->doBatch || options.priority() == QSparqlQueryOptions::LowPriority) {
funcToCall = QString::fromLatin1("BatchSparqlUpdate");
}
else {
funcToCall = QString::fromLatin1("SparqlUpdateBlank");
}
break;
}
default:
res->setLastError(QSparqlError(
QLatin1String("Non-supported statement type"),
QSparqlError::BackendError));
qWarning() << "QTrackerResult:" << res->lastError() << res->query();
return res;
break;
}
QDBusPendingCall call = d->iface->asyncCall(funcToCall,
QVariant(query));
res->d->setCall(call);
return res;
}
QSparqlBinding QTrackerResult::binding(int field) const
{
if (!isValid()) {
return QSparqlBinding();
}
int i = pos();
if (field >= d->data[i].count() || field < 0) {
qWarning() << "QTrackerResult::data: column" << field << "out of range";
return QSparqlBinding();
}
QString name = QString::fromLatin1("$%1").arg(field + 1);
return QSparqlBinding(name, QVariant(d->data[i][field]));
}
QVariant QTrackerResult::value(int field) const
{
if (!isValid()) {
return QVariant();
}
// The upper layer calls this function only when this Result is positioned
// in a valid position, so we don't need to check that.
int i = pos();
if (field >= d->data[i].count() || field < 0) {
qWarning() << "QTrackerResult::data: column" << field << "out of range";
return QVariant();
}
return d->data[i][field];
}
void QTrackerResult::waitForFinished()
{
if (d->watcher)
d->watcher->waitForFinished();
}
bool QTrackerResult::isFinished() const
{
if (d->watcher)
return d->watcher->isFinished();
return true;
}
int QTrackerResult::size() const
{
return d->data.count();
}
QSparqlResultRow QTrackerResult::current() const
{
if (!isValid()) {
return QSparqlResultRow();
}
QSparqlResultRow info;
if (pos() >= d->data.count() || pos() < 0)
return info;
QStringList resultStrings = d->data[pos()];
Q_FOREACH (const QString& str, resultStrings) {
// This only creates a binding with the values but with empty column
// names.
// TODO: how to add column names?
QSparqlBinding b(QString(), str);
info.append(b);
}
return info;
}
bool QTrackerResult::hasFeature(QSparqlResult::Feature feature) const
{
switch (feature) {
case QSparqlResult::Sync:
case QSparqlResult::ForwardOnly:
return false;
case QSparqlResult::QuerySize:
return true;
default:
return false;
}
}
QTrackerDriverPrivate::QTrackerDriverPrivate()
: iface(0), doBatch(false)
{
}
QTrackerDriverPrivate::~QTrackerDriverPrivate()
{
delete iface;
}
QTrackerDriver::QTrackerDriver(QObject* parent)
: QSparqlDriver(parent)
{
d = new QTrackerDriverPrivate();
qRegisterMetaType<QVector<QStringList> >();
qDBusRegisterMetaType<QVector<QStringList> >();
qRegisterMetaType<QMap<QString, QString> >();
qRegisterMetaType<QVector<QMap<QString, QString> > >();
qDBusRegisterMetaType<QVector<QMap<QString, QString> > >();
/*
if(!trackerBus().interface()->isServiceRegistered(service_g)
&& (trackerBus().interface()->startService(service_g)
, !trackerBus().interface()->isServiceRegistered(service_g)))
qCritical() << "cannot connect to org.freedesktop.Tracker1 service";
*/
}
QTrackerDriver::~QTrackerDriver()
{
delete d;
}
bool QTrackerDriver::hasFeature(QSparqlConnection::Feature f) const
{
switch (f) {
case QSparqlConnection::QuerySize:
case QSparqlConnection::DefaultGraph:
case QSparqlConnection::AskQueries:
case QSparqlConnection::UpdateQueries:
case QSparqlConnection::AsyncExec:
return true;
case QSparqlConnection::ConstructQueries:
case QSparqlConnection::SyncExec:
return false;
default:
return false;
}
return false;
}
bool QTrackerDriver::open(const QSparqlConnectionOptions& options)
{
// This option has been removed from API documentation as it is replaced by
// QSparqlQueryOption::LowPriority. The implemenation needs to be kept
// for backward compatibility.
QVariant batchOption = options.option(QString::fromLatin1("batch"));
if (!batchOption.isNull()) {
d->doBatch = batchOption.toBool();
}
if (isOpen())
close();
d->iface = new QDBusInterface(service, resourcesPath,
resourcesInterface,
QDBusConnection::sessionBus());
setOpen(true);
setOpenError(false);
return true;
}
void QTrackerDriver::close()
{
if (isOpen()) {
delete d->iface;
d->iface = 0;
setOpen(false);
setOpenError(false);
}
}
QT_END_NAMESPACE
#include "qsparql_tracker.moc"
<commit_msg>Use Q_EMIT in tracker results<commit_after>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
// #include "qsparql_tracker.h"
#include "qsparql_tracker_p.h"
#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlqueryoptions.h>
#include <qsparqlresultrow.h>
#include <qcoreapplication.h>
#include <qvariant.h>
#include <qstringlist.h>
#include <qvector.h>
#include <qstring.h>
#include <qregexp.h>
#include <qdebug.h>
Q_DECLARE_METATYPE(QVector<QStringList>)
/*
Allows a metatype to be declared for a type containing commas.
For example:
Q_DECLARE_METATYPE_COMMA(QList<QPair<QByteArray,QByteArray> >)
*/
#define Q_DECLARE_METATYPE_COMMA(...) \
QT_BEGIN_NAMESPACE \
template <> \
struct QMetaTypeId< __VA_ARGS__ > \
{ \
enum { Defined = 1 }; \
static int qt_metatype_id() \
{ \
static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \
if (!metatype_id) \
metatype_id = qRegisterMetaType< __VA_ARGS__ >( #__VA_ARGS__, \
reinterpret_cast< __VA_ARGS__ *>(quintptr(-1))); \
return metatype_id; \
} \
}; \
QT_END_NAMESPACE
Q_DECLARE_METATYPE_COMMA(QMap<QString, QString>)
Q_DECLARE_METATYPE_COMMA(QVector<QMap<QString, QString> >)
Q_DECLARE_METATYPE_COMMA(QVector<QVector<QMap<QString, QString> > >)
class QTrackerDriver;
QT_BEGIN_NAMESPACE
// This enum is defined in tracker-sparql.h, but copy it here for now
// to avoid a dependency on that header.
typedef enum {
TRACKER_SPARQL_ERROR_PARSE,
TRACKER_SPARQL_ERROR_UNKNOWN_CLASS,
TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY,
TRACKER_SPARQL_ERROR_TYPE,
TRACKER_SPARQL_ERROR_CONSTRAINT,
TRACKER_SPARQL_ERROR_NO_SPACE,
TRACKER_SPARQL_ERROR_INTERNAL,
TRACKER_SPARQL_ERROR_UNSUPPORTED
} TrackerSparqlError;
class QTrackerDriverPrivate {
public:
QTrackerDriverPrivate();
~QTrackerDriverPrivate();
QDBusInterface* iface;
bool doBatch; // true: call BatchSparqlUpdate on Tracker instead of
// SparqlUpdateBlank
};
class QTrackerResultPrivate : public QObject {
Q_OBJECT
public:
QTrackerResultPrivate(QTrackerResult* res,
QSparqlQuery::StatementType tp);
~QTrackerResultPrivate();
QDBusPendingCallWatcher* watcher;
QVector<QStringList> data;
QSparqlQuery::StatementType type;
void setCall(QDBusPendingCall& call);
static TrackerSparqlError errorNameToCode(const QString& name);
static QSparqlError::ErrorType errorCodeToType(TrackerSparqlError code);
private Q_SLOTS:
void onDBusCallFinished();
private:
QTrackerResult* q; // public part
};
namespace {
// How to recognize tracker
QLatin1String service("org.freedesktop.Tracker1");
QLatin1String basePath("/org/freedesktop/Tracker1");
QLatin1String resourcesInterface("org.freedesktop.Tracker1.Resources");
QLatin1String resourcesPath("/org/freedesktop/Tracker1/Resources");
} // end of unnamed namespace
QTrackerResultPrivate::QTrackerResultPrivate(QTrackerResult* res,
QSparqlQuery::StatementType tp)
: watcher(0), type(tp), q(res)
{
}
void QTrackerResultPrivate::setCall(QDBusPendingCall& call)
{
// This function should be called only once
watcher = new QDBusPendingCallWatcher(call);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
this, SLOT(onDBusCallFinished()));
}
QTrackerResultPrivate::~QTrackerResultPrivate()
{
delete watcher;
}
TrackerSparqlError QTrackerResultPrivate::errorNameToCode(const QString& name)
{
if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Parse")) {
return TRACKER_SPARQL_ERROR_PARSE;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.UnknownClass")) {
return TRACKER_SPARQL_ERROR_UNKNOWN_CLASS;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.UnknownProperty")) {
return TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Type")) {
return TRACKER_SPARQL_ERROR_TYPE;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Constraint")) {
return TRACKER_SPARQL_ERROR_CONSTRAINT;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.NoSpace")) {
return TRACKER_SPARQL_ERROR_NO_SPACE;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Internal")) {
return TRACKER_SPARQL_ERROR_INTERNAL;
} else if (name == QLatin1String("org.freedesktop.Tracker1.SparqlError.Unsupported")) {
return TRACKER_SPARQL_ERROR_UNSUPPORTED;
} else {
return static_cast<TrackerSparqlError>(-1);
}
}
QSparqlError::ErrorType QTrackerResultPrivate::errorCodeToType(TrackerSparqlError code)
{
switch (code) {
case TRACKER_SPARQL_ERROR_PARSE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_CLASS:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_UNKNOWN_PROPERTY:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_TYPE:
return QSparqlError::StatementError;
case TRACKER_SPARQL_ERROR_CONSTRAINT:
return QSparqlError::ConnectionError;
case TRACKER_SPARQL_ERROR_NO_SPACE:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_INTERNAL:
return QSparqlError::BackendError;
case TRACKER_SPARQL_ERROR_UNSUPPORTED:
return QSparqlError::BackendError;
default:
return QSparqlError::BackendError;
}
}
void QTrackerResultPrivate::onDBusCallFinished()
{
if (watcher->isError()) {
QSparqlError error(watcher->error().message());
if (watcher->error().type() == QDBusError::Other) {
TrackerSparqlError code = errorNameToCode(watcher->error().name());
error.setNumber(code);
error.setType(errorCodeToType(code));
} else {
// Error from D-Bus
error.setNumber((int)watcher->error().type());
error.setType(QSparqlError::ConnectionError);
}
q->setLastError(error);
Q_EMIT q->finished();
qWarning() << "QTrackerResult:" << q->lastError() << q->query();
return;
}
switch (type) {
case QSparqlQuery::AskStatement:
case QSparqlQuery::SelectStatement:
{
QDBusPendingReply<QVector<QStringList> > reply = *watcher;
data = reply.argumentAt<0>();
if (type == QSparqlQuery::AskStatement && data.count() == 1 && data[0].count() == 1)
{
QVariant boolValue = data[0][0];
q->setBoolValue(boolValue.toBool());
}
Q_EMIT q->dataReady(data.size());
break;
}
default:
// TODO: handle update results here
break;
}
Q_EMIT q->finished();
}
QTrackerResult::QTrackerResult(QSparqlQuery::StatementType tp)
{
d = new QTrackerResultPrivate(this, tp);
}
QTrackerResult::~QTrackerResult()
{
delete d;
}
QTrackerResult* QTrackerDriver::exec(const QString& query,
QSparqlQuery::StatementType type,
const QSparqlQueryOptions& options)
{
if (options.executionMethod() == QSparqlQueryOptions::SyncExec)
return 0;
QTrackerResult* res = new QTrackerResult(type);
res->setQuery(query);
QString funcToCall;
switch (type) {
case QSparqlQuery::AskStatement:
case QSparqlQuery::SelectStatement:
{
funcToCall = QString::fromLatin1("SparqlQuery");
break;
}
case QSparqlQuery::InsertStatement: // fall-through
case QSparqlQuery::DeleteStatement:
{
if (d->doBatch || options.priority() == QSparqlQueryOptions::LowPriority) {
funcToCall = QString::fromLatin1("BatchSparqlUpdate");
}
else {
funcToCall = QString::fromLatin1("SparqlUpdateBlank");
}
break;
}
default:
res->setLastError(QSparqlError(
QLatin1String("Non-supported statement type"),
QSparqlError::BackendError));
qWarning() << "QTrackerResult:" << res->lastError() << res->query();
return res;
break;
}
QDBusPendingCall call = d->iface->asyncCall(funcToCall,
QVariant(query));
res->d->setCall(call);
return res;
}
QSparqlBinding QTrackerResult::binding(int field) const
{
if (!isValid()) {
return QSparqlBinding();
}
int i = pos();
if (field >= d->data[i].count() || field < 0) {
qWarning() << "QTrackerResult::data: column" << field << "out of range";
return QSparqlBinding();
}
QString name = QString::fromLatin1("$%1").arg(field + 1);
return QSparqlBinding(name, QVariant(d->data[i][field]));
}
QVariant QTrackerResult::value(int field) const
{
if (!isValid()) {
return QVariant();
}
// The upper layer calls this function only when this Result is positioned
// in a valid position, so we don't need to check that.
int i = pos();
if (field >= d->data[i].count() || field < 0) {
qWarning() << "QTrackerResult::data: column" << field << "out of range";
return QVariant();
}
return d->data[i][field];
}
void QTrackerResult::waitForFinished()
{
if (d->watcher)
d->watcher->waitForFinished();
}
bool QTrackerResult::isFinished() const
{
if (d->watcher)
return d->watcher->isFinished();
return true;
}
int QTrackerResult::size() const
{
return d->data.count();
}
QSparqlResultRow QTrackerResult::current() const
{
if (!isValid()) {
return QSparqlResultRow();
}
QSparqlResultRow info;
if (pos() >= d->data.count() || pos() < 0)
return info;
QStringList resultStrings = d->data[pos()];
Q_FOREACH (const QString& str, resultStrings) {
// This only creates a binding with the values but with empty column
// names.
// TODO: how to add column names?
QSparqlBinding b(QString(), str);
info.append(b);
}
return info;
}
bool QTrackerResult::hasFeature(QSparqlResult::Feature feature) const
{
switch (feature) {
case QSparqlResult::Sync:
case QSparqlResult::ForwardOnly:
return false;
case QSparqlResult::QuerySize:
return true;
default:
return false;
}
}
QTrackerDriverPrivate::QTrackerDriverPrivate()
: iface(0), doBatch(false)
{
}
QTrackerDriverPrivate::~QTrackerDriverPrivate()
{
delete iface;
}
QTrackerDriver::QTrackerDriver(QObject* parent)
: QSparqlDriver(parent)
{
d = new QTrackerDriverPrivate();
qRegisterMetaType<QVector<QStringList> >();
qDBusRegisterMetaType<QVector<QStringList> >();
qRegisterMetaType<QMap<QString, QString> >();
qRegisterMetaType<QVector<QMap<QString, QString> > >();
qDBusRegisterMetaType<QVector<QMap<QString, QString> > >();
/*
if(!trackerBus().interface()->isServiceRegistered(service_g)
&& (trackerBus().interface()->startService(service_g)
, !trackerBus().interface()->isServiceRegistered(service_g)))
qCritical() << "cannot connect to org.freedesktop.Tracker1 service";
*/
}
QTrackerDriver::~QTrackerDriver()
{
delete d;
}
bool QTrackerDriver::hasFeature(QSparqlConnection::Feature f) const
{
switch (f) {
case QSparqlConnection::QuerySize:
case QSparqlConnection::DefaultGraph:
case QSparqlConnection::AskQueries:
case QSparqlConnection::UpdateQueries:
case QSparqlConnection::AsyncExec:
return true;
case QSparqlConnection::ConstructQueries:
case QSparqlConnection::SyncExec:
return false;
default:
return false;
}
return false;
}
bool QTrackerDriver::open(const QSparqlConnectionOptions& options)
{
// This option has been removed from API documentation as it is replaced by
// QSparqlQueryOption::LowPriority. The implemenation needs to be kept
// for backward compatibility.
QVariant batchOption = options.option(QString::fromLatin1("batch"));
if (!batchOption.isNull()) {
d->doBatch = batchOption.toBool();
}
if (isOpen())
close();
d->iface = new QDBusInterface(service, resourcesPath,
resourcesInterface,
QDBusConnection::sessionBus());
setOpen(true);
setOpenError(false);
return true;
}
void QTrackerDriver::close()
{
if (isOpen()) {
delete d->iface;
d->iface = 0;
setOpen(false);
setOpenError(false);
}
}
QT_END_NAMESPACE
#include "qsparql_tracker.moc"
<|endoftext|> |
<commit_before>#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <C5G/C5G.h>
#include <C5G/Grasp.h>
namespace C5G{
void C5G::moveCartesian(const Pose& p){
std::cout << "Relative movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
}
const Pose C5G::safePose={0.3, 0, 0.7, 0, 0, 0};
void C5G::moveCartesianGlobal(const Pose& p){
std::cout << "Global movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
}
void C5G::init(){
std::cout << "Initing the system..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(3));
std::cout << "Done.\n";
}
void C5G::standby(){
std::cout << "Goodbye, cruel world..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "I'm leaving you today..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye.\n";
}
void C5G::setGripping(double strength){
std::cout << "Closing the plier with strength " << strength << "\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
}
void C5G::executeGrasp(const Grasp& g){
moveCartesian(g.approach);
moveCartesian(g.grasp);
setGripping(g.force);
moveCartesian(g.approach);
}
}
<commit_msg>Whops C5G_dummy<commit_after>#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <C5G/C5G.h>
#include <C5G/Grasp.h>
namespace C5G{
void C5G::moveCartesian(const Pose& p){
std::cout << "Relative movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
}
const Pose C5G::safePose={0.3, 0, 0.7, 0, 0, 0};
void C5G::moveCartesianGlobal(const Pose& p){
std::cout << "Global movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
}
void C5G::init(const std::string& ip, const std::string& sysID){
std::cout << "Initing the system..\nConnecting to IP address: " << ip << "\nSystem ID: " << sysID << "\n";
boost::this_thread::sleep_for(boost::chrono::seconds(3));
std::cout << "Done.\n";
}
void C5G::standby(){
std::cout << "Goodbye, cruel world..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "I'm leaving you today..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye.\n";
}
void C5G::setGripping(double strength){
std::cout << "Closing the plier with strength " << strength << "\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
}
void C5G::executeGrasp(const Grasp& g){
moveCartesian(g.approach);
moveCartesian(g.grasp);
setGripping(g.force);
moveCartesian(g.approach);
}
C5G::~C5G(){
standby();
}
}
<|endoftext|> |
<commit_before>/************************************************************************
filename: CEGUIRenderer.cpp
created: 20/2/2004
author: Paul D Turner
purpose: Some base class implementation for Renderer objects
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
Copyright (C)2004 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIRenderer.h"
#include "CEGUIEventSet.h"
#include "CEGUIEvent.h"
#include "CEGUIDefaultResourceProvider.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Event name constants (static data definitions)
*************************************************************************/
const utf8 Renderer::EventDisplaySizeChanged[] = "DisplayModeChanged";
/*************************************************************************
Implementation constants
*************************************************************************/
const float Renderer::GuiZInitialValue = 1.0f;
const float Renderer::GuiZElementStep = 0.001f; // this is enough for 1000 Windows.
const float Renderer::GuiZLayerStep = 0.0001f; // provides space for 10 layers per Window.
/*************************************************************************
Constructor
*************************************************************************/
Renderer::Renderer(void)
{
// setup standard events available
addEvent(EventDisplaySizeChanged);
// default initialisation
resetZValue();
}
/*************************************************************************
Destructor
*************************************************************************/
Renderer::~Renderer(void)
{
if(d_resourceProvider)
{
delete d_resourceProvider;
d_resourceProvider = 0;
}
}
ResourceProvider* Renderer::createResourceProvider(void)
{
d_resourceProvider = new DefaultResourceProvider();
return d_resourceProvider;
}
} // End of CEGUI namespace section
<commit_msg>Initialise d_resourceProvider.<commit_after>/************************************************************************
filename: CEGUIRenderer.cpp
created: 20/2/2004
author: Paul D Turner
purpose: Some base class implementation for Renderer objects
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
Copyright (C)2004 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIRenderer.h"
#include "CEGUIEventSet.h"
#include "CEGUIEvent.h"
#include "CEGUIDefaultResourceProvider.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Event name constants (static data definitions)
*************************************************************************/
const utf8 Renderer::EventDisplaySizeChanged[] = "DisplayModeChanged";
/*************************************************************************
Implementation constants
*************************************************************************/
const float Renderer::GuiZInitialValue = 1.0f;
const float Renderer::GuiZElementStep = 0.001f; // this is enough for 1000 Windows.
const float Renderer::GuiZLayerStep = 0.0001f; // provides space for 10 layers per Window.
/*************************************************************************
Constructor
*************************************************************************/
Renderer::Renderer(void)
: d_resourceProvider(0)
{
// setup standard events available
addEvent(EventDisplaySizeChanged);
// default initialisation
resetZValue();
}
/*************************************************************************
Destructor
*************************************************************************/
Renderer::~Renderer(void)
{
if(d_resourceProvider)
{
delete d_resourceProvider;
d_resourceProvider = 0;
}
}
ResourceProvider* Renderer::createResourceProvider(void)
{
d_resourceProvider = new DefaultResourceProvider();
return d_resourceProvider;
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include <time.h>
#include "xsi_application.h"
#include "AlembicLicensing.h"
#include <string>
#include <sstream>
using namespace std;
#if defined( EXOCORTEX_RLM_ONLY )
#include "RlmSingletonDeclarations.h"
#endif // EXOCORTEX_RLM_ONLY
int s_alembicLicense = -1;
int GetAlembicLicense() {
static string pluginName(XSI::CString(PLUGIN_NAME).GetAsciiString());
if( s_alembicLicense != ALEMBIC_NO_LICENSE ) {
return s_alembicLicense;
}
bool isWriterLicense = XSI::Application().IsInteractive();
bool isForceReader = ( getenv("EXOCORTEX_ALEMBIC_FORCE_READER") != NULL );
bool isForceWriter = ( getenv("EXOCORTEX_ALEMBIC_FORCE_WRITER") != NULL );
if( isForceReader && isForceWriter ) {
ESS_LOG_ERROR( "Both environment variables EXOCORTEX_ALEMBIC_FORCE_READER and EXOCORTEX_ALEMBIC_FORCE_WRITER defined, these conflict" );
}
if( isWriterLicense ) {
if( isForceReader ) {
ESS_LOG_ERROR( "Environment variable EXOCORTEX_ALEMBIC_FORCE_READER defined, forcing usage of read-only license." );
isWriterLicense = false;
}
}
if( ! isWriterLicense ) {
if( isForceWriter ) {
ESS_LOG_ERROR( "Environment variable EXOCORTEX_ALEMBIC_FORCE_WRITER defined, forcing usage of write-capable license." );
isWriterLicense = true;
}
}
vector<RlmProductID> rlmProductIds;
int pluginLicenseResult;
if( isWriterLicense ) {
RlmProductID pluginLicenseIds[] = ALEMBIC_WRITER_LICENSE_IDS;
for( int i = 0; i < sizeof( pluginLicenseIds ) / sizeof( RlmProductID ); i ++ ) {
rlmProductIds.push_back( pluginLicenseIds[i] );
}
pluginLicenseResult = ALEMBIC_WRITER_LICENSE;
}
else {
RlmProductID pluginLicenseIds[] = ALEMBIC_READER_LICENSE_IDS;
for( int i = 0; i < sizeof( pluginLicenseIds ) / sizeof( RlmProductID ); i ++ ) {
rlmProductIds.push_back( pluginLicenseIds[i] );
}
pluginLicenseResult = ALEMBIC_READER_LICENSE;
}
Exocortex::RlmSingleton& rlmSingleton = Exocortex::RlmSingleton::getSingleton();
if( rlmSingleton.checkoutLicense( "", pluginName, rlmProductIds ) ) {
s_alembicLicense = pluginLicenseResult;
}
else {
s_alembicLicense = ALEMBIC_DEMO_LICENSE;
}
return s_alembicLicense;
}
bool HasAlembicWriterLicense() {
return ( GetAlembicLicense() == ALEMBIC_WRITER_LICENSE );
}
bool HasAlembicReaderLicense() {
return ( GetAlembicLicense() == ALEMBIC_WRITER_LICENSE )||( GetAlembicLicense() == ALEMBIC_READER_LICENSE );
}
#ifdef EXOCORTEX_SERVICES
namespace Exocortex {
void essOnDemandInitialization() {
static string pluginName(XSI::CString(PLUGIN_NAME).GetAsciiString());
essInitializeSoftimage( pluginName.c_str(), PLUGIN_MAJOR_VERSION, PLUGIN_MINOR_VERSION );
}
}
#endif // EXOCORTEX_SERVICES
<commit_msg>fixed bug #29.<commit_after>#include <time.h>
#include "xsi_application.h"
#include "AlembicLicensing.h"
#include <string>
#include <sstream>
using namespace std;
#if defined( EXOCORTEX_RLM_ONLY )
#include "RlmSingletonDeclarations.h"
#endif // EXOCORTEX_RLM_ONLY
int s_alembicLicense = -1;
int GetAlembicLicense() {
static string pluginName(XSI::CString(PLUGIN_NAME).GetAsciiString());
if( s_alembicLicense != ALEMBIC_NO_LICENSE ) {
return s_alembicLicense;
}
bool isWriterLicense = XSI::Application().IsInteractive();
bool isForceReader = ( getenv("EXOCORTEX_ALEMBIC_FORCE_READER") != NULL );
bool isForceWriter = ( getenv("EXOCORTEX_ALEMBIC_FORCE_WRITER") != NULL );
if( isForceReader && isForceWriter ) {
ESS_LOG_ERROR( "Both environment variables EXOCORTEX_ALEMBIC_FORCE_READER and EXOCORTEX_ALEMBIC_FORCE_WRITER defined, these conflict" );
}
if( isWriterLicense ) {
if( isForceReader ) {
ESS_LOG_WARNING( "Environment variable EXOCORTEX_ALEMBIC_FORCE_READER defined, forcing usage of read-only license." );
isWriterLicense = false;
}
}
if( ! isWriterLicense ) {
if( isForceWriter ) {
ESS_LOG_WARNING( "Environment variable EXOCORTEX_ALEMBIC_FORCE_WRITER defined, forcing usage of write-capable license." );
isWriterLicense = true;
}
}
vector<RlmProductID> rlmProductIds;
int pluginLicenseResult;
if( isWriterLicense ) {
RlmProductID pluginLicenseIds[] = ALEMBIC_WRITER_LICENSE_IDS;
for( int i = 0; i < sizeof( pluginLicenseIds ) / sizeof( RlmProductID ); i ++ ) {
rlmProductIds.push_back( pluginLicenseIds[i] );
}
pluginLicenseResult = ALEMBIC_WRITER_LICENSE;
}
else {
RlmProductID pluginLicenseIds[] = ALEMBIC_READER_LICENSE_IDS;
for( int i = 0; i < sizeof( pluginLicenseIds ) / sizeof( RlmProductID ); i ++ ) {
rlmProductIds.push_back( pluginLicenseIds[i] );
}
pluginLicenseResult = ALEMBIC_READER_LICENSE;
}
Exocortex::RlmSingleton& rlmSingleton = Exocortex::RlmSingleton::getSingleton();
if( rlmSingleton.checkoutLicense( "", pluginName, rlmProductIds ) ) {
s_alembicLicense = pluginLicenseResult;
}
else {
s_alembicLicense = ALEMBIC_DEMO_LICENSE;
}
return s_alembicLicense;
}
bool HasAlembicWriterLicense() {
return ( GetAlembicLicense() == ALEMBIC_WRITER_LICENSE );
}
bool HasAlembicReaderLicense() {
return ( GetAlembicLicense() == ALEMBIC_WRITER_LICENSE )||( GetAlembicLicense() == ALEMBIC_READER_LICENSE );
}
#ifdef EXOCORTEX_SERVICES
namespace Exocortex {
void essOnDemandInitialization() {
static string pluginName(XSI::CString(PLUGIN_NAME).GetAsciiString());
essInitializeSoftimage( pluginName.c_str(), PLUGIN_MAJOR_VERSION, PLUGIN_MINOR_VERSION );
}
}
#endif // EXOCORTEX_SERVICES
<|endoftext|> |
<commit_before>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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 "CaptureDevice.h"
#include "Error.h"
#include "logging.h"
#include "utils.h"
#include "serialization.h"
#include "CaptureDeviceImpl.h"
using namespace tcam;
CaptureDevice::CaptureDevice ()
: impl(new CaptureDeviceImpl())
{}
CaptureDevice::CaptureDevice (const DeviceInfo& info)
: impl(new CaptureDeviceImpl())
{
impl->open_device(info);
}
CaptureDevice::~CaptureDevice ()
{}
bool CaptureDevice::load_configuration (const std::string& filename)
{
return impl->load_configuration(filename);
}
bool CaptureDevice::save_configuration (const std::string& filename)
{
return impl->save_configuration(filename);
}
bool CaptureDevice::is_device_open () const
{
return impl->is_device_open ();
}
DeviceInfo CaptureDevice::get_device () const
{
return impl->get_device();
}
std::vector<Property*> CaptureDevice::get_available_properties ()
{
return impl->get_available_properties();
}
Property* CaptureDevice::get_property (TCAM_PROPERTY_ID id)
{
auto properties = get_available_properties();
for (auto& p : properties)
{
if (p->get_ID() == id)
{
return p;
}
}
return nullptr;
}
Property* CaptureDevice::get_property_by_name (const std::string& name)
{
auto properties = get_available_properties();
for (auto& p : properties)
{
if (p->get_name().compare(name) == 0)
{
return p;
}
}
return nullptr;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const int64_t& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_INTEGER)
{
return v->set_value(value);
}
}
}
return false;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const double& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_DOUBLE)
{
return v->set_value(value);
}
}
}
return false;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const bool& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_BOOLEAN)
{
return v->set_value(value);
}
}
}
return false;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const std::string& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_STRING)
{
return v->set_value(value);
}
}
}
return false;
}
std::vector<VideoFormatDescription> CaptureDevice::get_available_video_formats () const
{
return impl->get_available_video_formats();
}
bool CaptureDevice::set_video_format (const VideoFormat& new_format)
{
return impl->set_video_format(new_format);
}
VideoFormat CaptureDevice::get_active_video_format () const
{
return impl->get_active_video_format();
}
bool CaptureDevice::start_stream (std::shared_ptr<SinkInterface> sink)
{
return impl->start_stream(sink);
}
bool CaptureDevice::stop_stream ()
{
return impl->stop_stream();
}
std::shared_ptr<CaptureDevice> tcam::open_device (const std::string& serial)
{
for (const auto& d : get_device_list())
{
if (d.get_serial().compare(serial) == 0)
{
try
{
return std::make_shared<CaptureDevice>(CaptureDevice(d));
}
catch (const std::exception& err)
{
// TODO: set up error
tcam_log(TCAM_LOG_ERROR, "Could not open CaptureDevice. Exception:\"%s\"", err.what());
return nullptr;
}
}
}
return nullptr;
}
<commit_msg>Add check if name is empty<commit_after>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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 "CaptureDevice.h"
#include "Error.h"
#include "logging.h"
#include "utils.h"
#include "serialization.h"
#include "CaptureDeviceImpl.h"
using namespace tcam;
CaptureDevice::CaptureDevice ()
: impl(new CaptureDeviceImpl())
{}
CaptureDevice::CaptureDevice (const DeviceInfo& info)
: impl(new CaptureDeviceImpl())
{
impl->open_device(info);
}
CaptureDevice::~CaptureDevice ()
{}
bool CaptureDevice::load_configuration (const std::string& filename)
{
return impl->load_configuration(filename);
}
bool CaptureDevice::save_configuration (const std::string& filename)
{
return impl->save_configuration(filename);
}
bool CaptureDevice::is_device_open () const
{
return impl->is_device_open ();
}
DeviceInfo CaptureDevice::get_device () const
{
return impl->get_device();
}
std::vector<Property*> CaptureDevice::get_available_properties ()
{
return impl->get_available_properties();
}
Property* CaptureDevice::get_property (TCAM_PROPERTY_ID id)
{
auto properties = get_available_properties();
for (auto& p : properties)
{
if (p->get_ID() == id)
{
return p;
}
}
return nullptr;
}
Property* CaptureDevice::get_property_by_name (const std::string& name)
{
if (name.empty())
{
return nullptr;
}
auto properties = get_available_properties();
for (auto& p : properties)
{
if (p->get_name().compare(name) == 0)
{
return p;
}
}
return nullptr;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const int64_t& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_INTEGER)
{
return v->set_value(value);
}
}
}
return false;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const double& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_DOUBLE)
{
return v->set_value(value);
}
}
}
return false;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const bool& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_BOOLEAN)
{
return v->set_value(value);
}
}
}
return false;
}
bool CaptureDevice::set_property (TCAM_PROPERTY_ID id, const std::string& value)
{
auto vec = get_available_properties();
for (const auto& v : vec)
{
if (id == v->get_ID())
{
if (v->get_type() == TCAM_PROPERTY_TYPE_STRING)
{
return v->set_value(value);
}
}
}
return false;
}
std::vector<VideoFormatDescription> CaptureDevice::get_available_video_formats () const
{
return impl->get_available_video_formats();
}
bool CaptureDevice::set_video_format (const VideoFormat& new_format)
{
return impl->set_video_format(new_format);
}
VideoFormat CaptureDevice::get_active_video_format () const
{
return impl->get_active_video_format();
}
bool CaptureDevice::start_stream (std::shared_ptr<SinkInterface> sink)
{
return impl->start_stream(sink);
}
bool CaptureDevice::stop_stream ()
{
return impl->stop_stream();
}
std::shared_ptr<CaptureDevice> tcam::open_device (const std::string& serial)
{
for (const auto& d : get_device_list())
{
if (d.get_serial().compare(serial) == 0)
{
try
{
return std::make_shared<CaptureDevice>(CaptureDevice(d));
}
catch (const std::exception& err)
{
// TODO: set up error
tcam_log(TCAM_LOG_ERROR, "Could not open CaptureDevice. Exception:\"%s\"", err.what());
return nullptr;
}
}
}
return nullptr;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia 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 (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "vectorrealtotensor.h"
using namespace std;
namespace essentia {
namespace streaming {
const char* VectorRealToTensor::name = "VectorRealToTensor";
const char* VectorRealToTensor::category = "Standard";
const char* VectorRealToTensor::description = DOC("This algorithm generates tensors "
"out of a stream of input frames. The 4 dimensions of the tensors stand for (batchSize, channels, patchSize, featureSize):\n"
" - batchSize: Number of patches per tensor. If batchSize is set to 0 it will accumulate patches until the end of the stream is reached and then produce a single tensor. "
"Warning: This option may exhaust memory depending on the size of the stream.\n"
" - channels: Number of channels per tensor. Currently, only single-channel tensors are supported. Otherwise, an exception is thrown.\n"
" - patchSize: Number of timestamps (i.e., number of frames) per patch.\n"
" - featureSize: Expected number of features (e.g., mel bands) of every input frame. This algorithm throws an exception if the size of any frame is different from featureSize.\n"
"Additionally, the patchHopSize and batchHopSize parameters provide control over the amount of overlap on those dimensions.");
void VectorRealToTensor::configure() {
vector<int> shape = parameter("shape").toVectorInt();
_patchHopSize = parameter("patchHopSize").toInt();
_batchHopSize = parameter("batchHopSize").toInt();
_lastPatchMode = parameter("lastPatchMode").toString();
_shape.resize(shape.size());
for (size_t i = 0; i < shape.size(); i++) {
if (shape[i] == 0) {
throw EssentiaException("VectorRealToTensor: All dimensions should have a non-zero size.");
}
_shape[i] = shape[i];
}
if (shape[1] != 1) {
throw EssentiaException("VectorRealToTensor: Currently only single-channel tensors are supported.");
}
_timeStamps = shape[2];
_frame.setAcquireSize(_timeStamps);
if (shape[0] == -1) {
_accumulate = true;
}
if (_batchHopSize == 0) {
_batchHopSize = shape[0];
}
if (_patchHopSize == 0) {
_patchHopSize = _timeStamps;
}
_acc.assign(0, vector<vector<Real> >(_shape[2], vector<Real>(_shape[3], 0.0)));
_push = false;
if (_patchHopSize > _timeStamps) {
throw EssentiaException("VectorRealToTensor: `patchHopSize` has to be smaller that the number of timestamps");
}
if (shape[0] > 0) {
if (_batchHopSize > shape[0]) {
throw EssentiaException("VectorRealToTensor: `batchHopSize` has to be smaller than the batch size (shape[0])");
}
}
}
AlgorithmStatus VectorRealToTensor::process() {
EXEC_DEBUG("process()");
if (_timeStamps != _frame.acquireSize()) {
_frame.setAcquireSize(_timeStamps);
}
if (_patchHopSize != _frame.releaseSize()) {
_frame.setReleaseSize(_patchHopSize);
}
// Check if we have enough frames to add a patch.
int available = _frame.available();
bool addPatch = (available >= _timeStamps);
// If we should stop just take the remaining frames.
if (shouldStop() && (available < _timeStamps)) {
_frame.setAcquireSize(available);
_frame.setReleaseSize(available);
// Push if there are remaining frames
if (_lastPatchMode == "repeat" && available > 0) {
addPatch = true;
_push = true;
// or if we have been accumulating.
} else if (_accumulate && _acc.size() >= 1) {
addPatch = true;
_push = true;
}
}
// Return if there is nothing to do.
if ((!addPatch) && (!_push)) return NO_INPUT;
if (_push) {
_tensor.setAcquireSize(1);
_tensor.setReleaseSize(1);
// Don't get frames if we just want to push.
if (!addPatch) {
_frame.setAcquireSize(0);
_frame.setReleaseSize(0);
}
// Don't get a tensor if we are just accumulating.
} else {
_tensor.setAcquireSize(0);
_tensor.setReleaseSize(0);
}
AlgorithmStatus status = acquireData();
EXEC_DEBUG("data acquired (in: " << _frame.acquireSize()
<< " - out: " << _tensor.acquireSize() << ")");
if (status != OK) {
return status;
};
AlgorithmStatus outStatus = NO_OUTPUT;
// Frames accumulation step.
if (addPatch) {
const vector<vector<Real> >& frame = _frame.tokens();
// Sanity check.
for (size_t i = 0; i < frame.size(); i++) {
if ((int)frame[i].size() != _shape[3]) {
throw EssentiaException("VectorRealToTensor: Found input frame with size ", frame[i].size(),
" while the algorithm was configured to work with frames with size ", _shape[3]);
}
}
// Add a regular patch.
if ((int)frame.size() == _timeStamps) {
_acc.push_back(frame);
// If size does not match rather repeat frames or discard them.
} else {
if (_lastPatchMode == "repeat") {
if (frame.size() == 0) {
EXEC_DEBUG("VectorRealToTensor: 0 frames remaining.");
} else {
if (frame.size() < 10) {
E_WARNING("VectorRealToTensor: Last patch produced by repeating the last " << frame.size() << " frames. May result in unreliable predictions.");
}
vector<vector<Real> > padded_frame = frame;
for (int i = 0; i < _timeStamps; i++) {
padded_frame.push_back(frame[i % frame.size()]);
}
EXEC_DEBUG("VectorRealToTensor: Repeating the remaining " << frame.size() << " frames to make one last patch.");
_acc.push_back(padded_frame);
}
} else if (_lastPatchMode == "discard") {
EXEC_DEBUG("VectorRealToTensor: Discarding last frames");
} else {
throw EssentiaException("VectorRealToTensor: Incomplete patch found "
"before reaching the end of the stream. This is not supposed to happen");
}
}
}
// We only push if when we have filled the whole batch
// or if we have reached the end of the stream in
// accumulate mode.
if (_push) {
vector<int> shape = _shape;
int batchHopSize = _batchHopSize;
// If we have been accumulating we have to get the
// tensor's shape from the current status of the
// accumulator.
if (_accumulate) {
shape[0] = _acc.size();
batchHopSize = _acc.size();
if (_acc.size() == 0) {
throw EssentiaException("VectorRealToTensor: The stream has finished without enough frames to "
"produce a patch of the desired size. Consider setting the `lastPatchMode` "
"parameter to `repeat` in order to produce a batch.");
}
}
Tensor<Real>& tensor = *(Tensor<Real> *)_tensor.getFirstToken();
// Explicit convertion of std:vector to std::array<Eigen::Index> for Clang.
std::array<Eigen::Index, TENSORRANK> shapeEigenIndex;
std::copy_n(shape.begin(), TENSORRANK, shapeEigenIndex.begin());
tensor.resize(shapeEigenIndex);
for (int i = 0; i < shape[0]; i++) { // Batch axis
for (int j = 0; j < shape[2]; j++) { // Time axis
for (int k = 0; k < shape[3]; k++) { // Freq axis
tensor(i, 0, j, k) = _acc[i][j][k];
}
}
}
// Empty the accumulator.
_acc.erase(_acc.begin(), _acc.begin() + batchHopSize);
_push = false;
outStatus = OK;
}
// Check if we should push in the next process().
if (!_accumulate) {
if ((int)_acc.size() >= _shape[0]) _push = true;
}
EXEC_DEBUG("releasing");
releaseData();
EXEC_DEBUG("released");
return outStatus;
}
void VectorRealToTensor::reset() {
_acc.assign(0, vector<vector<Real> >(_shape[1], vector<Real>(_shape[2], 0.0)));
_push = false;
}
} // namespace streaming
} // namespace essentia
<commit_msg>Fix documentation<commit_after>/*
* Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia 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 (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "vectorrealtotensor.h"
using namespace std;
namespace essentia {
namespace streaming {
const char* VectorRealToTensor::name = "VectorRealToTensor";
const char* VectorRealToTensor::category = "Standard";
const char* VectorRealToTensor::description = DOC("This algorithm generates tensors "
"out of a stream of input frames. The 4 dimensions of the tensors stand for (batchSize, channels, patchSize, featureSize):\n"
" - batchSize: Number of patches per tensor. If batchSize is set to -1 it will accumulate patches until the end of the stream is reached and then produce a single tensor. "
"Warning: This option may exhaust memory depending on the size of the stream.\n"
" - channels: Number of channels per tensor. Currently, only single-channel tensors are supported. Otherwise, an exception is thrown.\n"
" - patchSize: Number of timestamps (i.e., number of frames) per patch.\n"
" - featureSize: Expected number of features (e.g., mel bands) of every input frame. This algorithm throws an exception if the size of any frame is different from featureSize.\n"
"Additionally, the patchHopSize and batchHopSize parameters provide control over the amount of overlap on those dimensions.");
void VectorRealToTensor::configure() {
vector<int> shape = parameter("shape").toVectorInt();
_patchHopSize = parameter("patchHopSize").toInt();
_batchHopSize = parameter("batchHopSize").toInt();
_lastPatchMode = parameter("lastPatchMode").toString();
_shape.resize(shape.size());
for (size_t i = 0; i < shape.size(); i++) {
if (shape[i] == 0) {
throw EssentiaException("VectorRealToTensor: All dimensions should have a non-zero size.");
}
_shape[i] = shape[i];
}
if (shape[1] != 1) {
throw EssentiaException("VectorRealToTensor: Currently only single-channel tensors are supported.");
}
_timeStamps = shape[2];
_frame.setAcquireSize(_timeStamps);
if (shape[0] == -1) {
_accumulate = true;
}
if (_batchHopSize == 0) {
_batchHopSize = shape[0];
}
if (_patchHopSize == 0) {
_patchHopSize = _timeStamps;
}
_acc.assign(0, vector<vector<Real> >(_shape[2], vector<Real>(_shape[3], 0.0)));
_push = false;
if (_patchHopSize > _timeStamps) {
throw EssentiaException("VectorRealToTensor: `patchHopSize` has to be smaller that the number of timestamps");
}
if (shape[0] > 0) {
if (_batchHopSize > shape[0]) {
throw EssentiaException("VectorRealToTensor: `batchHopSize` has to be smaller than the batch size (shape[0])");
}
}
}
AlgorithmStatus VectorRealToTensor::process() {
EXEC_DEBUG("process()");
if (_timeStamps != _frame.acquireSize()) {
_frame.setAcquireSize(_timeStamps);
}
if (_patchHopSize != _frame.releaseSize()) {
_frame.setReleaseSize(_patchHopSize);
}
// Check if we have enough frames to add a patch.
int available = _frame.available();
bool addPatch = (available >= _timeStamps);
// If we should stop just take the remaining frames.
if (shouldStop() && (available < _timeStamps)) {
_frame.setAcquireSize(available);
_frame.setReleaseSize(available);
// Push if there are remaining frames
if (_lastPatchMode == "repeat" && available > 0) {
addPatch = true;
_push = true;
// or if we have been accumulating.
} else if (_accumulate && _acc.size() >= 1) {
addPatch = true;
_push = true;
}
}
// Return if there is nothing to do.
if ((!addPatch) && (!_push)) return NO_INPUT;
if (_push) {
_tensor.setAcquireSize(1);
_tensor.setReleaseSize(1);
// Don't get frames if we just want to push.
if (!addPatch) {
_frame.setAcquireSize(0);
_frame.setReleaseSize(0);
}
// Don't get a tensor if we are just accumulating.
} else {
_tensor.setAcquireSize(0);
_tensor.setReleaseSize(0);
}
AlgorithmStatus status = acquireData();
EXEC_DEBUG("data acquired (in: " << _frame.acquireSize()
<< " - out: " << _tensor.acquireSize() << ")");
if (status != OK) {
return status;
};
AlgorithmStatus outStatus = NO_OUTPUT;
// Frames accumulation step.
if (addPatch) {
const vector<vector<Real> >& frame = _frame.tokens();
// Sanity check.
for (size_t i = 0; i < frame.size(); i++) {
if ((int)frame[i].size() != _shape[3]) {
throw EssentiaException("VectorRealToTensor: Found input frame with size ", frame[i].size(),
" while the algorithm was configured to work with frames with size ", _shape[3]);
}
}
// Add a regular patch.
if ((int)frame.size() == _timeStamps) {
_acc.push_back(frame);
// If size does not match rather repeat frames or discard them.
} else {
if (_lastPatchMode == "repeat") {
if (frame.size() == 0) {
EXEC_DEBUG("VectorRealToTensor: 0 frames remaining.");
} else {
if (frame.size() < 10) {
E_WARNING("VectorRealToTensor: Last patch produced by repeating the last " << frame.size() << " frames. May result in unreliable predictions.");
}
vector<vector<Real> > padded_frame = frame;
for (int i = 0; i < _timeStamps; i++) {
padded_frame.push_back(frame[i % frame.size()]);
}
EXEC_DEBUG("VectorRealToTensor: Repeating the remaining " << frame.size() << " frames to make one last patch.");
_acc.push_back(padded_frame);
}
} else if (_lastPatchMode == "discard") {
EXEC_DEBUG("VectorRealToTensor: Discarding last frames");
} else {
throw EssentiaException("VectorRealToTensor: Incomplete patch found "
"before reaching the end of the stream. This is not supposed to happen");
}
}
}
// We only push if when we have filled the whole batch
// or if we have reached the end of the stream in
// accumulate mode.
if (_push) {
vector<int> shape = _shape;
int batchHopSize = _batchHopSize;
// If we have been accumulating we have to get the
// tensor's shape from the current status of the
// accumulator.
if (_accumulate) {
shape[0] = _acc.size();
batchHopSize = _acc.size();
if (_acc.size() == 0) {
throw EssentiaException("VectorRealToTensor: The stream has finished without enough frames to "
"produce a patch of the desired size. Consider setting the `lastPatchMode` "
"parameter to `repeat` in order to produce a batch.");
}
}
Tensor<Real>& tensor = *(Tensor<Real> *)_tensor.getFirstToken();
// Explicit convertion of std:vector to std::array<Eigen::Index> for Clang.
std::array<Eigen::Index, TENSORRANK> shapeEigenIndex;
std::copy_n(shape.begin(), TENSORRANK, shapeEigenIndex.begin());
tensor.resize(shapeEigenIndex);
for (int i = 0; i < shape[0]; i++) { // Batch axis
for (int j = 0; j < shape[2]; j++) { // Time axis
for (int k = 0; k < shape[3]; k++) { // Freq axis
tensor(i, 0, j, k) = _acc[i][j][k];
}
}
}
// Empty the accumulator.
_acc.erase(_acc.begin(), _acc.begin() + batchHopSize);
_push = false;
outStatus = OK;
}
// Check if we should push in the next process().
if (!_accumulate) {
if ((int)_acc.size() >= _shape[0]) _push = true;
}
EXEC_DEBUG("releasing");
releaseData();
EXEC_DEBUG("released");
return outStatus;
}
void VectorRealToTensor::reset() {
_acc.assign(0, vector<vector<Real> >(_shape[1], vector<Real>(_shape[2], 0.0)));
_push = false;
}
} // namespace streaming
} // namespace essentia
<|endoftext|> |
<commit_before>#include "cpid.h"
#include "init.h"
#include "rpcclient.h"
#include "rpcserver.h"
#include "rpcprotocol.h"
#include "keystore.h"
#include "beacon.h"
double GetTotalBalance();
std::string GetBurnAddress() { return fTestNet ? "mk1e432zWKH1MW57ragKywuXaWAtHy1AHZ" : "S67nL4vELWwdDVzjgtEP4MxryarTZ9a8GB";
}
bool CheckMessageSignature(std::string sAction,std::string messagetype, std::string sMsg, std::string sSig, std::string strMessagePublicKey)
{
std::string strMasterPubKey = "";
if (messagetype=="project" || messagetype=="projectmapping")
{
strMasterPubKey= msMasterProjectPublicKey;
}
else
{
strMasterPubKey = msMasterMessagePublicKey;
}
if (!strMessagePublicKey.empty()) strMasterPubKey = strMessagePublicKey;
if (sAction=="D" && messagetype=="beacon") strMasterPubKey = msMasterProjectPublicKey;
if (sAction=="D" && messagetype=="poll") strMasterPubKey = msMasterProjectPublicKey;
if (sAction=="D" && messagetype=="vote") strMasterPubKey = msMasterProjectPublicKey;
if (messagetype=="protocol") strMasterPubKey = msMasterProjectPublicKey;
std::string db64 = DecodeBase64(sSig);
CKey key;
if (!key.SetPubKey(ParseHex(strMasterPubKey))) return false;
std::vector<unsigned char> vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchSig = std::vector<unsigned char>(db64.begin(), db64.end());
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return false;
return true;
}
bool VerifyCPIDSignature(std::string sCPID, std::string sBlockHash, std::string sSignature)
{
std::string sBeaconPublicKey = GetBeaconPublicKey(sCPID, false);
std::string sConcatMessage = sCPID + sBlockHash;
bool bValid = CheckMessageSignature("R","cpid", sConcatMessage, sSignature, sBeaconPublicKey);
if(!bValid)
LogPrintf("VerifyCPIDSignature: invalid signature sSignature=%s, cached key=%s"
,sSignature, sBeaconPublicKey);
return bValid;
}
std::string SignMessage(const std::string& sMsg, CKey& key)
{
std::vector<unsigned char> vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchSig;
if (!key.Sign(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
{
return "Unable to sign message, check private key.";
}
const std::string sig(vchSig.begin(), vchSig.end());
std::string SignedMessage = EncodeBase64(sig);
return SignedMessage;
}
std::string SignMessage(std::string sMsg, std::string sPrivateKey)
{
CKey key;
std::vector<unsigned char> vchPrivKey = ParseHex(sPrivateKey);
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
return SignMessage(sMsg, key);
}
std::string SendMessage(bool bAdd, std::string sType, std::string sPrimaryKey, std::string sValue,
std::string sMasterKey, int64_t MinimumBalance, double dFees, std::string strPublicKey)
{
std::string sAddress = GetBurnAddress();
CBitcoinAddress address(sAddress);
if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Gridcoin address");
int64_t nAmount = AmountFromValue(dFees);
// Wallet comments
CWalletTx wtx;
if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string sMessageType = "<MT>" + sType + "</MT>"; //Project or Smart Contract
std::string sMessageKey = "<MK>" + sPrimaryKey + "</MK>";
std::string sMessageValue = "<MV>" + sValue + "</MV>";
std::string sMessagePublicKey = "<MPK>"+ strPublicKey + "</MPK>";
std::string sMessageAction = bAdd ? "<MA>A</MA>" : "<MA>D</MA>"; //Add or Delete
//Sign Message
std::string sSig = SignMessage(sType+sPrimaryKey+sValue,sMasterKey);
std::string sMessageSignature = "<MS>" + sSig + "</MS>";
wtx.hashBoinc = sMessageType+sMessageKey+sMessageValue+sMessageAction+sMessagePublicKey+sMessageSignature;
std::string strError = pwalletMain->SendMoneyToDestinationWithMinimumBalance(address.Get(), nAmount, MinimumBalance, wtx);
if (!strError.empty()) throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex().c_str();
}
std::string SendContract(std::string sType, std::string sName, std::string sContract)
{
std::string sPass = (sType=="project" || sType=="projectmapping" || sType=="smart_contract") ? GetArgument("masterprojectkey", msMasterMessagePrivateKey) : msMasterMessagePrivateKey;
std::string result = SendMessage(true,sType,sName,sContract,sPass,AmountFromValue(1),.00001,"");
return result;
}
bool SignBlockWithCPID(const std::string& sCPID, const std::string& sBlockHash, std::string& sSignature, std::string& sError, bool bAdvertising=false)
{
// Check if there is a beacon for this user
// If not then return false as GetStoresBeaconPrivateKey grabs from the config
if (!HasActiveBeacon(sCPID) && !bAdvertising)
{
sError = "No active beacon";
return false;
}
// Returns the Signature of the CPID+BlockHash message.
CKey keyBeacon;
if(!GetStoredBeaconPrivateKey(sCPID, keyBeacon))
{
sError = "No beacon key";
return false;
}
std::string sMessage = sCPID + sBlockHash;
sSignature = SignMessage(sMessage,keyBeacon);
// If we failed to sign then return false
if (sSignature == "Unable to sign message, check private key.")
{
sError = sSignature;
sSignature = "";
return false;
}
return true;
}
int64_t AmountFromDouble(double dAmount)
{
if (dAmount <= 0.0 || dAmount > MAX_MONEY) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64_t nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
std::string executeRain(std::string sRecipients)
{
CWalletTx wtx;
wtx.mapValue["comment"] = "Rain";
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64_t> > vecSend;
std::string sRainCommand = ExtractXML(sRecipients,"<RAIN>","</RAIN>");
std::string sRainMessage = MakeSafeMessage(ExtractXML(sRecipients,"<RAINMESSAGE>","</RAINMESSAGE>"));
std::string sRain = "<NARR>Project Rain: " + sRainMessage + "</NARR>";
if (!sRainCommand.empty())
sRecipients = sRainCommand;
wtx.hashBoinc = sRain;
int64_t totalAmount = 0;
double dTotalToSend = 0;
std::vector<std::string> vRecipients = split(sRecipients.c_str(),"<ROW>");
LogPrintf("Creating Rain transaction with %" PRId64 " recipients. ", vRecipients.size());
for (unsigned int i = 0; i < vRecipients.size(); i++)
{
std::string sRow = vRecipients[i];
std::vector<std::string> vReward = split(sRow.c_str(),"<COL>");
if (vReward.size() > 1)
{
std::string sAddress = vReward[0];
std::string sAmount = vReward[1];
if (sAddress.length() > 10 && sAmount.length() > 0)
{
double dAmount = RoundFromString(sAmount,4);
if (dAmount > 0)
{
CBitcoinAddress address(sAddress);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Gridcoin address: ")+sAddress);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+sAddress);
setAddress.insert(address);
dTotalToSend += dAmount;
int64_t nAmount = AmountFromDouble(dAmount);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
}
}
}
EnsureWalletIsUnlocked();
// Check funds
double dBalance = GetTotalBalance();
if (dTotalToSend > dBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64_t nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
LogPrintf("Transaction Created.");
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
LogPrintf("Committing.");
// Rain the recipients
if (!pwalletMain->CommitTransaction(wtx, keyChange))
{
LogPrintf("Commit failed.");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
}
std::string sNarr = "Rain successful: Sent " + wtx.GetHash().GetHex() + ".";
LogPrintf("Success %s",sNarr.c_str());
return sNarr;
}
<commit_msg>Require addkey action scraper to use master key - Part II<commit_after>#include "cpid.h"
#include "init.h"
#include "rpcclient.h"
#include "rpcserver.h"
#include "rpcprotocol.h"
#include "keystore.h"
#include "beacon.h"
double GetTotalBalance();
std::string GetBurnAddress() { return fTestNet ? "mk1e432zWKH1MW57ragKywuXaWAtHy1AHZ" : "S67nL4vELWwdDVzjgtEP4MxryarTZ9a8GB";
}
bool CheckMessageSignature(std::string sAction,std::string messagetype, std::string sMsg, std::string sSig, std::string strMessagePublicKey)
{
std::string strMasterPubKey = "";
if (messagetype=="project" || messagetype=="projectmapping")
{
strMasterPubKey= msMasterProjectPublicKey;
}
else
{
strMasterPubKey = msMasterMessagePublicKey;
}
if (!strMessagePublicKey.empty()) strMasterPubKey = strMessagePublicKey;
if (sAction=="D" && messagetype=="beacon") strMasterPubKey = msMasterProjectPublicKey;
if (sAction=="D" && messagetype=="poll") strMasterPubKey = msMasterProjectPublicKey;
if (sAction=="D" && messagetype=="vote") strMasterPubKey = msMasterProjectPublicKey;
if (messagetype == "protocol" || messagetype == "scraper") strMasterPubKey = msMasterProjectPublicKey;
std::string db64 = DecodeBase64(sSig);
CKey key;
if (!key.SetPubKey(ParseHex(strMasterPubKey))) return false;
std::vector<unsigned char> vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchSig = std::vector<unsigned char>(db64.begin(), db64.end());
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return false;
return true;
}
bool VerifyCPIDSignature(std::string sCPID, std::string sBlockHash, std::string sSignature)
{
std::string sBeaconPublicKey = GetBeaconPublicKey(sCPID, false);
std::string sConcatMessage = sCPID + sBlockHash;
bool bValid = CheckMessageSignature("R","cpid", sConcatMessage, sSignature, sBeaconPublicKey);
if(!bValid)
LogPrintf("VerifyCPIDSignature: invalid signature sSignature=%s, cached key=%s"
,sSignature, sBeaconPublicKey);
return bValid;
}
std::string SignMessage(const std::string& sMsg, CKey& key)
{
std::vector<unsigned char> vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchSig;
if (!key.Sign(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
{
return "Unable to sign message, check private key.";
}
const std::string sig(vchSig.begin(), vchSig.end());
std::string SignedMessage = EncodeBase64(sig);
return SignedMessage;
}
std::string SignMessage(std::string sMsg, std::string sPrivateKey)
{
CKey key;
std::vector<unsigned char> vchPrivKey = ParseHex(sPrivateKey);
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
return SignMessage(sMsg, key);
}
std::string SendMessage(bool bAdd, std::string sType, std::string sPrimaryKey, std::string sValue,
std::string sMasterKey, int64_t MinimumBalance, double dFees, std::string strPublicKey)
{
std::string sAddress = GetBurnAddress();
CBitcoinAddress address(sAddress);
if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Gridcoin address");
int64_t nAmount = AmountFromValue(dFees);
// Wallet comments
CWalletTx wtx;
if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string sMessageType = "<MT>" + sType + "</MT>"; //Project or Smart Contract
std::string sMessageKey = "<MK>" + sPrimaryKey + "</MK>";
std::string sMessageValue = "<MV>" + sValue + "</MV>";
std::string sMessagePublicKey = "<MPK>"+ strPublicKey + "</MPK>";
std::string sMessageAction = bAdd ? "<MA>A</MA>" : "<MA>D</MA>"; //Add or Delete
//Sign Message
std::string sSig = SignMessage(sType+sPrimaryKey+sValue,sMasterKey);
std::string sMessageSignature = "<MS>" + sSig + "</MS>";
wtx.hashBoinc = sMessageType+sMessageKey+sMessageValue+sMessageAction+sMessagePublicKey+sMessageSignature;
std::string strError = pwalletMain->SendMoneyToDestinationWithMinimumBalance(address.Get(), nAmount, MinimumBalance, wtx);
if (!strError.empty()) throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex().c_str();
}
std::string SendContract(std::string sType, std::string sName, std::string sContract)
{
std::string sPass = (sType=="project" || sType=="projectmapping" || sType=="smart_contract") ? GetArgument("masterprojectkey", msMasterMessagePrivateKey) : msMasterMessagePrivateKey;
std::string result = SendMessage(true,sType,sName,sContract,sPass,AmountFromValue(1),.00001,"");
return result;
}
bool SignBlockWithCPID(const std::string& sCPID, const std::string& sBlockHash, std::string& sSignature, std::string& sError, bool bAdvertising=false)
{
// Check if there is a beacon for this user
// If not then return false as GetStoresBeaconPrivateKey grabs from the config
if (!HasActiveBeacon(sCPID) && !bAdvertising)
{
sError = "No active beacon";
return false;
}
// Returns the Signature of the CPID+BlockHash message.
CKey keyBeacon;
if(!GetStoredBeaconPrivateKey(sCPID, keyBeacon))
{
sError = "No beacon key";
return false;
}
std::string sMessage = sCPID + sBlockHash;
sSignature = SignMessage(sMessage,keyBeacon);
// If we failed to sign then return false
if (sSignature == "Unable to sign message, check private key.")
{
sError = sSignature;
sSignature = "";
return false;
}
return true;
}
int64_t AmountFromDouble(double dAmount)
{
if (dAmount <= 0.0 || dAmount > MAX_MONEY) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64_t nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
std::string executeRain(std::string sRecipients)
{
CWalletTx wtx;
wtx.mapValue["comment"] = "Rain";
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64_t> > vecSend;
std::string sRainCommand = ExtractXML(sRecipients,"<RAIN>","</RAIN>");
std::string sRainMessage = MakeSafeMessage(ExtractXML(sRecipients,"<RAINMESSAGE>","</RAINMESSAGE>"));
std::string sRain = "<NARR>Project Rain: " + sRainMessage + "</NARR>";
if (!sRainCommand.empty())
sRecipients = sRainCommand;
wtx.hashBoinc = sRain;
int64_t totalAmount = 0;
double dTotalToSend = 0;
std::vector<std::string> vRecipients = split(sRecipients.c_str(),"<ROW>");
LogPrintf("Creating Rain transaction with %" PRId64 " recipients. ", vRecipients.size());
for (unsigned int i = 0; i < vRecipients.size(); i++)
{
std::string sRow = vRecipients[i];
std::vector<std::string> vReward = split(sRow.c_str(),"<COL>");
if (vReward.size() > 1)
{
std::string sAddress = vReward[0];
std::string sAmount = vReward[1];
if (sAddress.length() > 10 && sAmount.length() > 0)
{
double dAmount = RoundFromString(sAmount,4);
if (dAmount > 0)
{
CBitcoinAddress address(sAddress);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Gridcoin address: ")+sAddress);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+sAddress);
setAddress.insert(address);
dTotalToSend += dAmount;
int64_t nAmount = AmountFromDouble(dAmount);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
}
}
}
EnsureWalletIsUnlocked();
// Check funds
double dBalance = GetTotalBalance();
if (dTotalToSend > dBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64_t nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
LogPrintf("Transaction Created.");
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
LogPrintf("Committing.");
// Rain the recipients
if (!pwalletMain->CommitTransaction(wtx, keyChange))
{
LogPrintf("Commit failed.");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
}
std::string sNarr = "Rain successful: Sent " + wtx.GetHash().GetHex() + ".";
LogPrintf("Success %s",sNarr.c_str());
return sNarr;
}
<|endoftext|> |
<commit_before>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2013-2017 Igor Mironchik
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ARGS__VALUE_UTILS_HPP__INCLUDED
#define ARGS__VALUE_UTILS_HPP__INCLUDED
// Args include.
#include "utils.hpp"
#include "exceptions.hpp"
#include "types.hpp"
// C++ include.
#include <algorithm>
namespace Args {
//
// eatValues
//
//! Eat values in context.
template< typename Container, typename Cmd, typename Ctx >
bool eatValues( Ctx & context, Container & container,
const String & errorDescription, Cmd * cmdLine )
{
if( !context.atEnd() )
{
auto begin = context.begin();
auto last = std::find_if( context.begin(), context.end(),
[ & ] ( const String & v ) -> bool
{
if( details::isArgument( v ) || details::isFlag( v ) )
return true;
else
return( cmdLine->findArgument( v ) != nullptr );
}
);
if( last != begin )
{
begin = context.next();
while( begin != last )
{
container.push_back( *begin );
begin = context.next();
}
if( last != context.end() )
context.putBack();
return true;
}
}
throw BaseException( errorDescription );
}
//
// eatOneValue
//
//! Eat one value.
template< typename Cmd, typename Ctx >
String eatOneValue( Ctx & context,
const String & errorDescription, Cmd * cmdLine )
{
if( !context.atEnd() )
{
auto val = context.next();
if( !details::isArgument( *val ) && !details::isFlag( *val ) )
{
if( !cmdLine->findArgument( *val ) )
return *val;
}
context.putBack();
}
throw BaseException( errorDescription );
}
} /* namespace Args */
#endif // ARGS__VALUE_UTILS_HPP__INCLUDED
<commit_msg>Allow to eat values started with "-", but don't allow to eat correct arguments' names.<commit_after>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2013-2017 Igor Mironchik
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ARGS__VALUE_UTILS_HPP__INCLUDED
#define ARGS__VALUE_UTILS_HPP__INCLUDED
// Args include.
#include "utils.hpp"
#include "exceptions.hpp"
#include "types.hpp"
// C++ include.
#include <algorithm>
namespace Args {
//
// eatValues
//
//! Eat values in context.
template< typename Container, typename Cmd, typename Ctx >
bool eatValues( Ctx & context, Container & container,
const String & errorDescription, Cmd * cmdLine )
{
if( !context.atEnd() )
{
auto begin = context.begin();
auto last = std::find_if( context.begin(), context.end(),
[ & ] ( const String & v ) -> bool
{
return( cmdLine->findArgument( v ) != nullptr );
}
);
if( last != begin )
{
begin = context.next();
while( begin != last )
{
container.push_back( *begin );
begin = context.next();
}
if( last != context.end() )
context.putBack();
return true;
}
}
throw BaseException( errorDescription );
}
//
// eatOneValue
//
//! Eat one value.
template< typename Cmd, typename Ctx >
String eatOneValue( Ctx & context,
const String & errorDescription, Cmd * cmdLine )
{
if( !context.atEnd() )
{
auto val = context.next();
if( !cmdLine->findArgument( *val ) )
return *val;
context.putBack();
}
throw BaseException( errorDescription );
}
} /* namespace Args */
#endif // ARGS__VALUE_UTILS_HPP__INCLUDED
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// 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.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling
// RUN: cat %s | %cling 2>&1 | FileCheck %s
// Test handling and recovery from calling an unresolved symbol.
.rawInput
int foo(); // extern C++
void bar() { foo(); }
.rawInput
extern "C" int functionWithoutDefinition();
int i = 42;
i = functionWithoutDefinition();
// CHECK: ExecutionContext: use of undefined symbol 'functionWithoutDefinition'!
// CHECK: ExecutionContext::executeFunction: symbol 'functionWithoutDefinition' unresolved while linking function
i = foo();
// CHECK: ExecutionContext: use of undefined symbol '{{.*}}foo{{.*}}'!
// CHECK: ExecutionContext::executeFunction: symbol '{{.*}}foo{{.*}}' unresolved while linking function
extern "C" int printf(const char* fmt, ...);
printf("got i=%d\n", i); // CHECK: got i=42
int a = 12// CHECK: (int) 12
foo()
// CHECK: ExecutionContext::executeFunction: symbol '{{.*}}foo{{.*}}' unresolved
functionWithoutDefinition();
// CHECK: ExecutionContext::executeFunction: symbol 'functionWithoutDefinition' unresolved while linking function
bar();
// CHECK: ExecutionContext: use of undefined symbol '{{.*}}foo{{.*}}'!
// CHECK: ExecutionContext::executeFunction: symbol '{{.*}}foo{{.*}}' unresolved while linking function
bar();
// CHECK: ExecutionContext: calling unresolved symbol, see previous error message!
i = 13 //CHECK: (int) 13
.q
<commit_msg>Follow the change ExecutionContext -> IncrementalExecutor.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// 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.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling
// RUN: cat %s | %cling 2>&1 | FileCheck %s
// Test handling and recovery from calling an unresolved symbol.
.rawInput
int foo(); // extern C++
void bar() { foo(); }
.rawInput
extern "C" int functionWithoutDefinition();
int i = 42;
i = functionWithoutDefinition();
// CHECK: IncrementalExecutor: use of undefined symbol 'functionWithoutDefinition'!
// CHECK: IncrementalExecutor::executeFunction: symbol 'functionWithoutDefinition' unresolved while linking function
i = foo();
// CHECK: IncrementalExecutor: use of undefined symbol '{{.*}}foo{{.*}}'!
// CHECK: IncrementalExecutor::executeFunction: symbol '{{.*}}foo{{.*}}' unresolved while linking function
extern "C" int printf(const char* fmt, ...);
printf("got i=%d\n", i); // CHECK: got i=42
int a = 12// CHECK: (int) 12
foo()
// CHECK: IncrementalExecutor::executeFunction: symbol '{{.*}}foo{{.*}}' unresolved
functionWithoutDefinition();
// CHECK: IncrementalExecutor::executeFunction: symbol 'functionWithoutDefinition' unresolved while linking function
bar();
// CHECK: IncrementalExecutor: use of undefined symbol '{{.*}}foo{{.*}}'!
// CHECK: IncrementalExecutor::executeFunction: symbol '{{.*}}foo{{.*}}' unresolved while linking function
bar();
// CHECK: IncrementalExecutor: calling unresolved symbol, see previous error message!
i = 13 //CHECK: (int) 13
.q
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <locale>
#include "commandline_options.hpp"
namespace kp19pp{
commandline_options_type::commandline_options_type() :
ifile_path_(), ofile_path_(), language_(language_cpp), indent_(indent_space4)
{}
namespace{
std::string str_to_upper(const char *str){
std::locale l;
std::string ret;
for(std::size_t i = 0; str[i]; ++i){
ret += std::toupper(str[i], l);
}
return ret;
}
}
bool commandline_options_type::get(int argc, const char **argv){
int state = 0;
for(int index = 1; index < argc; ++index){
if(argv[index][0] == '-'){
std::string str = str_to_upper(argv[index]);
if(
str == "-C++" ||
str == "-CPP"
){
language_ = language_cpp;
continue;
}
if(
str == "-C#" ||
str == "-CS" ||
str == "-CSHARP"
){
language_ = language_csharp;
continue;
}
if(str == "-D"){
language_ = language_d;
continue;
}
if(str == "-JAVA"){
language_ = language_java;
}
if(
str == "-JS" ||
str == "-JAVASCRIPT"
){
language_ = language_javascript;
continue;
}
if(str == "-INDENT=SPACE"){
indent_ = indent_space;
continue;
}
if(str == "-INDENT=SPACE4"){
indent_ = indent_space4;
continue;
}
if(str == "-INDENT=SPACE8"){
indent_ = indent_space8;
continue;
}
if(str == "-INDENT=TAB"){
indent_ = indent_tab;
continue;
}
std::cerr << "unknown options" << argv[index] << "\n";
return false;
}
switch(state){
case 0: ifile_path_ = argv[index]; ++state; break;
case 1: ofile_path_ = argv[index]; ++state; break;
default:
std::cerr << "too many arguments\n";
return false;
}
}
if(state < 2){
std::cout << "kp19pp usage: kp19pp [ -c++ | -cs | -d | -java | -javascript | -indent=space | -indent=tab ] ifile_name ofile_name\n";
return false;
}
return true;
}
const std::string &commandline_options_type::ifile_path() const{
return ifile_path_;
}
std::string commandline_options_type::ifile_name() const{
std::string ret;
for(std::size_t i = 0, length = ifile_path_.length(); i < length; ++i){
char c = ifile_path_[length - i - 1];
if(c == '/' || c == '\\'){ break; }
ret += c;
}
return ret;
}
const std::string &commandline_options_type::ofile_path() const{
return ofile_path_;
}
commandline_options_type::language_enum commandline_options_type::language() const{
return language_;
}
commandline_options_type::indent_enum commandline_options_type::indent() const{
return indent_;
}
}
<commit_msg>2012/04/09<commit_after>#include <iostream>
#include <algorithm>
#include <locale>
#include <cstdlib>
#include "commandline_options.hpp"
namespace kp19pp{
commandline_options_type::commandline_options_type() :
ifile_path_(), ofile_path_(), language_(language_cpp), indent_(indent_space4)
{}
namespace{
std::string str_to_upper(const char *str){
std::locale l;
std::string ret;
for(std::size_t i = 0; str[i]; ++i){
ret += std::toupper(str[i], l);
}
return ret;
}
}
bool commandline_options_type::get(int argc, const char **argv){
int state = 0;
for(int index = 1; index < argc; ++index){
if(argv[index][0] == '-'){
std::string str = str_to_upper(argv[index]);
if(
str == "-C++" ||
str == "-CPP"
){
language_ = language_cpp;
continue;
}
if(
str == "-C#" ||
str == "-CS" ||
str == "-CSHARP"
){
language_ = language_csharp;
continue;
}
if(str == "-D"){
language_ = language_d;
continue;
}
if(str == "-JAVA"){
language_ = language_java;
}
if(
str == "-JS" ||
str == "-JAVASCRIPT"
){
language_ = language_javascript;
continue;
}
if(str == "-INDENT=SPACE"){
indent_ = indent_space;
continue;
}
if(str == "-INDENT=SPACE4"){
indent_ = indent_space4;
continue;
}
if(str == "-INDENT=SPACE8"){
indent_ = indent_space8;
continue;
}
if(str == "-INDENT=TAB"){
indent_ = indent_tab;
continue;
}
std::cerr << "unknown options" << argv[index] << "\n";
return false;
}
switch(state){
case 0: ifile_path_ = argv[index]; ++state; break;
case 1: ofile_path_ = argv[index]; ++state; break;
default:
std::cerr << "too many arguments\n";
return false;
}
}
if(state < 2){
std::cout << "kp19pp usage: kp19pp [ -c++ | -cs | -d | -java | -javascript | -indent=space | -indent=tab ] ifile_name ofile_name\n";
return false;
}
return true;
}
const std::string &commandline_options_type::ifile_path() const{
return ifile_path_;
}
std::string commandline_options_type::ifile_name() const{
std::string ret;
for(std::size_t i = 0, length = ifile_path_.length(); i < length; ++i){
char c = ifile_path_[length - i - 1];
if(c == '/' || c == '\\'){ break; }
ret += c;
}
std::reverse(ret.begin(), ret.end());
return ret;
}
const std::string &commandline_options_type::ofile_path() const{
return ofile_path_;
}
commandline_options_type::language_enum commandline_options_type::language() const{
return language_;
}
commandline_options_type::indent_enum commandline_options_type::indent() const{
return indent_;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "CodeGen_Posix.h"
#include "CodeGen_Internal.h"
#include "LLVM_Headers.h"
#include "IR.h"
#include "IROperator.h"
#include "Debug.h"
#include "IRPrinter.h"
#include "Simplify.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using std::map;
using std::pair;
using std::make_pair;
using namespace llvm;
CodeGen_Posix::CodeGen_Posix(Target t) :
CodeGen_LLVM(t) {
}
Value *CodeGen_Posix::codegen_allocation_size(const std::string &name, Type type, const std::vector<Expr> &extents) {
// Compute size from list of extents checking for 32-bit signed overflow.
// Math is done using 64-bit intergers as overflow checked 32-bit mutliply
// does not work with NaCl at the moment.
Expr no_overflow = const_true(1);
Expr total_size = Expr((int64_t)(type.lanes() * type.bytes()));
Expr max_size = cast<int64_t>(0x7fffffff);
for (size_t i = 0; i < extents.size(); i++) {
total_size *= extents[i];
no_overflow = no_overflow && (total_size <= max_size);
}
// For constant-sized allocations this check should simplify away.
no_overflow = simplify(no_overflow);
if (!is_one(no_overflow)) {
create_assertion(codegen(no_overflow),
Call::make(Int(32), "halide_error_buffer_allocation_too_large",
{name, total_size, max_size}, Call::Extern));
}
total_size = simplify(cast<int32_t>(total_size));
return codegen(total_size);
}
CodeGen_Posix::Allocation CodeGen_Posix::create_allocation(const std::string &name, Type type,
const std::vector<Expr> &extents, Expr condition,
Expr new_expr, std::string free_function) {
Value *llvm_size = NULL;
int64_t stack_bytes = 0;
int32_t constant_bytes = 0;
if (constant_allocation_size(extents, name, constant_bytes)) {
constant_bytes *= type.bytes();
stack_bytes = constant_bytes;
if (stack_bytes > ((int64_t(1) << 31) - 1)) {
user_error << "Total size for allocation " << name << " is constant but exceeds 2^31 - 1.";
} else if (stack_bytes > 1024 * 16) {
stack_bytes = 0;
llvm_size = codegen(Expr(constant_bytes));
}
} else {
llvm_size = codegen_allocation_size(name, type, extents);
}
// Only allocate memory if the condition is true, otherwise 0.
if (llvm_size != NULL) {
// We potentially load one scalar value past the end of the
// buffer, so pad the allocation with an extra instance of the
// scalar type. If the allocation is on the stack, we can just
// read one past the top of the stack, so we only need this
// for heap allocations.
llvm_size = builder->CreateAdd(llvm_size,
ConstantInt::get(llvm_size->getType(), type.bytes()));
Value *llvm_condition = codegen(condition);
llvm_size = builder->CreateSelect(llvm_condition,
llvm_size,
ConstantInt::get(llvm_size->getType(), 0));
}
Allocation allocation;
allocation.constant_bytes = constant_bytes;
allocation.stack_bytes = new_expr.defined() ? 0 : stack_bytes;
allocation.type = type;
allocation.ptr = NULL;
allocation.destructor = NULL;
allocation.destructor_function = NULL;
if (!new_expr.defined() && stack_bytes != 0) {
// Try to find a free stack allocation we can use.
vector<Allocation>::iterator free = free_stack_allocs.end();
for (free = free_stack_allocs.begin(); free != free_stack_allocs.end(); ++free) {
AllocaInst *alloca_inst = dyn_cast<AllocaInst>(free->ptr);
llvm::Function *allocated_in = alloca_inst ? alloca_inst->getParent()->getParent() : NULL;
llvm::Function *current_func = builder->GetInsertBlock()->getParent();
if (allocated_in == current_func &&
free->type == type &&
free->stack_bytes >= stack_bytes) {
break;
}
}
if (free != free_stack_allocs.end()) {
debug(4) << "Reusing freed stack allocation of " << free->stack_bytes
<< " bytes for allocation " << name
<< " of " << stack_bytes << " bytes.\n";
// Use a free alloc we found.
allocation.ptr = free->ptr;
allocation.stack_bytes = free->stack_bytes;
// This allocation isn't free anymore.
free_stack_allocs.erase(free);
} else {
debug(4) << "Allocating " << stack_bytes << " bytes on the stack for " << name << "\n";
// We used to do the alloca locally and save and restore the
// stack pointer, but this makes llvm generate streams of
// spill/reloads.
int64_t stack_size = (stack_bytes + type.bytes() - 1) / type.bytes();
allocation.ptr = create_alloca_at_entry(llvm_type_of(type), stack_size, false, name);
allocation.stack_bytes = stack_bytes;
}
} else {
if (new_expr.defined()) {
allocation.ptr = codegen(new_expr);
} else {
// call malloc
llvm::Function *malloc_fn = module->getFunction("halide_malloc");
internal_assert(malloc_fn) << "Could not find halide_malloc in module\n";
malloc_fn->setDoesNotAlias(0);
llvm::Function::arg_iterator arg_iter = malloc_fn->arg_begin();
++arg_iter; // skip the user context *
llvm_size = builder->CreateIntCast(llvm_size, arg_iter->getType(), false);
debug(4) << "Creating call to halide_malloc for allocation " << name
<< " of size " << type.bytes();
for (Expr e : extents) {
debug(4) << " x " << e;
}
debug(4) << "\n";
Value *args[2] = { get_user_context(), llvm_size };
CallInst *call = builder->CreateCall(malloc_fn, args);
allocation.ptr = call;
}
// Assert that the allocation worked.
Value *check = builder->CreateIsNotNull(allocation.ptr);
if (!new_expr.defined()) { // Zero sized allocation if allowed for custom new...
Value *zero_size = builder->CreateIsNull(llvm_size);
check = builder->CreateOr(check, zero_size);
}
create_assertion(check, Call::make(Int(32), "halide_error_out_of_memory",
std::vector<Expr>(), Call::Extern));
// Register a destructor for this allocation.
if (free_function.empty()) {
free_function = "halide_free";
}
llvm::Function *free_fn = module->getFunction(free_function);
internal_assert(free_fn) << "Could not find " << free_function << " in module.\n";
allocation.destructor = register_destructor(free_fn, allocation.ptr, OnError);
allocation.destructor_function = free_fn;
}
// Push the allocation base pointer onto the symbol table
debug(3) << "Pushing allocation called " << name << ".host onto the symbol table\n";
allocations.push(name, allocation);
return allocation;
}
void CodeGen_Posix::visit(const Allocate *alloc) {
if (sym_exists(alloc->name + ".host")) {
user_error << "Can't have two different buffers with the same name: "
<< alloc->name << "\n";
}
Allocation allocation = create_allocation(alloc->name, alloc->type,
alloc->extents, alloc->condition,
alloc->new_expr, alloc->free_function);
sym_push(alloc->name + ".host", allocation.ptr);
codegen(alloc->body);
// Should have been freed
internal_assert(!sym_exists(alloc->name + ".host"));
internal_assert(!allocations.contains(alloc->name));
}
void CodeGen_Posix::visit(const Free *stmt) {
Allocation alloc = allocations.get(stmt->name);
if (alloc.stack_bytes) {
// Remember this allocation so it can be re-used by a later allocation.
free_stack_allocs.push_back(alloc);
} else {
internal_assert(alloc.destructor);
trigger_destructor(alloc.destructor_function, alloc.destructor);
}
allocations.pop(stmt->name);
sym_pop(stmt->name + ".host");
}
}}
<commit_msg>Fix stack-stomping on 32-bit platforms<commit_after>#include <iostream>
#include "CodeGen_Posix.h"
#include "CodeGen_Internal.h"
#include "LLVM_Headers.h"
#include "IR.h"
#include "IROperator.h"
#include "Debug.h"
#include "IRPrinter.h"
#include "Simplify.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using std::map;
using std::pair;
using std::make_pair;
using namespace llvm;
CodeGen_Posix::CodeGen_Posix(Target t) :
CodeGen_LLVM(t) {
}
Value *CodeGen_Posix::codegen_allocation_size(const std::string &name, Type type, const std::vector<Expr> &extents) {
// Compute size from list of extents checking for 32-bit signed overflow.
// Math is done using 64-bit intergers as overflow checked 32-bit mutliply
// does not work with NaCl at the moment.
Expr no_overflow = const_true(1);
Expr total_size = Expr((int64_t)(type.lanes() * type.bytes()));
Expr max_size = cast<int64_t>(0x7fffffff);
for (size_t i = 0; i < extents.size(); i++) {
total_size *= extents[i];
no_overflow = no_overflow && (total_size <= max_size);
}
// For constant-sized allocations this check should simplify away.
no_overflow = simplify(no_overflow);
if (!is_one(no_overflow)) {
create_assertion(codegen(no_overflow),
Call::make(Int(32), "halide_error_buffer_allocation_too_large",
{name, total_size, max_size}, Call::Extern));
}
total_size = simplify(cast<int32_t>(total_size));
return codegen(total_size);
}
CodeGen_Posix::Allocation CodeGen_Posix::create_allocation(const std::string &name, Type type,
const std::vector<Expr> &extents, Expr condition,
Expr new_expr, std::string free_function) {
Value *llvm_size = NULL;
int64_t stack_bytes = 0;
int32_t constant_bytes = 0;
if (constant_allocation_size(extents, name, constant_bytes)) {
constant_bytes *= type.bytes();
stack_bytes = constant_bytes;
if (stack_bytes > ((int64_t(1) << 31) - 1)) {
user_error << "Total size for allocation " << name << " is constant but exceeds 2^31 - 1.";
} else if (stack_bytes > 1024 * 16) {
stack_bytes = 0;
llvm_size = codegen(Expr(constant_bytes));
}
} else {
llvm_size = codegen_allocation_size(name, type, extents);
}
// Only allocate memory if the condition is true, otherwise 0.
if (llvm_size != NULL) {
// We potentially load one scalar value past the end of the
// buffer, so pad the allocation with an extra instance of the
// scalar type. If the allocation is on the stack, we can just
// read one past the top of the stack, so we only need this
// for heap allocations.
llvm_size = builder->CreateAdd(llvm_size,
ConstantInt::get(llvm_size->getType(), type.bytes()));
Value *llvm_condition = codegen(condition);
llvm_size = builder->CreateSelect(llvm_condition,
llvm_size,
ConstantInt::get(llvm_size->getType(), 0));
}
Allocation allocation;
allocation.constant_bytes = constant_bytes;
allocation.stack_bytes = new_expr.defined() ? 0 : stack_bytes;
allocation.type = type;
allocation.ptr = NULL;
allocation.destructor = NULL;
allocation.destructor_function = NULL;
if (!new_expr.defined() && stack_bytes != 0) {
// Try to find a free stack allocation we can use.
vector<Allocation>::iterator free = free_stack_allocs.end();
for (free = free_stack_allocs.begin(); free != free_stack_allocs.end(); ++free) {
AllocaInst *alloca_inst = dyn_cast<AllocaInst>(free->ptr);
llvm::Function *allocated_in = alloca_inst ? alloca_inst->getParent()->getParent() : NULL;
llvm::Function *current_func = builder->GetInsertBlock()->getParent();
if (allocated_in == current_func &&
free->type == type &&
free->stack_bytes >= stack_bytes) {
break;
}
}
if (free != free_stack_allocs.end()) {
debug(4) << "Reusing freed stack allocation of " << free->stack_bytes
<< " bytes for allocation " << name
<< " of " << stack_bytes << " bytes.\n";
// Use a free alloc we found.
allocation.ptr = free->ptr;
allocation.stack_bytes = free->stack_bytes;
// This allocation isn't free anymore.
free_stack_allocs.erase(free);
} else {
debug(4) << "Allocating " << stack_bytes << " bytes on the stack for " << name << "\n";
// We used to do the alloca locally and save and restore the
// stack pointer, but this makes llvm generate streams of
// spill/reloads.
int64_t stack_size = (stack_bytes + type.bytes() - 1) / type.bytes();
// Handles are stored as uint64s
llvm::Type *t = llvm_type_of(type.is_handle() ? UInt(64, type.lanes()) : type);
allocation.ptr = create_alloca_at_entry(t, stack_size, false, name);
allocation.stack_bytes = stack_bytes;
}
} else {
if (new_expr.defined()) {
allocation.ptr = codegen(new_expr);
} else {
// call malloc
llvm::Function *malloc_fn = module->getFunction("halide_malloc");
internal_assert(malloc_fn) << "Could not find halide_malloc in module\n";
malloc_fn->setDoesNotAlias(0);
llvm::Function::arg_iterator arg_iter = malloc_fn->arg_begin();
++arg_iter; // skip the user context *
llvm_size = builder->CreateIntCast(llvm_size, arg_iter->getType(), false);
debug(4) << "Creating call to halide_malloc for allocation " << name
<< " of size " << type.bytes();
for (Expr e : extents) {
debug(4) << " x " << e;
}
debug(4) << "\n";
Value *args[2] = { get_user_context(), llvm_size };
CallInst *call = builder->CreateCall(malloc_fn, args);
allocation.ptr = call;
}
// Assert that the allocation worked.
Value *check = builder->CreateIsNotNull(allocation.ptr);
if (!new_expr.defined()) { // Zero sized allocation if allowed for custom new...
Value *zero_size = builder->CreateIsNull(llvm_size);
check = builder->CreateOr(check, zero_size);
}
create_assertion(check, Call::make(Int(32), "halide_error_out_of_memory",
std::vector<Expr>(), Call::Extern));
// Register a destructor for this allocation.
if (free_function.empty()) {
free_function = "halide_free";
}
llvm::Function *free_fn = module->getFunction(free_function);
internal_assert(free_fn) << "Could not find " << free_function << " in module.\n";
allocation.destructor = register_destructor(free_fn, allocation.ptr, OnError);
allocation.destructor_function = free_fn;
}
// Push the allocation base pointer onto the symbol table
debug(3) << "Pushing allocation called " << name << ".host onto the symbol table\n";
allocations.push(name, allocation);
return allocation;
}
void CodeGen_Posix::visit(const Allocate *alloc) {
if (sym_exists(alloc->name + ".host")) {
user_error << "Can't have two different buffers with the same name: "
<< alloc->name << "\n";
}
Allocation allocation = create_allocation(alloc->name, alloc->type,
alloc->extents, alloc->condition,
alloc->new_expr, alloc->free_function);
sym_push(alloc->name + ".host", allocation.ptr);
codegen(alloc->body);
// Should have been freed
internal_assert(!sym_exists(alloc->name + ".host"));
internal_assert(!allocations.contains(alloc->name));
}
void CodeGen_Posix::visit(const Free *stmt) {
Allocation alloc = allocations.get(stmt->name);
if (alloc.stack_bytes) {
// Remember this allocation so it can be re-used by a later allocation.
free_stack_allocs.push_back(alloc);
} else {
internal_assert(alloc.destructor);
trigger_destructor(alloc.destructor_function, alloc.destructor);
}
allocations.pop(stmt->name);
sym_pop(stmt->name + ".host");
}
}}
<|endoftext|> |
<commit_before>/// \file ROOT/TDisplayItem.h
/// \ingroup Base ROOT7
/// \author Sergey Linev
/// \date 2017-05-31
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TPadDisplayItem
#define ROOT7_TPadDisplayItem
#include <ROOT/TDisplayItem.hxx>
#include <ROOT/TFrame.hxx>
#include <ROOT/TPad.hxx>
namespace ROOT {
namespace Experimental {
// list of snapshot for primitives in pad
using TDisplayItemsVector = std::vector<std::unique_ptr<TDisplayItem>>;
/// Display item for the pad
/// Includes different graphical properties of the pad itself plus
/// list of created items for all primitives
class TPadDisplayItem : public TDisplayItem {
protected:
const TFrame *fFrame{nullptr}; ///< temporary pointer on frame object
const TPadDrawingOpts *fDrawOpts{nullptr}; ///< temporary pointer on pad drawing options
const TPadExtent *fSize{nullptr}; ///< temporary pointer on pad size attributes
TDisplayItemsVector fPrimitives; ///< display items for all primitives in the pad
public:
TPadDisplayItem() = default;
virtual ~TPadDisplayItem() {}
void SetFrame(const TFrame *f) { fFrame = f; }
void SetDrawOpts(const TPadDrawingOpts *opts) { fDrawOpts = opts; }
void SetSize(const TPadExtent *sz) { fSize = sz; }
TDisplayItemsVector &GetPrimitives() { return fPrimitives; }
void Add(std::unique_ptr<TDisplayItem> &&item) { fPrimitives.push_back(std::move(item)); }
void Clear()
{
fPrimitives.clear();
fFrame = nullptr;
fDrawOpts = nullptr;
fSize = nullptr;
}
};
} // Experimental
} // ROOT
#endif
<commit_msg>Make using directive a class member.<commit_after>/// \file ROOT/TDisplayItem.h
/// \ingroup Base ROOT7
/// \author Sergey Linev
/// \date 2017-05-31
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TPadDisplayItem
#define ROOT7_TPadDisplayItem
#include <ROOT/TDisplayItem.hxx>
#include <ROOT/TFrame.hxx>
#include <ROOT/TPad.hxx>
namespace ROOT {
namespace Experimental {
/// Display item for the pad
/// Includes different graphical properties of the pad itself plus
/// list of created items for all primitives
class TPadDisplayItem : public TDisplayItem {
public:
// list of snapshot for primitives in pad
using PadPrimitives_t = std::vector<std::unique_ptr<TDisplayItem>>;
protected:
const TFrame *fFrame{nullptr}; ///< temporary pointer on frame object
const TPadDrawingOpts *fDrawOpts{nullptr}; ///< temporary pointer on pad drawing options
const TPadExtent *fSize{nullptr}; ///< temporary pointer on pad size attributes
PadPrimitives_t fPrimitives; ///< display items for all primitives in the pad
public:
TPadDisplayItem() = default;
virtual ~TPadDisplayItem() {}
void SetFrame(const TFrame *f) { fFrame = f; }
void SetDrawOpts(const TPadDrawingOpts *opts) { fDrawOpts = opts; }
void SetSize(const TPadExtent *sz) { fSize = sz; }
PadPrimitives_t &GetPrimitives() { return fPrimitives; }
void Add(std::unique_ptr<TDisplayItem> &&item) { fPrimitives.push_back(std::move(item)); }
void Clear()
{
fPrimitives.clear();
fFrame = nullptr;
fDrawOpts = nullptr;
fSize = nullptr;
}
};
} // Experimental
} // ROOT
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"
#include <stdlib.h>
#include <set>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "cc/base/switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/result_codes.h"
#include "extensions/browser/extension_system.h"
#include "net/base/filename_util.h"
#include "ui/gl/gl_switches.h"
#include "xwalk/application/browser/application.h"
#include "xwalk/application/browser/application_system.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#if !defined(DISABLE_NACL)
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/browser/nacl_process_host.h"
#include "xwalk/runtime/browser/nacl_host/nacl_browser_delegate_impl.h"
#endif
#if defined(USE_AURA) && defined(USE_X11)
#include "ui/base/ime/input_method_initializer.h"
#include "ui/events/x/touch_factory_x11.h"
#endif
namespace {
// FIXME: Compare with method in startup_browser_creator.cc.
GURL GetURLFromCommandLine(const CommandLine& command_line) {
const CommandLine::StringVector& args = command_line.GetArgs();
if (args.empty())
return GURL();
GURL url(args[0]);
if (url.is_valid() && url.has_scheme())
return url;
base::FilePath path(args[0]);
if (!path.IsAbsolute())
path = MakeAbsoluteFilePath(path);
return net::FilePathToFileURL(path);
}
} // namespace
namespace xswitches {
// Redefine settings not exposed by content module.
const char kEnableOverlayScrollbars[] = "enable-overlay-scrollbars";
}
namespace xwalk {
XWalkBrowserMainParts::XWalkBrowserMainParts(
const content::MainFunctionParams& parameters)
: xwalk_runner_(XWalkRunner::GetInstance()),
startup_url_(url::kAboutBlankURL),
parameters_(parameters),
run_default_message_loop_(true) {
#if defined(OS_LINUX)
// FIXME: We disable the setuid sandbox on Linux because we don't ship
// the setuid binary. It is important to remember that the seccomp-bpf
// sandbox is still fully operational if supported by the kernel. See
// issue #496.
//
// switches::kDisableSetuidSandbox is not being used here because it
// doesn't have the CONTENT_EXPORT macro despite the fact it is exposed by
// content_switches.h.
CommandLine::ForCurrentProcess()->AppendSwitch("disable-setuid-sandbox");
#endif
}
XWalkBrowserMainParts::~XWalkBrowserMainParts() {
}
void XWalkBrowserMainParts::PreMainMessageLoopStart() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kEnableViewport);
command_line->AppendSwitch(switches::kEnableViewportMeta);
command_line->AppendSwitch(xswitches::kEnableOverlayScrollbars);
// Enable multithreaded GPU compositing of web content.
// This also enables pinch on Tizen.
command_line->AppendSwitch(switches::kEnableThreadedCompositing);
// FIXME: Add comment why this is needed on Android and Tizen.
command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
// Enable SIMD.JS API by default.
/*
std::string js_flags("--simd_object");
if (command_line->HasSwitch(switches::kJavaScriptFlags)) {
js_flags += " ";
js_flags +=
command_line->GetSwitchValueASCII(switches::kJavaScriptFlags);
}
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, js_flags);
*/
startup_url_ = GetURLFromCommandLine(*command_line);
}
void XWalkBrowserMainParts::PostMainMessageLoopStart() {
}
void XWalkBrowserMainParts::PreEarlyInitialization() {
#if defined(USE_AURA) && defined(USE_X11)
ui::InitializeInputMethodForTesting();
#endif
}
int XWalkBrowserMainParts::PreCreateThreads() {
return content::RESULT_CODE_NORMAL_EXIT;
}
void XWalkBrowserMainParts::RegisterExternalExtensions() {
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
#if defined(OS_TIZEN)
std::string value = cmd_line->GetSwitchValueASCII(
switches::kXWalkExternalExtensionsPath);
#if defined(ARCH_CPU_64_BITS)
const char tec_path[] = "/usr/lib64/tizen-extensions-crosswalk";
#else
const char tec_path[] = "/usr/lib/tizen-extensions-crosswalk";
#endif
if (value.empty())
cmd_line->AppendSwitchASCII(switches::kXWalkExternalExtensionsPath,
tec_path);
else if (value != tec_path)
VLOG(0) << "Loading Tizen extensions from " << value << " rather than " <<
tec_path;
cmd_line->AppendSwitch(
switches::kXWalkAllowExternalExtensionsForRemoteSources);
#else
if (!cmd_line->HasSwitch(switches::kXWalkExternalExtensionsPath))
return;
#endif
if (!cmd_line->HasSwitch(
switches::kXWalkAllowExternalExtensionsForRemoteSources) &&
(!startup_url_.is_empty() && !startup_url_.SchemeIsFile())) {
VLOG(0) << "Unsupported scheme for external extensions: " <<
startup_url_.scheme();
return;
}
base::FilePath extensions_dir =
cmd_line->GetSwitchValuePath(switches::kXWalkExternalExtensionsPath);
if (!base::DirectoryExists(extensions_dir)) {
LOG(WARNING) << "Ignoring non-existent extension directory: "
<< extensions_dir.AsUTF8Unsafe();
return;
}
extension_service_->RegisterExternalExtensionsForPath(extensions_dir);
}
void XWalkBrowserMainParts::PreMainMessageLoopRun() {
xwalk_runner_->PreMainMessageLoopRun();
extension_service_ = xwalk_runner_->extension_service();
if (extension_service_)
RegisterExternalExtensions();
#if !defined(DISABLE_NACL)
NaClBrowserDelegateImpl* delegate = new NaClBrowserDelegateImpl();
nacl::NaClBrowser::SetDelegate(delegate);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(nacl::NaClProcessHost::EarlyStartup));
#endif
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int port;
base::StringToInt(port_str, &port);
xwalk_runner_->EnableRemoteDebugging(port);
}
NativeAppWindow::Initialize();
if (command_line->HasSwitch(switches::kListFeaturesFlags)) {
XWalkRuntimeFeatures::GetInstance()->DumpFeaturesFlags();
run_default_message_loop_ = false;
return;
}
#if !defined(SHARED_PROCESS_MODE)
application::ApplicationSystem* app_system = xwalk_runner_->app_system();
app_system->LaunchFromCommandLine(*command_line, startup_url_,
run_default_message_loop_);
// If the |ui_task| is specified in main function parameter, it indicates
// that we will run this UI task instead of running the the default main
// message loop. See |content::BrowserTestBase::SetUp| for |ui_task| usage
// case.
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
#endif
}
bool XWalkBrowserMainParts::MainMessageLoopRun(int* result_code) {
return !run_default_message_loop_;
}
void XWalkBrowserMainParts::PostMainMessageLoopRun() {
xwalk_runner_->PostMainMessageLoopRun();
}
void XWalkBrowserMainParts::CreateInternalExtensionsForUIThread(
content::RenderProcessHost* host,
extensions::XWalkExtensionVector* extensions) {
}
void XWalkBrowserMainParts::CreateInternalExtensionsForExtensionThread(
content::RenderProcessHost* host,
extensions::XWalkExtensionVector* extensions) {
}
} // namespace xwalk
<commit_msg>Reenable --simd-object after M38 rebasing.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"
#include <stdlib.h>
#include <set>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "cc/base/switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/result_codes.h"
#include "extensions/browser/extension_system.h"
#include "net/base/filename_util.h"
#include "ui/gl/gl_switches.h"
#include "xwalk/application/browser/application.h"
#include "xwalk/application/browser/application_system.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#if !defined(DISABLE_NACL)
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/browser/nacl_process_host.h"
#include "xwalk/runtime/browser/nacl_host/nacl_browser_delegate_impl.h"
#endif
#if defined(USE_AURA) && defined(USE_X11)
#include "ui/base/ime/input_method_initializer.h"
#include "ui/events/x/touch_factory_x11.h"
#endif
namespace {
// FIXME: Compare with method in startup_browser_creator.cc.
GURL GetURLFromCommandLine(const CommandLine& command_line) {
const CommandLine::StringVector& args = command_line.GetArgs();
if (args.empty())
return GURL();
GURL url(args[0]);
if (url.is_valid() && url.has_scheme())
return url;
base::FilePath path(args[0]);
if (!path.IsAbsolute())
path = MakeAbsoluteFilePath(path);
return net::FilePathToFileURL(path);
}
} // namespace
namespace xswitches {
// Redefine settings not exposed by content module.
const char kEnableOverlayScrollbars[] = "enable-overlay-scrollbars";
}
namespace xwalk {
XWalkBrowserMainParts::XWalkBrowserMainParts(
const content::MainFunctionParams& parameters)
: xwalk_runner_(XWalkRunner::GetInstance()),
startup_url_(url::kAboutBlankURL),
parameters_(parameters),
run_default_message_loop_(true) {
#if defined(OS_LINUX)
// FIXME: We disable the setuid sandbox on Linux because we don't ship
// the setuid binary. It is important to remember that the seccomp-bpf
// sandbox is still fully operational if supported by the kernel. See
// issue #496.
//
// switches::kDisableSetuidSandbox is not being used here because it
// doesn't have the CONTENT_EXPORT macro despite the fact it is exposed by
// content_switches.h.
CommandLine::ForCurrentProcess()->AppendSwitch("disable-setuid-sandbox");
#endif
}
XWalkBrowserMainParts::~XWalkBrowserMainParts() {
}
void XWalkBrowserMainParts::PreMainMessageLoopStart() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kEnableViewport);
command_line->AppendSwitch(switches::kEnableViewportMeta);
command_line->AppendSwitch(xswitches::kEnableOverlayScrollbars);
// Enable multithreaded GPU compositing of web content.
// This also enables pinch on Tizen.
command_line->AppendSwitch(switches::kEnableThreadedCompositing);
// FIXME: Add comment why this is needed on Android and Tizen.
command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
// Enable SIMD.JS API by default.
std::string js_flags("--simd_object");
if (command_line->HasSwitch(switches::kJavaScriptFlags)) {
js_flags += " ";
js_flags +=
command_line->GetSwitchValueASCII(switches::kJavaScriptFlags);
}
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, js_flags);
startup_url_ = GetURLFromCommandLine(*command_line);
}
void XWalkBrowserMainParts::PostMainMessageLoopStart() {
}
void XWalkBrowserMainParts::PreEarlyInitialization() {
#if defined(USE_AURA) && defined(USE_X11)
ui::InitializeInputMethodForTesting();
#endif
}
int XWalkBrowserMainParts::PreCreateThreads() {
return content::RESULT_CODE_NORMAL_EXIT;
}
void XWalkBrowserMainParts::RegisterExternalExtensions() {
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
#if defined(OS_TIZEN)
std::string value = cmd_line->GetSwitchValueASCII(
switches::kXWalkExternalExtensionsPath);
#if defined(ARCH_CPU_64_BITS)
const char tec_path[] = "/usr/lib64/tizen-extensions-crosswalk";
#else
const char tec_path[] = "/usr/lib/tizen-extensions-crosswalk";
#endif
if (value.empty())
cmd_line->AppendSwitchASCII(switches::kXWalkExternalExtensionsPath,
tec_path);
else if (value != tec_path)
VLOG(0) << "Loading Tizen extensions from " << value << " rather than " <<
tec_path;
cmd_line->AppendSwitch(
switches::kXWalkAllowExternalExtensionsForRemoteSources);
#else
if (!cmd_line->HasSwitch(switches::kXWalkExternalExtensionsPath))
return;
#endif
if (!cmd_line->HasSwitch(
switches::kXWalkAllowExternalExtensionsForRemoteSources) &&
(!startup_url_.is_empty() && !startup_url_.SchemeIsFile())) {
VLOG(0) << "Unsupported scheme for external extensions: " <<
startup_url_.scheme();
return;
}
base::FilePath extensions_dir =
cmd_line->GetSwitchValuePath(switches::kXWalkExternalExtensionsPath);
if (!base::DirectoryExists(extensions_dir)) {
LOG(WARNING) << "Ignoring non-existent extension directory: "
<< extensions_dir.AsUTF8Unsafe();
return;
}
extension_service_->RegisterExternalExtensionsForPath(extensions_dir);
}
void XWalkBrowserMainParts::PreMainMessageLoopRun() {
xwalk_runner_->PreMainMessageLoopRun();
extension_service_ = xwalk_runner_->extension_service();
if (extension_service_)
RegisterExternalExtensions();
#if !defined(DISABLE_NACL)
NaClBrowserDelegateImpl* delegate = new NaClBrowserDelegateImpl();
nacl::NaClBrowser::SetDelegate(delegate);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(nacl::NaClProcessHost::EarlyStartup));
#endif
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int port;
base::StringToInt(port_str, &port);
xwalk_runner_->EnableRemoteDebugging(port);
}
NativeAppWindow::Initialize();
if (command_line->HasSwitch(switches::kListFeaturesFlags)) {
XWalkRuntimeFeatures::GetInstance()->DumpFeaturesFlags();
run_default_message_loop_ = false;
return;
}
#if !defined(SHARED_PROCESS_MODE)
application::ApplicationSystem* app_system = xwalk_runner_->app_system();
app_system->LaunchFromCommandLine(*command_line, startup_url_,
run_default_message_loop_);
// If the |ui_task| is specified in main function parameter, it indicates
// that we will run this UI task instead of running the the default main
// message loop. See |content::BrowserTestBase::SetUp| for |ui_task| usage
// case.
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
#endif
}
bool XWalkBrowserMainParts::MainMessageLoopRun(int* result_code) {
return !run_default_message_loop_;
}
void XWalkBrowserMainParts::PostMainMessageLoopRun() {
xwalk_runner_->PostMainMessageLoopRun();
}
void XWalkBrowserMainParts::CreateInternalExtensionsForUIThread(
content::RenderProcessHost* host,
extensions::XWalkExtensionVector* extensions) {
}
void XWalkBrowserMainParts::CreateInternalExtensionsForExtensionThread(
content::RenderProcessHost* host,
extensions::XWalkExtensionVector* extensions) {
}
} // namespace xwalk
<|endoftext|> |
<commit_before>// RUN: %libomp-cxx-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
#include <iostream>
#include <thread>
#if !defined(__NetBSD__)
#include <alloca.h>
#else
#include <cstdlib>
#endif
#include "callback.h"
#include "omp.h"
int condition = 0;
void f() {
// Call OpenMP API function to force initialization of OMPT.
// (omp_get_thread_num() does not work because it just returns 0 if the
// runtime isn't initialized yet...)
omp_get_num_threads();
// Call alloca() to force availability of frame pointer
void *p = alloca(0);
OMPT_SIGNAL(condition);
// Wait for both initial threads to arrive that will eventually become the
// master threads in the following parallel region.
OMPT_WAIT(condition, 2);
#pragma omp parallel num_threads(2)
{
// Wait for all threads to arrive so that no worker thread can be reused...
OMPT_SIGNAL(condition);
OMPT_WAIT(condition, 6);
}
}
int main() {
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_schedule'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_begin'
// CHECK: 0: NULL_POINTER=[[NULL:.*$]]
// first master thread
// CHECK: {{^}}[[MASTER_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_1]]
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_1:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1:[0-9]+]], requested_team_size=2
// CHECK-SAME: codeptr_ra=0x{{[0-f]+}}, invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1]], task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_1]]
// second master thread
// CHECK: {{^}}[[MASTER_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_2]]
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_2:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2:[0-9]+]]
// CHECK-SAME: requested_team_size=2, codeptr_ra=0x{{[0-f]+}}
// CHECK-SAME: invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2]], task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_2]]
// first worker thread
// CHECK: {{^}}[[THREAD_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_1]]
// CHECK: {{^}}[[THREAD_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_1]]
// second worker thread
// CHECK: {{^}}[[THREAD_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_2]]
// CHECK: {{^}}[[THREAD_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_2]]
<commit_msg>Fix interoperability test compilation on FreeBSD<commit_after>// RUN: %libomp-cxx-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
#include <iostream>
#include <thread>
#if !defined(__FreeBSD__) && !defined(__NetBSD__)
#include <alloca.h>
#else
#include <cstdlib>
#endif
#include "callback.h"
#include "omp.h"
int condition = 0;
void f() {
// Call OpenMP API function to force initialization of OMPT.
// (omp_get_thread_num() does not work because it just returns 0 if the
// runtime isn't initialized yet...)
omp_get_num_threads();
// Call alloca() to force availability of frame pointer
void *p = alloca(0);
OMPT_SIGNAL(condition);
// Wait for both initial threads to arrive that will eventually become the
// master threads in the following parallel region.
OMPT_WAIT(condition, 2);
#pragma omp parallel num_threads(2)
{
// Wait for all threads to arrive so that no worker thread can be reused...
OMPT_SIGNAL(condition);
OMPT_WAIT(condition, 6);
}
}
int main() {
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_schedule'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_begin'
// CHECK: 0: NULL_POINTER=[[NULL:.*$]]
// first master thread
// CHECK: {{^}}[[MASTER_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_1]]
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_1:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1:[0-9]+]], requested_team_size=2
// CHECK-SAME: codeptr_ra=0x{{[0-f]+}}, invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1]], task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_1]]
// second master thread
// CHECK: {{^}}[[MASTER_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_2]]
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_2:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2:[0-9]+]]
// CHECK-SAME: requested_team_size=2, codeptr_ra=0x{{[0-f]+}}
// CHECK-SAME: invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2]], task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_2]]
// first worker thread
// CHECK: {{^}}[[THREAD_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_1]]
// CHECK: {{^}}[[THREAD_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_1]]
// second worker thread
// CHECK: {{^}}[[THREAD_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_2]]
// CHECK: {{^}}[[THREAD_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_2]]
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief 固定サイズ文字列クラス @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <algorithm>
#include <cstring>
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 固定サイズ文字列クラス
@param[in] SIZE 文字列サイズ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint16_t SIZE>
class fixed_string {
char text_[SIZE];
uint16_t pos_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
fixed_string() : pos_(0) { text_[0] = 0; }
//-----------------------------------------------------------------//
/*!
@brief 最大サイズを返す
@return 最大サイズ
*/
//-----------------------------------------------------------------//
uint16_t max_size() const { return SIZE; }
//-----------------------------------------------------------------//
/*!
@brief 現在のサイズを返す
@return 現在のサイズ
*/
//-----------------------------------------------------------------//
uint16_t size() const { return pos_; }
//-----------------------------------------------------------------//
/*!
@brief 文字列をクリア
*/
//-----------------------------------------------------------------//
void clear() noexcept {
pos_ = 0;
text_[pos_] = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を返す
@return 文字列
*/
//-----------------------------------------------------------------//
const char* c_str() const noexcept { return text_; }
//-----------------------------------------------------------------//
/*!
@brief 交換
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
void swap(fixed_string& src) {
std::swap(src.text_, text_);
std::swap(src.pos_, pos_);
}
//-----------------------------------------------------------------//
/*!
@brief 代入
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator = (const fixed_string& src) {
std::strcpy(text_, src.text_);
pos_ = src.pos_;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字を加える
@param[in] ch 文字
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (char ch) {
if(pos_ < (SIZE - 1)) {
text_[pos_] = ch;
++pos_;
text_[pos_] = 0;
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字参照
@param[in] pos 配列位置
@return 文字
*/
//-----------------------------------------------------------------//
char& operator [] (uint32_t pos) {
if(pos >= pos_) {
static char tmp = 0;
return tmp;
}
return text_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 一致比較
@param[in] text 文字列
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator == (const char* text) const {
if(text == nullptr) {
return pos_ == 0;
}
return std::strcmp(text_, text) == 0;
}
//-----------------------------------------------------------------//
/*!
@brief 一致比較
@param[in] th 比較対象
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator == (const fixed_string& th) const {
return std::strcmp(c_str(), th.c_str()) == 0;
}
//-----------------------------------------------------------------//
/*!
@brief 不一致比較
@param[in] th 比較対象
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator != (const fixed_string& th) const {
return std::strcmp(c_str(), th.c_str()) != 0;
}
};
}
<commit_msg>update new version (for tested code)<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief 固定サイズ文字列クラス @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <algorithm>
#include <cstring>
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 固定サイズ文字列クラス
@param[in] SIZE 文字列サイズ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t SIZE>
class fixed_string {
char text_[SIZE];
uint32_t pos_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
@param[in] str 初期設定文字列
*/
//-----------------------------------------------------------------//
fixed_string(const char* str = nullptr) : pos_(0) {
if(str != nullptr) {
std::strcpy(text_, str);
pos_ = std::strlen(text_);
} else {
text_[pos_] = 0;
}
}
//-----------------------------------------------------------------//
/*!
@brief 格納可能な最大サイズを返す(終端の数を除外)
@return 格納可能な最大サイズ
*/
//-----------------------------------------------------------------//
uint32_t capacity() const noexcept { return SIZE - 1; }
//-----------------------------------------------------------------//
/*!
@brief 現在のサイズを返す
@return 現在のサイズ
*/
//-----------------------------------------------------------------//
uint32_t size() const noexcept { return pos_; }
//-----------------------------------------------------------------//
/*!
@brief 文字列をクリア(リセット)
*/
//-----------------------------------------------------------------//
void clear() noexcept {
pos_ = 0;
text_[pos_] = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を返す
@return 文字列
*/
//-----------------------------------------------------------------//
const char* c_str() const noexcept { return text_; }
//-----------------------------------------------------------------//
/*!
@brief 交換
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
void swap(fixed_string& src) noexcept {
std::swap(src.text_, text_);
std::swap(src.pos_, pos_);
}
//-----------------------------------------------------------------//
/*!
@brief 代入
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator = (const fixed_string& src) {
std::strcpy(text_, src.c_str());
pos_ = src.pos_;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字を追加
@param[in] ch 文字
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (char ch) {
if(pos_ < (SIZE - 1)) {
text_[pos_] = ch;
++pos_;
text_[pos_] = 0;
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を追加
@param[in] str 文字列
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (const char* str) {
if(str == nullptr) {
return *this;
}
uint32_t l = std::strlen(str);
if((pos_ + l) < (SIZE - 1)) {
std::strcpy(&text_[pos_], str);
pos_ += l;
} else { // バッファが許す範囲でコピー
l = SIZE - pos_ - 1;
std::strncpy(&text_[pos_], str, l);
pos_ = SIZE - 1;
}
text_[pos_] = 0;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字参照
@param[in] pos 配列位置
@return 文字
*/
//-----------------------------------------------------------------//
char& operator [] (uint32_t pos) noexcept {
if(pos >= pos_) {
static char tmp = 0;
return tmp;
}
return text_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 一致比較
@param[in] text 文字列
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool cmp(const char* text) const noexcept {
if(text == nullptr) {
return pos_ == 0;
}
return std::strcmp(c_str(), text) == 0;
}
//-----------------------------------------------------------------//
/*!
@brief 一致比較(オペレーター)
@param[in] text 文字列
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator == (const char* text) const { return cmp(text); }
//-----------------------------------------------------------------//
/*!
@brief 不一致比較(オペレーター)
@param[in] text 文字列
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator != (const char* text) const { return !cmp(text); }
//-----------------------------------------------------------------//
/*!
@brief クラス、一致比較(オペレーター)
@param[in] th 比較対象
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator == (const fixed_string& th) const {
return std::strcmp(c_str(), th.c_str()) == 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス、不一致比較(オペレーター)
@param[in] th 比較対象
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator != (const fixed_string& th) const {
return std::strcmp(c_str(), th.c_str()) != 0;
}
};
}
<|endoftext|> |
<commit_before>#include "signalcenter.h"
#include "dispatchentry.h"
// TEST: git subtree commit in upstream repo
// TEST 2: git subtree commit made in application repo
// TEST 3: git subtree commit made in application repo and pushed with git subtree push
// TEST 4: yet another git subtree commit made in application repo and pushed with git subtree push
/*!
\class SignalCenter
\inmodule QtxCore
\brief The SignalCenter class provides a mechanism for dispatching
notifications within an application.
*/
/*!
Returns a pointer to the application's default SignalCenter instance.
*/
SignalCenter* SignalCenter::instance()
{
static SignalCenter *center = 0;
if (!center) {
center = new SignalCenter();
}
return center;
}
/*!
Constructs a SignalCenter object with the given \a parent.
*/
SignalCenter::SignalCenter(QObject *parent /* = 0 */)
: QObject(parent),
mPoster(0)
{
}
/*!
Destroy the object.
*/
SignalCenter::~SignalCenter()
{
}
/*!
TODO: \a signal \a receiver \a slot
*/
void SignalCenter::observe(const QString & signal, QObject *receiver, const char *slot)
{
observe(0, signal, receiver, slot);
}
/*!
TODO: \a sender \a signal \a receiver \a slot
*/
void SignalCenter::observe(const QObject *sender, const QString & signal,
QObject *receiver, const char *slot)
{
DispatchEntry *entry = new DispatchEntry(sender, signal, receiver, slot);
mDispatchTable.append(entry);
QObject::connect(receiver, SIGNAL(destroyed(QObject *)), SLOT(onDestroyed(QObject *)));
}
/*!
TODO: \a receiver
*/
void SignalCenter::unobserve(const QObject *receiver)
{
unobserve(0, "", receiver);
}
/*!
TODO: \a sender \a signal \a receiver
*/
void SignalCenter::unobserve(const QObject *sender, const QString & signal, const QObject *receiver)
{
QMutableListIterator<DispatchEntry *> itr(mDispatchTable);
while (itr.hasNext()) {
DispatchEntry* entry = itr.next();
if (entry->receiver() == receiver
&& (entry->sender() == sender || !sender)
&& (entry->signal() == signal || signal.isEmpty())) {
itr.remove();
}
}
}
/*!
TODO: \a sender \a signal \a val0 \a val1 \a val2 \a val3 \a val4 \a val5 \a val6 \a val7 \a val8 \a val9
*/
void SignalCenter::post(QObject *sender, const QString & signal,
QGenericArgument val0 /* = QGenericArgument( 0 ) */, QGenericArgument val1 /* = QGenericArgument() */, QGenericArgument val2 /* = QGenericArgument() */, QGenericArgument val3 /* = QGenericArgument() */, QGenericArgument val4 /* = QGenericArgument() */, QGenericArgument val5 /* = QGenericArgument() */, QGenericArgument val6 /* = QGenericArgument() */, QGenericArgument val7 /* = QGenericArgument() */, QGenericArgument val8 /* = QGenericArgument() */, QGenericArgument val9 /* = QGenericArgument() */)
{
mPoster = sender;
QList<DispatchEntry *> table(mDispatchTable);
QMutableListIterator<DispatchEntry *> itr(table);
while (itr.hasNext()) {
DispatchEntry* entry = itr.next();
if ((entry->sender() == sender || !entry->sender())
&& (entry->signal() == signal || entry->signal().isEmpty())) {
QObject *receiver = entry->receiver();
const char *slot = entry->slot();
const QMetaObject* metaReceiver = receiver->metaObject();
int idx = metaReceiver->indexOfSlot(slot);
if (idx == -1) {
continue;
}
QMetaMethod method = metaReceiver->method(idx);
method.invoke(receiver, Qt::DirectConnection, val0, val1, val2, val3, val4, val5, val6, val7, val8, val9);
}
}
mPoster = 0;
}
/*!
TODO:
*/
QObject *SignalCenter::poster() const
{
return mPoster;
}
void SignalCenter::onDestroyed(QObject * obj /* = 0 */)
{
if (!obj) {
return;
}
unobserve(obj);
}
<commit_msg>Remove comments made while testing git subtree.<commit_after>#include "signalcenter.h"
#include "dispatchentry.h"
/*!
\class SignalCenter
\inmodule QtxCore
\brief The SignalCenter class provides a mechanism for dispatching
notifications within an application.
*/
/*!
Returns a pointer to the application's default SignalCenter instance.
*/
SignalCenter* SignalCenter::instance()
{
static SignalCenter *center = 0;
if (!center) {
center = new SignalCenter();
}
return center;
}
/*!
Constructs a SignalCenter object with the given \a parent.
*/
SignalCenter::SignalCenter(QObject *parent /* = 0 */)
: QObject(parent),
mPoster(0)
{
}
/*!
Destroy the object.
*/
SignalCenter::~SignalCenter()
{
}
/*!
TODO: \a signal \a receiver \a slot
*/
void SignalCenter::observe(const QString & signal, QObject *receiver, const char *slot)
{
observe(0, signal, receiver, slot);
}
/*!
TODO: \a sender \a signal \a receiver \a slot
*/
void SignalCenter::observe(const QObject *sender, const QString & signal,
QObject *receiver, const char *slot)
{
DispatchEntry *entry = new DispatchEntry(sender, signal, receiver, slot);
mDispatchTable.append(entry);
QObject::connect(receiver, SIGNAL(destroyed(QObject *)), SLOT(onDestroyed(QObject *)));
}
/*!
TODO: \a receiver
*/
void SignalCenter::unobserve(const QObject *receiver)
{
unobserve(0, "", receiver);
}
/*!
TODO: \a sender \a signal \a receiver
*/
void SignalCenter::unobserve(const QObject *sender, const QString & signal, const QObject *receiver)
{
QMutableListIterator<DispatchEntry *> itr(mDispatchTable);
while (itr.hasNext()) {
DispatchEntry* entry = itr.next();
if (entry->receiver() == receiver
&& (entry->sender() == sender || !sender)
&& (entry->signal() == signal || signal.isEmpty())) {
itr.remove();
}
}
}
/*!
TODO: \a sender \a signal \a val0 \a val1 \a val2 \a val3 \a val4 \a val5 \a val6 \a val7 \a val8 \a val9
*/
void SignalCenter::post(QObject *sender, const QString & signal,
QGenericArgument val0 /* = QGenericArgument( 0 ) */, QGenericArgument val1 /* = QGenericArgument() */, QGenericArgument val2 /* = QGenericArgument() */, QGenericArgument val3 /* = QGenericArgument() */, QGenericArgument val4 /* = QGenericArgument() */, QGenericArgument val5 /* = QGenericArgument() */, QGenericArgument val6 /* = QGenericArgument() */, QGenericArgument val7 /* = QGenericArgument() */, QGenericArgument val8 /* = QGenericArgument() */, QGenericArgument val9 /* = QGenericArgument() */)
{
mPoster = sender;
QList<DispatchEntry *> table(mDispatchTable);
QMutableListIterator<DispatchEntry *> itr(table);
while (itr.hasNext()) {
DispatchEntry* entry = itr.next();
if ((entry->sender() == sender || !entry->sender())
&& (entry->signal() == signal || entry->signal().isEmpty())) {
QObject *receiver = entry->receiver();
const char *slot = entry->slot();
const QMetaObject* metaReceiver = receiver->metaObject();
int idx = metaReceiver->indexOfSlot(slot);
if (idx == -1) {
continue;
}
QMetaMethod method = metaReceiver->method(idx);
method.invoke(receiver, Qt::DirectConnection, val0, val1, val2, val3, val4, val5, val6, val7, val8, val9);
}
}
mPoster = 0;
}
/*!
TODO:
*/
QObject *SignalCenter::poster() const
{
return mPoster;
}
void SignalCenter::onDestroyed(QObject * obj /* = 0 */)
{
if (!obj) {
return;
}
unobserve(obj);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: rtl_old_testbyteseq.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-05-03 08:55:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// LLA:
// this file is converted to use with testshl2
// original was placed in sal/test/textenc.cxx
// -----------------------------------------------------------------------------
#include <stdio.h>
// #include <osl/diagnose.h>
#include <rtl/byteseq.hxx>
using namespace ::rtl;
#include <cppunit/simpleheader.hxx>
namespace rtl_testbyteseq
{
// -----------------------------------------------------------------------------
class oldbyteseq : public CppUnit::TestFixture
{
public:
void test_bytesequence_001();
CPPUNIT_TEST_SUITE( oldbyteseq );
CPPUNIT_TEST( test_bytesequence_001 );
CPPUNIT_TEST_SUITE_END( );
};
// -----------------------------------------------------------------------------
void oldbyteseq::test_bytesequence_001()
{
signed char a[5] = { 1 , 2 , 3 , 4 , 5 };
// test the c++ wrapper
{
ByteSequence seq;
OSL_ENSURE( ! seq.getLength() , "" );
ByteSequence seq2( a , 5 );
OSL_ENSURE( !( seq == seq2) , "" );
seq = seq2;
OSL_ENSURE( seq == seq2 , "" );
seq[0] = 2;
OSL_ENSURE( !(seq == seq2) , "" );
seq = ByteSequence( a , 5 );
OSL_ENSURE( seq == seq2 , "" );
seq = ByteSequence( 5 ); // default value is 0 for each byte
OSL_ENSURE( !( seq == seq2 ) , "" );
}
{
sal_Sequence *pSeq = 0;
rtl_byte_sequence_construct( &pSeq , 0 );
// implementation dependent test.
OSL_ENSURE( pSeq->nRefCount == 2 , "invalid refcount for empty sequence" );
sal_Sequence *pSeq2 = 0;
rtl_byte_sequence_constructFromArray( &pSeq2 , a , 5 );
OSL_ENSURE( ! rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_assign( &pSeq , pSeq2 );
OSL_ENSURE( pSeq == pSeq2 , "" );
OSL_ENSURE( rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_reference2One( &pSeq );
(( sal_Int8*) rtl_byte_sequence_getConstArray( pSeq ) )[0] = 2;
OSL_ENSURE( ! rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_constructFromArray( &pSeq , a , 5 );
OSL_ENSURE( rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_construct( &pSeq , 5 );
OSL_ENSURE( ! rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_release( pSeq2 );
rtl_byte_sequence_release( pSeq );
}
printf( "test bytesequence OK\n" );
}
} // namespace osl_test_file
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_testbyteseq::oldbyteseq, "rtl_ByteSequence" );
// -----------------------------------------------------------------------------
NOADDITIONAL;
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.162); FILE MERGED 2005/09/05 17:44:40 rt 1.2.162.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rtl_old_testbyteseq.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:15:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// LLA:
// this file is converted to use with testshl2
// original was placed in sal/test/textenc.cxx
// -----------------------------------------------------------------------------
#include <stdio.h>
// #include <osl/diagnose.h>
#include <rtl/byteseq.hxx>
using namespace ::rtl;
#include <cppunit/simpleheader.hxx>
namespace rtl_testbyteseq
{
// -----------------------------------------------------------------------------
class oldbyteseq : public CppUnit::TestFixture
{
public:
void test_bytesequence_001();
CPPUNIT_TEST_SUITE( oldbyteseq );
CPPUNIT_TEST( test_bytesequence_001 );
CPPUNIT_TEST_SUITE_END( );
};
// -----------------------------------------------------------------------------
void oldbyteseq::test_bytesequence_001()
{
signed char a[5] = { 1 , 2 , 3 , 4 , 5 };
// test the c++ wrapper
{
ByteSequence seq;
OSL_ENSURE( ! seq.getLength() , "" );
ByteSequence seq2( a , 5 );
OSL_ENSURE( !( seq == seq2) , "" );
seq = seq2;
OSL_ENSURE( seq == seq2 , "" );
seq[0] = 2;
OSL_ENSURE( !(seq == seq2) , "" );
seq = ByteSequence( a , 5 );
OSL_ENSURE( seq == seq2 , "" );
seq = ByteSequence( 5 ); // default value is 0 for each byte
OSL_ENSURE( !( seq == seq2 ) , "" );
}
{
sal_Sequence *pSeq = 0;
rtl_byte_sequence_construct( &pSeq , 0 );
// implementation dependent test.
OSL_ENSURE( pSeq->nRefCount == 2 , "invalid refcount for empty sequence" );
sal_Sequence *pSeq2 = 0;
rtl_byte_sequence_constructFromArray( &pSeq2 , a , 5 );
OSL_ENSURE( ! rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_assign( &pSeq , pSeq2 );
OSL_ENSURE( pSeq == pSeq2 , "" );
OSL_ENSURE( rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_reference2One( &pSeq );
(( sal_Int8*) rtl_byte_sequence_getConstArray( pSeq ) )[0] = 2;
OSL_ENSURE( ! rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_constructFromArray( &pSeq , a , 5 );
OSL_ENSURE( rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_construct( &pSeq , 5 );
OSL_ENSURE( ! rtl_byte_sequence_equals( pSeq , pSeq2 ) , "" );
rtl_byte_sequence_release( pSeq2 );
rtl_byte_sequence_release( pSeq );
}
printf( "test bytesequence OK\n" );
}
} // namespace osl_test_file
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_testbyteseq::oldbyteseq, "rtl_ByteSequence" );
// -----------------------------------------------------------------------------
NOADDITIONAL;
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, 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.
*
* $Id$
*
*/
/**
\author Radu Bogdan Rusu
**/
#include "pcl/pcl_base.h"
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::PCLBase<sensor_msgs::PointCloud2>::setInputCloud (const PointCloud2ConstPtr &cloud)
{
input_ = cloud;
for (size_t d = 0; d < cloud->fields.size (); ++d)
{
if (cloud->fields[d].name == x_field_name_)
x_idx_ = d;
if (cloud->fields[d].name == y_field_name_)
y_idx_ = d;
if (cloud->fields[d].name == z_field_name_)
z_idx_ = d;
}
// Obtain the size of all fields. Restrict to sizeof FLOAT32 for now
field_sizes_.resize (input_->fields.size ());
for (size_t d = 0; d < input_->fields.size (); ++d)
{
int fsize;
switch (input_->fields[d].datatype)
{
case sensor_msgs::PointField::INT8:
case sensor_msgs::PointField::UINT8:
{
fsize = 1;
break;
}
case sensor_msgs::PointField::INT16:
case sensor_msgs::PointField::UINT16:
{
fsize = 2;
break;
}
case sensor_msgs::PointField::INT32:
case sensor_msgs::PointField::UINT32:
case sensor_msgs::PointField::FLOAT32:
{
fsize = 4;
break;
}
case sensor_msgs::PointField::FLOAT64:
{
fsize = 8;
break;
}
default:
{
PCL_ERROR ("[PCLBase::setInputCloud] Invalid field type (%d)!\n", input_->fields[d].datatype);
fsize = 0;
break;
}
}
field_sizes_[d] = (std::min) (fsize, (int)sizeof (float));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::deinitCompute ()
{
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::initCompute ()
{
// Check if input was set
if (!input_)
return (false);
// If no point indices have been given, construct a set of indices for the entire input point cloud
if (!indices_)
{
fake_indices_ = true;
indices_.reset (new std::vector<int>);
try
{
indices_->resize (input_->width * input_->height);
}
catch (std::bad_alloc)
{
PCL_ERROR ("[initCompute] Failed to allocate %lu indices.\n", (unsigned long) (input_->width * input_->height));
}
for (size_t i = 0; i < indices_->size (); ++i) { (*indices_)[i] = i; }
}
// If we have a set of fake indices, but they do not match the number of points in the cloud, update them
if (fake_indices_ && indices_->size () != (input_->width * input_->height))
{
size_t indices_size = indices_->size ();
indices_->resize (input_->width * input_->height);
for (size_t i = indices_size; i < indices_->size (); ++i) { (*indices_)[i] = i; }
}
return (true);
}
<commit_msg>license change<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-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.
*
* $Id$
*
*/
#include "pcl/pcl_base.h"
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::PCLBase<sensor_msgs::PointCloud2>::setInputCloud (const PointCloud2ConstPtr &cloud)
{
input_ = cloud;
for (size_t d = 0; d < cloud->fields.size (); ++d)
{
if (cloud->fields[d].name == x_field_name_)
x_idx_ = d;
if (cloud->fields[d].name == y_field_name_)
y_idx_ = d;
if (cloud->fields[d].name == z_field_name_)
z_idx_ = d;
}
// Obtain the size of all fields. Restrict to sizeof FLOAT32 for now
field_sizes_.resize (input_->fields.size ());
for (size_t d = 0; d < input_->fields.size (); ++d)
{
int fsize;
switch (input_->fields[d].datatype)
{
case sensor_msgs::PointField::INT8:
case sensor_msgs::PointField::UINT8:
{
fsize = 1;
break;
}
case sensor_msgs::PointField::INT16:
case sensor_msgs::PointField::UINT16:
{
fsize = 2;
break;
}
case sensor_msgs::PointField::INT32:
case sensor_msgs::PointField::UINT32:
case sensor_msgs::PointField::FLOAT32:
{
fsize = 4;
break;
}
case sensor_msgs::PointField::FLOAT64:
{
fsize = 8;
break;
}
default:
{
PCL_ERROR ("[PCLBase::setInputCloud] Invalid field type (%d)!\n", input_->fields[d].datatype);
fsize = 0;
break;
}
}
field_sizes_[d] = (std::min) (fsize, (int)sizeof (float));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::deinitCompute ()
{
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::initCompute ()
{
// Check if input was set
if (!input_)
return (false);
// If no point indices have been given, construct a set of indices for the entire input point cloud
if (!indices_)
{
fake_indices_ = true;
indices_.reset (new std::vector<int>);
try
{
indices_->resize (input_->width * input_->height);
}
catch (std::bad_alloc)
{
PCL_ERROR ("[initCompute] Failed to allocate %lu indices.\n", (unsigned long) (input_->width * input_->height));
}
for (size_t i = 0; i < indices_->size (); ++i) { (*indices_)[i] = i; }
}
// If we have a set of fake indices, but they do not match the number of points in the cloud, update them
if (fake_indices_ && indices_->size () != (input_->width * input_->height))
{
size_t indices_size = indices_->size ();
indices_->resize (input_->width * input_->height);
for (size_t i = indices_size; i < indices_->size (); ++i) { (*indices_)[i] = i; }
}
return (true);
}
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/pipeline/version.h>
#include <vistk/version.h>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/module.hpp>
/**
* \file version.cxx
*
* \brief Python bindings for version.
*/
using namespace boost::python;
class compile
{
public:
typedef vistk::version::version_t version_t;
static bool check(version_t major_, version_t minor_, version_t patch_);
};
class runtime
{
};
BOOST_PYTHON_MODULE(version)
{
class_<compile>("compile"
, "Compile-time version information."
, no_init)
.def_readonly("major", VISTK_VERSION_MAJOR)
.def_readonly("minor", VISTK_VERSION_MINOR)
.def_readonly("patch", VISTK_VERSION_PATCH)
.def_readonly("version_string", VISTK_VERSION)
.def_readonly("git_build",
#ifdef VISTK_BUILT_FROM_GIT
true
#else
false
#endif
)
.def_readonly("git_hash", VISTK_GIT_HASH)
.def_readonly("git_hash_short", VISTK_GIT_HASH_SHORT)
.def_readonly("git_dirty", VISTK_GIT_DIRTY)
.def("check", &compile::check
, (arg("major"), arg("minor"), arg("patch"))
, "Check for a vistk of at least the given version.")
.staticmethod("check")
;
class_<runtime>("runtime"
, "Runtime version information."
, no_init)
.def_readonly("major", vistk::version::major)
.def_readonly("minor", vistk::version::minor)
.def_readonly("patch", vistk::version::patch)
.def_readonly("version_string", vistk::version::version_string)
.def_readonly("git_build", vistk::version::git_build)
.def_readonly("git_hash", vistk::version::git_hash)
.def_readonly("git_hash_short", vistk::version::git_hash_short)
.def_readonly("git_dirty", vistk::version::git_dirty)
.def("check", &vistk::version::check
, (arg("major"), arg("minor"), arg("patch"))
, "Check for a vistk of at least the given version.")
.staticmethod("check")
;
}
bool
compile
::check(version_t major_, version_t minor_, version_t patch_)
{
// If any of the version components are 0, we get compare warnings. Turn
// them off here.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
return VISTK_VERSION_CHECK(major_, minor_, patch_);
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
}
<commit_msg>Move warning pragmas outside the function body<commit_after>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/pipeline/version.h>
#include <vistk/version.h>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/module.hpp>
/**
* \file version.cxx
*
* \brief Python bindings for version.
*/
using namespace boost::python;
class compile
{
public:
typedef vistk::version::version_t version_t;
static bool check(version_t major_, version_t minor_, version_t patch_);
};
class runtime
{
};
BOOST_PYTHON_MODULE(version)
{
class_<compile>("compile"
, "Compile-time version information."
, no_init)
.def_readonly("major", VISTK_VERSION_MAJOR)
.def_readonly("minor", VISTK_VERSION_MINOR)
.def_readonly("patch", VISTK_VERSION_PATCH)
.def_readonly("version_string", VISTK_VERSION)
.def_readonly("git_build",
#ifdef VISTK_BUILT_FROM_GIT
true
#else
false
#endif
)
.def_readonly("git_hash", VISTK_GIT_HASH)
.def_readonly("git_hash_short", VISTK_GIT_HASH_SHORT)
.def_readonly("git_dirty", VISTK_GIT_DIRTY)
.def("check", &compile::check
, (arg("major"), arg("minor"), arg("patch"))
, "Check for a vistk of at least the given version.")
.staticmethod("check")
;
class_<runtime>("runtime"
, "Runtime version information."
, no_init)
.def_readonly("major", vistk::version::major)
.def_readonly("minor", vistk::version::minor)
.def_readonly("patch", vistk::version::patch)
.def_readonly("version_string", vistk::version::version_string)
.def_readonly("git_build", vistk::version::git_build)
.def_readonly("git_hash", vistk::version::git_hash)
.def_readonly("git_hash_short", vistk::version::git_hash_short)
.def_readonly("git_dirty", vistk::version::git_dirty)
.def("check", &vistk::version::check
, (arg("major"), arg("minor"), arg("patch"))
, "Check for a vistk of at least the given version.")
.staticmethod("check")
;
}
// If any of the version components are 0, we get compare warnings. Turn
// them off here.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
bool
compile
::check(version_t major_, version_t minor_, version_t patch_)
{
return VISTK_VERSION_CHECK(major_, minor_, patch_);
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.