text stringlengths 54 60.6k |
|---|
<commit_before>/*
RegistExt.cpp, Robert Oeffner 2017
The MIT License (MIT)
Copyright (c) 2017 Robert Oeffner
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.
Compile on Windows:
cl /Fohelpers.obj /c helpers.cpp /EHsc ^
&& cl /Foratiohistogram.obj /c ratiohistogram.cpp /EHsc ^
&& cl /Fohistogram.obj /c histogram.cpp /EHsc ^
&& cl /Fomeanhistogram.obj /c meanhistogram.cpp /EHsc ^
&& cl /FoRegistExt.obj /c RegistExt.cpp /EHsc ^
&& link /DLL /OUT:histograms.dll helpers.obj RegistExt.obj meanhistogram.obj histogram.obj ratiohistogram.obj
With debug info:
cl /Fohelpers.obj /c helpers.cpp /DDEBUG /ZI /EHsc ^
&& cl /Foratiohistogram.obj /c ratiohistogram.cpp /DDEBUG /ZI /EHsc ^
&& cl /Fomeanhistogram.obj /c meanhistogram.cpp /DDEBUG /ZI /EHsc ^
&& cl /Fohistogram.obj /c histogram.cpp /DDEBUG /ZI /EHsc ^
&& cl /FoRegistExt.obj /c RegistExt.cpp /DDEBUG /ZI /EHsc ^
&& link /DLL /DEBUG /debugtype:cv /OUT:histograms.dll helpers.obj meanhistogram.obj RegistExt.obj histogram.obj ratiohistogram.obj
Compile on Linux:
g++ -fPIC -lm -shared histogram.cpp helpers.cpp meanhistogram.cpp ratiohistogram.cpp RegistExt.cpp -o libhistograms.so
*/
#include "RegistExt.h"
#ifdef __cplusplus
extern "C" {
#endif
SQLITE_EXTENSION_INIT1
sqlite3 *thisdb = NULL;
#ifdef _WIN32
__declspec(dllexport)
#endif
/* The built library file name excluding its file extension must be part of the
function name below as documented on http://www.sqlite.org/loadext.html
*/
int sqlite3_histograms_init( // always use lower case
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
)
{
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if (sqlite3_libversion_number()<3008012)
{
*pzErrMsg = sqlite3_mprintf("Histogram extension requires SQLite 3.8.12 or later");
return SQLITE_ERROR;
}
rc = sqlite3_create_module(db, "HISTO", &histoModule, 0);
rc = sqlite3_create_module(db, "RATIOHISTO", &ratiohistoModule, 0);
rc = sqlite3_create_module(db, "MEANHISTO", &meanhistoModule, 0);
#endif
return rc;
}
#ifdef __cplusplus
}
#endif
<commit_msg>Comments for loading on Linux<commit_after>/*
RegistExt.cpp, Robert Oeffner 2017
The MIT License (MIT)
Copyright (c) 2017 Robert Oeffner
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.
Compile on Windows:
cl /Fohelpers.obj /c helpers.cpp /EHsc ^
&& cl /Foratiohistogram.obj /c ratiohistogram.cpp /EHsc ^
&& cl /Fohistogram.obj /c histogram.cpp /EHsc ^
&& cl /Fomeanhistogram.obj /c meanhistogram.cpp /EHsc ^
&& cl /FoRegistExt.obj /c RegistExt.cpp /EHsc ^
&& link /DLL /OUT:histograms.dll helpers.obj RegistExt.obj meanhistogram.obj histogram.obj ratiohistogram.obj
With debug info:
cl /Fohelpers.obj /c helpers.cpp /DDEBUG /ZI /EHsc ^
&& cl /Foratiohistogram.obj /c ratiohistogram.cpp /DDEBUG /ZI /EHsc ^
&& cl /Fomeanhistogram.obj /c meanhistogram.cpp /DDEBUG /ZI /EHsc ^
&& cl /Fohistogram.obj /c histogram.cpp /DDEBUG /ZI /EHsc ^
&& cl /FoRegistExt.obj /c RegistExt.cpp /DDEBUG /ZI /EHsc ^
&& link /DLL /DEBUG /debugtype:cv /OUT:histograms.dll helpers.obj meanhistogram.obj RegistExt.obj histogram.obj ratiohistogram.obj
Compile on Linux:
g++ -fPIC -lm -shared histogram.cpp helpers.cpp meanhistogram.cpp ratiohistogram.cpp RegistExt.cpp -o libhistograms.so
From the sqlite commandline load the extension
on Windows
sqlite> .load histograms.dll
sqlite>
on Linux
sqlite> .load ./histograms.so
sqlite>
*/
#include "RegistExt.h"
#ifdef __cplusplus
extern "C" {
#endif
SQLITE_EXTENSION_INIT1
sqlite3 *thisdb = NULL;
#ifdef _WIN32
__declspec(dllexport)
#endif
/* The built library file name excluding its file extension must be part of the
function name below as documented on http://www.sqlite.org/loadext.html
*/
int sqlite3_histograms_init( // always use lower case
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
)
{
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if (sqlite3_libversion_number()<3008012)
{
*pzErrMsg = sqlite3_mprintf("Histogram extension requires SQLite 3.8.12 or later");
return SQLITE_ERROR;
}
rc = sqlite3_create_module(db, "HISTO", &histoModule, 0);
rc = sqlite3_create_module(db, "RATIOHISTO", &ratiohistoModule, 0);
rc = sqlite3_create_module(db, "MEANHISTO", &meanhistoModule, 0);
#endif
return rc;
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>// Example qclserver code.
#include <QtGui> // ### TODO: include relevant headers only
#include "qc.h"
class ChatWindow : public QWidget
{
Q_OBJECT
public:
ChatWindow()
: log_(0)
, edit_(0)
, html_("<table></table>")
{
QVBoxLayout *layout = new QVBoxLayout;
QLabel *label = new QLabel("CHAT WINDOW MOCKUP");
label->setStyleSheet("QLabel { background-color : yellow; color : black; }");
label->setAlignment(Qt::AlignCenter);
layout->addWidget(label);
log_ = new QTextBrowser;
log_->setHtml(html_);
log_->setReadOnly(true);
log_->setOpenExternalLinks(true);
layout->addWidget(log_);
edit_ = new QLineEdit;
connect(edit_, SIGNAL(returnPressed()), SLOT(sendChatMessage()));
layout->addWidget(edit_);
setLayout(layout);
resize(1000, 400);
}
void appendEvent(const QString &text, const QString &user, int timestamp, int type)
{
html_.insert(html_.lastIndexOf("</table>"), formatEvent(text, user, timestamp, type));
log_->setHtml(html_);
}
// Prepends history (i.e. in front of any individual events that may have arrived
// in the meantime!)
void prependHistory(const QStringList &h)
{
if (h.size() == 0)
return;
QRegExp rx("^(\\S+)\\s+(\\d+)\\s+(\\d+)\\s+(.*)$");
QStringList events;
QListIterator<QString> it(h);
while (it.hasNext()) {
QString item = it.next();
if (rx.indexIn(item) == -1)
qFatal("regexp mismatch: %s", item.toLatin1().data());
const QString user = rx.cap(1);
const int timestamp = rx.cap(2).toInt();
const int type = rx.cap(3).toInt();
const QString text = rx.cap(4);
events << formatEvent(text, user, timestamp, type);
}
html_.insert(html_.indexOf("<table>") + QString("<table>").size(), events.join(""));
log_->setHtml(html_);
}
void scrollToBottom()
{
log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum());
}
private:
QTextBrowser *log_;
QLineEdit *edit_;
QString html_;
void closeEvent(QCloseEvent *event)
{
// prevent the close event from terminating the application
hide();
event->ignore();
}
void showEvent(QShowEvent *)
{
scrollToBottom();
emit windowShown();
}
void hideEvent(QHideEvent *)
{
emit windowHidden();
}
// Returns a version of \a s where hyperlinks are embedded in HTML <a> tags.
static QString toAnchorTagged(const QString &s)
{
return QString(s).replace(
QRegExp("(http://\\S*)"), "<a href=\"\\1\" style=\"text-decoration: none;\">\\1</a>");
}
static QString toTimeString(int timestamp)
{
return QDateTime::fromTime_t(timestamp).toString("yyyy MMM dd hh:mm:ss");
}
static QString formatEvent(const QString &text, const QString &user, int timestamp, int type)
{
QString userTdStyle("style=\"padding-left:20px\"");
QString textTdStyle("style=\"padding-left:2px\"");
QString s("<tr>");
s += QString("<td><span style=\"color:%1\">[%2]</span></td>").arg("#888").arg(toTimeString(timestamp));
s += QString("<td align=\"right\" %1><span style=\"color:%2\"><%3></span></td>")
.arg(userTdStyle).arg("#000").arg(user);
if (type == CHATMESSAGE)
s += QString("<td %1><span style=\"color:black\">%2</span></td>")
.arg(textTdStyle).arg(toAnchorTagged(text));
else if (type == NOTIFICATION)
s += QString("<td %1><span style=\"color:%2\">%3</span></td>")
.arg(textTdStyle).arg("#916409").arg(toAnchorTagged(text));
else
qFatal("invalid type: %d", type);
s += "</tr>";
return s;
}
private slots:
void sendChatMessage()
{
const QString text = edit_->text().trimmed();
edit_->clear();
if (!text.isEmpty())
emit chatMessage(text);
}
signals:
void windowShown();
void windowHidden();
void chatMessage(const QString &);
};
class Interactor : public QObject
{
Q_OBJECT
public:
Interactor(QCClientChannels *cchannels, QCServerChannel *schannel, ChatWindow *window)
: cchannels_(cchannels)
, schannel_(schannel)
, window_(window)
{
user_ = qgetenv("USER");
if (user_.isEmpty()) {
qWarning("failed to extract string from environment variable USER; using '<unknown>'");
user_ = QString("<unknown>");
}
connect(cchannels_, SIGNAL(clientConnected(qint64)), SLOT(clientConnected(qint64)));
connect(cchannels_, SIGNAL(chatWindowShown()), window_, SLOT(show()));
connect(cchannels_, SIGNAL(chatWindowHidden()), window_, SLOT(hide()));
connect(
cchannels_, SIGNAL(notification(const QString &, const QString &, int)),
SLOT(localNotification(const QString &)));
connect(
schannel_, SIGNAL(chatMessage(const QString &, const QString &, int)),
SLOT(centralChatMessage(const QString &, const QString &, int)));
connect(
schannel_, SIGNAL(notification(const QString &, const QString &, int)),
SLOT(centralNotification(const QString &, const QString &, int)));
connect(schannel_, SIGNAL(history(const QStringList &)), SLOT(history(const QStringList &)));
connect(window_, SIGNAL(windowShown()), SLOT(showChatWindow()));
connect(window_, SIGNAL(windowHidden()), SLOT(hideChatWindow()));
connect(window_, SIGNAL(chatMessage(const QString &)), SLOT(localChatMessage(const QString &)));
schannel_->sendHistoryRequest();
}
private:
QCClientChannels *cchannels_; // qcapp channels
QCServerChannel *schannel_; // qccserver channel
ChatWindow *window_;
QString user_;
private slots:
void clientConnected(qint64 id)
{
// inform about current chat window visibility
if (window_->isVisible())
cchannels_->showChatWindow(id);
else
cchannels_->hideChatWindow(id);
}
void localNotification(const QString &text)
{
//qDebug() << "notification (from a local qcapp):" << text;
schannel_->sendNotification(text, user_);
}
void centralChatMessage(const QString &text, const QString &user, int timestamp)
{
//qDebug() << "chat message (from qccserver) (timestamp:" << timestamp << "):" << text;
window_->appendEvent(text, user, timestamp, CHATMESSAGE);
window_->scrollToBottom();
}
void centralNotification(const QString &text, const QString &user, int timestamp)
{
//qDebug() << "notification (from qccserver) (timestamp:" << timestamp << "):" << text;
cchannels_->sendNotification(text, user, timestamp);
window_->appendEvent(text, user, timestamp, NOTIFICATION);
window_->scrollToBottom();
}
void history(const QStringList &h)
{
//qDebug() << "history (from qccserver):" << h;
window_->prependHistory(h);
}
void showChatWindow()
{
cchannels_->showChatWindow();
}
void hideChatWindow()
{
cchannels_->hideChatWindow();
}
void localChatMessage(const QString &text)
{
//qDebug() << "chat message (from local window):" << text;
schannel_->sendChatMessage(text, user_);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// extract information from environment
bool ok;
const quint16 qclport = qgetenv("QCLPORT").toUInt(&ok);
if (!ok) {
qDebug("failed to extract int from environment variable QCLPORT");
return 1;
}
const QString qcchost = qgetenv("QCCHOST");
if (qcchost.isEmpty()) {
qDebug("failed to extract string from environment variable QCCHOST");
return 1;
}
const quint16 qccport = qgetenv("QCCPORT").toUInt(&ok);
if (!ok) {
qDebug("failed to extract int from environment variable QCCPORT");
return 1;
}
// listen for incoming qcapp connections
QCClientChannels cchannels;
if (!cchannels.listen(qclport)) {
qDebug(
"failed to listen for incoming qcapp connections: cchannels.listen() failed: %s",
cchannels.lastError().toLatin1().data());
return 1;
}
// establish channel to qccserver
QCServerChannel schannel;
if (!schannel.connectToServer(qcchost, qccport)) {
qDebug(
"failed to connect to qccserver: schannel.connectToServer() failed: %s",
schannel.lastError().toLatin1().data());
return 1;
}
// create a chat window
ChatWindow *window = new ChatWindow;
//window->show();
// create object to handle interaction between qcapps, qccserver, and chat window
Interactor interactor(&cchannels, &schannel, window);
return app.exec();
}
#include "main.moc"
<commit_msg>Changed chat window layout<commit_after>// Example qclserver code.
#include <QtGui> // ### TODO: include relevant headers only
#include "qc.h"
class ChatWindow : public QWidget
{
Q_OBJECT
public:
ChatWindow()
: log_(0)
, edit_(0)
, html_("<table></table>")
{
QHBoxLayout *layout1 = new QHBoxLayout;
QVBoxLayout *layout2 = new QVBoxLayout;
layout1->addLayout(layout2);
QHBoxLayout *layout2_1 = new QHBoxLayout;
layout2->addLayout(layout2_1);
channelCBox_ = new QComboBox;
channelCBox_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
channelCBox_->addItem("channel A");
channelCBox_->addItem("channnnnel B");
layout2_1->addWidget(channelCBox_);
QLabel *label1 = new QLabel;
// QLabel *label1 = new QLabel("CHAT WINDOW MOCKUP");
// label1->setStyleSheet("QLabel { background-color : yellow; color : black; }");
label1->setAlignment(Qt::AlignCenter);
layout2_1->addWidget(label1);
log_ = new QTextBrowser;
log_->setHtml(html_);
log_->setReadOnly(true);
log_->setOpenExternalLinks(true);
log_->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding);
layout2->addWidget(log_);
edit_ = new QLineEdit;
connect(edit_, SIGNAL(returnPressed()), SLOT(sendChatMessage()));
edit_->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);
layout2->addWidget(edit_);
usersLayout_ = new QVBoxLayout;
layout1->addLayout(usersLayout_);
QLabel *label2 = new QLabel("Users");
label2->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
//label2->setStyleSheet("QLabel { background-color : cyan; color : black; }");
label2->setAlignment(Qt::AlignLeft);
usersLayout_->addWidget(label2);
userList_ = new QListWidget;
userList_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
userList_->setFixedWidth(100);
// userList_->addItem("joa");
// userList_->addItem("juergens");
usersLayout_->addWidget(userList_);
setLayout(layout1);
resize(1000, 400);
}
void appendEvent(const QString &text, const QString &user, int timestamp, int type)
{
html_.insert(html_.lastIndexOf("</table>"), formatEvent(text, user, timestamp, type));
log_->setHtml(html_);
}
// Prepends history (i.e. in front of any individual events that may have arrived
// in the meantime!)
void prependHistory(const QStringList &h)
{
if (h.size() == 0)
return;
QRegExp rx("^(\\S+)\\s+(\\d+)\\s+(\\d+)\\s+(.*)$");
QStringList events;
QListIterator<QString> it(h);
while (it.hasNext()) {
QString item = it.next();
if (rx.indexIn(item) == -1)
qFatal("regexp mismatch: %s", item.toLatin1().data());
const QString user = rx.cap(1);
const int timestamp = rx.cap(2).toInt();
const int type = rx.cap(3).toInt();
const QString text = rx.cap(4);
events << formatEvent(text, user, timestamp, type);
}
html_.insert(html_.indexOf("<table>") + QString("<table>").size(), events.join(""));
log_->setHtml(html_);
}
void scrollToBottom()
{
log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum());
}
private:
QVBoxLayout *usersLayout_;
QComboBox *channelCBox_;
QListWidget *userList_;
QTextBrowser *log_;
QLineEdit *edit_;
QString html_;
void closeEvent(QCloseEvent *event)
{
// prevent the close event from terminating the application
hide();
event->ignore();
}
void showEvent(QShowEvent *)
{
scrollToBottom();
emit windowShown();
}
void hideEvent(QHideEvent *)
{
emit windowHidden();
}
// Returns a version of \a s where hyperlinks are embedded in HTML <a> tags.
static QString toAnchorTagged(const QString &s)
{
return QString(s).replace(
QRegExp("(http://\\S*)"), "<a href=\"\\1\" style=\"text-decoration: none;\">\\1</a>");
}
static QString toTimeString(int timestamp)
{
return QDateTime::fromTime_t(timestamp).toString("yyyy MMM dd hh:mm:ss");
}
static QString formatEvent(const QString &text, const QString &user, int timestamp, int type)
{
QString userTdStyle("style=\"padding-left:20px\"");
QString textTdStyle("style=\"padding-left:2px\"");
QString s("<tr>");
s += QString("<td><span style=\"color:%1\">[%2]</span></td>").arg("#888").arg(toTimeString(timestamp));
s += QString("<td align=\"right\" %1><span style=\"color:%2\"><%3></span></td>")
.arg(userTdStyle).arg("#000").arg(user);
if (type == CHATMESSAGE)
s += QString("<td %1><span style=\"color:black\">%2</span></td>")
.arg(textTdStyle).arg(toAnchorTagged(text));
else if (type == NOTIFICATION)
s += QString("<td %1><span style=\"color:%2\">%3</span></td>")
.arg(textTdStyle).arg("#916409").arg(toAnchorTagged(text));
else
qFatal("invalid type: %d", type);
s += "</tr>";
return s;
}
private slots:
void sendChatMessage()
{
const QString text = edit_->text().trimmed();
edit_->clear();
if (!text.isEmpty())
emit chatMessage(text);
}
signals:
void windowShown();
void windowHidden();
void chatMessage(const QString &);
};
class Interactor : public QObject
{
Q_OBJECT
public:
Interactor(QCClientChannels *cchannels, QCServerChannel *schannel, ChatWindow *window)
: cchannels_(cchannels)
, schannel_(schannel)
, window_(window)
{
user_ = qgetenv("USER");
if (user_.isEmpty()) {
qWarning("failed to extract string from environment variable USER; using '<unknown>'");
user_ = QString("<unknown>");
}
connect(cchannels_, SIGNAL(clientConnected(qint64)), SLOT(clientConnected(qint64)));
connect(cchannels_, SIGNAL(chatWindowShown()), window_, SLOT(show()));
connect(cchannels_, SIGNAL(chatWindowHidden()), window_, SLOT(hide()));
connect(
cchannels_, SIGNAL(notification(const QString &, const QString &, int)),
SLOT(localNotification(const QString &)));
connect(
schannel_, SIGNAL(chatMessage(const QString &, const QString &, int)),
SLOT(centralChatMessage(const QString &, const QString &, int)));
connect(
schannel_, SIGNAL(notification(const QString &, const QString &, int)),
SLOT(centralNotification(const QString &, const QString &, int)));
connect(schannel_, SIGNAL(history(const QStringList &)), SLOT(history(const QStringList &)));
connect(window_, SIGNAL(windowShown()), SLOT(showChatWindow()));
connect(window_, SIGNAL(windowHidden()), SLOT(hideChatWindow()));
connect(window_, SIGNAL(chatMessage(const QString &)), SLOT(localChatMessage(const QString &)));
schannel_->sendHistoryRequest();
}
private:
QCClientChannels *cchannels_; // qcapp channels
QCServerChannel *schannel_; // qccserver channel
ChatWindow *window_;
QString user_;
private slots:
void clientConnected(qint64 id)
{
// inform about current chat window visibility
if (window_->isVisible())
cchannels_->showChatWindow(id);
else
cchannels_->hideChatWindow(id);
}
void localNotification(const QString &text)
{
//qDebug() << "notification (from a local qcapp):" << text;
schannel_->sendNotification(text, user_);
}
void centralChatMessage(const QString &text, const QString &user, int timestamp)
{
//qDebug() << "chat message (from qccserver) (timestamp:" << timestamp << "):" << text;
window_->appendEvent(text, user, timestamp, CHATMESSAGE);
window_->scrollToBottom();
}
void centralNotification(const QString &text, const QString &user, int timestamp)
{
//qDebug() << "notification (from qccserver) (timestamp:" << timestamp << "):" << text;
cchannels_->sendNotification(text, user, timestamp);
window_->appendEvent(text, user, timestamp, NOTIFICATION);
window_->scrollToBottom();
}
void history(const QStringList &h)
{
//qDebug() << "history (from qccserver):" << h;
window_->prependHistory(h);
}
void showChatWindow()
{
cchannels_->showChatWindow();
}
void hideChatWindow()
{
cchannels_->hideChatWindow();
}
void localChatMessage(const QString &text)
{
//qDebug() << "chat message (from local window):" << text;
schannel_->sendChatMessage(text, user_);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// extract information from environment
bool ok;
const quint16 qclport = qgetenv("QCLPORT").toUInt(&ok);
if (!ok) {
qDebug("failed to extract int from environment variable QCLPORT");
return 1;
}
const QString qcchost = qgetenv("QCCHOST");
if (qcchost.isEmpty()) {
qDebug("failed to extract string from environment variable QCCHOST");
return 1;
}
const quint16 qccport = qgetenv("QCCPORT").toUInt(&ok);
if (!ok) {
qDebug("failed to extract int from environment variable QCCPORT");
return 1;
}
// listen for incoming qcapp connections
QCClientChannels cchannels;
if (!cchannels.listen(qclport)) {
qDebug(
"failed to listen for incoming qcapp connections: cchannels.listen() failed: %s",
cchannels.lastError().toLatin1().data());
return 1;
}
// establish channel to qccserver
QCServerChannel schannel;
if (!schannel.connectToServer(qcchost, qccport)) {
qDebug(
"failed to connect to qccserver: schannel.connectToServer() failed: %s",
schannel.lastError().toLatin1().data());
return 1;
}
// create a chat window
ChatWindow *window = new ChatWindow;
//window->show();
// create object to handle interaction between qcapps, qccserver, and chat window
Interactor interactor(&cchannels, &schannel, window);
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>#include "scan_entity.h"
#include "scan_files.h"
#include "deduplicate_vector.h"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
std::vector<std::string> scanAircraft(std::ostream & log, const boost::filesystem::path & acf_path) {
boost::filesystem::path aircraft_dir = boost::filesystem::path(acf_path).parent_path();
std::vector<std::string> all_refs;
// list file
boost::filesystem::path list_file_path = aircraft_dir / "dataref.txt";
if(boost::filesystem::exists(list_file_path)) {
std::vector<std::string> refs = loadListFile(log, list_file_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
//cdataref.txt
boost::filesystem::path cdataref_path = aircraft_dir / "cdataref.txt";
if(boost::filesystem::exists(cdataref_path) && boost::filesystem::is_regular_file(cdataref_path)) {
std::ifstream inFile(cdataref_path.string());
std::stringstream file_contents_ss;
file_contents_ss << inFile.rdbuf();
std::string file_contents = file_contents_ss.str();
std::vector<std::string> cdataref_entries;
boost::split(cdataref_entries, file_contents, boost::is_any_of("\n\r\t, "));
for(std::string & s : cdataref_entries) {
boost::algorithm::trim(s);
}
//remove empty lines
cdataref_entries.erase(std::remove_if(cdataref_entries.begin(), cdataref_entries.end(), [](const std::string & a)-> bool { return a.size() < 8; }), cdataref_entries.end());
all_refs.insert(all_refs.begin(), cdataref_entries.begin(), cdataref_entries.end());
log << "Found " << cdataref_entries.size() << " unique possible datarefs in " << cdataref_path << "\n";
}
//plugins
boost::filesystem::path plugin_dir_path = aircraft_dir / "plugins";
//for each directory inside plugin path
if(boost::filesystem::exists(plugin_dir_path)) {
boost::filesystem::directory_iterator dir_end_it;
for(boost::filesystem::directory_iterator dir_it(plugin_dir_path); dir_it != dir_end_it; dir_it++) {
std::vector<std::string> refs = scanPluginFolder(log, dir_it->path());
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
}
//object files in aircraft directory
std::vector<boost::filesystem::path> paths;
boost::filesystem::directory_iterator dir_end_it;
for(boost::filesystem::directory_iterator dir_it(aircraft_dir); dir_it != dir_end_it; dir_it++) {
boost::filesystem::path file_path = dir_it->path();
if(boost::filesystem::is_regular_file(file_path)) {
if(".obj" == file_path.extension() || ".acf" == file_path.extension()) {
paths.push_back(file_path);
}
}
}
paths.push_back(aircraft_dir / "Custom Avionics"); // apparently SASL / LUA code is often in this directory
paths.push_back(aircraft_dir / "objects");
boost::filesystem::path xlua_scripts_dir = aircraft_dir / "plugins" / "xlua" / "scripts"; // find xlua LUA scripts from X-Plane 11.00+
if(boost::filesystem::exists(xlua_scripts_dir)) {
paths.push_back(xlua_scripts_dir);
}
std::unordered_set<std::string> extensions_to_scan = {".obj", ".acf", ".lua"};
while(false == paths.empty()) {
boost::filesystem::path path = paths.back();
paths.pop_back();
if(boost::filesystem::is_directory(path)) {
//iterate over directory, pushing back
for(boost::filesystem::directory_iterator dir_it(path); dir_it != dir_end_it; dir_it++) {
paths.push_back(dir_it->path());
}
}
if(boost::filesystem::is_regular_file(path)) {
std::string extension = path.extension().string();
boost::algorithm::to_lower(extension);
if(extensions_to_scan.cend() != extensions_to_scan.find(extension)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
}
}
deduplicate_vector(all_refs);
log << "Found " << all_refs.size() << " unique possible datarefs for aircraft " << acf_path << "\n";
return all_refs;
}
std::vector<std::string> scanLuaFolder(std::ostream & log, const boost::filesystem::path & lua_dir_path) {
std::vector<std::string> lua_folder_datarefs;
if(boost::filesystem::is_directory(lua_dir_path)) { // if this is true, it also exists
for(auto& file_de : boost::make_iterator_range(boost::filesystem::directory_iterator(lua_dir_path), {})) {
if(file_de.path().extension() == ".lua") {
std::vector<std::string> this_script_datarefs = scanFileForDatarefStrings(log, file_de.path());
lua_folder_datarefs.insert(lua_folder_datarefs.cend(), this_script_datarefs.begin(), this_script_datarefs.end());
}
}
}
return lua_folder_datarefs;
}
std::vector<std::string> scanPluginFolder(std::ostream & log, const boost::filesystem::path & plugin_xpl_path) {
#ifdef __APPLE__
static const std::string plugin_name = "mac.xpl";
#elif defined _WIN32 || defined _WIN64
static const std::string plugin_name = "win.xpl";
#else
static const std::string plugin_name = "lin.xpl";
#endif
std::vector<std::string> all_refs;
boost::filesystem::path plugin_dir(plugin_xpl_path.parent_path());
boost::filesystem::path plugin_old_path = plugin_dir / plugin_name;
boost::filesystem::path plugin_new_path = plugin_dir / "64" / plugin_name;
if(boost::filesystem::exists(plugin_old_path)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, plugin_old_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
if(boost::filesystem::exists(plugin_new_path)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, plugin_new_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
deduplicate_vector(all_refs);
return all_refs;
}
<commit_msg>Scan XP11 plugin paths.<commit_after>#include "scan_entity.h"
#include "scan_files.h"
#include "deduplicate_vector.h"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
std::vector<std::string> scanAircraft(std::ostream & log, const boost::filesystem::path & acf_path) {
boost::filesystem::path aircraft_dir = boost::filesystem::path(acf_path).parent_path();
std::vector<std::string> all_refs;
// list file
boost::filesystem::path list_file_path = aircraft_dir / "dataref.txt";
if(boost::filesystem::exists(list_file_path)) {
std::vector<std::string> refs = loadListFile(log, list_file_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
//cdataref.txt
boost::filesystem::path cdataref_path = aircraft_dir / "cdataref.txt";
if(boost::filesystem::exists(cdataref_path) && boost::filesystem::is_regular_file(cdataref_path)) {
std::ifstream inFile(cdataref_path.string());
std::stringstream file_contents_ss;
file_contents_ss << inFile.rdbuf();
std::string file_contents = file_contents_ss.str();
std::vector<std::string> cdataref_entries;
boost::split(cdataref_entries, file_contents, boost::is_any_of("\n\r\t, "));
for(std::string & s : cdataref_entries) {
boost::algorithm::trim(s);
}
//remove empty lines
cdataref_entries.erase(std::remove_if(cdataref_entries.begin(), cdataref_entries.end(), [](const std::string & a)-> bool { return a.size() < 8; }), cdataref_entries.end());
all_refs.insert(all_refs.begin(), cdataref_entries.begin(), cdataref_entries.end());
log << "Found " << cdataref_entries.size() << " unique possible datarefs in " << cdataref_path << "\n";
}
//plugins
boost::filesystem::path plugin_dir_path = aircraft_dir / "plugins";
//for each directory inside plugin path
if(boost::filesystem::exists(plugin_dir_path)) {
boost::filesystem::directory_iterator dir_end_it;
for(boost::filesystem::directory_iterator dir_it(plugin_dir_path); dir_it != dir_end_it; dir_it++) {
std::vector<std::string> refs = scanPluginFolder(log, dir_it->path());
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
}
//object files in aircraft directory
std::vector<boost::filesystem::path> paths;
boost::filesystem::directory_iterator dir_end_it;
for(boost::filesystem::directory_iterator dir_it(aircraft_dir); dir_it != dir_end_it; dir_it++) {
boost::filesystem::path file_path = dir_it->path();
if(boost::filesystem::is_regular_file(file_path)) {
if(".obj" == file_path.extension() || ".acf" == file_path.extension()) {
paths.push_back(file_path);
}
}
}
paths.push_back(aircraft_dir / "Custom Avionics"); // apparently SASL / LUA code is often in this directory
paths.push_back(aircraft_dir / "objects");
boost::filesystem::path xlua_scripts_dir = aircraft_dir / "plugins" / "xlua" / "scripts"; // find xlua LUA scripts from X-Plane 11.00+
if(boost::filesystem::exists(xlua_scripts_dir)) {
paths.push_back(xlua_scripts_dir);
}
std::unordered_set<std::string> extensions_to_scan = {".obj", ".acf", ".lua"};
while(false == paths.empty()) {
boost::filesystem::path path = paths.back();
paths.pop_back();
if(boost::filesystem::is_directory(path)) {
//iterate over directory, pushing back
for(boost::filesystem::directory_iterator dir_it(path); dir_it != dir_end_it; dir_it++) {
paths.push_back(dir_it->path());
}
}
if(boost::filesystem::is_regular_file(path)) {
std::string extension = path.extension().string();
boost::algorithm::to_lower(extension);
if(extensions_to_scan.cend() != extensions_to_scan.find(extension)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
}
}
deduplicate_vector(all_refs);
log << "Found " << all_refs.size() << " unique possible datarefs for aircraft " << acf_path << "\n";
return all_refs;
}
std::vector<std::string> scanLuaFolder(std::ostream & log, const boost::filesystem::path & lua_dir_path) {
std::vector<std::string> lua_folder_datarefs;
if(boost::filesystem::is_directory(lua_dir_path)) { // if this is true, it also exists
for(auto& file_de : boost::make_iterator_range(boost::filesystem::directory_iterator(lua_dir_path), {})) {
if(file_de.path().extension() == ".lua") {
std::vector<std::string> this_script_datarefs = scanFileForDatarefStrings(log, file_de.path());
lua_folder_datarefs.insert(lua_folder_datarefs.cend(), this_script_datarefs.begin(), this_script_datarefs.end());
}
}
}
return lua_folder_datarefs;
}
std::vector<std::string> scanPluginFolder(std::ostream & log, const boost::filesystem::path & plugin_xpl_path) {
#ifdef __APPLE__
static const std::string plugin_name = "mac.xpl";
static const std::string xp11_plugin_dir_name = "mac_x64";
#elif defined _WIN32 || defined _WIN64
static const std::string plugin_name = "win.xpl";
static const std::string xp11_plugin_dir_name = "win_x64";
#else
static const std::string plugin_name = "lin.xpl";
static const std::string xp11_plugin_dir_name = "lin_x64";
#endif
std::vector<std::string> all_refs;
boost::filesystem::path plugin_dir(plugin_xpl_path.parent_path());
boost::filesystem::path plugin_old_path = plugin_dir / plugin_name;
boost::filesystem::path plugin_new_path = plugin_dir / "64" / plugin_name;
boost::filesystem::path plugin_xp11_path = plugin_dir / xp11_plugin_dir_name / (plugin_dir.filename().string() + ".xpl");
if(boost::filesystem::exists(plugin_old_path)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, plugin_old_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
if(boost::filesystem::exists(plugin_new_path)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, plugin_new_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
if(boost::filesystem::exists(plugin_xp11_path)) {
std::vector<std::string> refs = scanFileForDatarefStrings(log, plugin_xp11_path);
all_refs.insert(all_refs.begin(), refs.begin(), refs.end());
}
deduplicate_vector(all_refs);
return all_refs;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
int main () {
int rows = 4;
int cols = 4;
std::vector<std::vector<int>> matrix(rows);
auto func_init = [cols](auto vec) {
std::cout << "hello!";
vec.assign(cols,0); };
for_each(matrix.begin(), matrix.end(), func_init);
for (auto rows: matrix) {
std::cout << "row\n";
for (auto elem: rows) {
std::cout << "col\n";
std::cout << elem <<"\n";
}
}
}
<commit_msg>added first car specification<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
struct Car {
int point_start;
int point_stop;
Car(int point_start_, int point_stop_): point_start(point_start_), point_stop(point_stop_) {};
static std::shared_ptr<Car> newCar(int point_start_, int point_stop_) {
return std::make_shared<Car>(point_start_, point_stop_);
}
};
void print_matrix(std::vector<std::vector<int>> & matrix) {
for (auto row: matrix) {
for (auto elem: row) {
std::cout << elem;
}
std::cout << "\n";
}
}
int main () {
int rows = 4;
int cols = 4;
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));
auto car = Car::newCar(1,1);
//std::for_each(std::begin(matrix), std::end(matrix), [] (auto & v) mutable { for (auto& e: v) std::cin >> e;});
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libpagemaker 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/.
*/
#include <libpagemaker/libpagemaker.h>
#include <boost/scoped_ptr.hpp>
#include "PMDCollector.h"
#include "PMDParser.h"
#include "libpagemaker_utils.h"
namespace libpagemaker
{
bool PMDocument::isSupported(librevenge::RVNGInputStream * /*input*/) try
{
// TODO: Fix this.
return true;
}
catch (...)
{
return false;
}
bool PMDocument::parse(librevenge::RVNGInputStream *input, librevenge::RVNGDrawingInterface *painter)
{
PMDCollector collector;
PMD_DEBUG_MSG(("About to start parsing...\n"));
boost::scoped_ptr<librevenge::RVNGInputStream>
pmdStream(input->getSubStreamByName("PageMaker"));
PMDParser(pmdStream.get(), &collector).parse();
PMD_DEBUG_MSG(("About to start drawing...\n"));
collector.draw(painter);
return true;
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>Take ownership of the RVNGInputStream so it's not leaked.<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libpagemaker 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/.
*/
#include <libpagemaker/libpagemaker.h>
#include <boost/scoped_ptr.hpp>
#include "PMDCollector.h"
#include "PMDParser.h"
#include "libpagemaker_utils.h"
namespace libpagemaker
{
bool PMDocument::isSupported(librevenge::RVNGInputStream * /*input*/) try
{
// TODO: Fix this.
return true;
}
catch (...)
{
return false;
}
bool PMDocument::parse(librevenge::RVNGInputStream *input, librevenge::RVNGDrawingInterface *painter)
{
PMDCollector collector;
PMD_DEBUG_MSG(("About to start parsing...\n"));
boost::scoped_ptr<librevenge::RVNGInputStream>
pmdStream(input->getSubStreamByName("PageMaker"));
PMDParser(pmdStream.get(), &collector).parse();
PMD_DEBUG_MSG(("About to start drawing...\n"));
collector.draw(painter);
return true;
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|> |
<commit_before>/**
* This file is part of the Marble Desktop Globe.
*
* Copyright 2005-2007 Torsten Rahn <tackat@kde.org>"
* Copyright 2007 Inge Wallin <ingwa@kde.org>"
* Copyright 2008,2009 Jens-Michael Hoffmann <jensmh@gmx.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "TileLoader.h"
#include "global.h"
#include "GeoSceneLayer.h"
#include "GeoSceneTexture.h"
#include "HttpDownloadManager.h"
#include "DatasetProvider.h"
#include "TextureTile.h"
#include "MarbleDirs.h"
#include "MarbleModel.h"
#include "TileLoaderHelper.h"
#include <QtCore/QCache>
#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtGui/QImage>
#ifdef Q_CC_MSVC
# ifndef KDEWIN_MATH_H
long double log(int i) { return log((long double)i); }
# endif
#endif
namespace Marble
{
class TileLoaderPrivate
{
public:
TileLoaderPrivate()
: m_datasetProvider( 0 ),
m_downloadManager( 0 ),
m_layer( 0 ),
m_tileWidth( 0 ),
m_tileHeight( 0 )
{
m_tileCache.setMaxCost( 20000 * 1024 ); // Cache size measured in bytes
}
DatasetProvider *m_datasetProvider;
HttpDownloadManager *m_downloadManager;
GeoSceneLayer *m_layer;
QHash <TileId, TextureTile*> m_tilesOnDisplay;
int m_tileWidth;
int m_tileHeight;
QCache <TileId, TextureTile> m_tileCache;
};
TileLoader::TileLoader( HttpDownloadManager *downloadManager, MarbleModel* parent)
: d( new TileLoaderPrivate() ),
m_parent(parent)
{
setDownloadManager( downloadManager );
}
TileLoader::~TileLoader()
{
flush();
d->m_tileCache.clear();
if ( d->m_downloadManager != 0 )
d->m_downloadManager->disconnect( this );
delete d;
}
void TileLoader::setDownloadManager( HttpDownloadManager *downloadManager )
{
if ( d->m_downloadManager != 0 ) {
d->m_downloadManager->disconnect( this );
d->m_downloadManager = 0;
}
d->m_downloadManager = downloadManager;
if ( d->m_downloadManager != 0 ) {
connect( d->m_downloadManager, SIGNAL( downloadComplete( QString, QString ) ),
this, SLOT( reloadTile( QString, QString ) ) );
}
}
void TileLoader::setLayer( GeoSceneLayer * layer )
{
// Initialize map theme.
flush();
d->m_tileCache.clear();
if ( !layer ) {
qDebug() << "No layer specified! (GeoSceneLayer * layer = 0)";
return;
}
d->m_layer = layer;
TileId id;
TextureTile tile( id );
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
tile.loadDataset( texture, 0, 0, 0 );
// We assume that all tiles have the same size. TODO: check to be safe
d->m_tileWidth = tile.rawtile().width();
d->m_tileHeight = tile.rawtile().height();
}
void TileLoader::resetTilehash()
{
QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();
QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; pos != end; ++pos ) {
pos.value()->setUsed( false );
}
}
void TileLoader::cleanupTilehash()
{
// Make sure that tiles which haven't been used during the last
// rendering of the map at all get removed from the tile hash.
QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );
while ( it.hasNext() ) {
it.next();
if ( !it.value()->used() ) {
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
d->m_tilesOnDisplay.remove( it.key() );
}
}
}
void TileLoader::flush()
{
// Remove all tiles from m_tilesOnDisplay
QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );
while ( it.hasNext() ) {
it.next();
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
d->m_tilesOnDisplay.remove( it.key() );
}
d->m_tilesOnDisplay.clear();
}
int TileLoader::tileWidth() const
{
return d->m_tileWidth;
}
int TileLoader::tileHeight() const
{
return d->m_tileHeight;
}
int TileLoader::globalWidth( int level ) const
{
if ( !d->m_layer ) return 0;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
return d->m_tileWidth * TileLoaderHelper::levelToColumn(
texture->levelZeroColumns(), level );
}
int TileLoader::globalHeight( int level ) const
{
if ( !d->m_layer ) return 0;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
return d->m_tileHeight * TileLoaderHelper::levelToRow(
texture->levelZeroRows(), level );
}
TextureTile* TileLoader::loadTile( int tilx, int tily, int tileLevel )
{
if ( !d->m_layer ) return 0;
TileId tileId( tileLevel, tilx, tily );
// check if the tile is in the hash
TextureTile * tile = d->m_tilesOnDisplay.value( tileId, 0 );
if ( tile ) {
tile->setUsed( true );
return tile;
}
// here ends the performance critical section of this method
// the tile was not in the hash or has been removed because of expiration
// so check if it is in the cache
tile = d->m_tileCache.take( tileId );
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
if ( tile ) {
// the tile was in the cache, but is it up to date?
const QDateTime now = QDateTime::currentDateTime();
if ( tile->created().secsTo( now ) < texture->expire()) {
d->m_tilesOnDisplay[tileId] = tile;
tile->setUsed( true );
return tile;
} else {
delete tile;
tile = 0;
}
}
// tile (valid) has not been found in hash or cache, so load it from disk
// and place it in the hash from where it will get transfered to the cache
// qDebug() << "load Tile from Disk: " << tileId.toString();
tile = new TextureTile( tileId );
d->m_tilesOnDisplay[tileId] = tile;
// FIXME: Implement asynchronous tile loading
// d->m_datasetProvider->loadDatasets( tile );
if ( d->m_downloadManager != 0 ) {
connect( tile, SIGNAL( downloadTile( QUrl, QString, QString ) ),
d->m_downloadManager, SLOT( addJob( QUrl, QString, QString ) ) );
}
connect( tile, SIGNAL( tileUpdateDone() ),
this, SIGNAL( tileUpdateAvailable() ) );
tile->loadDataset( texture, tileLevel, tilx, tily, &( d->m_tileCache ) );
tile->initJumpTables( false );
// TODO should emit signal rather than directly calling paintTile
// emit paintTile( tile, tilx, tily, tileLevel, d->m_theme, false );
m_parent->paintTile( tile, tilx, tily, tileLevel, texture, false );
return tile;
}
GeoSceneLayer * TileLoader::layer() const
{
return d->m_layer;
}
quint64 TileLoader::volatileCacheLimit() const
{
return d->m_tileCache.maxCost() / 1024;
}
QList<TileId> TileLoader::tilesOnDisplay() const
{
QList<TileId> result;
QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();
QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; pos != end; ++pos ) {
if ( pos.value()->used() ) {
result.append( pos.key() );
}
}
return result;
}
int TileLoader::maxPartialTileLevel( GeoSceneLayer * layer )
{
int maxtilelevel = -1;
if ( !layer ) return maxtilelevel;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );
if ( !texture ) return maxtilelevel;
QString tilepath = MarbleDirs::path( TileLoaderHelper::themeStr( texture ) );
// qDebug() << "TileLoader::maxPartialTileLevel tilepath" << tilepath;
QStringList leveldirs = ( QDir( tilepath ) ).entryList( QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );
bool ok = true;
QStringList::const_iterator pos = leveldirs.constBegin();
QStringList::const_iterator const end = leveldirs.constEnd();
for (; pos != end; ++pos ) {
int value = (*pos).toInt( &ok, 10 );
if ( ok && value > maxtilelevel )
maxtilelevel = value;
}
// qDebug() << "Detected maximum tile level that contains data: "
// << maxtilelevel;
return maxtilelevel;
}
bool TileLoader::baseTilesAvailable( GeoSceneLayer * layer )
{
if ( !layer ) return false;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );
const int levelZeroColumns = texture->levelZeroColumns();
const int levelZeroRows = texture->levelZeroRows();
bool noerr = true;
// Check whether the tiles from the lowest texture level are available
//
for ( int column = 0; noerr && column < levelZeroColumns; ++column ) {
for ( int row = 0; noerr && row < levelZeroRows; ++row ) {
const QString tilepath = MarbleDirs::path( TileLoaderHelper::relativeTileFileName(
texture, 0, column, row ));
noerr = QFile::exists( tilepath );
}
}
return noerr;
}
void TileLoader::setVolatileCacheLimit( quint64 kiloBytes )
{
qDebug() << QString("Setting tile cache to %1 kilobytes.").arg( kiloBytes );
d->m_tileCache.setMaxCost( kiloBytes * 1024 );
}
void TileLoader::reloadTile( const QString &idStr )
{
if ( !d->m_layer ) return;
// qDebug() << "TileLoader::reloadTile:" << idStr;
const TileId id = TileId::fromString( idStr );
if ( d->m_tilesOnDisplay.contains( id ) ) {
int level = id.zoomLevel();
int y = id.y();
int x = id.x();
// TODO should emit signal rather than directly calling paintTile
// emit paintTile( d->m_tilesOnDisplay[id], x, y, level, d->m_theme, true );
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
(d->m_tilesOnDisplay[id])->loadDataset( texture, level, x, y, &( d->m_tileCache ) );
m_parent->paintTile( d->m_tilesOnDisplay[id], x, y, level, texture, true );
// (d->m_tilesOnDisplay[id])->reloadTile( x, y, level, d->m_theme );
} else {
// Remove "false" tile from cache so it doesn't get loaded anymore
d->m_tileCache.remove( id );
qDebug() << "No such ID:" << idStr;
}
}
void TileLoader::reloadTile( const QString &relativeUrlString, const QString &_id )
{
Q_UNUSED( relativeUrlString );
// qDebug() << "Reloading Tile" << relativeUrlString << "id:" << _id;
reloadTile( _id );
}
void TileLoader::reloadTile( const QString& serverUrlString, const QString &relativeUrlString,
const QString &_id )
{
Q_UNUSED( serverUrlString );
Q_UNUSED( relativeUrlString );
// qDebug() << "Reloading Tile" << serverUrlString << relativeUrlString << "id:" << _id;
reloadTile( _id );
}
void TileLoader::update()
{
qDebug() << "TileLoader::update()";
flush(); // trigger a reload of all tiles that are currently in use
d->m_tileCache.clear(); // clear the tile cache in physical memory
emit tileUpdateAvailable();
}
}
#include "TileLoader.moc"
<commit_msg>Remove unnecessary braces.<commit_after>/**
* This file is part of the Marble Desktop Globe.
*
* Copyright 2005-2007 Torsten Rahn <tackat@kde.org>"
* Copyright 2007 Inge Wallin <ingwa@kde.org>"
* Copyright 2008,2009 Jens-Michael Hoffmann <jensmh@gmx.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "TileLoader.h"
#include "global.h"
#include "GeoSceneLayer.h"
#include "GeoSceneTexture.h"
#include "HttpDownloadManager.h"
#include "DatasetProvider.h"
#include "TextureTile.h"
#include "MarbleDirs.h"
#include "MarbleModel.h"
#include "TileLoaderHelper.h"
#include <QtCore/QCache>
#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtGui/QImage>
#ifdef Q_CC_MSVC
# ifndef KDEWIN_MATH_H
long double log(int i) { return log((long double)i); }
# endif
#endif
namespace Marble
{
class TileLoaderPrivate
{
public:
TileLoaderPrivate()
: m_datasetProvider( 0 ),
m_downloadManager( 0 ),
m_layer( 0 ),
m_tileWidth( 0 ),
m_tileHeight( 0 )
{
m_tileCache.setMaxCost( 20000 * 1024 ); // Cache size measured in bytes
}
DatasetProvider *m_datasetProvider;
HttpDownloadManager *m_downloadManager;
GeoSceneLayer *m_layer;
QHash <TileId, TextureTile*> m_tilesOnDisplay;
int m_tileWidth;
int m_tileHeight;
QCache <TileId, TextureTile> m_tileCache;
};
TileLoader::TileLoader( HttpDownloadManager *downloadManager, MarbleModel* parent)
: d( new TileLoaderPrivate() ),
m_parent(parent)
{
setDownloadManager( downloadManager );
}
TileLoader::~TileLoader()
{
flush();
d->m_tileCache.clear();
if ( d->m_downloadManager != 0 )
d->m_downloadManager->disconnect( this );
delete d;
}
void TileLoader::setDownloadManager( HttpDownloadManager *downloadManager )
{
if ( d->m_downloadManager != 0 ) {
d->m_downloadManager->disconnect( this );
d->m_downloadManager = 0;
}
d->m_downloadManager = downloadManager;
if ( d->m_downloadManager != 0 ) {
connect( d->m_downloadManager, SIGNAL( downloadComplete( QString, QString ) ),
this, SLOT( reloadTile( QString, QString ) ) );
}
}
void TileLoader::setLayer( GeoSceneLayer * layer )
{
// Initialize map theme.
flush();
d->m_tileCache.clear();
if ( !layer ) {
qDebug() << "No layer specified! (GeoSceneLayer * layer = 0)";
return;
}
d->m_layer = layer;
TileId id;
TextureTile tile( id );
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
tile.loadDataset( texture, 0, 0, 0 );
// We assume that all tiles have the same size. TODO: check to be safe
d->m_tileWidth = tile.rawtile().width();
d->m_tileHeight = tile.rawtile().height();
}
void TileLoader::resetTilehash()
{
QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();
QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; pos != end; ++pos ) {
pos.value()->setUsed( false );
}
}
void TileLoader::cleanupTilehash()
{
// Make sure that tiles which haven't been used during the last
// rendering of the map at all get removed from the tile hash.
QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );
while ( it.hasNext() ) {
it.next();
if ( !it.value()->used() ) {
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
d->m_tilesOnDisplay.remove( it.key() );
}
}
}
void TileLoader::flush()
{
// Remove all tiles from m_tilesOnDisplay
QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );
while ( it.hasNext() ) {
it.next();
// If insert call result is false then the cache is too small to store the tile
// but the item will get deleted nevertheless and the pointer we have
// doesn't get set to zero (so don't delete it in this case or it will crash!)
d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );
d->m_tilesOnDisplay.remove( it.key() );
}
d->m_tilesOnDisplay.clear();
}
int TileLoader::tileWidth() const
{
return d->m_tileWidth;
}
int TileLoader::tileHeight() const
{
return d->m_tileHeight;
}
int TileLoader::globalWidth( int level ) const
{
if ( !d->m_layer ) return 0;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
return d->m_tileWidth * TileLoaderHelper::levelToColumn(
texture->levelZeroColumns(), level );
}
int TileLoader::globalHeight( int level ) const
{
if ( !d->m_layer ) return 0;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
return d->m_tileHeight * TileLoaderHelper::levelToRow(
texture->levelZeroRows(), level );
}
TextureTile* TileLoader::loadTile( int tilx, int tily, int tileLevel )
{
if ( !d->m_layer ) return 0;
TileId tileId( tileLevel, tilx, tily );
// check if the tile is in the hash
TextureTile * tile = d->m_tilesOnDisplay.value( tileId, 0 );
if ( tile ) {
tile->setUsed( true );
return tile;
}
// here ends the performance critical section of this method
// the tile was not in the hash or has been removed because of expiration
// so check if it is in the cache
tile = d->m_tileCache.take( tileId );
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
if ( tile ) {
// the tile was in the cache, but is it up to date?
const QDateTime now = QDateTime::currentDateTime();
if ( tile->created().secsTo( now ) < texture->expire()) {
d->m_tilesOnDisplay[tileId] = tile;
tile->setUsed( true );
return tile;
} else {
delete tile;
tile = 0;
}
}
// tile (valid) has not been found in hash or cache, so load it from disk
// and place it in the hash from where it will get transfered to the cache
// qDebug() << "load Tile from Disk: " << tileId.toString();
tile = new TextureTile( tileId );
d->m_tilesOnDisplay[tileId] = tile;
// FIXME: Implement asynchronous tile loading
// d->m_datasetProvider->loadDatasets( tile );
if ( d->m_downloadManager != 0 ) {
connect( tile, SIGNAL( downloadTile( QUrl, QString, QString ) ),
d->m_downloadManager, SLOT( addJob( QUrl, QString, QString ) ) );
}
connect( tile, SIGNAL( tileUpdateDone() ),
this, SIGNAL( tileUpdateAvailable() ) );
tile->loadDataset( texture, tileLevel, tilx, tily, &d->m_tileCache );
tile->initJumpTables( false );
// TODO should emit signal rather than directly calling paintTile
// emit paintTile( tile, tilx, tily, tileLevel, d->m_theme, false );
m_parent->paintTile( tile, tilx, tily, tileLevel, texture, false );
return tile;
}
GeoSceneLayer * TileLoader::layer() const
{
return d->m_layer;
}
quint64 TileLoader::volatileCacheLimit() const
{
return d->m_tileCache.maxCost() / 1024;
}
QList<TileId> TileLoader::tilesOnDisplay() const
{
QList<TileId> result;
QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();
QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();
for (; pos != end; ++pos ) {
if ( pos.value()->used() ) {
result.append( pos.key() );
}
}
return result;
}
int TileLoader::maxPartialTileLevel( GeoSceneLayer * layer )
{
int maxtilelevel = -1;
if ( !layer ) return maxtilelevel;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );
if ( !texture ) return maxtilelevel;
QString tilepath = MarbleDirs::path( TileLoaderHelper::themeStr( texture ) );
// qDebug() << "TileLoader::maxPartialTileLevel tilepath" << tilepath;
QStringList leveldirs = QDir( tilepath ).entryList( QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );
bool ok = true;
QStringList::const_iterator pos = leveldirs.constBegin();
QStringList::const_iterator const end = leveldirs.constEnd();
for (; pos != end; ++pos ) {
int value = (*pos).toInt( &ok, 10 );
if ( ok && value > maxtilelevel )
maxtilelevel = value;
}
// qDebug() << "Detected maximum tile level that contains data: "
// << maxtilelevel;
return maxtilelevel;
}
bool TileLoader::baseTilesAvailable( GeoSceneLayer * layer )
{
if ( !layer ) return false;
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );
const int levelZeroColumns = texture->levelZeroColumns();
const int levelZeroRows = texture->levelZeroRows();
bool noerr = true;
// Check whether the tiles from the lowest texture level are available
//
for ( int column = 0; noerr && column < levelZeroColumns; ++column ) {
for ( int row = 0; noerr && row < levelZeroRows; ++row ) {
const QString tilepath = MarbleDirs::path( TileLoaderHelper::relativeTileFileName(
texture, 0, column, row ));
noerr = QFile::exists( tilepath );
}
}
return noerr;
}
void TileLoader::setVolatileCacheLimit( quint64 kiloBytes )
{
qDebug() << QString("Setting tile cache to %1 kilobytes.").arg( kiloBytes );
d->m_tileCache.setMaxCost( kiloBytes * 1024 );
}
void TileLoader::reloadTile( const QString &idStr )
{
if ( !d->m_layer ) return;
// qDebug() << "TileLoader::reloadTile:" << idStr;
const TileId id = TileId::fromString( idStr );
if ( d->m_tilesOnDisplay.contains( id ) ) {
int level = id.zoomLevel();
int y = id.y();
int x = id.x();
// TODO should emit signal rather than directly calling paintTile
// emit paintTile( d->m_tilesOnDisplay[id], x, y, level, d->m_theme, true );
GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );
d->m_tilesOnDisplay[id]->loadDataset( texture, level, x, y, &d->m_tileCache );
m_parent->paintTile( d->m_tilesOnDisplay[id], x, y, level, texture, true );
// (d->m_tilesOnDisplay[id])->reloadTile( x, y, level, d->m_theme );
} else {
// Remove "false" tile from cache so it doesn't get loaded anymore
d->m_tileCache.remove( id );
qDebug() << "No such ID:" << idStr;
}
}
void TileLoader::reloadTile( const QString &relativeUrlString, const QString &_id )
{
Q_UNUSED( relativeUrlString );
// qDebug() << "Reloading Tile" << relativeUrlString << "id:" << _id;
reloadTile( _id );
}
void TileLoader::reloadTile( const QString& serverUrlString, const QString &relativeUrlString,
const QString &_id )
{
Q_UNUSED( serverUrlString );
Q_UNUSED( relativeUrlString );
// qDebug() << "Reloading Tile" << serverUrlString << relativeUrlString << "id:" << _id;
reloadTile( _id );
}
void TileLoader::update()
{
qDebug() << "TileLoader::update()";
flush(); // trigger a reload of all tiles that are currently in use
d->m_tileCache.clear(); // clear the tile cache in physical memory
emit tileUpdateAvailable();
}
}
#include "TileLoader.moc"
<|endoftext|> |
<commit_before><commit_msg>Use require_var_t to simplify code<commit_after><|endoftext|> |
<commit_before>#include "findManager.h"
FindManager::FindManager(qrRepo::RepoControlInterface &controlApi
, qrRepo::LogicalRepoApi &logicalApi
, qReal::gui::MainWindowInterpretersInterface *mainWindow
, FindReplaceDialog *findReplaceDialog
, QObject *parent)
: QObject(parent)
, mControlApi(controlApi)
, mLogicalApi(logicalApi)
, mFindReplaceDialog(findReplaceDialog)
, mMainWindow(mainWindow)
{
}
void FindManager::handleRefsDialog(qReal::Id const &id)
{
mMainWindow->selectItemOrDiagram(id);
}
qReal::IdList FindManager::foundByMode(QString key, QString currentMode, bool sensitivity
, bool regExpression)
{
// TODO: replace mode string with modifiers
if (currentMode == tr("by name")) {
return mControlApi.findElementsByName(key, sensitivity, regExpression);
} else if (currentMode == tr("by type")) {
return mLogicalApi.elementsByType(key, sensitivity, regExpression);
} else if (currentMode == tr("by property")) {
return mControlApi.elementsByProperty(key, sensitivity, regExpression);
} else if (currentMode == tr("by property content")) {
return mControlApi.elementsByPropertyContent(key, sensitivity, regExpression);
} else {
return qReal::IdList();
}
}
QMap<QString, QString> FindManager::findItems(QStringList const &searchData)
{
QMap<QString, QString> found;
bool sensitivity = searchData.contains(tr("case sensitivity"));
bool regExpression = searchData.contains(tr("by regular expression"));
for(int i = 1; i < searchData.length(); i++) {
if (searchData[i] != tr("case sensitivity") && searchData[i] != tr("by regular expression")) {
qReal::IdList byMode = foundByMode(searchData.first(), searchData[i], sensitivity
, regExpression);
foreach (qReal::Id currentId, byMode) {
if (found.contains(currentId.toString())) {
found[currentId.toString()] += tr(", ") + searchData[i];
continue;
}
found.insert(currentId.toString(), tr(" :: ") + searchData[i]);
}
}
}
return found;
}
void FindManager::handleFindDialog(QStringList const &searchData)
{
mFindReplaceDialog->initIds(findItems(searchData));
}
void FindManager::handleReplaceDialog(QStringList &searchData)
{
if (searchData.contains(tr("by name"))) {
qReal::IdList toRename = foundByMode(searchData.first(), tr("by name")
, searchData.contains(tr("case sensitivity"))
,searchData.contains(tr("by regular expression")));
foreach (qReal::Id currentId, toRename) {
mLogicalApi.setName(currentId, searchData[1]);
}
}
if (searchData.contains(tr("by property content"))) {
qReal::IdList toRename = foundByMode(searchData.first(), tr("by property content")
, searchData.contains(tr("case sensitivity"))
, searchData.contains(tr("by regular expression")));
mLogicalApi.replaceProperties(toRename, searchData[0], searchData[1]);
}
}
<commit_msg>again styleguide<commit_after>#include "findManager.h"
FindManager::FindManager(qrRepo::RepoControlInterface &controlApi
, qrRepo::LogicalRepoApi &logicalApi
, qReal::gui::MainWindowInterpretersInterface *mainWindow
, FindReplaceDialog *findReplaceDialog
, QObject *parent)
: QObject(parent)
, mControlApi(controlApi)
, mLogicalApi(logicalApi)
, mFindReplaceDialog(findReplaceDialog)
, mMainWindow(mainWindow)
{
}
void FindManager::handleRefsDialog(qReal::Id const &id)
{
mMainWindow->selectItemOrDiagram(id);
}
qReal::IdList FindManager::foundByMode(QString key, QString currentMode, bool sensitivity
, bool regExpression)
{
// TODO: replace mode string with modifiers
if (currentMode == tr("by name")) {
return mControlApi.findElementsByName(key, sensitivity, regExpression);
} else if (currentMode == tr("by type")) {
return mLogicalApi.elementsByType(key, sensitivity, regExpression);
} else if (currentMode == tr("by property")) {
return mControlApi.elementsByProperty(key, sensitivity, regExpression);
} else if (currentMode == tr("by property content")) {
return mControlApi.elementsByPropertyContent(key, sensitivity, regExpression);
} else {
return qReal::IdList();
}
}
QMap<QString, QString> FindManager::findItems(QStringList const &searchData)
{
QMap<QString, QString> found;
bool sensitivity = searchData.contains(tr("case sensitivity"));
bool regExpression = searchData.contains(tr("by regular expression"));
for(int i = 1; i < searchData.length(); i++) {
if (searchData[i] != tr("case sensitivity") && searchData[i] != tr("by regular expression")) {
qReal::IdList byMode = foundByMode(searchData.first(), searchData[i], sensitivity
, regExpression);
foreach (qReal::Id currentId, byMode) {
if (found.contains(currentId.toString())) {
found[currentId.toString()] += tr(", ") + searchData[i];
continue;
}
found.insert(currentId.toString(), tr(" :: ") + searchData[i]);
}
}
}
return found;
}
void FindManager::handleFindDialog(QStringList const &searchData)
{
mFindReplaceDialog->initIds(findItems(searchData));
}
void FindManager::handleReplaceDialog(QStringList &searchData)
{
if (searchData.contains(tr("by name"))) {
qReal::IdList toRename = foundByMode(searchData.first(), tr("by name")
, searchData.contains(tr("case sensitivity"))
, searchData.contains(tr("by regular expression")));
foreach (qReal::Id currentId, toRename) {
mLogicalApi.setName(currentId, searchData[1]);
}
}
if (searchData.contains(tr("by property content"))) {
qReal::IdList toRename = foundByMode(searchData.first(), tr("by property content")
, searchData.contains(tr("case sensitivity"))
, searchData.contains(tr("by regular expression")));
mLogicalApi.replaceProperties(toRename, searchData[0], searchData[1]);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 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 "quic/qbone/qbone_session_base.h"
#include <netinet/icmp6.h>
#include <netinet/ip6.h>
#include <utility>
#include "absl/strings/string_view.h"
#include "quic/core/quic_buffer_allocator.h"
#include "quic/core/quic_data_reader.h"
#include "quic/core/quic_types.h"
#include "quic/platform/api/quic_exported_stats.h"
#include "quic/platform/api/quic_logging.h"
#include "quic/platform/api/quic_testvalue.h"
#include "quic/qbone/platform/icmp_packet.h"
#include "quic/qbone/qbone_constants.h"
DEFINE_QUIC_COMMAND_LINE_FLAG(
bool,
qbone_close_ephemeral_frames,
true,
"If true, we'll call CloseStream even when we receive ephemeral frames.");
namespace quic {
#define ENDPOINT \
(perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ")
QboneSessionBase::QboneSessionBase(
QuicConnection* connection,
Visitor* owner,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions,
QbonePacketWriter* writer)
: QuicSession(connection,
owner,
config,
supported_versions,
/*num_expected_unidirectional_static_streams = */ 0) {
set_writer(writer);
const uint32_t max_streams =
(std::numeric_limits<uint32_t>::max() / kMaxAvailableStreamsMultiplier) -
1;
this->config()->SetMaxBidirectionalStreamsToSend(max_streams);
if (VersionHasIetfQuicFrames(transport_version())) {
this->config()->SetMaxUnidirectionalStreamsToSend(max_streams);
}
}
QboneSessionBase::~QboneSessionBase() {}
void QboneSessionBase::Initialize() {
crypto_stream_ = CreateCryptoStream();
QuicSession::Initialize();
}
const QuicCryptoStream* QboneSessionBase::GetCryptoStream() const {
return crypto_stream_.get();
}
QuicCryptoStream* QboneSessionBase::GetMutableCryptoStream() {
return crypto_stream_.get();
}
QuicStream* QboneSessionBase::CreateOutgoingStream() {
return ActivateDataStream(
CreateDataStream(GetNextOutgoingUnidirectionalStreamId()));
}
void QboneSessionBase::OnStreamFrame(const QuicStreamFrame& frame) {
if (frame.offset == 0 && frame.fin && frame.data_length > 0) {
++num_ephemeral_packets_;
ProcessPacketFromPeer(
absl::string_view(frame.data_buffer, frame.data_length));
flow_controller()->AddBytesConsumed(frame.data_length);
// TODO(b/147817422): Add a counter for how many streams were actually
// closed here.
if (GetQuicFlag(FLAGS_qbone_close_ephemeral_frames)) {
ResetStream(frame.stream_id, QUIC_STREAM_CANCELLED);
}
return;
}
QuicSession::OnStreamFrame(frame);
}
void QboneSessionBase::OnMessageReceived(absl::string_view message) {
++num_message_packets_;
ProcessPacketFromPeer(message);
}
QuicStream* QboneSessionBase::CreateIncomingStream(QuicStreamId id) {
return ActivateDataStream(CreateDataStream(id));
}
QuicStream* QboneSessionBase::CreateIncomingStream(PendingStream* /*pending*/) {
QUIC_NOTREACHED();
return nullptr;
}
bool QboneSessionBase::ShouldKeepConnectionAlive() const {
// QBONE connections stay alive until they're explicitly closed.
return true;
}
std::unique_ptr<QuicStream> QboneSessionBase::CreateDataStream(
QuicStreamId id) {
if (crypto_stream_ == nullptr || !crypto_stream_->encryption_established()) {
// Encryption not active so no stream created
return nullptr;
}
if (IsIncomingStream(id)) {
++num_streamed_packets_;
return std::make_unique<QboneReadOnlyStream>(id, this);
}
return std::make_unique<QboneWriteOnlyStream>(id, this);
}
QuicStream* QboneSessionBase::ActivateDataStream(
std::unique_ptr<QuicStream> stream) {
// Transfer ownership of the data stream to the session via ActivateStream().
QuicStream* raw = stream.get();
if (stream) {
// Make QuicSession take ownership of the stream.
ActivateStream(std::move(stream));
}
return raw;
}
void QboneSessionBase::SendPacketToPeer(absl::string_view packet) {
if (crypto_stream_ == nullptr) {
QUIC_BUG(quic_bug_10987_1)
<< "Attempting to send packet before encryption established";
return;
}
if (send_packets_as_messages_) {
QuicMemSlice slice(QuicBuffer::Copy(
connection()->helper()->GetStreamSendBufferAllocator(), packet));
switch (SendMessage(absl::MakeSpan(&slice, 1), /*flush=*/true).status) {
case MESSAGE_STATUS_SUCCESS:
break;
case MESSAGE_STATUS_TOO_LARGE: {
if (packet.size() < sizeof(ip6_hdr)) {
QUIC_BUG(quic_bug_10987_2)
<< "Dropped malformed packet: IPv6 header too short";
break;
}
auto* header = reinterpret_cast<const ip6_hdr*>(packet.begin());
icmp6_hdr icmp_header{};
icmp_header.icmp6_type = ICMP6_PACKET_TOO_BIG;
icmp_header.icmp6_mtu =
connection()->GetGuaranteedLargestMessagePayload();
CreateIcmpPacket(header->ip6_dst, header->ip6_src, icmp_header, packet,
[this](absl::string_view icmp_packet) {
writer_->WritePacketToNetwork(icmp_packet.data(),
icmp_packet.size());
});
break;
}
case MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED:
QUIC_BUG(quic_bug_10987_3)
<< "MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED";
break;
case MESSAGE_STATUS_UNSUPPORTED:
QUIC_BUG(quic_bug_10987_4) << "MESSAGE_STATUS_UNSUPPORTED";
break;
case MESSAGE_STATUS_BLOCKED:
QUIC_BUG(quic_bug_10987_5) << "MESSAGE_STATUS_BLOCKED";
break;
case MESSAGE_STATUS_INTERNAL_ERROR:
QUIC_BUG(quic_bug_10987_6) << "MESSAGE_STATUS_INTERNAL_ERROR";
break;
}
return;
}
// QBONE streams are ephemeral.
QuicStream* stream = CreateOutgoingStream();
if (!stream) {
QUIC_BUG(quic_bug_10987_7) << "Failed to create an outgoing QBONE stream.";
return;
}
QboneWriteOnlyStream* qbone_stream =
static_cast<QboneWriteOnlyStream*>(stream);
qbone_stream->WritePacketToQuicStream(packet);
}
uint64_t QboneSessionBase::GetNumEphemeralPackets() const {
return num_ephemeral_packets_;
}
uint64_t QboneSessionBase::GetNumStreamedPackets() const {
return num_streamed_packets_;
}
uint64_t QboneSessionBase::GetNumMessagePackets() const {
return num_message_packets_;
}
uint64_t QboneSessionBase::GetNumFallbackToStream() const {
return num_fallback_to_stream_;
}
void QboneSessionBase::set_writer(QbonePacketWriter* writer) {
writer_ = writer;
quic::AdjustTestValue("quic_QbonePacketWriter", &writer_);
}
} // namespace quic
<commit_msg>Consult session instead of crypto_stream on whether encryption is established in QBONE sessions as the former can be overridden to incorporate other signals.<commit_after>// Copyright (c) 2019 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 "quic/qbone/qbone_session_base.h"
#include <netinet/icmp6.h>
#include <netinet/ip6.h>
#include <utility>
#include "absl/strings/string_view.h"
#include "quic/core/quic_buffer_allocator.h"
#include "quic/core/quic_data_reader.h"
#include "quic/core/quic_types.h"
#include "quic/platform/api/quic_exported_stats.h"
#include "quic/platform/api/quic_logging.h"
#include "quic/platform/api/quic_testvalue.h"
#include "quic/qbone/platform/icmp_packet.h"
#include "quic/qbone/qbone_constants.h"
DEFINE_QUIC_COMMAND_LINE_FLAG(
bool,
qbone_close_ephemeral_frames,
true,
"If true, we'll call CloseStream even when we receive ephemeral frames.");
namespace quic {
#define ENDPOINT \
(perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ")
QboneSessionBase::QboneSessionBase(
QuicConnection* connection,
Visitor* owner,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions,
QbonePacketWriter* writer)
: QuicSession(connection,
owner,
config,
supported_versions,
/*num_expected_unidirectional_static_streams = */ 0) {
set_writer(writer);
const uint32_t max_streams =
(std::numeric_limits<uint32_t>::max() / kMaxAvailableStreamsMultiplier) -
1;
this->config()->SetMaxBidirectionalStreamsToSend(max_streams);
if (VersionHasIetfQuicFrames(transport_version())) {
this->config()->SetMaxUnidirectionalStreamsToSend(max_streams);
}
}
QboneSessionBase::~QboneSessionBase() {}
void QboneSessionBase::Initialize() {
crypto_stream_ = CreateCryptoStream();
QuicSession::Initialize();
}
const QuicCryptoStream* QboneSessionBase::GetCryptoStream() const {
return crypto_stream_.get();
}
QuicCryptoStream* QboneSessionBase::GetMutableCryptoStream() {
return crypto_stream_.get();
}
QuicStream* QboneSessionBase::CreateOutgoingStream() {
return ActivateDataStream(
CreateDataStream(GetNextOutgoingUnidirectionalStreamId()));
}
void QboneSessionBase::OnStreamFrame(const QuicStreamFrame& frame) {
if (frame.offset == 0 && frame.fin && frame.data_length > 0) {
++num_ephemeral_packets_;
ProcessPacketFromPeer(
absl::string_view(frame.data_buffer, frame.data_length));
flow_controller()->AddBytesConsumed(frame.data_length);
// TODO(b/147817422): Add a counter for how many streams were actually
// closed here.
if (GetQuicFlag(FLAGS_qbone_close_ephemeral_frames)) {
ResetStream(frame.stream_id, QUIC_STREAM_CANCELLED);
}
return;
}
QuicSession::OnStreamFrame(frame);
}
void QboneSessionBase::OnMessageReceived(absl::string_view message) {
++num_message_packets_;
ProcessPacketFromPeer(message);
}
QuicStream* QboneSessionBase::CreateIncomingStream(QuicStreamId id) {
return ActivateDataStream(CreateDataStream(id));
}
QuicStream* QboneSessionBase::CreateIncomingStream(PendingStream* /*pending*/) {
QUIC_NOTREACHED();
return nullptr;
}
bool QboneSessionBase::ShouldKeepConnectionAlive() const {
// QBONE connections stay alive until they're explicitly closed.
return true;
}
std::unique_ptr<QuicStream> QboneSessionBase::CreateDataStream(
QuicStreamId id) {
if (!IsEncryptionEstablished()) {
// Encryption not active so no stream created
return nullptr;
}
if (IsIncomingStream(id)) {
++num_streamed_packets_;
return std::make_unique<QboneReadOnlyStream>(id, this);
}
return std::make_unique<QboneWriteOnlyStream>(id, this);
}
QuicStream* QboneSessionBase::ActivateDataStream(
std::unique_ptr<QuicStream> stream) {
// Transfer ownership of the data stream to the session via ActivateStream().
QuicStream* raw = stream.get();
if (stream) {
// Make QuicSession take ownership of the stream.
ActivateStream(std::move(stream));
}
return raw;
}
void QboneSessionBase::SendPacketToPeer(absl::string_view packet) {
if (crypto_stream_ == nullptr) {
QUIC_BUG(quic_bug_10987_1)
<< "Attempting to send packet before encryption established";
return;
}
if (send_packets_as_messages_) {
QuicMemSlice slice(QuicBuffer::Copy(
connection()->helper()->GetStreamSendBufferAllocator(), packet));
switch (SendMessage(absl::MakeSpan(&slice, 1), /*flush=*/true).status) {
case MESSAGE_STATUS_SUCCESS:
break;
case MESSAGE_STATUS_TOO_LARGE: {
if (packet.size() < sizeof(ip6_hdr)) {
QUIC_BUG(quic_bug_10987_2)
<< "Dropped malformed packet: IPv6 header too short";
break;
}
auto* header = reinterpret_cast<const ip6_hdr*>(packet.begin());
icmp6_hdr icmp_header{};
icmp_header.icmp6_type = ICMP6_PACKET_TOO_BIG;
icmp_header.icmp6_mtu =
connection()->GetGuaranteedLargestMessagePayload();
CreateIcmpPacket(header->ip6_dst, header->ip6_src, icmp_header, packet,
[this](absl::string_view icmp_packet) {
writer_->WritePacketToNetwork(icmp_packet.data(),
icmp_packet.size());
});
break;
}
case MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED:
QUIC_BUG(quic_bug_10987_3)
<< "MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED";
break;
case MESSAGE_STATUS_UNSUPPORTED:
QUIC_BUG(quic_bug_10987_4) << "MESSAGE_STATUS_UNSUPPORTED";
break;
case MESSAGE_STATUS_BLOCKED:
QUIC_BUG(quic_bug_10987_5) << "MESSAGE_STATUS_BLOCKED";
break;
case MESSAGE_STATUS_INTERNAL_ERROR:
QUIC_BUG(quic_bug_10987_6) << "MESSAGE_STATUS_INTERNAL_ERROR";
break;
}
return;
}
// QBONE streams are ephemeral.
QuicStream* stream = CreateOutgoingStream();
if (!stream) {
QUIC_BUG(quic_bug_10987_7) << "Failed to create an outgoing QBONE stream.";
return;
}
QboneWriteOnlyStream* qbone_stream =
static_cast<QboneWriteOnlyStream*>(stream);
qbone_stream->WritePacketToQuicStream(packet);
}
uint64_t QboneSessionBase::GetNumEphemeralPackets() const {
return num_ephemeral_packets_;
}
uint64_t QboneSessionBase::GetNumStreamedPackets() const {
return num_streamed_packets_;
}
uint64_t QboneSessionBase::GetNumMessagePackets() const {
return num_message_packets_;
}
uint64_t QboneSessionBase::GetNumFallbackToStream() const {
return num_fallback_to_stream_;
}
void QboneSessionBase::set_writer(QbonePacketWriter* writer) {
writer_ = writer;
quic::AdjustTestValue("quic_QbonePacketWriter", &writer_);
}
} // namespace quic
<|endoftext|> |
<commit_before>#include "rapid_utils/command_line.h"
#include <iostream>
#include "boost/algorithm/string.hpp"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
namespace rapid {
namespace utils {
CommandLine::CommandLine() : commands_() {}
void CommandLine::AddCommand(CommandInterface* command) {
commands_.push_back(command);
}
bool CommandLine::Next() {
ShowCommands();
cout << "Enter a command: ";
string input;
if (std::getline(std::cin, input)) {
cout << endl;
} else {
return false;
}
CommandInterface* command;
vector<string> args;
bool valid = ParseLine(input, &command, &args);
if (valid) {
command->Execute(args);
cout << endl;
} else {
cout << "Invalid command." << endl;
cout << endl;
}
return true;
}
void CommandLine::ShowCommands() const {
cout << "Commands:" << endl;
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
cout << " " << command->name() << " " << command->description() << endl;
}
}
bool CommandLine::ParseLine(const std::string& line,
CommandInterface** command_pp,
std::vector<std::string>* args) const {
vector<string> tokens;
boost::split(tokens, line, boost::is_space());
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
int match_length = ParseCommand(tokens, command->name());
if (match_length == 0) {
continue;
}
// At this point, we have a matching command, which we return.
*command_pp = command;
args->clear();
for (size_t j = match_length; j < tokens.size(); ++j) {
args->push_back(tokens[j]);
}
return true;
}
return false;
}
int CommandLine::ParseCommand(const std::vector<std::string>& tokens,
const std::string& name) const {
vector<string> command_tokens;
boost::split(command_tokens, name, boost::is_space());
if (command_tokens.size() > tokens.size()) {
return 0;
}
for (size_t j = 0; j < command_tokens.size(); ++j) {
if (command_tokens[j] != tokens[j]) {
return 0;
}
}
return command_tokens.size();
}
} // namespace utils
} // namespace rapid
<commit_msg>Newline after Ctrl+D<commit_after>#include "rapid_utils/command_line.h"
#include <iostream>
#include "boost/algorithm/string.hpp"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
namespace rapid {
namespace utils {
CommandLine::CommandLine() : commands_() {}
void CommandLine::AddCommand(CommandInterface* command) {
commands_.push_back(command);
}
bool CommandLine::Next() {
ShowCommands();
cout << "Enter a command: ";
string input;
if (std::getline(std::cin, input)) {
cout << endl;
} else {
cout << endl;
return false;
}
CommandInterface* command;
vector<string> args;
bool valid = ParseLine(input, &command, &args);
if (valid) {
command->Execute(args);
cout << endl;
} else {
cout << "Invalid command." << endl;
cout << endl;
}
return true;
}
void CommandLine::ShowCommands() const {
cout << "Commands:" << endl;
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
cout << " " << command->name() << " " << command->description() << endl;
}
}
bool CommandLine::ParseLine(const std::string& line,
CommandInterface** command_pp,
std::vector<std::string>* args) const {
vector<string> tokens;
boost::split(tokens, line, boost::is_space());
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
int match_length = ParseCommand(tokens, command->name());
if (match_length == 0) {
continue;
}
// At this point, we have a matching command, which we return.
*command_pp = command;
args->clear();
for (size_t j = match_length; j < tokens.size(); ++j) {
args->push_back(tokens[j]);
}
return true;
}
return false;
}
int CommandLine::ParseCommand(const std::vector<std::string>& tokens,
const std::string& name) const {
vector<string> command_tokens;
boost::split(command_tokens, name, boost::is_space());
if (command_tokens.size() > tokens.size()) {
return 0;
}
for (size_t j = 0; j < command_tokens.size(); ++j) {
if (command_tokens[j] != tokens[j]) {
return 0;
}
}
return command_tokens.size();
}
} // namespace utils
} // namespace rapid
<|endoftext|> |
<commit_before>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-12-12 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <stdint.h>
#include <utf8.h>
#include <rime/candidate.h>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/service.h>
#include <rime/translation.h>
#include <rime/gear/simplifier.h>
#include <opencc/Config.hpp> // Place OpenCC #includes here to avoid VS2015 compilation errors
#include <opencc/Converter.hpp>
#include <opencc/Conversion.hpp>
#include <opencc/ConversionChain.hpp>
#include <opencc/Dict.hpp>
#include <opencc/DictEntry.hpp>
static const char* quote_left = "\xe3\x80\x94"; //"\xef\xbc\x88";
static const char* quote_right = "\xe3\x80\x95"; //"\xef\xbc\x89";
namespace rime {
class Opencc {
public:
Opencc(const string& config_path) {
LOG(INFO) << "initilizing opencc: " << config_path;
opencc::Config config;
converter_ = config.NewFromFile(config_path);
const list<opencc::ConversionPtr> conversions =
converter_->GetConversionChain()->GetConversions();
dict_ = conversions.front()->GetDict();
}
bool ConvertWord(const string& text,
vector<string>* forms) {
opencc::Optional<const opencc::DictEntry*> item = dict_->Match(text);
if (item.IsNull()) {
// Match not found
return false;
} else {
const opencc::DictEntry* entry = item.Get();
for (const char* value : entry->Values()) {
forms->push_back(value);
}
return forms->size() > 0;
}
}
bool RandomConvertText(const string& text,
string* simplified) {
const char *phrase = text.c_str();
std::ostringstream buffer;
for (const char* pstr = phrase; *pstr != '\0';) {
opencc::Optional<const opencc::DictEntry*> matched = dict_->MatchPrefix(pstr);
size_t matchedLength;
if (matched.IsNull()) {
matchedLength = opencc::UTF8Util::NextCharLength(pstr);
buffer << opencc::UTF8Util::FromSubstr(pstr, matchedLength);
} else {
matchedLength = matched.Get()->KeyLength();
size_t i = rand() % (matched.Get()->NumValues());
buffer << matched.Get()->Values().at(i);
}
pstr += matchedLength;
}
*simplified = buffer.str();
return *simplified != text;
}
bool ConvertText(const string& text,
string* simplified) {
*simplified = converter_->Convert(text);
return *simplified != text;
}
private:
opencc::ConverterPtr converter_;
opencc::DictPtr dict_;
};
// Simplifier
Simplifier::Simplifier(const Ticket& ticket) : Filter(ticket),
TagMatching(ticket) {
if (name_space_ == "filter") {
name_space_ = "simplifier";
}
if (Config* config = engine_->schema()->config()) {
string tips;
if (config->GetString(name_space_ + "/tips", &tips) ||
config->GetString(name_space_ + "/tip", &tips)) {
tips_level_ = (tips == "all") ? kTipsAll :
(tips == "char") ? kTipsChar : kTipsNone;
}
config->GetBool(name_space_ + "/show_in_comment", &show_in_comment_);
comment_formatter_.Load(config->GetList(name_space_ + "/comment_format"));
config->GetBool(name_space_ + "/random", &random_);
config->GetString(name_space_ + "/option_name", &option_name_);
config->GetString(name_space_ + "/opencc_config", &opencc_config_);
if (auto types = config->GetList(name_space_ + "/excluded_types")) {
for (auto it = types->begin(); it != types->end(); ++it) {
if (auto value = As<ConfigValue>(*it)) {
excluded_types_.insert(value->str());
}
}
}
}
if (option_name_.empty()) {
option_name_ = "simplification"; // default switcher option
}
if (opencc_config_.empty()) {
opencc_config_ = "t2s.json"; // default opencc config file
}
if (random_) {
srand((unsigned)time(NULL));
}
}
void Simplifier::Initialize() {
using namespace boost::filesystem;
initialized_ = true; // no retry
path opencc_config_path = opencc_config_;
if (opencc_config_path.extension().string() == ".ini") {
LOG(ERROR) << "please upgrade opencc_config to an opencc 1.0 config file.";
return;
}
if (opencc_config_path.is_relative()) {
path user_config_path = Service::instance().deployer().user_data_dir;
path shared_config_path = Service::instance().deployer().shared_data_dir;
(user_config_path /= "opencc") /= opencc_config_path;
(shared_config_path /= "opencc") /= opencc_config_path;
if (exists(user_config_path)) {
opencc_config_path = user_config_path;
}
else if (exists(shared_config_path)) {
opencc_config_path = shared_config_path;
}
}
try {
opencc_.reset(new Opencc(opencc_config_path.string()));
}
catch (opencc::Exception& e) {
LOG(ERROR) << "Error initializing opencc: " << e.what();
}
}
class SimplifiedTranslation : public PrefetchTranslation {
public:
SimplifiedTranslation(an<Translation> translation,
Simplifier* simplifier)
: PrefetchTranslation(translation), simplifier_(simplifier) {
}
protected:
virtual bool Replenish();
Simplifier* simplifier_;
};
bool SimplifiedTranslation::Replenish() {
auto next = translation_->Peek();
translation_->Next();
if (next && !simplifier_->Convert(next, &cache_)) {
cache_.push_back(next);
}
return !cache_.empty();
}
an<Translation> Simplifier::Apply(an<Translation> translation,
CandidateList* candidates) {
if (!engine_->context()->get_option(option_name_)) { // off
return translation;
}
if (!initialized_) {
Initialize();
}
if (!opencc_) {
return translation;
}
return New<SimplifiedTranslation>(translation, this);
}
void Simplifier::PushBack(const an<Candidate>& original,
CandidateQueue* result, const string& simplified) {
string tips;
string text;
if (show_in_comment_) {
text = original->text();
tips = simplified;
comment_formatter_.Apply(&tips);
} else {
size_t length = utf8::unchecked::distance(original->text().c_str(),
original->text().c_str()
+ original->text().length());
text = simplified;
if ((tips_level_ == kTipsChar && length == 1) || tips_level_ == kTipsAll) {
tips = original->text();
bool modified = comment_formatter_.Apply(&tips);
if (!modified) {
tips = quote_left + original->text() + quote_right;
}
}
}
result->push_back(
New<ShadowCandidate>(
original,
"simplified",
text,
tips));
}
bool Simplifier::Convert(const an<Candidate>& original,
CandidateQueue* result) {
if (excluded_types_.find(original->type()) != excluded_types_.end()) {
return false;
}
bool success = false;
if (random_) {
string simplified;
success = opencc_->RandomConvertText(original->text(), &simplified);
if (success) {
PushBack(original, result, simplified);
}
} else { //!random_
vector<string> forms;
success = opencc_->ConvertWord(original->text(), &forms);
if (success) {
for (size_t i = 0; i < forms.size(); ++i) {
if (forms[i] == original->text()) {
result->push_back(original);
} else {
PushBack(original, result, forms[i]);
}
}
} else {
string simplified;
success = opencc_->ConvertText(original->text(), &simplified);
if (success) {
PushBack(original, result, simplified);
}
}
}
return success;
}
} // namespace rime
<commit_msg>fix(simplifier): tips option for show_in_comment simplifier<commit_after>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-12-12 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <stdint.h>
#include <utf8.h>
#include <rime/candidate.h>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/service.h>
#include <rime/translation.h>
#include <rime/gear/simplifier.h>
#include <opencc/Config.hpp> // Place OpenCC #includes here to avoid VS2015 compilation errors
#include <opencc/Converter.hpp>
#include <opencc/Conversion.hpp>
#include <opencc/ConversionChain.hpp>
#include <opencc/Dict.hpp>
#include <opencc/DictEntry.hpp>
static const char* quote_left = "\xe3\x80\x94"; //"\xef\xbc\x88";
static const char* quote_right = "\xe3\x80\x95"; //"\xef\xbc\x89";
namespace rime {
class Opencc {
public:
Opencc(const string& config_path) {
LOG(INFO) << "initilizing opencc: " << config_path;
opencc::Config config;
converter_ = config.NewFromFile(config_path);
const list<opencc::ConversionPtr> conversions =
converter_->GetConversionChain()->GetConversions();
dict_ = conversions.front()->GetDict();
}
bool ConvertWord(const string& text,
vector<string>* forms) {
opencc::Optional<const opencc::DictEntry*> item = dict_->Match(text);
if (item.IsNull()) {
// Match not found
return false;
} else {
const opencc::DictEntry* entry = item.Get();
for (const char* value : entry->Values()) {
forms->push_back(value);
}
return forms->size() > 0;
}
}
bool RandomConvertText(const string& text,
string* simplified) {
const char *phrase = text.c_str();
std::ostringstream buffer;
for (const char* pstr = phrase; *pstr != '\0';) {
opencc::Optional<const opencc::DictEntry*> matched = dict_->MatchPrefix(pstr);
size_t matchedLength;
if (matched.IsNull()) {
matchedLength = opencc::UTF8Util::NextCharLength(pstr);
buffer << opencc::UTF8Util::FromSubstr(pstr, matchedLength);
} else {
matchedLength = matched.Get()->KeyLength();
size_t i = rand() % (matched.Get()->NumValues());
buffer << matched.Get()->Values().at(i);
}
pstr += matchedLength;
}
*simplified = buffer.str();
return *simplified != text;
}
bool ConvertText(const string& text,
string* simplified) {
*simplified = converter_->Convert(text);
return *simplified != text;
}
private:
opencc::ConverterPtr converter_;
opencc::DictPtr dict_;
};
// Simplifier
Simplifier::Simplifier(const Ticket& ticket) : Filter(ticket),
TagMatching(ticket) {
if (name_space_ == "filter") {
name_space_ = "simplifier";
}
if (Config* config = engine_->schema()->config()) {
string tips;
if (config->GetString(name_space_ + "/tips", &tips) ||
config->GetString(name_space_ + "/tip", &tips)) {
tips_level_ = (tips == "all") ? kTipsAll :
(tips == "char") ? kTipsChar : kTipsNone;
}
config->GetBool(name_space_ + "/show_in_comment", &show_in_comment_);
comment_formatter_.Load(config->GetList(name_space_ + "/comment_format"));
config->GetBool(name_space_ + "/random", &random_);
config->GetString(name_space_ + "/option_name", &option_name_);
config->GetString(name_space_ + "/opencc_config", &opencc_config_);
if (auto types = config->GetList(name_space_ + "/excluded_types")) {
for (auto it = types->begin(); it != types->end(); ++it) {
if (auto value = As<ConfigValue>(*it)) {
excluded_types_.insert(value->str());
}
}
}
}
if (option_name_.empty()) {
option_name_ = "simplification"; // default switcher option
}
if (opencc_config_.empty()) {
opencc_config_ = "t2s.json"; // default opencc config file
}
if (random_) {
srand((unsigned)time(NULL));
}
}
void Simplifier::Initialize() {
using namespace boost::filesystem;
initialized_ = true; // no retry
path opencc_config_path = opencc_config_;
if (opencc_config_path.extension().string() == ".ini") {
LOG(ERROR) << "please upgrade opencc_config to an opencc 1.0 config file.";
return;
}
if (opencc_config_path.is_relative()) {
path user_config_path = Service::instance().deployer().user_data_dir;
path shared_config_path = Service::instance().deployer().shared_data_dir;
(user_config_path /= "opencc") /= opencc_config_path;
(shared_config_path /= "opencc") /= opencc_config_path;
if (exists(user_config_path)) {
opencc_config_path = user_config_path;
}
else if (exists(shared_config_path)) {
opencc_config_path = shared_config_path;
}
}
try {
opencc_.reset(new Opencc(opencc_config_path.string()));
}
catch (opencc::Exception& e) {
LOG(ERROR) << "Error initializing opencc: " << e.what();
}
}
class SimplifiedTranslation : public PrefetchTranslation {
public:
SimplifiedTranslation(an<Translation> translation,
Simplifier* simplifier)
: PrefetchTranslation(translation), simplifier_(simplifier) {
}
protected:
virtual bool Replenish();
Simplifier* simplifier_;
};
bool SimplifiedTranslation::Replenish() {
auto next = translation_->Peek();
translation_->Next();
if (next && !simplifier_->Convert(next, &cache_)) {
cache_.push_back(next);
}
return !cache_.empty();
}
an<Translation> Simplifier::Apply(an<Translation> translation,
CandidateList* candidates) {
if (!engine_->context()->get_option(option_name_)) { // off
return translation;
}
if (!initialized_) {
Initialize();
}
if (!opencc_) {
return translation;
}
return New<SimplifiedTranslation>(translation, this);
}
void Simplifier::PushBack(const an<Candidate>& original,
CandidateQueue* result, const string& simplified) {
string tips;
string text;
size_t length = utf8::unchecked::distance(original->text().c_str(),
original->text().c_str()
+ original->text().length());
bool show_tips = (tips_level_ == kTipsChar && length == 1) || tips_level_ == kTipsAll;
if (show_in_comment_) {
text = original->text();
if (show_tips) {
tips = simplified;
comment_formatter_.Apply(&tips);
}
} else {
text = simplified;
if (show_tips) {
tips = original->text();
bool modified = comment_formatter_.Apply(&tips);
if (!modified) {
tips = quote_left + original->text() + quote_right;
}
}
}
result->push_back(
New<ShadowCandidate>(
original,
"simplified",
text,
tips));
}
bool Simplifier::Convert(const an<Candidate>& original,
CandidateQueue* result) {
if (excluded_types_.find(original->type()) != excluded_types_.end()) {
return false;
}
bool success = false;
if (random_) {
string simplified;
success = opencc_->RandomConvertText(original->text(), &simplified);
if (success) {
PushBack(original, result, simplified);
}
} else { //!random_
vector<string> forms;
success = opencc_->ConvertWord(original->text(), &forms);
if (success) {
for (size_t i = 0; i < forms.size(); ++i) {
if (forms[i] == original->text()) {
result->push_back(original);
} else {
PushBack(original, result, forms[i]);
}
}
} else {
string simplified;
success = opencc_->ConvertText(original->text(), &simplified);
if (success) {
PushBack(original, result, simplified);
}
}
}
return success;
}
} // namespace rime
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <unordered_map>
#include <boost/range/iterator_range.hpp>
#include <boost/range/join.hpp>
#include "cql3/column_specification.hh"
#include "core/shared_ptr.hh"
#include "types.hh"
#include "tuple.hh"
#include "gc_clock.hh"
using column_id = uint32_t;
class column_definition final {
private:
bytes _name;
public:
enum class column_kind { PARTITION, CLUSTERING, REGULAR, STATIC };
column_definition(bytes name, data_type type, column_id id, column_kind kind);
data_type type;
column_id id; // unique within (kind, schema instance)
column_kind kind;
::shared_ptr<cql3::column_specification> column_specification;
bool is_static() const { return kind == column_kind::STATIC; }
bool is_partition_key() const { return kind == column_kind::PARTITION; }
bool is_clustering_key() const { return kind == column_kind::CLUSTERING; }
bool is_primary_key() const { return kind == column_kind::PARTITION || kind == column_kind::CLUSTERING; }
bool is_atomic() const { return !type->is_multi_cell(); }
bool is_compact_value() const;
const sstring& name_as_text() const;
const bytes& name() const;
friend std::ostream& operator<<(std::ostream& os, const column_definition& cd) {
return os << cd.name_as_text();
}
};
struct thrift_schema {
shared_ptr<abstract_type> partition_key_type;
};
/*
* Keep this effectively immutable.
*/
class schema final {
private:
std::unordered_map<bytes, column_definition*> _columns_by_name;
std::map<bytes, column_definition*, serialized_compare> _regular_columns_by_name;
std::vector<column_definition> _partition_key;
std::vector<column_definition> _clustering_key;
std::vector<column_definition> _regular_columns; // sorted by name
std::vector<column_definition> _static_columns; // sorted by name, present only when there's any clustering column
sstring _comment;
public:
struct column {
bytes name;
data_type type;
struct name_compare {
shared_ptr<abstract_type> type;
name_compare(shared_ptr<abstract_type> type) : type(type) {}
bool operator()(const column& cd1, const column& cd2) const {
return type->less(cd1.name, cd2.name);
}
};
};
private:
void build_columns(const std::vector<column>& columns, column_definition::column_kind kind, std::vector<column_definition>& dst);
::shared_ptr<cql3::column_specification> make_column_specification(column_definition& def);
public:
gc_clock::duration default_time_to_live = gc_clock::duration::zero();
const sstring ks_name;
const sstring cf_name;
shared_ptr<tuple_type<>> partition_key_type;
shared_ptr<tuple_type<>> clustering_key_type;
shared_ptr<tuple_prefix> clustering_key_prefix_type;
data_type regular_column_name_type;
thrift_schema thrift;
public:
schema(sstring ks_name, sstring cf_name,
std::vector<column> partition_key,
std::vector<column> clustering_key,
std::vector<column> regular_columns,
std::vector<column> static_columns,
shared_ptr<abstract_type> regular_column_name_type,
sstring comment = {});
bool is_dense() const {
return false;
}
bool is_counter() const {
return false;
}
column_definition* get_column_definition(const bytes& name);
auto regular_begin() {
return _regular_columns.begin();
}
auto regular_end() {
return _regular_columns.end();
}
auto regular_lower_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::lower_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.lower_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return _regular_columns.begin() + i->second->id;
}
}
auto regular_upper_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::upper_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.upper_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return _regular_columns.begin() + i->second->id;
}
}
data_type column_name_type(column_definition& def) {
return def.kind == column_definition::column_kind::REGULAR ? regular_column_name_type : utf8_type;
}
column_definition& regular_column_at(column_id id) {
return _regular_columns[id];
}
column_definition& static_column_at(column_id id) {
return _static_columns[id];
}
bool is_last_partition_key(column_definition& def) {
return &_partition_key[_partition_key.size() - 1] == &def;
}
bool has_static_columns() {
return !_static_columns.empty();
}
size_t partition_key_size() const { return _partition_key.size(); }
size_t clustering_key_size() const { return _clustering_key.size(); }
size_t static_columns_count() const { return _static_columns.size(); }
size_t regular_columns_count() const { return _regular_columns.size(); }
// Returns a range of column definitions
auto partition_key_columns() const {
return boost::make_iterator_range(_partition_key.begin(), _partition_key.end());
}
// Returns a range of column definitions
auto clustering_key_columns() const {
return boost::make_iterator_range(_clustering_key.begin(), _clustering_key.end());
}
// Returns a range of column definitions
auto static_columns() const {
return boost::make_iterator_range(_static_columns.begin(), _static_columns.end());
}
// Returns a range of column definitions
auto regular_columns() const {
return boost::make_iterator_range(_regular_columns.begin(), _regular_columns.end());
}
// Returns a range of column definitions
auto all_columns_in_select_order() const {
return boost::join(partition_key_columns(),
boost::join(clustering_key_columns(),
boost::join(static_columns(), regular_columns())));
}
};
using schema_ptr = lw_shared_ptr<schema>;
<commit_msg>schema: Introduce schema::position(column_definition&)<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <unordered_map>
#include <boost/range/iterator_range.hpp>
#include <boost/range/join.hpp>
#include "cql3/column_specification.hh"
#include "core/shared_ptr.hh"
#include "types.hh"
#include "tuple.hh"
#include "gc_clock.hh"
using column_id = uint32_t;
class column_definition final {
private:
bytes _name;
public:
enum class column_kind { PARTITION, CLUSTERING, REGULAR, STATIC };
column_definition(bytes name, data_type type, column_id id, column_kind kind);
data_type type;
// Unique within (kind, schema instance).
// schema::position() depends on the fact that for PK columns this is
// equivalent to component index.
column_id id;
column_kind kind;
::shared_ptr<cql3::column_specification> column_specification;
bool is_static() const { return kind == column_kind::STATIC; }
bool is_partition_key() const { return kind == column_kind::PARTITION; }
bool is_clustering_key() const { return kind == column_kind::CLUSTERING; }
bool is_primary_key() const { return kind == column_kind::PARTITION || kind == column_kind::CLUSTERING; }
bool is_atomic() const { return !type->is_multi_cell(); }
bool is_compact_value() const;
const sstring& name_as_text() const;
const bytes& name() const;
friend std::ostream& operator<<(std::ostream& os, const column_definition& cd) {
return os << cd.name_as_text();
}
};
struct thrift_schema {
shared_ptr<abstract_type> partition_key_type;
};
/*
* Keep this effectively immutable.
*/
class schema final {
private:
std::unordered_map<bytes, column_definition*> _columns_by_name;
std::map<bytes, column_definition*, serialized_compare> _regular_columns_by_name;
std::vector<column_definition> _partition_key;
std::vector<column_definition> _clustering_key;
std::vector<column_definition> _regular_columns; // sorted by name
std::vector<column_definition> _static_columns; // sorted by name, present only when there's any clustering column
sstring _comment;
public:
struct column {
bytes name;
data_type type;
struct name_compare {
shared_ptr<abstract_type> type;
name_compare(shared_ptr<abstract_type> type) : type(type) {}
bool operator()(const column& cd1, const column& cd2) const {
return type->less(cd1.name, cd2.name);
}
};
};
private:
void build_columns(const std::vector<column>& columns, column_definition::column_kind kind, std::vector<column_definition>& dst);
::shared_ptr<cql3::column_specification> make_column_specification(column_definition& def);
public:
gc_clock::duration default_time_to_live = gc_clock::duration::zero();
const sstring ks_name;
const sstring cf_name;
shared_ptr<tuple_type<>> partition_key_type;
shared_ptr<tuple_type<>> clustering_key_type;
shared_ptr<tuple_prefix> clustering_key_prefix_type;
data_type regular_column_name_type;
thrift_schema thrift;
public:
schema(sstring ks_name, sstring cf_name,
std::vector<column> partition_key,
std::vector<column> clustering_key,
std::vector<column> regular_columns,
std::vector<column> static_columns,
shared_ptr<abstract_type> regular_column_name_type,
sstring comment = {});
bool is_dense() const {
return false;
}
bool is_counter() const {
return false;
}
column_definition* get_column_definition(const bytes& name);
auto regular_begin() {
return _regular_columns.begin();
}
auto regular_end() {
return _regular_columns.end();
}
auto regular_lower_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::lower_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.lower_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return _regular_columns.begin() + i->second->id;
}
}
auto regular_upper_bound(const bytes& name) {
// TODO: use regular_columns and a version of std::upper_bound() with heterogeneous comparator
auto i = _regular_columns_by_name.upper_bound(name);
if (i == _regular_columns_by_name.end()) {
return regular_end();
} else {
return _regular_columns.begin() + i->second->id;
}
}
data_type column_name_type(column_definition& def) {
return def.kind == column_definition::column_kind::REGULAR ? regular_column_name_type : utf8_type;
}
column_definition& regular_column_at(column_id id) {
return _regular_columns[id];
}
column_definition& static_column_at(column_id id) {
return _static_columns[id];
}
bool is_last_partition_key(column_definition& def) {
return &_partition_key[_partition_key.size() - 1] == &def;
}
bool has_static_columns() {
return !_static_columns.empty();
}
size_t partition_key_size() const { return _partition_key.size(); }
size_t clustering_key_size() const { return _clustering_key.size(); }
size_t static_columns_count() const { return _static_columns.size(); }
size_t regular_columns_count() const { return _regular_columns.size(); }
// Returns a range of column definitions
auto partition_key_columns() const {
return boost::make_iterator_range(_partition_key.begin(), _partition_key.end());
}
// Returns a range of column definitions
auto clustering_key_columns() const {
return boost::make_iterator_range(_clustering_key.begin(), _clustering_key.end());
}
// Returns a range of column definitions
auto static_columns() const {
return boost::make_iterator_range(_static_columns.begin(), _static_columns.end());
}
// Returns a range of column definitions
auto regular_columns() const {
return boost::make_iterator_range(_regular_columns.begin(), _regular_columns.end());
}
// Returns a range of column definitions
auto all_columns_in_select_order() const {
return boost::join(partition_key_columns(),
boost::join(clustering_key_columns(),
boost::join(static_columns(), regular_columns())));
}
uint32_t position(const column_definition& column) const {
if (column.is_primary_key()) {
return column.id;
}
return _clustering_key.size();
}
};
using schema_ptr = lw_shared_ptr<schema>;
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/elem_cutter.h"
#include "libmesh/elem.h"
#include "libmesh/serial_mesh.h"
// C++ includes
namespace libMesh
{
// ------------------------------------------------------------
// ElemCutter implementation
ElemCutter::ElemCutter()
{
_working_mesh_2D.reset (new SerialMesh);
_working_mesh_3D.reset (new SerialMesh);
}
ElemCutter::~ElemCutter()
{}
void ElemCutter::operator()(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
libmesh_assert_equal_to (vertex_distance_func.size(), elem.n_vertices());
_inside_elem.clear();
_outside_elem.clear();
// check for quick return?
{
Real
nmin = vertex_distance_func.front(),
nmax = nmin;
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
{
nmin = std::min (nmin, *it);
nmax = std::max (nmax, *it);
}
// completely outside?
if (nmin >= 0.)
{
_outside_elem.push_back(&elem);
return;
}
// completely inside?
else if (nmax <= 0.)
{
_inside_elem.push_back(&elem);
return;
}
libmesh_assert_greater (nmax, 0.);
libmesh_assert_less (nmin, 0.);
}
// we now know we are in a cut element, find the intersecting points.
this->find_intersection_points (elem, vertex_distance_func);
// and then dispatch the proper method
switch (elem.dim())
{
case 1: this->cut_1D(); break;
case 2: this->cut_2D(); break;
case 3: this->cut_3D(); break;
default: libmesh_error();
}
}
void ElemCutter::find_intersection_points(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
_intersection_pts.clear();
for (unsigned int e=0; e<elem.n_edges(); e++)
{
AutoPtr<Elem> edge (elem.build_edge(e));
// find the element nodes el0, el1 that map
unsigned int
el0 = elem.get_node_index(edge->get_node(0)),
el1 = elem.get_node_index(edge->get_node(1));
libmesh_assert (elem.is_vertex(el0));
libmesh_assert (elem.is_vertex(el1));
libmesh_assert_less (el0, vertex_distance_func.size());
libmesh_assert_less (el1, vertex_distance_func.size());
const Real
d0 = vertex_distance_func[el0],
d1 = vertex_distance_func[el1];
// if this egde has a 0 crossing
if (d0*d1 < 0.)
{
libmesh_assert_not_equal_to (d0, d1);
// then find d_star in [0,1], the
// distance from el0 to el1 where the 0 lives.
const Real d_star = d0 / (d0 - d1);
const Point x_star = (edge->point(0)*(1.-d_star) +
edge->point(1)*d_star);
_intersection_pts.push_back (x_star);
}
}
}
void ElemCutter::cut_1D ()
{
libmesh_not_implemented();
}
void ElemCutter::cut_2D ()
{
libmesh_not_implemented();
}
void ElemCutter::cut_3D ()
{
libmesh_not_implemented();
}
} // namespace libMesh
<commit_msg>some execution tracing statements<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/elem_cutter.h"
#include "libmesh/elem.h"
#include "libmesh/serial_mesh.h"
// C++ includes
namespace libMesh
{
// ------------------------------------------------------------
// ElemCutter implementation
ElemCutter::ElemCutter()
{
_working_mesh_2D.reset (new SerialMesh);
_working_mesh_3D.reset (new SerialMesh);
}
ElemCutter::~ElemCutter()
{}
void ElemCutter::operator()(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
libmesh_assert_equal_to (vertex_distance_func.size(), elem.n_vertices());
_inside_elem.clear();
_outside_elem.clear();
// check for quick return?
{
Real
nmin = vertex_distance_func.front(),
nmax = nmin;
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
{
nmin = std::min (nmin, *it);
nmax = std::max (nmax, *it);
}
// completely outside?
if (nmin >= 0.)
{
std::cout << "element completely outside\n";
_outside_elem.push_back(&elem);
return;
}
// completely inside?
else if (nmax <= 0.)
{
std::cout << "element completely inside\n";
_inside_elem.push_back(&elem);
return;
}
libmesh_assert_greater (nmax, 0.);
libmesh_assert_less (nmin, 0.);
}
// we now know we are in a cut element, find the intersecting points.
this->find_intersection_points (elem, vertex_distance_func);
// and then dispatch the proper method
switch (elem.dim())
{
case 1: this->cut_1D(); break;
case 2: this->cut_2D(); break;
case 3: this->cut_3D(); break;
default: libmesh_error();
}
}
void ElemCutter::find_intersection_points(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
_intersection_pts.clear();
for (unsigned int e=0; e<elem.n_edges(); e++)
{
AutoPtr<Elem> edge (elem.build_edge(e));
// find the element nodes el0, el1 that map
unsigned int
el0 = elem.get_node_index(edge->get_node(0)),
el1 = elem.get_node_index(edge->get_node(1));
libmesh_assert (elem.is_vertex(el0));
libmesh_assert (elem.is_vertex(el1));
libmesh_assert_less (el0, vertex_distance_func.size());
libmesh_assert_less (el1, vertex_distance_func.size());
const Real
d0 = vertex_distance_func[el0],
d1 = vertex_distance_func[el1];
// if this egde has a 0 crossing
if (d0*d1 < 0.)
{
libmesh_assert_not_equal_to (d0, d1);
// then find d_star in [0,1], the
// distance from el0 to el1 where the 0 lives.
const Real d_star = d0 / (d0 - d1);
const Point x_star = (edge->point(0)*(1.-d_star) +
edge->point(1)*d_star);
std::cout << "adding cut point " << x_star << std::endl;
_intersection_pts.push_back (x_star);
}
}
}
void ElemCutter::cut_1D ()
{
libmesh_not_implemented();
}
void ElemCutter::cut_2D ()
{
//libmesh_not_implemented();
std::cout << "Inside cut element!\n";
}
void ElemCutter::cut_3D ()
{
libmesh_not_implemented();
}
} // namespace libMesh
<|endoftext|> |
<commit_before>#include "Collisions.hpp"
#include "Geometry.hpp"
#include "compsys/Entity.hpp"
#include "TileCollideableGroup.hpp"
#include "RectCollideableGroup.hpp"
#include "comp/TileCollisionComponent.hpp"
#include "container.hpp"
#include "svc/ServiceLocator.hpp"
#include "Tilemap.hpp"
#include "LuaFunction.hpp"
static char const libname[] = "Collisions";
#include "ExportThis.hpp"
#include <luabind/out_value_policy.hpp>
namespace {
static WeakRef<Entity> Collision_getEntity(Collision const& c)
{
return c.entity->ref();
}
static void Collision_setEntity(Collision& c, WeakRef<Entity> e)
{
c.entity = e.getOpt();
}
static std::vector<Collision> const CollideableGroup_colliding(
CollideableGroup& self, sf::FloatRect const& r)
{
return self.colliding(r);
}
static void TileStackCollideableGroup_setFilter(
TileStackCollideableGroup& this_, luabind::object filter)
{
this_.setFilter(LuaFunction<void>(filter));
}
} // anonymous namespace
static void init(LuaVm& vm)
{
typedef std::vector<Collision> CollisionVec;
typedef std::vector<Vector3u> PositionVec;
luabind::class_<CollisionVec> cCollisionVec("CollisionList");
exportRandomAccessContainer(cCollisionVec);
luabind::class_<PositionVec> cPositionVec("PositionList");
exportRandomAccessContainer(cPositionVec);
LHMODULE [
# define LHCURCLASS Collision
LHCLASS
.property("entity", &Collision_getEntity, &Collision_setEntity)
.LHPROPRW(rect),
# undef LHCURCLASS
cCollisionVec,
cPositionVec,
# define LHCURCLASS CollideableGroup
LHCLASS
.def("colliding", &CollideableGroup_colliding)
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::FloatRect const&, Entity* e))
&LHCURCLASS::colliding)
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::Vector2f, sf::Vector2f))
&LHCURCLASS::colliding)
.LHMEMFN(collideWith)
.LHMEMFN(collide)
.LHMEMFN(clear),
# undef LHCURCLASS
# define LHCURCLASS TileCollideableInfo
LHCLASS
.def(constructor<jd::Tilemap&>())
.LHMEMFN(setProxy)
.LHMEMFN(proxy)
.LHMEMFN(setColliding)
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::FloatRect const&, Entity* e, PositionVec*))
&LHCURCLASS::colliding, pure_out_value(_4))
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::Vector2f, sf::Vector2f, PositionVec*))
&LHCURCLASS::colliding, pure_out_value(_4))
.def("colliding",
(TileCollisionComponent* (LHCURCLASS::*)(Vector3u))&LHCURCLASS::colliding)
.LHPROPG(tilemap),
# undef LHCURCLASS
# define LHCURCLASS TileLayersCollideableGroup
class_<LHCURCLASS, CollideableGroup>("TileLayersCollideableGroup")
.def(constructor<TileCollideableInfo*, unsigned, unsigned>())
.property("firstLayer", &LHCURCLASS::firstLayer, &LHCURCLASS::setFirstLayer)
.property("endLayer", &LHCURCLASS::endLayer, &LHCURCLASS::setEndLayer)
.LHPROPG(data),
# undef LHCURCLASS
# define LHCURCLASS TileStackCollideableGroup
class_<LHCURCLASS, CollideableGroup>("TileStackCollideableGroup")
.def(constructor<TileCollideableInfo*>())
.def("setFilter", &TileStackCollideableGroup_setFilter)
.LHPROPG(data),
# undef LHCURCLASS
# define LHCURCLASS RectCollideableGroup
class_<LHCURCLASS, CollideableGroup>("RectCollideableGroup")
.def(constructor<>())
.LHMEMFN(add)
.LHMEMFN(remove),
# undef LHCURCLASS
# define LHCURCLASS CollideableGroupGroup
class_<LHCURCLASS, CollideableGroup>("CollideableGroupGroup")
.def(constructor<>())
.LHMEMFN(add)
.LHMEMFN(remove)
# undef LHCURCLASS
];
}<commit_msg>Collisions lexp: +TileStackCollideableGroup::Info.<commit_after>#include "Collisions.hpp"
#include "Geometry.hpp"
#include "compsys/Entity.hpp"
#include "TileCollideableGroup.hpp"
#include "RectCollideableGroup.hpp"
#include "comp/TileCollisionComponent.hpp"
#include "container.hpp"
#include "svc/ServiceLocator.hpp"
#include "Tilemap.hpp"
#include "LuaFunction.hpp"
static char const libname[] = "Collisions";
#include "ExportThis.hpp"
#include <luabind/out_value_policy.hpp>
namespace {
static WeakRef<Entity> Collision_getEntity(Collision const& c)
{
return c.entity->ref();
}
static void Collision_setEntity(Collision& c, WeakRef<Entity> e)
{
c.entity = e.getOpt();
}
static std::vector<Collision> const CollideableGroup_colliding(
CollideableGroup& self, sf::FloatRect const& r)
{
return self.colliding(r);
}
static void TileStackCollideableGroup_setFilter(
TileStackCollideableGroup& this_, luabind::object filter)
{
this_.setFilter(LuaFunction<void>(filter));
}
} // anonymous namespace
static void init(LuaVm& vm)
{
typedef std::vector<Collision> CollisionVec;
typedef std::vector<Vector3u> PositionVec;
luabind::class_<CollisionVec> cCollisionVec("CollisionList");
exportRandomAccessContainer(cCollisionVec);
luabind::class_<PositionVec> cPositionVec("PositionList");
exportRandomAccessContainer(cPositionVec);
LHMODULE [
# define LHCURCLASS Collision
LHCLASS
.property("entity", &Collision_getEntity, &Collision_setEntity)
.LHPROPRW(rect),
# undef LHCURCLASS
cCollisionVec,
cPositionVec,
# define LHCURCLASS CollideableGroup
LHCLASS
.def("colliding", &CollideableGroup_colliding)
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::FloatRect const&, Entity* e))
&LHCURCLASS::colliding)
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::Vector2f, sf::Vector2f))
&LHCURCLASS::colliding)
.LHMEMFN(collideWith)
.LHMEMFN(collide)
.LHMEMFN(clear),
# undef LHCURCLASS
# define LHCURCLASS TileCollideableInfo
LHCLASS
.def(constructor<jd::Tilemap&>())
.LHMEMFN(setProxy)
.LHMEMFN(proxy)
.LHMEMFN(setColliding)
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::FloatRect const&, Entity* e, PositionVec*))
&LHCURCLASS::colliding, pure_out_value(_4))
.def("colliding",
(CollisionVec (LHCURCLASS::*)(sf::Vector2f, sf::Vector2f, PositionVec*))
&LHCURCLASS::colliding, pure_out_value(_4))
.def("colliding",
(TileCollisionComponent* (LHCURCLASS::*)(Vector3u))&LHCURCLASS::colliding)
.LHPROPG(tilemap),
# undef LHCURCLASS
# define LHCURCLASS TileLayersCollideableGroup
class_<LHCURCLASS, CollideableGroup>("TileLayersCollideableGroup")
.def(constructor<TileCollideableInfo*, unsigned, unsigned>())
.property("firstLayer", &LHCURCLASS::firstLayer, &LHCURCLASS::setFirstLayer)
.property("endLayer", &LHCURCLASS::endLayer, &LHCURCLASS::setEndLayer)
.LHPROPG(data),
# undef LHCURCLASS
# define LHCURCLASS TileStackCollideableGroup
class_<LHCURCLASS, CollideableGroup>("TileStackCollideableGroup")
.def(constructor<TileCollideableInfo*>())
.def("setFilter", &TileStackCollideableGroup_setFilter)
.LHPROPG(data)
.scope [
# undef LHCURCLASS // keep Visual Studio happy
# define LHCURCLASS TileStackCollideableGroup::Info
LHCLASS
.def(constructor<>())
.def(constructor<unsigned, WeakRef<Entity> const&>())
.LHPROPRW(tileId)
.LHPROPRW(entity)
.LHPROPRW(discard)
],
# undef LHCURCLASS
# define LHCURCLASS RectCollideableGroup
class_<LHCURCLASS, CollideableGroup>("RectCollideableGroup")
.def(constructor<>())
.LHMEMFN(add)
.LHMEMFN(remove),
# undef LHCURCLASS
# define LHCURCLASS CollideableGroupGroup
class_<LHCURCLASS, CollideableGroup>("CollideableGroupGroup")
.def(constructor<>())
.LHMEMFN(add)
.LHMEMFN(remove)
# undef LHCURCLASS
];
}<|endoftext|> |
<commit_before>/*
Copyright 2014-2015 Adam Grandquist
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.
*/
/**
* @author Adam Grandquist
* @copyright Apache
*/
#include "ReQL-expr.hpp"
#include "ReQL.hpp"
#include <limits>
namespace ReQL {
Expr::Expr() {
Query _val = expr(_reql_new_null());
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(_ReQL_AST_Function f, std::vector<Query> args, std::map<std::string, Query> kwargs) {
query = new _ReQL_Obj_t();
Query _args(args);
sub_query.push_back(_args);
Query _kwargs(kwargs);
sub_query.push_back(_kwargs);
f(query, _args.query, _kwargs.query);
}
Expr::Expr(_ReQL_Obj_t *val) {
query = val;
}
Expr::Expr(std::string val) {
Query _val = expr(_reql_new_string(val));
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(double val) {
Query _val = expr(_reql_new_number(val));
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(bool val) {
Query _val = expr(_reql_new_bool(val));
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(std::vector<Query> val) {
if (val.size() > std::numeric_limits<std::uint32_t>::max()) {
throw;
}
sub_query.assign(val.begin(), val.end());
Query _val = expr(_reql_new_array(static_cast<std::uint32_t>(val.size())));
sub_query.push_back(_val);
std::vector<Query>::iterator iter;
for (iter=val.begin(); iter!=val.end(); ++iter) {
_reql_array_append(_val.query, iter->query);
}
query = _reql_new_make_array(_val.query);
}
Expr::Expr(std::map<std::string, Query> val) {
if (val.size() > std::numeric_limits<std::uint32_t>::max()) {
throw;
}
Query _val = expr(_reql_new_object(static_cast<std::uint32_t>(val.size())));
sub_query.push_back(_val);
std::map<std::string, Query>::iterator iter;
for (iter=val.begin(); iter!=val.end(); ++iter) {
Query key(iter->first);
sub_query.push_back(key);
sub_query.push_back(iter->second);
_reql_object_add(_val.query, key.query, iter->second.query);
}
query = _reql_new_make_obj(_val.query);
}
Expr::~Expr() {
switch (_reql_datum_type(query)) {
case _REQL_R_ARRAY: {
delete [] query->obj.datum.json.array;
break;
}
case _REQL_R_OBJECT: {
delete [] query->obj.datum.json.pair;
break;
}
default:
break;
}
delete query;
}
Query
expr() {
return Query();
}
Query
expr(_ReQL_Obj_t *val) {
return Query(val);
}
Query
expr(std::string val) {
return Query(val);
}
Query
expr(double val) {
return Query(val);
}
Query
expr(bool val) {
return Query(val);
}
Query
expr(std::vector<Query> val) {
return Query(val);
}
Query
expr(std::map<std::string, Query> val) {
return Query(val);
}
}
<commit_msg>Whitespace.<commit_after>/*
Copyright 2014-2015 Adam Grandquist
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.
*/
/**
* @author Adam Grandquist
* @copyright Apache
*/
#include "ReQL-expr.hpp"
#include "ReQL.hpp"
#include <limits>
namespace ReQL {
Expr::Expr() {
Query _val = expr(_reql_new_null());
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(_ReQL_AST_Function f, std::vector<Query> args, std::map<std::string, Query> kwargs) {
query = new _ReQL_Obj_t();
Query _args(args);
sub_query.push_back(_args);
Query _kwargs(kwargs);
sub_query.push_back(_kwargs);
f(query, _args.query, _kwargs.query);
}
Expr::Expr(_ReQL_Obj_t *val) {
query = val;
}
Expr::Expr(std::string val) {
Query _val = expr(_reql_new_string(val));
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(double val) {
Query _val = expr(_reql_new_number(val));
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(bool val) {
Query _val = expr(_reql_new_bool(val));
sub_query.push_back(_val);
query = _reql_new_datum(_val.query);
}
Expr::Expr(std::vector<Query> val) {
if (val.size() > std::numeric_limits<std::uint32_t>::max()) {
throw;
}
sub_query.assign(val.begin(), val.end());
Query _val = expr(_reql_new_array(static_cast<std::uint32_t>(val.size())));
sub_query.push_back(_val);
std::vector<Query>::iterator iter;
for (iter=val.begin(); iter!=val.end(); ++iter) {
_reql_array_append(_val.query, iter->query);
}
query = _reql_new_make_array(_val.query);
}
Expr::Expr(std::map<std::string, Query> val) {
if (val.size() > std::numeric_limits<std::uint32_t>::max()) {
throw;
}
Query _val = expr(_reql_new_object(static_cast<std::uint32_t>(val.size())));
sub_query.push_back(_val);
std::map<std::string, Query>::iterator iter;
for (iter=val.begin(); iter!=val.end(); ++iter) {
Query key(iter->first);
sub_query.push_back(key);
sub_query.push_back(iter->second);
_reql_object_add(_val.query, key.query, iter->second.query);
}
query = _reql_new_make_obj(_val.query);
}
Expr::~Expr() {
switch (_reql_datum_type(query)) {
case _REQL_R_ARRAY: {
delete [] query->obj.datum.json.array;
break;
}
case _REQL_R_OBJECT: {
delete [] query->obj.datum.json.pair;
break;
}
default:
break;
}
delete query;
}
Query
expr() {
return Query();
}
Query
expr(_ReQL_Obj_t *val) {
return Query(val);
}
Query
expr(std::string val) {
return Query(val);
}
Query
expr(double val) {
return Query(val);
}
Query
expr(bool val) {
return Query(val);
}
Query
expr(std::vector<Query> val) {
return Query(val);
}
Query
expr(std::map<std::string, Query> val) {
return Query(val);
}
}
<|endoftext|> |
<commit_before>#ifndef LIBIRCPPCLIENT_HPP
#define LIBIRCPPCLIENT_HPP
#include "connection.hpp"
#include <vector>
namespace libircppclient {
/*
* It really feels like this isn't the quick-n-simple implementation
* we're looking for.
*/
struct config {
/* Default values. */
std::string
address = "",
port = "6667",
nick = "Temeraire",
user = nick,
/* Optional */
/* For identification with NickServ */
nick_pw = "",
server_pw = "";
/* Support not yet implemented */
bool ssl = true;
};
class client {
public:
client(const config &c);
void nick(const std::string &nick);
void join(const std::string chan, const std::string &key);
void msg(const std::string target, const std::string message);
void quit(const std::string &message);
/*
* As this lib is not feature-done, yet:
* Send the given content directly to the server
* as a command.
*/
void raw_cmd(const std::string &content);
void start();
void stop()
{
/*
* Haven't I forgotten something?
* Some async function that needs terminating, maybe?
*/
con.stop_ping();
con.stop();
}
/* Add a read_handler that may not exist in this class. */
void add_read_handler(read_handler_t func);
protected:
config conf_;
/*
* Filled with lambdas at run-time which will decide how
* to handle certain messages from the server.
*/
void read_handler(const std::string &content);
std::vector<read_handler_t> read_handlers_;
connection con;
private:
void initialize();
};
/* ns libircppclient */
}
/* endif LIBIRCPPCLIENT */
#endif
<commit_msg>Missed two not-yet-existing references<commit_after>#ifndef LIBIRCPPCLIENT_HPP
#define LIBIRCPPCLIENT_HPP
#include "connection.hpp"
#include <vector>
namespace libircppclient {
/*
* It really feels like this isn't the quick-n-simple implementation
* we're looking for.
*/
struct config {
/* Default values. */
std::string
address = "",
port = "6667",
nick = "Temeraire",
user = nick,
/* Optional */
/* For identification with NickServ */
nick_pw = "",
server_pw = "";
/* Support not yet implemented */
bool ssl = true;
};
class client {
public:
client(const config &c);
void nick(const std::string &nick);
void join(const std::string &chan, const std::string &key);
void msg(const std::string &target, const std::string &message);
void quit(const std::string &message);
/*
* As this lib is not feature-done, yet:
* Send the given content directly to the server
* as a command.
*/
void raw_cmd(const std::string &content);
void start();
void stop()
{
/*
* Haven't I forgotten something?
* Some async function that needs terminating, maybe?
*/
con.stop_ping();
con.stop();
}
/* Add a read_handler that may not exist in this class. */
void add_read_handler(read_handler_t func);
protected:
config conf_;
/*
* Filled with lambdas at run-time which will decide how
* to handle certain messages from the server.
*/
void read_handler(const std::string &content);
std::vector<read_handler_t> read_handlers_;
connection con;
private:
void initialize();
};
/* ns libircppclient */
}
/* endif LIBIRCPPCLIENT */
#endif
<|endoftext|> |
<commit_before>/****************************************************************
m_scheme.cpp
Patrick J. Fasano
University of Notre Dame
European Centre for Theoretical Studies
in Nuclear Physics and Related Areas
****************************************************************/
#include <iomanip> // for debugging output
#include <iostream>
#include <sstream>
#include <set>
#include <algorithm>
#include "am/am.h"
#include "mcutils/parsing.h"
#include "basis/proton_neutron.h"
#include "m_scheme.h"
namespace basis {
////////////////////////////////////////////////////////////////
// single-particle states
////////////////////////////////////////////////////////////////
/**
* Construct a subspace with a particular species from an OrbitalSubspacePN.
*
* @param[in] orbital_subspace orbital subspace
*/
SingleParticleSubspacePN::SingleParticleSubspacePN(const OrbitalSubspacePN& orbital_subspace)
{
// set values
labels_ = SubspaceLabelsType(orbital_subspace.labels());
weight_max_ = orbital_subspace.weight_max();
// iterate over all states, enumerating m-substates
for (int i=0; i < orbital_subspace.size(); ++i) {
OrbitalStatePN orbital(orbital_subspace, i);
for (HalfInt m = -orbital.j(); m <= orbital.j(); ++m) {
PushStateLabels(StateLabelsType(orbital.n(),orbital.l(),orbital.j(),m));
weights_.push_back(orbital.weight());
}
}
// check if oscillator-like and set Nmax
is_oscillator_like_ = orbital_subspace.is_oscillator_like();
if (is_oscillator_like()) {
Nmax_ = orbital_subspace.Nmax();
} else {
Nmax_ = -1;
}
}
/**
* Generate a string representation of the subspace labels.
* @return subspace labels as a string
*/
std::string SingleParticleSubspacePN::LabelStr() const
{
std::ostringstream os;
const int width = 0; // for now, no fixed width
os << "["
<< " " << std::setw(width) << int(orbital_species())
<< " " << "]";
return os.str();
}
/**
* Generate a string representation, useful for debugging.
* @return debug string
*/
std::string SingleParticleSubspacePN::DebugStr() const
{
std::ostringstream os;
const int width = 3;
std::string oscillator_like_indicator = (is_oscillator_like() ? "true" : "false");
os << " weight_max " << weight_max()
<< " Nmax " << Nmax()
<< " (oscillator-like: " << oscillator_like_indicator << ")"
<< std::endl;
for (int state_index=0; state_index<size(); ++state_index)
{
SingleParticleStatePN state(*this,state_index);
os
<< " " << "index"
<< " " << std::setw(width) << state_index
<< " " << "nljm"
<< " " << std::setw(width) << state.n()
<< " " << std::setw(width) << state.l()
<< " " << std::setw(width+2) << state.j().Str()
<< " " << std::setw(width+3) << state.m().Str()
<< " " << "weight"
<< " " << state.weight()
<< std::endl;
}
return os.str();
}
/**
* Generate a string representation of the orbital labels.
* @return orbital labels as a string
*/
std::string SingleParticleStatePN::LabelStr() const
{
std::ostringstream os;
const int width = 0; // for now, no fixed width
os << "["
<< " " << std::setw(width) << int(orbital_species())
<< " " << std::setw(width) << index()
<< " :"
<< " " << std::setw(width) << n()
<< " " << std::setw(width) << l()
<< " " << std::setw(width) << j()
<< " " << std::setw(width) << m()
<< " :"
<< " " << std::setw(width) << weight()
<< " " << "]";
return os.str();
}
/**
* Construct a space with species subspaces from an OrbitalSpacePN.
*
* @param[in] states vector of orbitals
*/
SingleParticleSpacePN::SingleParticleSpacePN(const OrbitalSpacePN& orbital_space)
{
weight_max_ = orbital_space.weight_max();
// construct subspaces
for (int i=0; i<orbital_space.size(); ++i)
{
const OrbitalSubspacePN& orbital_subspace = orbital_space.GetSubspace(i);
PushSubspace(SingleParticleSubspacePN(orbital_subspace));
}
// check if oscillator-like and set Nmax
is_oscillator_like_ = orbital_space.is_oscillator_like();
if (is_oscillator_like()) {
Nmax_ = orbital_space.Nmax();
} else {
Nmax_ = -1;
}
}
/**
* Generate a string representation, useful for debugging.
* @return debug string
*/
std::string SingleParticleSpacePN::DebugStr() const
{
std::ostringstream os;
const int width = 3;
std::string oscillator_like_indicator = (is_oscillator_like() ? "true" : "false");
os << " weight_max " << weight_max()
<< " Nmax " << Nmax()
<< " (oscillator-like: " << oscillator_like_indicator << ")"
<< std::endl;
for (int subspace_index=0; subspace_index<size(); ++subspace_index)
{
const SubspaceType& subspace = GetSubspace(subspace_index);
os
<< " " << "index"
<< " " << std::setw(width) << subspace_index
<< " " << "species"
<< " " << std::setw(width) << int(subspace.orbital_species())
<< " " << "dim"
<< " " << std::setw(width) << subspace.size()
<< " " << std::endl;
}
return os.str();
}
} // namespace basis
<commit_msg>m_scheme: Fix include<commit_after>/****************************************************************
m_scheme.cpp
Patrick J. Fasano
University of Notre Dame
European Centre for Theoretical Studies
in Nuclear Physics and Related Areas
****************************************************************/
#include <iomanip> // for debugging output
#include <iostream>
#include <sstream>
#include <set>
#include <algorithm>
#include "am/am.h"
#include "mcutils/parsing.h"
#include "basis/proton_neutron.h"
#include "basis/m_scheme.h"
namespace basis {
////////////////////////////////////////////////////////////////
// single-particle states
////////////////////////////////////////////////////////////////
/**
* Construct a subspace with a particular species from an OrbitalSubspacePN.
*
* @param[in] orbital_subspace orbital subspace
*/
SingleParticleSubspacePN::SingleParticleSubspacePN(const OrbitalSubspacePN& orbital_subspace)
{
// set values
labels_ = SubspaceLabelsType(orbital_subspace.labels());
weight_max_ = orbital_subspace.weight_max();
// iterate over all states, enumerating m-substates
for (int i=0; i < orbital_subspace.size(); ++i) {
OrbitalStatePN orbital(orbital_subspace, i);
for (HalfInt m = -orbital.j(); m <= orbital.j(); ++m) {
PushStateLabels(StateLabelsType(orbital.n(),orbital.l(),orbital.j(),m));
weights_.push_back(orbital.weight());
}
}
// check if oscillator-like and set Nmax
is_oscillator_like_ = orbital_subspace.is_oscillator_like();
if (is_oscillator_like()) {
Nmax_ = orbital_subspace.Nmax();
} else {
Nmax_ = -1;
}
}
/**
* Generate a string representation of the subspace labels.
* @return subspace labels as a string
*/
std::string SingleParticleSubspacePN::LabelStr() const
{
std::ostringstream os;
const int width = 0; // for now, no fixed width
os << "["
<< " " << std::setw(width) << int(orbital_species())
<< " " << "]";
return os.str();
}
/**
* Generate a string representation, useful for debugging.
* @return debug string
*/
std::string SingleParticleSubspacePN::DebugStr() const
{
std::ostringstream os;
const int width = 3;
std::string oscillator_like_indicator = (is_oscillator_like() ? "true" : "false");
os << " weight_max " << weight_max()
<< " Nmax " << Nmax()
<< " (oscillator-like: " << oscillator_like_indicator << ")"
<< std::endl;
for (int state_index=0; state_index<size(); ++state_index)
{
SingleParticleStatePN state(*this,state_index);
os
<< " " << "index"
<< " " << std::setw(width) << state_index
<< " " << "nljm"
<< " " << std::setw(width) << state.n()
<< " " << std::setw(width) << state.l()
<< " " << std::setw(width+2) << state.j().Str()
<< " " << std::setw(width+3) << state.m().Str()
<< " " << "weight"
<< " " << state.weight()
<< std::endl;
}
return os.str();
}
/**
* Generate a string representation of the orbital labels.
* @return orbital labels as a string
*/
std::string SingleParticleStatePN::LabelStr() const
{
std::ostringstream os;
const int width = 0; // for now, no fixed width
os << "["
<< " " << std::setw(width) << int(orbital_species())
<< " " << std::setw(width) << index()
<< " :"
<< " " << std::setw(width) << n()
<< " " << std::setw(width) << l()
<< " " << std::setw(width) << j()
<< " " << std::setw(width) << m()
<< " :"
<< " " << std::setw(width) << weight()
<< " " << "]";
return os.str();
}
/**
* Construct a space with species subspaces from an OrbitalSpacePN.
*
* @param[in] states vector of orbitals
*/
SingleParticleSpacePN::SingleParticleSpacePN(const OrbitalSpacePN& orbital_space)
{
weight_max_ = orbital_space.weight_max();
// construct subspaces
for (int i=0; i<orbital_space.size(); ++i)
{
const OrbitalSubspacePN& orbital_subspace = orbital_space.GetSubspace(i);
PushSubspace(SingleParticleSubspacePN(orbital_subspace));
}
// check if oscillator-like and set Nmax
is_oscillator_like_ = orbital_space.is_oscillator_like();
if (is_oscillator_like()) {
Nmax_ = orbital_space.Nmax();
} else {
Nmax_ = -1;
}
}
/**
* Generate a string representation, useful for debugging.
* @return debug string
*/
std::string SingleParticleSpacePN::DebugStr() const
{
std::ostringstream os;
const int width = 3;
std::string oscillator_like_indicator = (is_oscillator_like() ? "true" : "false");
os << " weight_max " << weight_max()
<< " Nmax " << Nmax()
<< " (oscillator-like: " << oscillator_like_indicator << ")"
<< std::endl;
for (int subspace_index=0; subspace_index<size(); ++subspace_index)
{
const SubspaceType& subspace = GetSubspace(subspace_index);
os
<< " " << "index"
<< " " << std::setw(width) << subspace_index
<< " " << "species"
<< " " << std::setw(width) << int(subspace.orbital_species())
<< " " << "dim"
<< " " << std::setw(width) << subspace.size()
<< " " << std::endl;
}
return os.str();
}
} // namespace basis
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2018 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <vector>
#include <votca/xtp/fragment.h>
using namespace votca::ctp;
using namespace std;
namespace votca { namespace xtp {
Fragment::Fragment(Fragment *stencil)
: _id(stencil->getId()), _name(stencil->getName()+"_ghost"),
_top(NULL), _mol(NULL), _rotateQM2MD(stencil->getRotQM2MD()),
_CoQM(stencil->getCoQM()), _CoMD(stencil->getCoMD()),
_trihedron(stencil->getTrihedron()) {
vector< Atom* > ::iterator ait;
for (ait = stencil->Atoms().begin();
ait < stencil->Atoms().end();
ait++) {
Atom *newAtom = new Atom(*ait);
this->AddAtom(newAtom);
}
}
Fragment::~Fragment() {
vector < Atom* > ::iterator atmit;
for (atmit = this->Atoms().begin();
atmit < this->Atoms().end();
++atmit) {
delete *atmit;
}
_weights.clear();
_atoms.clear();
vector < PolarSite* > ::iterator pit;
for (pit = this->PolarSites().begin();
pit < this->PolarSites().end();
++pit) {
delete *pit;
}
_polarSites.clear();
}
void Fragment::AddAtom(Atom* atom) {
_atoms.push_back( atom );
atom->setFragment(this);
_weights.push_back( atom->getWeight() );
}
void Fragment::AddPolarSite(PolarSite *pole) {
_polarSites.push_back(pole);
pole->setFragment(this);
}
void Fragment::AddAPolarSite(APolarSite *pole) {
_apolarSites.push_back(pole);
pole->setFragment(this);
}
void Fragment::Rotate(matrix spin, vec refPos) {
vector <Atom*> ::iterator ait;
for (ait = _atoms.begin(); ait < _atoms.end(); ait++) {
vec dir = (*ait)->getQMPos() - refPos;
dir = spin * dir;
vec pos = refPos + dir;
(*ait)->setQMPos(pos);
}
}
void Fragment::TranslateBy(const vec &shift) {
_CoMD = _CoMD + shift;
vector <Atom*> ::iterator ait;
for (ait = _atoms.begin(); ait < _atoms.end(); ait++) {
(*ait)->TranslateBy(shift);
}
}
void Fragment::RotTransQM2MD() {
vector <Atom*> ::iterator ait;
for (ait= _atoms.begin(); ait < _atoms.end(); ait++) {
vec newQMPos = _rotateQM2MD*( (*ait)->getQMPos() - this->_CoQM )
+ this->_CoMD;
(*ait)->setQMPos(newQMPos);
}
}
void Fragment::calcPos(string tag) {
vec pos = vec(0,0,0);
double totWeight = 0.0;
for (unsigned int i = 0; i< _atoms.size(); i++) {
if (tag == "MD") {
pos += _atoms[i]->getPos() * _atoms[i]->getWeight();
}
else if (tag == "QM") {
if (_atoms[i]->HasQMPart())
pos += _atoms[i]->getQMPos() * _atoms[i]->getWeight();
else
assert(_atoms[i]->getWeight() < 1e-6);
}
totWeight += _atoms[i]->getWeight();
}
if (tag == "MD") {
_CoMD = pos / totWeight;
}
else if (tag == "QM") {
_CoQM = pos / totWeight;
}
}
void Fragment::Rigidify(bool Auto) {
// +++++++++++++++++++++++++++++++++++++++++ //
// Establish reference atoms for local frame //
// +++++++++++++++++++++++++++++++++++++++++ //
vector<Atom*> trihedron;
if (Auto) {
// Automated search for suitable atoms
bool enough = false;
vector< Atom* > ::iterator ait = this->Atoms().begin();
while (!enough) {
if (ait == this->Atoms().end()) { break; }
Atom *atm = *ait;
ait++;
// When specifying mapping weights for rigid fragments,
// mobile atoms (whose position can vary significantly with
// respect to the rigid plane, for instance) should have a weight 0.
// We do not want to pick those to establish the local frame.
if (atm->getWeight() == 0.0) { continue; }
else {
trihedron.push_back(atm);
if (trihedron.size() == 3) { enough = true; }
}
}
}
else {
// Take atoms specified in mapping file <= DEFAULT
vector<Atom*> ::iterator ait;
for (ait = _atoms.begin(); ait < _atoms.end(); ait++) {
if ( ! (*ait)->HasQMPart() ) { continue; }
if ( (*ait)->getQMId() == _trihedron[0] ||
(*ait)->getQMId() == _trihedron[1] ||
(*ait)->getQMId() == _trihedron[2] ) {
Atom *atm = *ait;
trihedron.push_back(atm);
}
}
}
_symmetry = trihedron.size();
// [-Wlogical-not-parentheses]
if ( trihedron.size() != _trihedron.size() ) {
cout << endl << "ERROR Local frame ill-defined" << flush;
}
// +++++++++++++++++++++++ //
// Construct trihedra axes //
// +++++++++++++++++++++++ //
vec xMD, yMD, zMD;
vec xQM, yQM, zQM;
if (_symmetry == 3) {
vec r1MD = trihedron[0]->getPos();
vec r2MD = trihedron[1]->getPos();
vec r3MD = trihedron[2]->getPos();
vec r1QM = trihedron[0]->getQMPos();
vec r2QM = trihedron[1]->getQMPos();
vec r3QM = trihedron[2]->getQMPos();
xMD = r2MD - r1MD;
yMD = r3MD - r1MD;
xQM = r2QM - r1QM;
yQM = r3QM - r1QM;
zMD = xMD ^ yMD;
zQM = xQM ^ yQM;
yMD = zMD ^ xMD;
yQM = zQM ^ xQM;
xMD = xMD.normalize();
yMD = yMD.normalize();
zMD = zMD.normalize();
xQM = xQM.normalize();
yQM = yQM.normalize();
zQM = zQM.normalize();
}
else if (_symmetry == 2) {
vec r1MD = trihedron[0]->getPos();
vec r2MD = trihedron[1]->getPos();
vec r1QM = trihedron[0]->getQMPos();
vec r2QM = trihedron[1]->getQMPos();
xMD = r2MD - r1MD;
xQM = r2QM - r1QM;
// Normalising not necessary, but recommendable, when doing...
xMD = xMD.normalize();
xQM = xQM.normalize();
vec yMDtmp = vec(0,0,0);
vec yQMtmp = vec(0,0,0);
// ... this: Check whether one of the components is equal or close to
// zero. If so, this easily gives a second leg for the trihedron.
if ( xMD.getX()*xMD.getX() < 1e-6 ) { yMDtmp = vec(1,0,0); }
else if ( xMD.getY()*xMD.getY() < 1e-6 ) { yMDtmp = vec(0,1,0); }
else if ( xMD.getZ()*xMD.getZ() < 1e-6 ) { yMDtmp = vec(0,0,1); }
if ( xQM.getX()*xQM.getX() < 1e-6 ) { yQMtmp = vec(1,0,0); }
else if ( xQM.getY()*xQM.getY() < 1e-6 ) { yQMtmp = vec(0,1,0); }
else if ( xQM.getZ()*xQM.getZ() < 1e-6 ) { yQMtmp = vec(0,0,1); }
if ( abs(yMDtmp) < 0.5 ) {
// All components of xMD are unequal to zero => division is safe.
// Choose vector from plane with xMD * inPlaneVec = 0:
double tmp_x = 1.;
double tmp_y = 1.;
double tmp_z = 1/xMD.getZ() * (-xMD.getX()*tmp_x - xMD.getY()*tmp_y);
yMDtmp = vec(tmp_x, tmp_y, tmp_z);
yMDtmp.normalize();
}
if ( abs(yQMtmp) < 0.5 ) {
double tmp_x = 1.;
double tmp_y = 1.;
double tmp_z = 1/xQM.getZ() * (-xQM.getX()*tmp_x - xQM.getY()*tmp_y);
yQMtmp = vec(tmp_x, tmp_y, tmp_z);
yQMtmp.normalize();
}
// Now proceed as for symmetry 3
zMD = xMD ^ yMDtmp;
yMD = zMD ^ xMD;
zQM = xQM ^ yQMtmp;
yQM = zQM ^ xQM;
xMD.normalize();
yMD.normalize();
zMD.normalize();
xQM.normalize();
yQM.normalize();
zQM.normalize();
}
else if (_symmetry == 1) {
xMD = vec(1,0,0);
yMD = vec(0,1,0);
zMD = vec(0,0,1);
xQM = vec(1,0,0);
yQM = vec(0,1,0);
zQM = vec(0,0,1);
}
else {
cout << endl
<< "NOTE: Invalid definition of local frame in fragment "
<< this->getName();
cout << ". Assuming point particle for mapping. "
<< endl;
xMD = vec(1,0,0);
yMD = vec(0,1,0);
zMD = vec(0,0,1);
xQM = vec(1,0,0);
yQM = vec(0,1,0);
zQM = vec(0,0,1);
}
// +++++++++++++++++ //
// Rotation matrices //
// +++++++++++++++++ //
matrix rotMD = matrix(xMD, yMD, zMD);
matrix rotQM = matrix(xQM, yQM, zQM);
matrix rotateQM2MD = rotMD * rotQM.Transpose();
_rotateQM2MD = rotateQM2MD;
// ++++++++++++++++++ //
// Transform fragment //
// ++++++++++++++++++ //
this->calcPos("QM");
this->RotTransQM2MD();
_translateQM2MD = _CoMD - _CoQM;
}
}}
<commit_msg>Removed use of namespace ctp and included xtp apolar and polar header files<commit_after>/*
* Copyright 2009-2018 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <vector>
#include <votca/xtp/fragment.h>
#include <votca/xtp/apolarsite.h>
#include <votca/xtp/polarsite.h>
using namespace std;
namespace votca { namespace xtp {
Fragment::Fragment(Fragment *stencil)
: _id(stencil->getId()), _name(stencil->getName()+"_ghost"),
_top(NULL), _mol(NULL), _rotateQM2MD(stencil->getRotQM2MD()),
_CoQM(stencil->getCoQM()), _CoMD(stencil->getCoMD()),
_trihedron(stencil->getTrihedron()) {
vector< Atom* > ::iterator ait;
for (ait = stencil->Atoms().begin();
ait < stencil->Atoms().end();
ait++) {
Atom *newAtom = new Atom(*ait);
this->AddAtom(newAtom);
}
}
Fragment::~Fragment() {
vector < Atom* > ::iterator atmit;
for (atmit = this->Atoms().begin();
atmit < this->Atoms().end();
++atmit) {
delete *atmit;
}
_weights.clear();
_atoms.clear();
vector < PolarSite* > ::iterator pit;
for (pit = this->PolarSites().begin();
pit < this->PolarSites().end();
++pit) {
delete *pit;
}
_polarSites.clear();
}
void Fragment::AddAtom(Atom* atom) {
_atoms.push_back( atom );
atom->setFragment(this);
_weights.push_back( atom->getWeight() );
}
void Fragment::AddPolarSite(PolarSite *pole) {
_polarSites.push_back(pole);
pole->setFragment(this);
}
void Fragment::AddAPolarSite(APolarSite *pole) {
_apolarSites.push_back(pole);
pole->setFragment(this);
}
void Fragment::Rotate(matrix spin, vec refPos) {
vector <Atom*> ::iterator ait;
for (ait = _atoms.begin(); ait < _atoms.end(); ait++) {
vec dir = (*ait)->getQMPos() - refPos;
dir = spin * dir;
vec pos = refPos + dir;
(*ait)->setQMPos(pos);
}
}
void Fragment::TranslateBy(const vec &shift) {
_CoMD = _CoMD + shift;
vector <Atom*> ::iterator ait;
for (ait = _atoms.begin(); ait < _atoms.end(); ait++) {
(*ait)->TranslateBy(shift);
}
}
void Fragment::RotTransQM2MD() {
vector <Atom*> ::iterator ait;
for (ait= _atoms.begin(); ait < _atoms.end(); ait++) {
vec newQMPos = _rotateQM2MD*( (*ait)->getQMPos() - this->_CoQM )
+ this->_CoMD;
(*ait)->setQMPos(newQMPos);
}
}
void Fragment::calcPos(string tag) {
vec pos = vec(0,0,0);
double totWeight = 0.0;
for (unsigned int i = 0; i< _atoms.size(); i++) {
if (tag == "MD") {
pos += _atoms[i]->getPos() * _atoms[i]->getWeight();
}
else if (tag == "QM") {
if (_atoms[i]->HasQMPart())
pos += _atoms[i]->getQMPos() * _atoms[i]->getWeight();
else
assert(_atoms[i]->getWeight() < 1e-6);
}
totWeight += _atoms[i]->getWeight();
}
if (tag == "MD") {
_CoMD = pos / totWeight;
}
else if (tag == "QM") {
_CoQM = pos / totWeight;
}
}
void Fragment::Rigidify(bool Auto) {
// +++++++++++++++++++++++++++++++++++++++++ //
// Establish reference atoms for local frame //
// +++++++++++++++++++++++++++++++++++++++++ //
vector<Atom*> trihedron;
if (Auto) {
// Automated search for suitable atoms
bool enough = false;
vector< Atom* > ::iterator ait = this->Atoms().begin();
while (!enough) {
if (ait == this->Atoms().end()) { break; }
Atom *atm = *ait;
ait++;
// When specifying mapping weights for rigid fragments,
// mobile atoms (whose position can vary significantly with
// respect to the rigid plane, for instance) should have a weight 0.
// We do not want to pick those to establish the local frame.
if (atm->getWeight() == 0.0) { continue; }
else {
trihedron.push_back(atm);
if (trihedron.size() == 3) { enough = true; }
}
}
}
else {
// Take atoms specified in mapping file <= DEFAULT
vector<Atom*> ::iterator ait;
for (ait = _atoms.begin(); ait < _atoms.end(); ait++) {
if ( ! (*ait)->HasQMPart() ) { continue; }
if ( (*ait)->getQMId() == _trihedron[0] ||
(*ait)->getQMId() == _trihedron[1] ||
(*ait)->getQMId() == _trihedron[2] ) {
Atom *atm = *ait;
trihedron.push_back(atm);
}
}
}
_symmetry = trihedron.size();
// [-Wlogical-not-parentheses]
if ( trihedron.size() != _trihedron.size() ) {
cout << endl << "ERROR Local frame ill-defined" << flush;
}
// +++++++++++++++++++++++ //
// Construct trihedra axes //
// +++++++++++++++++++++++ //
vec xMD, yMD, zMD;
vec xQM, yQM, zQM;
if (_symmetry == 3) {
vec r1MD = trihedron[0]->getPos();
vec r2MD = trihedron[1]->getPos();
vec r3MD = trihedron[2]->getPos();
vec r1QM = trihedron[0]->getQMPos();
vec r2QM = trihedron[1]->getQMPos();
vec r3QM = trihedron[2]->getQMPos();
xMD = r2MD - r1MD;
yMD = r3MD - r1MD;
xQM = r2QM - r1QM;
yQM = r3QM - r1QM;
zMD = xMD ^ yMD;
zQM = xQM ^ yQM;
yMD = zMD ^ xMD;
yQM = zQM ^ xQM;
xMD = xMD.normalize();
yMD = yMD.normalize();
zMD = zMD.normalize();
xQM = xQM.normalize();
yQM = yQM.normalize();
zQM = zQM.normalize();
}
else if (_symmetry == 2) {
vec r1MD = trihedron[0]->getPos();
vec r2MD = trihedron[1]->getPos();
vec r1QM = trihedron[0]->getQMPos();
vec r2QM = trihedron[1]->getQMPos();
xMD = r2MD - r1MD;
xQM = r2QM - r1QM;
// Normalising not necessary, but recommendable, when doing...
xMD = xMD.normalize();
xQM = xQM.normalize();
vec yMDtmp = vec(0,0,0);
vec yQMtmp = vec(0,0,0);
// ... this: Check whether one of the components is equal or close to
// zero. If so, this easily gives a second leg for the trihedron.
if ( xMD.getX()*xMD.getX() < 1e-6 ) { yMDtmp = vec(1,0,0); }
else if ( xMD.getY()*xMD.getY() < 1e-6 ) { yMDtmp = vec(0,1,0); }
else if ( xMD.getZ()*xMD.getZ() < 1e-6 ) { yMDtmp = vec(0,0,1); }
if ( xQM.getX()*xQM.getX() < 1e-6 ) { yQMtmp = vec(1,0,0); }
else if ( xQM.getY()*xQM.getY() < 1e-6 ) { yQMtmp = vec(0,1,0); }
else if ( xQM.getZ()*xQM.getZ() < 1e-6 ) { yQMtmp = vec(0,0,1); }
if ( abs(yMDtmp) < 0.5 ) {
// All components of xMD are unequal to zero => division is safe.
// Choose vector from plane with xMD * inPlaneVec = 0:
double tmp_x = 1.;
double tmp_y = 1.;
double tmp_z = 1/xMD.getZ() * (-xMD.getX()*tmp_x - xMD.getY()*tmp_y);
yMDtmp = vec(tmp_x, tmp_y, tmp_z);
yMDtmp.normalize();
}
if ( abs(yQMtmp) < 0.5 ) {
double tmp_x = 1.;
double tmp_y = 1.;
double tmp_z = 1/xQM.getZ() * (-xQM.getX()*tmp_x - xQM.getY()*tmp_y);
yQMtmp = vec(tmp_x, tmp_y, tmp_z);
yQMtmp.normalize();
}
// Now proceed as for symmetry 3
zMD = xMD ^ yMDtmp;
yMD = zMD ^ xMD;
zQM = xQM ^ yQMtmp;
yQM = zQM ^ xQM;
xMD.normalize();
yMD.normalize();
zMD.normalize();
xQM.normalize();
yQM.normalize();
zQM.normalize();
}
else if (_symmetry == 1) {
xMD = vec(1,0,0);
yMD = vec(0,1,0);
zMD = vec(0,0,1);
xQM = vec(1,0,0);
yQM = vec(0,1,0);
zQM = vec(0,0,1);
}
else {
cout << endl
<< "NOTE: Invalid definition of local frame in fragment "
<< this->getName();
cout << ". Assuming point particle for mapping. "
<< endl;
xMD = vec(1,0,0);
yMD = vec(0,1,0);
zMD = vec(0,0,1);
xQM = vec(1,0,0);
yQM = vec(0,1,0);
zQM = vec(0,0,1);
}
// +++++++++++++++++ //
// Rotation matrices //
// +++++++++++++++++ //
matrix rotMD = matrix(xMD, yMD, zMD);
matrix rotQM = matrix(xQM, yQM, zQM);
matrix rotateQM2MD = rotMD * rotQM.Transpose();
_rotateQM2MD = rotateQM2MD;
// ++++++++++++++++++ //
// Transform fragment //
// ++++++++++++++++++ //
this->calcPos("QM");
this->RotTransQM2MD();
_translateQM2MD = _CoMD - _CoQM;
}
}}
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include <rapicorn.hh>
#include "../rcore/rsvg/svg.hh" // FIXME
#include <string.h>
#include <stdlib.h>
namespace {
using namespace Rapicorn;
static void
help_usage (bool usage_error)
{
const char *usage = "Usage: rapidrun [OPTIONS] <GuiFile.xml>";
if (usage_error)
{
printerr ("%s\n", usage);
printerr ("Try 'rapidrun --help' for more information.\n");
Rapicorn::exit (1);
}
printout ("%s\n", usage);
/* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
printout ("Show Rapicorn dialogs defined in GuiFile.xml.\n");
printout ("This tool will read the GUI description file listed on the command\n");
printout ("line, look for a dialog named 'test-dialog' and show it.\n");
printout ("\n");
printout ("Options:\n");
printout (" --parse-test Parse GuiFile.xml and exit.\n");
printout (" -l <uilib> Load ''uilib'' upon startup.\n");
printout (" -x Enable auto-exit after first expose.\n");
printout (" --list List parsed definitions.\n");
printout (" --test-dump Dump test stream after first expose.\n");
printout (" --test-matched-node PATTERN Filter nodes in test dumps.\n");
printout (" -h, --help Display this help and exit.\n");
printout (" -v, --version Display version and exit.\n");
}
static bool parse_test = false;
static bool auto_exit = false;
static bool list_definitions = false;
static bool test_dump = false;
static vector<String> test_dump_matched_nodes;
static void
parse_args (int *argc_p,
char ***argv_p)
{
char **argv = *argv_p;
uint argc = *argc_p;
for (uint i = 1; i < argc; i++)
{
if (strcmp (argv[i], "--parse-test") == 0)
{
parse_test = true;
argv[i] = NULL;
}
else if (strcmp (argv[i], "-x") == 0)
{
auto_exit = true;
argv[i] = NULL;
}
else if (strcmp (argv[i], "-l") == 0 ||
strncmp ("-l=", argv[i], 2) == 0)
{
const char *v = NULL, *equal = argv[i] + 2;
if (*equal == '=')
v = equal + 1;
else if (i + 1 < argc)
{
argv[i++] = NULL;
v = argv[i];
}
if (v)
Svg::Library::add_library (v);
argv[i] = NULL;
}
else if (strcmp (argv[i], "--list") == 0)
{
list_definitions = true;
argv[i] = NULL;
}
else if (strcmp (argv[i], "--test-dump") == 0)
{
test_dump = true;
argv[i] = NULL;
}
else if (strcmp ("--test-matched-node", argv[i]) == 0 ||
strncmp ("--test-matched-node=", argv[i], 20) == 0)
{
char *v = NULL, *equal = argv[i] + 19;
if (*equal == '=')
v = equal + 1;
else if (i + 1 < argc)
{
argv[i++] = NULL;
v = argv[i];
}
if (v)
test_dump_matched_nodes.push_back (v);
argv[i] = NULL;
}
else if (strcmp (argv[i], "--help") == 0 || strcmp (argv[i], "-h") == 0)
{
help_usage (false);
Rapicorn::exit (0);
}
else if (strcmp (argv[i], "--version") == 0 || strcmp (argv[i], "-v") == 0)
{
printout ("rapidrun (Rapicorn utilities) %s\n", RAPICORN_VERSION);
printout ("Copyright (C) 2007 Tim Janik.\n");
printout ("This is free software and comes with ABSOLUTELY NO WARRANTY; see\n");
printout ("the source for copying conditions. Sources, examples and contact\n");
printout ("information are available at http://rapicorn.org/.\n");
Rapicorn::exit (0);
}
}
uint e = 1;
for (uint i = 1; i < argc; i++)
if (argv[i])
{
argv[e++] = argv[i];
if (i >= e)
argv[i] = NULL;
}
*argc_p = e;
}
static void
window_displayed (Window &window)
{
if (test_dump)
{
#if 0 // FIXME
for (uint i = 0; i < test_dump_matched_nodes.size(); i++)
tstream->filter_matched_nodes (test_dump_matched_nodes[i]);
#endif
String s = window.test_dump();
printout ("%s", s.c_str());
test_dump = false;
}
if (auto_exit)
window.close();
}
extern "C" int
main (int argc,
char *argv[])
{
/* initialize Rapicorn and its backend (X11) */
Application app = Rapicorn::init_app ("Rapidrun", &argc, argv); // acquires Rapicorn mutex
parse_args (&argc, &argv);
if (argc != 2)
help_usage (true);
/* find GUI definition file, relative to CWD */
String filename = app.auto_path (argv[1], ".");
/* load GUI definitions, fancy version of app.auto_load() */
StringList definitions = app.auto_load ("RapicornTest", filename, "");
/* print definitions */
String dialog;
for (uint i = 0; i < definitions.size(); i++)
{
bool iswindow = app.factory_window (definitions[i]);
if (list_definitions)
printout ("%s%s\n", definitions[i].c_str(), iswindow ? " (window)" : "");
if (dialog == "" && iswindow)
dialog = definitions[i];
}
if (list_definitions)
Rapicorn::exit (0);
/* bail out without any dialogs */
if (dialog == "")
{
printerr ("%s: no dialog definitions\n", filename.c_str());
return 1;
}
// create window, hook up post-display handler
Window window = app.create_window (dialog);
window.sig_displayed() += window_displayed;
/* show window and process events */
window.show();
return app.run_and_exit();
}
} // anon
<commit_msg>TOOLS: added --snapshot to rapidrun<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include <rapicorn.hh>
#include "../rcore/rsvg/svg.hh" // FIXME
#include <string.h>
#include <stdlib.h>
namespace {
using namespace Rapicorn;
static void
help_usage (bool usage_error)
{
const char *usage = "Usage: rapidrun [OPTIONS] <GuiFile.xml>";
if (usage_error)
{
printerr ("%s\n", usage);
printerr ("Try 'rapidrun --help' for more information.\n");
Rapicorn::exit (1);
}
printout ("%s\n", usage);
/* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
printout ("Show Rapicorn dialogs defined in GuiFile.xml.\n");
printout ("This tool will read the GUI description file listed on the command\n");
printout ("line, look for a dialog named 'test-dialog' and show it.\n");
printout ("\n");
printout ("Options:\n");
printout (" --parse-test Parse GuiFile.xml and exit.\n");
printout (" -l <uilib> Load ''uilib'' upon startup.\n");
printout (" -x Enable auto-exit after first expose.\n");
printout (" --list List parsed definitions.\n");
printout (" --snapshot pngname Dump a snapshot to <pngname>.\n");
printout (" --test-dump Dump test stream after first expose.\n");
printout (" --test-matched-node PATTERN Filter nodes in test dumps.\n");
printout (" -h, --help Display this help and exit.\n");
printout (" -v, --version Display version and exit.\n");
}
static bool parse_test = false;
static bool auto_exit = false;
static bool list_definitions = false;
static String dump_snapshot = "";
static bool test_dump = false;
static vector<String> test_dump_matched_nodes;
static void
parse_args (int *argc_p,
char ***argv_p)
{
char **argv = *argv_p;
uint argc = *argc_p;
for (uint i = 1; i < argc; i++)
{
if (strcmp (argv[i], "--parse-test") == 0)
{
parse_test = true;
argv[i] = NULL;
}
else if (strcmp (argv[i], "-x") == 0)
{
auto_exit = true;
argv[i] = NULL;
}
else if (strcmp (argv[i], "-l") == 0 ||
strncmp ("-l=", argv[i], 2) == 0)
{
const char *v = NULL, *equal = argv[i] + 2;
if (*equal == '=')
v = equal + 1;
else if (i + 1 < argc)
{
argv[i++] = NULL;
v = argv[i];
}
if (v)
Svg::Library::add_library (v);
argv[i] = NULL;
}
else if (strcmp (argv[i], "--list") == 0)
{
list_definitions = true;
argv[i] = NULL;
}
else if (strcmp ("--snapshot", argv[i]) == 0 ||
strncmp ("--snapshot=", argv[i], 11) == 0)
{
char *v = NULL, *equal = argv[i] + 10;
if (*equal == '=')
v = equal + 1;
else if (i + 1 < argc)
{
argv[i++] = NULL;
v = argv[i];
}
if (v)
dump_snapshot = v;
argv[i] = NULL;
}
else if (strcmp (argv[i], "--test-dump") == 0)
{
test_dump = true;
argv[i] = NULL;
}
else if (strcmp ("--test-matched-node", argv[i]) == 0 ||
strncmp ("--test-matched-node=", argv[i], 20) == 0)
{
char *v = NULL, *equal = argv[i] + 19;
if (*equal == '=')
v = equal + 1;
else if (i + 1 < argc)
{
argv[i++] = NULL;
v = argv[i];
}
if (v)
test_dump_matched_nodes.push_back (v);
argv[i] = NULL;
}
else if (strcmp (argv[i], "--help") == 0 || strcmp (argv[i], "-h") == 0)
{
help_usage (false);
Rapicorn::exit (0);
}
else if (strcmp (argv[i], "--version") == 0 || strcmp (argv[i], "-v") == 0)
{
printout ("rapidrun (Rapicorn utilities) %s\n", RAPICORN_VERSION);
printout ("Copyright (C) 2007 Tim Janik.\n");
printout ("This is free software and comes with ABSOLUTELY NO WARRANTY; see\n");
printout ("the source for copying conditions. Sources, examples and contact\n");
printout ("information are available at http://rapicorn.org/.\n");
Rapicorn::exit (0);
}
}
uint e = 1;
for (uint i = 1; i < argc; i++)
if (argv[i])
{
argv[e++] = argv[i];
if (i >= e)
argv[i] = NULL;
}
*argc_p = e;
}
static void
window_displayed (Window &window)
{
if (!dump_snapshot.empty())
{
window.snapshot (dump_snapshot);
}
if (test_dump)
{
#if 0 // FIXME
for (uint i = 0; i < test_dump_matched_nodes.size(); i++)
tstream->filter_matched_nodes (test_dump_matched_nodes[i]);
#endif
String s = window.test_dump();
printout ("%s", s.c_str());
test_dump = false;
}
if (auto_exit)
window.close();
}
extern "C" int
main (int argc,
char *argv[])
{
/* initialize Rapicorn and its backend (X11) */
Application app = Rapicorn::init_app ("Rapidrun", &argc, argv); // acquires Rapicorn mutex
parse_args (&argc, &argv);
if (argc != 2)
help_usage (true);
/* find GUI definition file, relative to CWD */
String filename = app.auto_path (argv[1], ".");
/* load GUI definitions, fancy version of app.auto_load() */
StringList definitions = app.auto_load ("RapicornTest", filename, "");
/* print definitions */
String dialog;
for (uint i = 0; i < definitions.size(); i++)
{
bool iswindow = app.factory_window (definitions[i]);
if (list_definitions)
printout ("%s%s\n", definitions[i].c_str(), iswindow ? " (window)" : "");
if (dialog == "" && iswindow)
dialog = definitions[i];
}
if (list_definitions)
Rapicorn::exit (0);
/* bail out without any dialogs */
if (dialog == "")
{
printerr ("%s: no dialog definitions\n", filename.c_str());
return 1;
}
// create window, hook up post-display handler
Window window = app.create_window (dialog);
window.sig_displayed() += window_displayed;
/* show window and process events */
window.show();
return app.run_and_exit();
}
} // anon
<|endoftext|> |
<commit_before>/*
* A auto-growing buffer you can write to.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_GROWING_BUFFER_HXX
#define BENG_PROXY_GROWING_BUFFER_HXX
#include <inline/compiler.h>
#include <stddef.h>
struct pool;
template<typename T> struct ConstBuffer;
template<typename T> struct WritableBuffer;
class IstreamBucketList;
class GrowingBuffer {
friend class GrowingBufferReader;
struct Buffer {
Buffer *next = nullptr;
const size_t size;
size_t fill = 0;
char data[sizeof(size_t)];
explicit Buffer(size_t _size)
:size(_size) {}
static Buffer *New(struct pool &pool, size_t size);
bool IsFull() const {
return fill == size;
}
WritableBuffer<void> Write();
size_t WriteSome(ConstBuffer<void> src);
};
struct pool &pool;
const size_t default_size;
Buffer *head = nullptr, *tail = nullptr;
public:
GrowingBuffer(struct pool &_pool, size_t _default_size);
GrowingBuffer(GrowingBuffer &&src)
:pool(src.pool),
default_size(src.default_size),
head(src.head), tail(src.tail) {
src.Release();
}
/**
* Release the buffer list, which may now be owned by somebody
* else.
*/
void Release() {
head = tail = nullptr;
}
void *Write(size_t length);
void Write(const void *p, size_t length);
void Write(const char *p);
void AppendMoveFrom(GrowingBuffer &&src);
/**
* Returns the total size of the buffer.
*/
gcc_pure
size_t GetSize() const;
/**
* Duplicates the whole buffer (including all chunks) to one
* contiguous buffer.
*/
WritableBuffer<void> Dup(struct pool &pool) const;
private:
void AppendBuffer(Buffer &buffer);
Buffer &AppendBuffer(size_t min_size);
void CopyTo(void *dest) const;
};
class GrowingBufferReader {
#ifndef NDEBUG
const GrowingBuffer *growing_buffer;
#endif
const GrowingBuffer::Buffer *buffer;
size_t position;
public:
explicit GrowingBufferReader(const GrowingBuffer &gb);
/**
* Update the reader object after data has been appended to the
* underlying buffer.
*/
void Update(const GrowingBuffer &gb);
gcc_pure
bool IsEOF() const;
gcc_pure
size_t Available() const;
gcc_pure
ConstBuffer<void> Read() const;
/**
* Consume data returned by Read().
*/
void Consume(size_t length);
/**
* Peek data from the buffer following the current one.
*/
ConstBuffer<void> PeekNext() const;
/**
* Skip an arbitrary number of data bytes, which may span over
* multiple internal buffers.
*/
void Skip(size_t length);
void FillBucketList(IstreamBucketList &list) const;
size_t ConsumeBucketList(size_t nbytes);
};
GrowingBuffer *gcc_malloc
growing_buffer_new(struct pool *pool, size_t initial_size);
#endif
<commit_msg>growing_buffer: add methods IsEmpty(), Clear()<commit_after>/*
* A auto-growing buffer you can write to.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_GROWING_BUFFER_HXX
#define BENG_PROXY_GROWING_BUFFER_HXX
#include <inline/compiler.h>
#include <stddef.h>
struct pool;
template<typename T> struct ConstBuffer;
template<typename T> struct WritableBuffer;
class IstreamBucketList;
class GrowingBuffer {
friend class GrowingBufferReader;
struct Buffer {
Buffer *next = nullptr;
const size_t size;
size_t fill = 0;
char data[sizeof(size_t)];
explicit Buffer(size_t _size)
:size(_size) {}
static Buffer *New(struct pool &pool, size_t size);
bool IsFull() const {
return fill == size;
}
WritableBuffer<void> Write();
size_t WriteSome(ConstBuffer<void> src);
};
struct pool &pool;
const size_t default_size;
Buffer *head = nullptr, *tail = nullptr;
public:
GrowingBuffer(struct pool &_pool, size_t _default_size);
GrowingBuffer(GrowingBuffer &&src)
:pool(src.pool),
default_size(src.default_size),
head(src.head), tail(src.tail) {
src.Release();
}
bool IsEmpty() const {
return head == nullptr;
}
void Clear() {
Release();
}
/**
* Release the buffer list, which may now be owned by somebody
* else.
*/
void Release() {
head = tail = nullptr;
}
void *Write(size_t length);
void Write(const void *p, size_t length);
void Write(const char *p);
void AppendMoveFrom(GrowingBuffer &&src);
/**
* Returns the total size of the buffer.
*/
gcc_pure
size_t GetSize() const;
/**
* Duplicates the whole buffer (including all chunks) to one
* contiguous buffer.
*/
WritableBuffer<void> Dup(struct pool &pool) const;
private:
void AppendBuffer(Buffer &buffer);
Buffer &AppendBuffer(size_t min_size);
void CopyTo(void *dest) const;
};
class GrowingBufferReader {
#ifndef NDEBUG
const GrowingBuffer *growing_buffer;
#endif
const GrowingBuffer::Buffer *buffer;
size_t position;
public:
explicit GrowingBufferReader(const GrowingBuffer &gb);
/**
* Update the reader object after data has been appended to the
* underlying buffer.
*/
void Update(const GrowingBuffer &gb);
gcc_pure
bool IsEOF() const;
gcc_pure
size_t Available() const;
gcc_pure
ConstBuffer<void> Read() const;
/**
* Consume data returned by Read().
*/
void Consume(size_t length);
/**
* Peek data from the buffer following the current one.
*/
ConstBuffer<void> PeekNext() const;
/**
* Skip an arbitrary number of data bytes, which may span over
* multiple internal buffers.
*/
void Skip(size_t length);
void FillBucketList(IstreamBucketList &list) const;
size_t ConsumeBucketList(size_t nbytes);
};
GrowingBuffer *gcc_malloc
growing_buffer_new(struct pool *pool, size_t initial_size);
#endif
<|endoftext|> |
<commit_before>#include "util/bitmap.h"
#include "tabbed-box.h"
#include "menu/menu.h"
#include "util/font.h"
#include "gui/context-box.h"
using namespace Gui;
#if 0
/* FIXME add rounded tabs */
static void roundTab( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color, bool bottom = true ){
const int width = x2 - x1;
const int height = y2 - y1;
radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
work.circleFill(x1+radius, y1+radius, radius, color);
work.circleFill((x1+width)-radius, y1+radius, radius, color);
work.circleFill(x1+radius, (y1+height)-radius, radius, color);
work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);
work.line(x1+radius, y1, x1+width-radius, y1, color);
work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
work.line(x1, y1+radius,x1, y1+height-radius, color);
work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);
arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}
#endif
Tab::Tab():
context(new ContextBox()),
active(false){
// Set alpha to 0 as we are not interested in the box
context->colors.borderAlpha = 0;
context->colors.bodyAlpha = 0;
}
Tab::~Tab(){
delete context;
}
TabbedBox::TabbedBox():
current(0),
fontWidth(24),
fontHeight(24),
inTab(false),
tabWidthMax(0),
tabFontColor(Bitmap::makeColor(255,255,255)),
currentTabFontColor(Bitmap::makeColor(0,0,255)){
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
TabbedBox::TabbedBox(const TabbedBox & b):
activeTabFontColor(NULL){
this->location = b.location;
this->workArea = b.workArea;
}
TabbedBox::~TabbedBox(){
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
if (tab){
delete tab;
}
}
if (activeTabFontColor){
delete activeTabFontColor;
}
}
TabbedBox &TabbedBox::operator=( const TabbedBox ©){
location = copy.location;
workArea = copy.workArea;
return *this;
}
// Logic
void TabbedBox::act(){
if (!tabs.empty()){
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
//tabWidthMax = location.getWidth()/tabs.size();
const int width = vFont.textLength(tabs[current]->name.c_str()) + 5;
tabWidthMax = (location.getWidth() - width) / (tabs.size() - 1);
} else {
return;
}
if (!tabs[current]->active){
tabs[current]->active = true;
}
tabs[current]->context->act();
if (inTab){
if (activeTabFontColor){
activeTabFontColor->update();
}
}
}
// Render
void TabbedBox::render(const Bitmap & work){
const int tabHeight = fontHeight + 5;
checkWorkArea();
// Check if we are using a rounded box
if (location.getRadius() > 0){
//roundRectFill( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
//roundRect( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
} else {
workArea->rectangleFill(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.body );
workArea->rectangle(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.border );
}
tabs[current]->context->render(*workArea);
renderTabs(*workArea);
Bitmap::transBlender( 0, 0, 0, colors.bodyAlpha );
/* FIXME: only render the background in translucent mode, the text should
* not be translucent
*/
workArea->drawTrans(location.getX(), location.getY(), work);
}
// Add tab
void TabbedBox::addTab(const std::string & name, const std::vector<ContextItem *> & list){
for (std::vector<Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Tab * tab = *i;
if (tab->name == name){
return;
}
}
Tab * tab = new Tab();
tab->name = name;
tab->context->setList(list);
tab->context->setFont(font, fontWidth, fontHeight);
tab->context->location.setPosition(Gui::AbsolutePoint(0, fontHeight+5));
tab->context->location.setPosition2(Gui::AbsolutePoint(location.getWidth(), location.getHeight()));
tab->context->open();
tabs.push_back(tab);
}
void TabbedBox::moveTab(int direction){
tabs[current]->context->close();
tabs[current]->active = false;
current = (current + direction + tabs.size()) % tabs.size();
/*
if (current == 0){
current = tabs.size()-1;
} else {
current--;
}
*/
tabs[current]->context->open();
tabs[current]->active = true;
}
void TabbedBox::up(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->previous();
}
}
void TabbedBox::down(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->next();
}
}
void TabbedBox::left(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->adjustLeft();
}
}
void TabbedBox::right(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->adjustRight();
}
}
void TabbedBox::toggleTabSelect(){
inTab = !inTab;
}
unsigned int TabbedBox::getCurrentIndex() const {
if (tabs.size() == 0){
return 0;
}
return this->tabs[current]->context->getCurrentIndex();
}
void TabbedBox::setTabFontColor(int color){
tabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::setSelectedTabFontColor(int color){
currentTabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::renderTabs(const Bitmap & bmp){
const int tabHeight = fontHeight + 5;
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
int x = 0;
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
const int textWidth = vFont.textLength(tab->name.c_str()) + 5;
// for last tab
int modifier = 0;
// Check last tab so we can ensure proper sizing
if ( i == (tabs.begin() + tabs.size() -1)){
if ( ( (tabWidthMax * (tabs.size() - 1) ) + textWidth ) != (unsigned int)location.getWidth() ){
modifier = location.getWidth() - x - (tab->active ? textWidth : tabWidthMax);
}
}
if (tab->context->location.getRadius() > 0){
} else {
if (tab->active){
if (!inTab){
bmp.rectangle(x, 0, x+textWidth + modifier - 1, tabHeight, colors.border);
bmp.rectangleFill( x+1, 1, x+textWidth + modifier - 2, tabHeight, colors.body );
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, currentTabFontColor, bmp, tab->name, 0 );
} else {
bmp.rectangle(x, 0, x+textWidth + modifier -1, tabHeight, colors.border);
bmp.rectangleFill( x+1, 1, x+textWidth-2 + modifier, tabHeight, colors.body );
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, activeTabFontColor->current(), bmp, tab->name, 0 );
}
x+=textWidth + modifier;
} else {
bmp.rectangle(x, 0, x+tabWidthMax + modifier -1, tabHeight, tabColors.border);
bmp.rectangleFill( x+1, 1, x+tabWidthMax + modifier -2, tabHeight-2, tabColors.body );
bmp.setClipRect(x+2, 1, x+tabWidthMax + modifier -3, tabHeight-1);
vFont.printf(x + (((tabWidthMax + modifier)/2)-((textWidth + modifier)/2)), 0, tabFontColor, bmp, tab->name, 0 );
x+=tabWidthMax + modifier;
}
bmp.setClipRect(0, 0, bmp.getWidth(), bmp.getHeight());
}
}
}
<commit_msg>Make line more even with regard to current tab.<commit_after>#include "util/bitmap.h"
#include "tabbed-box.h"
#include "menu/menu.h"
#include "util/font.h"
#include "gui/context-box.h"
using namespace Gui;
#if 0
/* FIXME add rounded tabs */
static void roundTab( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color, bool bottom = true ){
const int width = x2 - x1;
const int height = y2 - y1;
radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
work.circleFill(x1+radius, y1+radius, radius, color);
work.circleFill((x1+width)-radius, y1+radius, radius, color);
work.circleFill(x1+radius, (y1+height)-radius, radius, color);
work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);
work.line(x1+radius, y1, x1+width-radius, y1, color);
work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
work.line(x1, y1+radius,x1, y1+height-radius, color);
work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);
arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}
#endif
Tab::Tab():
context(new ContextBox()),
active(false){
// Set alpha to 0 as we are not interested in the box
context->colors.borderAlpha = 0;
context->colors.bodyAlpha = 0;
}
Tab::~Tab(){
delete context;
}
TabbedBox::TabbedBox():
current(0),
fontWidth(24),
fontHeight(24),
inTab(false),
tabWidthMax(0),
tabFontColor(Bitmap::makeColor(255,255,255)),
currentTabFontColor(Bitmap::makeColor(0,0,255)){
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
TabbedBox::TabbedBox(const TabbedBox & b):
activeTabFontColor(NULL){
this->location = b.location;
this->workArea = b.workArea;
}
TabbedBox::~TabbedBox(){
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
if (tab){
delete tab;
}
}
if (activeTabFontColor){
delete activeTabFontColor;
}
}
TabbedBox &TabbedBox::operator=( const TabbedBox ©){
location = copy.location;
workArea = copy.workArea;
return *this;
}
// Logic
void TabbedBox::act(){
if (!tabs.empty()){
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
//tabWidthMax = location.getWidth()/tabs.size();
const int width = vFont.textLength(tabs[current]->name.c_str()) + 5;
tabWidthMax = (location.getWidth() - width) / (tabs.size() - 1);
} else {
return;
}
if (!tabs[current]->active){
tabs[current]->active = true;
}
tabs[current]->context->act();
if (inTab){
if (activeTabFontColor){
activeTabFontColor->update();
}
}
}
// Render
void TabbedBox::render(const Bitmap & work){
const int tabHeight = fontHeight + 5;
checkWorkArea();
// Check if we are using a rounded box
if (location.getRadius() > 0){
//roundRectFill( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
//roundRect( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
} else {
workArea->rectangleFill(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.body );
workArea->rectangle(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.border );
}
tabs[current]->context->render(*workArea);
renderTabs(*workArea);
Bitmap::transBlender( 0, 0, 0, colors.bodyAlpha );
/* FIXME: only render the background in translucent mode, the text should
* not be translucent
*/
workArea->drawTrans(location.getX(), location.getY(), work);
}
// Add tab
void TabbedBox::addTab(const std::string & name, const std::vector<ContextItem *> & list){
for (std::vector<Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Tab * tab = *i;
if (tab->name == name){
return;
}
}
Tab * tab = new Tab();
tab->name = name;
tab->context->setList(list);
tab->context->setFont(font, fontWidth, fontHeight);
tab->context->location.setPosition(Gui::AbsolutePoint(0, fontHeight+5));
tab->context->location.setPosition2(Gui::AbsolutePoint(location.getWidth(), location.getHeight()));
tab->context->open();
tabs.push_back(tab);
}
void TabbedBox::moveTab(int direction){
tabs[current]->context->close();
tabs[current]->active = false;
current = (current + direction + tabs.size()) % tabs.size();
/*
if (current == 0){
current = tabs.size()-1;
} else {
current--;
}
*/
tabs[current]->context->open();
tabs[current]->active = true;
}
void TabbedBox::up(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->previous();
}
}
void TabbedBox::down(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->next();
}
}
void TabbedBox::left(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->adjustLeft();
}
}
void TabbedBox::right(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->adjustRight();
}
}
void TabbedBox::toggleTabSelect(){
inTab = !inTab;
}
unsigned int TabbedBox::getCurrentIndex() const {
if (tabs.size() == 0){
return 0;
}
return this->tabs[current]->context->getCurrentIndex();
}
void TabbedBox::setTabFontColor(int color){
tabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::setSelectedTabFontColor(int color){
currentTabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::renderTabs(const Bitmap & bmp){
const int tabHeight = fontHeight + 5;
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
int x = 0;
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
const int textWidth = vFont.textLength(tab->name.c_str()) + 5;
// for last tab
int modifier = 0;
// Check last tab so we can ensure proper sizing
if ( i == (tabs.begin() + tabs.size() -1)){
if ( ( (tabWidthMax * (tabs.size() - 1) ) + textWidth ) != (unsigned int)location.getWidth() ){
modifier = location.getWidth() - x - (tab->active ? textWidth : tabWidthMax);
}
}
if (tab->context->location.getRadius() > 0){
} else {
if (tab->active){
if (!inTab){
bmp.rectangle(x, 0, x+textWidth + modifier - 1, tabHeight, colors.border);
bmp.rectangleFill( x+1, 1, x+textWidth + modifier - 2, tabHeight, colors.body );
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, currentTabFontColor, bmp, tab->name, 0 );
} else {
bmp.rectangle(x, 0, x+textWidth + modifier -1, tabHeight, colors.border);
bmp.rectangleFill( x+1, 1, x+textWidth-2 + modifier, tabHeight, colors.body );
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, activeTabFontColor->current(), bmp, tab->name, 0 );
}
x+=textWidth + modifier;
} else {
bmp.rectangle(x, 0, x+tabWidthMax + modifier -1, tabHeight, tabColors.border);
bmp.hLine(x, tabHeight, x+textWidth + modifier - 1, colors.border);
bmp.rectangleFill( x+1, 1, x+tabWidthMax + modifier -2, tabHeight-2, tabColors.body );
bmp.setClipRect(x+2, 1, x+tabWidthMax + modifier -3, tabHeight-1);
vFont.printf(x + (((tabWidthMax + modifier)/2)-((textWidth + modifier)/2)), 0, tabFontColor, bmp, tab->name, 0 );
x+=tabWidthMax + modifier;
}
bmp.setClipRect(0, 0, bmp.getWidth(), bmp.getHeight());
}
}
}
<|endoftext|> |
<commit_before>#include "RapidJsonHandler.h"
#include "JsonViewDlg.h"
const char* const STR_NULL = "null";
const char* const STR_TRUE = "true";
const char* const STR_FALSE = "false";
bool RapidJsonHandler::Null()
{
if (!m_NodeStack.size())
return false;
TreeNode* parent = m_NodeStack.top();
parent->node.type = JsonNodeType::BOOL;
parent->node.key = m_strLastKey;
parent->node.value = STR_NULL;
m_strLastKey.clear();
// Print and pop the value
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : " + parent->node.value);
return true;
}
bool RapidJsonHandler::Bool(bool b)
{
if (!m_NodeStack.size())
return false;
TreeNode* parent = m_NodeStack.top();
parent->node.type = JsonNodeType::BOOL;
parent->node.key = m_strLastKey;
parent->node.value = b ? STR_TRUE : STR_FALSE;
m_strLastKey.clear();
// Print and pop the value
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : " + parent->node.value);
return true;
}
bool RapidJsonHandler::Int(int /*i*/)
{
return true;
}
bool RapidJsonHandler::Uint(unsigned /*i*/)
{
return true;
}
bool RapidJsonHandler::Int64(int64_t /*i*/)
{
return true;
}
bool RapidJsonHandler::Uint64(uint64_t /*i*/)
{
return true;
}
bool RapidJsonHandler::Double(double /*d*/)
{
return true;
}
bool RapidJsonHandler::RawNumber(const Ch* str, unsigned /*length*/, bool /*copy*/)
{
if (!m_NodeStack.size())
return false;
TreeNode* parent = m_NodeStack.top();
parent->node.type = JsonNodeType::NUMBER;
parent->node.key = m_strLastKey;
parent->node.value = str;
m_strLastKey.clear();
// Print and pop the value
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : " + parent->node.value);
return true;
}
bool RapidJsonHandler::String(const Ch* str, unsigned /*length*/, bool /*copy*/)
{
if (!str)
return false;
// handle case, when there is only a value in input
if (m_NodeStack.empty())
{
m_dlg->InsertToTree(m_treeRoot, str);
return true;
}
TreeNode* parent = m_NodeStack.top();
if (parent->node.type != JsonNodeType::ARRAY)
{
parent->node.key = m_strLastKey;
parent->node.value = str;
m_strLastKey.clear();
}
else
{
parent->counter++;
}
// insert
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : \"" + parent->node.value + "\"");
return true;
}
bool RapidJsonHandler::Key(const Ch* str, unsigned /*length*/, bool /*copy*/)
{
m_strLastKey = "\"";
m_strLastKey += str;
m_strLastKey += "\"";
return true;
}
bool RapidJsonHandler::StartObject()
{
TreeNode* parent = nullptr;
if (m_NodeStack.empty())
{
parent = new TreeNode;
parent->node.type = JsonNodeType::OBJECT;
parent->subRoot = m_treeRoot;
parent->counter = 0;
m_NodeStack.push(parent);
}
else
{
parent = m_NodeStack.top();
}
if (!m_strLastKey.empty() || parent->node.type == JsonNodeType::ARRAY)
{
HTREEITEM newNode = nullptr;
if (parent->node.type != JsonNodeType::ARRAY)
{
newNode = m_dlg->InsertToTree(parent->subRoot, m_strLastKey);
m_strLastKey.clear();
}
else
{
// It is an array
std::string arr = "[" + std::to_string(parent->counter) + "]";
newNode = m_dlg->InsertToTree(parent->subRoot, arr);
}
parent->counter++;
TreeNode* newTreeNode = new TreeNode;
newTreeNode->node.type = JsonNodeType::OBJECT;
newTreeNode->subRoot = newNode;
newTreeNode->counter = 0;
m_NodeStack.push(newTreeNode);
}
return true;
}
bool RapidJsonHandler::EndObject(unsigned /*memberCount*/)
{
if (!m_NodeStack.empty())
{
TreeNode* node = m_NodeStack.top();
m_NodeStack.pop();
delete node;
}
return true;
}
bool RapidJsonHandler::StartArray()
{
TreeNode* parent = nullptr;
if (m_NodeStack.empty())
{
parent = new TreeNode;
parent->node.type = JsonNodeType::ARRAY;
parent->subRoot = m_treeRoot;
parent->counter = 0;
m_NodeStack.push(parent);
return true;
}
else
{
parent = m_NodeStack.top();
}
if (!m_strLastKey.empty() || parent->node.type == JsonNodeType::ARRAY)
{
HTREEITEM newNode;
if (parent->node.type != JsonNodeType::ARRAY)
{
newNode = m_dlg->InsertToTree(parent->subRoot, m_strLastKey);
m_strLastKey.clear();
}
else
{
// It is an array
std::string arr = "[" + std::to_string(parent->counter) + "]";
newNode = m_dlg->InsertToTree(parent->subRoot, arr);
}
parent->counter++;
TreeNode* newTreeNode = new TreeNode;
newTreeNode->node.type = JsonNodeType::ARRAY;
newTreeNode->subRoot = newNode;
newTreeNode->counter = 0;
m_NodeStack.push(newTreeNode);
}
return true;
}
bool RapidJsonHandler::EndArray(unsigned /*elementCount*/)
{
if (!m_NodeStack.empty())
{
TreeNode* node = m_NodeStack.top();
m_NodeStack.pop();
delete node;
}
return true;
}
<commit_msg>Fix regression <commit_after>#include "RapidJsonHandler.h"
#include "JsonViewDlg.h"
const char* const STR_NULL = "null";
const char* const STR_TRUE = "true";
const char* const STR_FALSE = "false";
bool RapidJsonHandler::Null()
{
if (!m_NodeStack.size())
return false;
TreeNode* parent = m_NodeStack.top();
parent->node.type = JsonNodeType::BOOL;
parent->node.key = m_strLastKey;
parent->node.value = STR_NULL;
m_strLastKey.clear();
// Print and pop the value
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : " + parent->node.value);
return true;
}
bool RapidJsonHandler::Bool(bool b)
{
if (!m_NodeStack.size())
return false;
TreeNode* parent = m_NodeStack.top();
parent->node.type = JsonNodeType::BOOL;
parent->node.key = m_strLastKey;
parent->node.value = b ? STR_TRUE : STR_FALSE;
m_strLastKey.clear();
// Print and pop the value
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : " + parent->node.value);
return true;
}
bool RapidJsonHandler::Int(int /*i*/)
{
return true;
}
bool RapidJsonHandler::Uint(unsigned /*i*/)
{
return true;
}
bool RapidJsonHandler::Int64(int64_t /*i*/)
{
return true;
}
bool RapidJsonHandler::Uint64(uint64_t /*i*/)
{
return true;
}
bool RapidJsonHandler::Double(double /*d*/)
{
return true;
}
bool RapidJsonHandler::RawNumber(const Ch* str, unsigned /*length*/, bool /*copy*/)
{
if (!m_NodeStack.size())
return false;
TreeNode* parent = m_NodeStack.top();
parent->node.type = JsonNodeType::NUMBER;
parent->node.key = m_strLastKey;
parent->node.value = str;
m_strLastKey.clear();
// Print and pop the value
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : " + parent->node.value);
return true;
}
bool RapidJsonHandler::String(const Ch* str, unsigned /*length*/, bool /*copy*/)
{
if (!str)
return false;
// handle case, when there is only a value in input
if (m_NodeStack.empty())
{
m_dlg->InsertToTree(m_treeRoot, str);
return true;
}
TreeNode* parent = m_NodeStack.top();
if (parent->node.type != JsonNodeType::ARRAY)
{
parent->node.key = m_strLastKey;
parent->node.value = str;
m_strLastKey.clear();
}
else
{
parent->node.key = std::to_string(parent->counter);
parent->node.value = str;
parent->counter++;
}
// insert
m_dlg->InsertToTree(parent->subRoot, parent->node.key + " : \"" + parent->node.value + "\"");
return true;
}
bool RapidJsonHandler::Key(const Ch* str, unsigned /*length*/, bool /*copy*/)
{
m_strLastKey = "\"";
m_strLastKey += str;
m_strLastKey += "\"";
return true;
}
bool RapidJsonHandler::StartObject()
{
TreeNode* parent = nullptr;
if (m_NodeStack.empty())
{
parent = new TreeNode;
parent->node.type = JsonNodeType::OBJECT;
parent->subRoot = m_treeRoot;
parent->counter = 0;
m_NodeStack.push(parent);
}
else
{
parent = m_NodeStack.top();
}
if (!m_strLastKey.empty() || parent->node.type == JsonNodeType::ARRAY)
{
HTREEITEM newNode = nullptr;
if (parent->node.type != JsonNodeType::ARRAY)
{
newNode = m_dlg->InsertToTree(parent->subRoot, m_strLastKey);
m_strLastKey.clear();
}
else
{
// It is an array
std::string arr = "[" + std::to_string(parent->counter) + "]";
newNode = m_dlg->InsertToTree(parent->subRoot, arr);
}
parent->counter++;
TreeNode* newTreeNode = new TreeNode;
newTreeNode->node.type = JsonNodeType::OBJECT;
newTreeNode->subRoot = newNode;
newTreeNode->counter = 0;
m_NodeStack.push(newTreeNode);
}
return true;
}
bool RapidJsonHandler::EndObject(unsigned /*memberCount*/)
{
if (!m_NodeStack.empty())
{
TreeNode* node = m_NodeStack.top();
m_NodeStack.pop();
delete node;
}
return true;
}
bool RapidJsonHandler::StartArray()
{
TreeNode* parent = nullptr;
if (m_NodeStack.empty())
{
parent = new TreeNode;
parent->node.type = JsonNodeType::ARRAY;
parent->subRoot = m_treeRoot;
parent->counter = 0;
m_NodeStack.push(parent);
return true;
}
else
{
parent = m_NodeStack.top();
}
if (!m_strLastKey.empty() || parent->node.type == JsonNodeType::ARRAY)
{
HTREEITEM newNode;
if (parent->node.type != JsonNodeType::ARRAY)
{
newNode = m_dlg->InsertToTree(parent->subRoot, m_strLastKey);
m_strLastKey.clear();
}
else
{
// It is an array
std::string arr = "[" + std::to_string(parent->counter) + "]";
newNode = m_dlg->InsertToTree(parent->subRoot, arr);
}
parent->counter++;
TreeNode* newTreeNode = new TreeNode;
newTreeNode->node.type = JsonNodeType::ARRAY;
newTreeNode->subRoot = newNode;
newTreeNode->counter = 0;
m_NodeStack.push(newTreeNode);
}
return true;
}
bool RapidJsonHandler::EndArray(unsigned /*elementCount*/)
{
if (!m_NodeStack.empty())
{
TreeNode* node = m_NodeStack.top();
m_NodeStack.pop();
delete node;
}
return true;
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <kretz@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "audiodeviceenumerator.h"
#include "audiodeviceenumerator_p.h"
#include "audiodevice_p.h"
#include <QtCore/QFileSystemWatcher>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <solid/devicenotifier.h>
#include <solid/device.h>
#include <solid/audiointerface.h>
#include <kconfiggroup.h>
#include <kio/kdirwatch.h>
#include <phonon/config-alsa.h>
#ifdef HAVE_LIBASOUND2
#include <alsa/asoundlib.h>
#endif // HAVE_LIBASOUND2
namespace Phonon
{
K_GLOBAL_STATIC(AudioDeviceEnumeratorPrivate, audioDeviceEnumeratorPrivate)
AudioDeviceEnumerator::AudioDeviceEnumerator(AudioDeviceEnumeratorPrivate *dd)
: d(dd)
{
}
AudioDeviceEnumeratorPrivate::AudioDeviceEnumeratorPrivate()
: q(this)
{
config = KSharedConfig::openConfig("phonondevicesrc", KConfig::NoGlobals);
findDevices();
QObject::connect(Solid::DeviceNotifier::instance(), SIGNAL(deviceAdded(const QString &)), &q, SLOT(_k_deviceAdded(const QString &)));
QObject::connect(Solid::DeviceNotifier::instance(), SIGNAL(deviceRemoved(const QString &)), &q, SLOT(_k_deviceRemoved(const QString &)));
}
AudioDeviceEnumerator *AudioDeviceEnumerator::self()
{
return &audioDeviceEnumeratorPrivate->q;
}
void AudioDeviceEnumeratorPrivate::findDevices()
{
// ask Solid for the available audio hardware
QSet<QString> alreadyFoundCards;
QList<Solid::Device> devices = Solid::Device::listFromQuery("AudioInterface.deviceType & 'AudioInput|AudioOutput'");
foreach (Solid::Device device, devices) {
AudioDevice dev(device, config);
if (dev.isValid()) {
if (dev.isCaptureDevice()) {
capturedevicelist << dev;
if (dev.isPlaybackDevice()) {
playbackdevicelist << dev;
alreadyFoundCards << QLatin1String("AudioIODevice_") + dev.cardName();
} else {
alreadyFoundCards << QLatin1String("AudioCaptureDevice_") + dev.cardName();
}
} else {
playbackdevicelist << dev;
alreadyFoundCards << QLatin1String("AudioOutputDevice_") + dev.cardName();
}
}
}
// now look in the config file for disconnected devices
QStringList groupList = config->groupList();
foreach (QString groupName, groupList) {
if (alreadyFoundCards.contains(groupName) || !groupName.startsWith(QLatin1String("Audio"))) {
continue;
}
KConfigGroup configGroup(config.data(), groupName);
AudioDevice dev(configGroup);
if (dev.isValid()) {
if (dev.isCaptureDevice()) {
capturedevicelist << dev;
if (dev.isPlaybackDevice()) {
playbackdevicelist << dev;
}
} else {
playbackdevicelist << dev;
}
alreadyFoundCards << groupName;
}
}
// now that we know about the hardware let's see what virtual devices we can find in
// ~/.asoundrc and /etc/asound.conf
findVirtualDevices();
//X QFileSystemWatcher *watcher = new QFileSystemWatcher(QCoreApplication::instance());
//X watcher->addPath(QDir::homePath() + QLatin1String("/.asoundrc"));
//X watcher->addPath(QLatin1String("/etc/asound.conf"));
//X q.connect(watcher, SIGNAL(fileChanged(const QString &)), &q, SLOT(_k_asoundrcChanged(const QString &)));
KDirWatch *dirWatch = KDirWatch::self();
dirWatch->addFile(QDir::homePath() + QLatin1String("/.asoundrc"));
dirWatch->addFile(QLatin1String("/etc/asound.conf"));
q.connect(dirWatch, SIGNAL(dirty(const QString &)), &q, SLOT(_k_asoundrcChanged(const QString &)));
}
struct DeviceHint
{
QString name;
QString description;
};
void AudioDeviceEnumeratorPrivate::findVirtualDevices()
{
#ifdef HAS_LIBASOUND_DEVICE_NAME_HINT
QList<DeviceHint> deviceHints;
void **hints;
//snd_config_update();
if (snd_device_name_hint(-1, "pcm", &hints) < 0) {
kDebug(600) << "snd_device_name_hint failed for 'pcm'";
}
for (void **cStrings = hints; *cStrings; ++cStrings) {
DeviceHint nextHint;
char *x = snd_device_name_get_hint(*cStrings, "NAME");
nextHint.name = QString::fromUtf8(x);
free(x);
if (nextHint.name.startsWith("front:") ||
nextHint.name.startsWith("surround40:") ||
nextHint.name.startsWith("surround41:") ||
nextHint.name.startsWith("surround50:") ||
nextHint.name.startsWith("surround51:") ||
nextHint.name.startsWith("surround71:") ||
nextHint.name == "null"
) {
continue;
}
x = snd_device_name_get_hint(*cStrings, "DESC");
nextHint.description = QString::fromUtf8(x);
free(x);
deviceHints << nextHint;
}
snd_device_name_free_hint(hints);
snd_config_update_free_global();
snd_config_update();
Q_ASSERT(snd_config);
// after recreating the global configuration we can go and install custom configuration
{
// x-phonon: device
QFile phononDefinition(":/phonon/phonondevice.alsa");
phononDefinition.open(QIODevice::ReadOnly);
const QByteArray phononDefinitionData = phononDefinition.readAll();
snd_input_t *sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, phononDefinitionData.constData(), phononDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#if 0
// phonon_softvol: device
QFile softvolDefinition(":/phonon/softvol.alsa");
softvolDefinition.open(QIODevice::ReadOnly);
const QByteArray softvolDefinitionData = softvolDefinition.readAll();
sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, softvolDefinitionData.constData(), softvolDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#endif
}
foreach (const DeviceHint &deviceHint, deviceHints) {
AudioDevice dev(deviceHint.name, deviceHint.description, config);
if (dev.isPlaybackDevice()) {
playbackdevicelist << dev;
}
if (dev.isCaptureDevice()) {
capturedevicelist << dev;
} else {
if (!dev.isPlaybackDevice()) {
kDebug(600) << deviceHint.name << " doesn't work.";
}
}
}
#elif defined(HAVE_LIBASOUND2)
#warning "please update your libasound! this code is not supported"
snd_config_update();
Q_ASSERT(snd_config);
// after recreating the global configuration we can go and install custom configuration
{
// x-phonon: device
QFile phononDefinition(":/phonon/phonondevice.alsa");
phononDefinition.open(QIODevice::ReadOnly);
const QByteArray phononDefinitionData = phononDefinition.readAll();
snd_input_t *sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, phononDefinitionData.constData(), phononDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#if 0
// phonon_softvol: device
QFile softvolDefinition(":/phonon/softvol.alsa");
softvolDefinition.open(QIODevice::ReadOnly);
const QByteArray softvolDefinitionData = softvolDefinition.readAll();
sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, softvolDefinitionData.constData(), softvolDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#endif
}
#endif //HAS_LIBASOUND_DEVICE_NAME_HINT / HAVE_LIBASOUND2
}
void AudioDeviceEnumeratorPrivate::_k_asoundrcChanged(const QString &file)
{
#ifdef HAVE_LIBASOUND2
kDebug(600) << file;
QFileInfo changedFile(file);
QFileInfo asoundrc(QDir::homePath() + QLatin1String("/.asoundrc"));
if (changedFile != asoundrc) {
asoundrc.setFile("/etc/asound.conf");
if (changedFile != asoundrc) {
return;
}
}
QList<AudioDevice> oldPlaybackdevicelist = playbackdevicelist;
QList<AudioDevice> oldCapturedevicelist = capturedevicelist;
QList<AudioDevice>::Iterator it = playbackdevicelist.begin();
while (it != playbackdevicelist.end()) {
if (it->d->driver == Solid::AudioInterface::Alsa &&
it->d->deviceIds.size() == 1 &&
it->d->deviceIds.first() == it->cardName()) {
it = playbackdevicelist.erase(it);
} else {
++it;
}
}
it = capturedevicelist.begin();
while (it != capturedevicelist.end()) {
if (it->d->driver == Solid::AudioInterface::Alsa &&
it->d->deviceIds.size() == 1 &&
it->d->deviceIds.first() == it->cardName()) {
it = capturedevicelist.erase(it);
} else {
++it;
}
}
snd_config_update_free_global();
snd_config_update();
findVirtualDevices();
foreach (const AudioDevice &dev, oldCapturedevicelist) {
if (!capturedevicelist.contains(dev)) {
emit q.deviceUnplugged(dev);
}
}
foreach (const AudioDevice &dev, oldPlaybackdevicelist) {
if (!playbackdevicelist.contains(dev)) {
emit q.deviceUnplugged(dev);
}
}
foreach (const AudioDevice &dev, playbackdevicelist) {
if (!oldPlaybackdevicelist.contains(dev)) {
emit q.devicePlugged(dev);
}
}
foreach (const AudioDevice &dev, capturedevicelist) {
if (!oldCapturedevicelist.contains(dev)) {
emit q.devicePlugged(dev);
}
}
#endif // HAVE_LIBASOUND2
}
void AudioDeviceEnumeratorPrivate::_k_deviceAdded(const QString &udi)
{
kDebug(600) << udi;
Solid::Device _device(udi);
Solid::AudioInterface *audiohw = _device.as<Solid::AudioInterface>();
if (audiohw && (audiohw->deviceType() & (Solid::AudioInterface::AudioInput |
Solid::AudioInterface::AudioOutput))) {
// an audio i/o device was plugged in
AudioDevice dev(_device, config);
if (dev.isValid()) {
if (dev.isCaptureDevice()) {
foreach (const AudioDevice &listedDev, capturedevicelist) {
if (listedDev == dev && !listedDev.isAvailable()) {
// listedDev is the same devices as dev but shown as unavailable
kDebug(600) << "removing from capturedevicelist: " << listedDev.cardName();
capturedevicelist.removeAll(listedDev);
break;
}
}
capturedevicelist << dev;
}
if (dev.isPlaybackDevice()) {
foreach (const AudioDevice &listedDev, playbackdevicelist) {
if (listedDev == dev && !listedDev.isAvailable()) {
// listedDev is the same devices as dev but shown as unavailable
kDebug(600) << "removing from playbackdevicelist: " << listedDev.cardName();
playbackdevicelist.removeAll(listedDev);
break;
}
}
playbackdevicelist << dev;
}
kDebug(600) << "emit q.devicePlugged " << dev.cardName();
emit q.devicePlugged(dev);
}
}
}
void AudioDeviceEnumeratorPrivate::_k_deviceRemoved(const QString &udi)
{
kDebug(600) << udi;
AudioDevice dev;
foreach (const AudioDevice &listedDev, capturedevicelist) {
if (listedDev.udi() == udi && listedDev.isAvailable()) {
// listedDev is the same devices as was removed
kDebug(600) << "removing from capturedevicelist: " << listedDev.cardName();
dev = listedDev;
capturedevicelist.removeAll(listedDev);
break;
}
}
foreach (const AudioDevice &listedDev, playbackdevicelist) {
if (listedDev.udi() == udi && listedDev.isAvailable()) {
// listedDev is the same devices as was removed
kDebug(600) << "removing from playbackdevicelist: " << listedDev.cardName();
dev = listedDev;
playbackdevicelist.removeAll(listedDev);
break;
}
}
if (dev.isValid()) {
kDebug(600) << "emit q.deviceUnplugged " << dev.cardName();
emit q.deviceUnplugged(dev);
}
}
AudioDeviceEnumerator::~AudioDeviceEnumerator()
{
}
QList<AudioDevice> AudioDeviceEnumerator::availablePlaybackDevices()
{
return audioDeviceEnumeratorPrivate->playbackdevicelist;
}
QList<AudioDevice> AudioDeviceEnumerator::availableCaptureDevices()
{
return audioDeviceEnumeratorPrivate->capturedevicelist;
}
} // namespace Phonon
#include "audiodeviceenumerator.moc"
// vim: sw=4 sts=4 et tw=100
<commit_msg>from Solid we already create default: devices, no need to list them a second time<commit_after>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <kretz@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "audiodeviceenumerator.h"
#include "audiodeviceenumerator_p.h"
#include "audiodevice_p.h"
#include <QtCore/QFileSystemWatcher>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <solid/devicenotifier.h>
#include <solid/device.h>
#include <solid/audiointerface.h>
#include <kconfiggroup.h>
#include <kio/kdirwatch.h>
#include <phonon/config-alsa.h>
#ifdef HAVE_LIBASOUND2
#include <alsa/asoundlib.h>
#endif // HAVE_LIBASOUND2
namespace Phonon
{
K_GLOBAL_STATIC(AudioDeviceEnumeratorPrivate, audioDeviceEnumeratorPrivate)
AudioDeviceEnumerator::AudioDeviceEnumerator(AudioDeviceEnumeratorPrivate *dd)
: d(dd)
{
}
AudioDeviceEnumeratorPrivate::AudioDeviceEnumeratorPrivate()
: q(this)
{
config = KSharedConfig::openConfig("phonondevicesrc", KConfig::NoGlobals);
findDevices();
QObject::connect(Solid::DeviceNotifier::instance(), SIGNAL(deviceAdded(const QString &)), &q, SLOT(_k_deviceAdded(const QString &)));
QObject::connect(Solid::DeviceNotifier::instance(), SIGNAL(deviceRemoved(const QString &)), &q, SLOT(_k_deviceRemoved(const QString &)));
}
AudioDeviceEnumerator *AudioDeviceEnumerator::self()
{
return &audioDeviceEnumeratorPrivate->q;
}
void AudioDeviceEnumeratorPrivate::findDevices()
{
// ask Solid for the available audio hardware
QSet<QString> alreadyFoundCards;
QList<Solid::Device> devices = Solid::Device::listFromQuery("AudioInterface.deviceType & 'AudioInput|AudioOutput'");
foreach (Solid::Device device, devices) {
AudioDevice dev(device, config);
if (dev.isValid()) {
if (dev.isCaptureDevice()) {
capturedevicelist << dev;
if (dev.isPlaybackDevice()) {
playbackdevicelist << dev;
alreadyFoundCards << QLatin1String("AudioIODevice_") + dev.cardName();
} else {
alreadyFoundCards << QLatin1String("AudioCaptureDevice_") + dev.cardName();
}
} else {
playbackdevicelist << dev;
alreadyFoundCards << QLatin1String("AudioOutputDevice_") + dev.cardName();
}
}
}
// now look in the config file for disconnected devices
QStringList groupList = config->groupList();
foreach (QString groupName, groupList) {
if (alreadyFoundCards.contains(groupName) || !groupName.startsWith(QLatin1String("Audio"))) {
continue;
}
KConfigGroup configGroup(config.data(), groupName);
AudioDevice dev(configGroup);
if (dev.isValid()) {
if (dev.isCaptureDevice()) {
capturedevicelist << dev;
if (dev.isPlaybackDevice()) {
playbackdevicelist << dev;
}
} else {
playbackdevicelist << dev;
}
alreadyFoundCards << groupName;
}
}
// now that we know about the hardware let's see what virtual devices we can find in
// ~/.asoundrc and /etc/asound.conf
findVirtualDevices();
//X QFileSystemWatcher *watcher = new QFileSystemWatcher(QCoreApplication::instance());
//X watcher->addPath(QDir::homePath() + QLatin1String("/.asoundrc"));
//X watcher->addPath(QLatin1String("/etc/asound.conf"));
//X q.connect(watcher, SIGNAL(fileChanged(const QString &)), &q, SLOT(_k_asoundrcChanged(const QString &)));
KDirWatch *dirWatch = KDirWatch::self();
dirWatch->addFile(QDir::homePath() + QLatin1String("/.asoundrc"));
dirWatch->addFile(QLatin1String("/etc/asound.conf"));
q.connect(dirWatch, SIGNAL(dirty(const QString &)), &q, SLOT(_k_asoundrcChanged(const QString &)));
}
struct DeviceHint
{
QString name;
QString description;
};
void AudioDeviceEnumeratorPrivate::findVirtualDevices()
{
#ifdef HAS_LIBASOUND_DEVICE_NAME_HINT
QList<DeviceHint> deviceHints;
void **hints;
//snd_config_update();
if (snd_device_name_hint(-1, "pcm", &hints) < 0) {
kDebug(600) << "snd_device_name_hint failed for 'pcm'";
}
for (void **cStrings = hints; *cStrings; ++cStrings) {
DeviceHint nextHint;
char *x = snd_device_name_get_hint(*cStrings, "NAME");
nextHint.name = QString::fromUtf8(x);
free(x);
if (nextHint.name.startsWith("front:") ||
nextHint.name.startsWith("surround40:") ||
nextHint.name.startsWith("surround41:") ||
nextHint.name.startsWith("surround50:") ||
nextHint.name.startsWith("surround51:") ||
nextHint.name.startsWith("surround71:") ||
nextHint.name.startsWith("default:") ||
nextHint.name == "null"
) {
continue;
}
x = snd_device_name_get_hint(*cStrings, "DESC");
nextHint.description = QString::fromUtf8(x);
free(x);
deviceHints << nextHint;
}
snd_device_name_free_hint(hints);
snd_config_update_free_global();
snd_config_update();
Q_ASSERT(snd_config);
// after recreating the global configuration we can go and install custom configuration
{
// x-phonon: device
QFile phononDefinition(":/phonon/phonondevice.alsa");
phononDefinition.open(QIODevice::ReadOnly);
const QByteArray phononDefinitionData = phononDefinition.readAll();
snd_input_t *sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, phononDefinitionData.constData(), phononDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#if 0
// phonon_softvol: device
QFile softvolDefinition(":/phonon/softvol.alsa");
softvolDefinition.open(QIODevice::ReadOnly);
const QByteArray softvolDefinitionData = softvolDefinition.readAll();
sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, softvolDefinitionData.constData(), softvolDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#endif
}
foreach (const DeviceHint &deviceHint, deviceHints) {
AudioDevice dev(deviceHint.name, deviceHint.description, config);
if (dev.isPlaybackDevice()) {
playbackdevicelist << dev;
}
if (dev.isCaptureDevice()) {
capturedevicelist << dev;
} else {
if (!dev.isPlaybackDevice()) {
kDebug(600) << deviceHint.name << " doesn't work.";
}
}
}
#elif defined(HAVE_LIBASOUND2)
#warning "please update your libasound! this code is not supported"
snd_config_update();
Q_ASSERT(snd_config);
// after recreating the global configuration we can go and install custom configuration
{
// x-phonon: device
QFile phononDefinition(":/phonon/phonondevice.alsa");
phononDefinition.open(QIODevice::ReadOnly);
const QByteArray phononDefinitionData = phononDefinition.readAll();
snd_input_t *sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, phononDefinitionData.constData(), phononDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#if 0
// phonon_softvol: device
QFile softvolDefinition(":/phonon/softvol.alsa");
softvolDefinition.open(QIODevice::ReadOnly);
const QByteArray softvolDefinitionData = softvolDefinition.readAll();
sndInput = 0;
if (0 == snd_input_buffer_open(&sndInput, softvolDefinitionData.constData(), softvolDefinitionData.size())) {
Q_ASSERT(sndInput);
snd_config_load(snd_config, sndInput);
snd_input_close(sndInput);
}
#endif
}
#endif //HAS_LIBASOUND_DEVICE_NAME_HINT / HAVE_LIBASOUND2
}
void AudioDeviceEnumeratorPrivate::_k_asoundrcChanged(const QString &file)
{
#ifdef HAVE_LIBASOUND2
kDebug(600) << file;
QFileInfo changedFile(file);
QFileInfo asoundrc(QDir::homePath() + QLatin1String("/.asoundrc"));
if (changedFile != asoundrc) {
asoundrc.setFile("/etc/asound.conf");
if (changedFile != asoundrc) {
return;
}
}
QList<AudioDevice> oldPlaybackdevicelist = playbackdevicelist;
QList<AudioDevice> oldCapturedevicelist = capturedevicelist;
QList<AudioDevice>::Iterator it = playbackdevicelist.begin();
while (it != playbackdevicelist.end()) {
if (it->d->driver == Solid::AudioInterface::Alsa &&
it->d->deviceIds.size() == 1 &&
it->d->deviceIds.first() == it->cardName()) {
it = playbackdevicelist.erase(it);
} else {
++it;
}
}
it = capturedevicelist.begin();
while (it != capturedevicelist.end()) {
if (it->d->driver == Solid::AudioInterface::Alsa &&
it->d->deviceIds.size() == 1 &&
it->d->deviceIds.first() == it->cardName()) {
it = capturedevicelist.erase(it);
} else {
++it;
}
}
snd_config_update_free_global();
snd_config_update();
findVirtualDevices();
foreach (const AudioDevice &dev, oldCapturedevicelist) {
if (!capturedevicelist.contains(dev)) {
emit q.deviceUnplugged(dev);
}
}
foreach (const AudioDevice &dev, oldPlaybackdevicelist) {
if (!playbackdevicelist.contains(dev)) {
emit q.deviceUnplugged(dev);
}
}
foreach (const AudioDevice &dev, playbackdevicelist) {
if (!oldPlaybackdevicelist.contains(dev)) {
emit q.devicePlugged(dev);
}
}
foreach (const AudioDevice &dev, capturedevicelist) {
if (!oldCapturedevicelist.contains(dev)) {
emit q.devicePlugged(dev);
}
}
#endif // HAVE_LIBASOUND2
}
void AudioDeviceEnumeratorPrivate::_k_deviceAdded(const QString &udi)
{
kDebug(600) << udi;
Solid::Device _device(udi);
Solid::AudioInterface *audiohw = _device.as<Solid::AudioInterface>();
if (audiohw && (audiohw->deviceType() & (Solid::AudioInterface::AudioInput |
Solid::AudioInterface::AudioOutput))) {
// an audio i/o device was plugged in
AudioDevice dev(_device, config);
if (dev.isValid()) {
if (dev.isCaptureDevice()) {
foreach (const AudioDevice &listedDev, capturedevicelist) {
if (listedDev == dev && !listedDev.isAvailable()) {
// listedDev is the same devices as dev but shown as unavailable
kDebug(600) << "removing from capturedevicelist: " << listedDev.cardName();
capturedevicelist.removeAll(listedDev);
break;
}
}
capturedevicelist << dev;
}
if (dev.isPlaybackDevice()) {
foreach (const AudioDevice &listedDev, playbackdevicelist) {
if (listedDev == dev && !listedDev.isAvailable()) {
// listedDev is the same devices as dev but shown as unavailable
kDebug(600) << "removing from playbackdevicelist: " << listedDev.cardName();
playbackdevicelist.removeAll(listedDev);
break;
}
}
playbackdevicelist << dev;
}
kDebug(600) << "emit q.devicePlugged " << dev.cardName();
emit q.devicePlugged(dev);
}
}
}
void AudioDeviceEnumeratorPrivate::_k_deviceRemoved(const QString &udi)
{
kDebug(600) << udi;
AudioDevice dev;
foreach (const AudioDevice &listedDev, capturedevicelist) {
if (listedDev.udi() == udi && listedDev.isAvailable()) {
// listedDev is the same devices as was removed
kDebug(600) << "removing from capturedevicelist: " << listedDev.cardName();
dev = listedDev;
capturedevicelist.removeAll(listedDev);
break;
}
}
foreach (const AudioDevice &listedDev, playbackdevicelist) {
if (listedDev.udi() == udi && listedDev.isAvailable()) {
// listedDev is the same devices as was removed
kDebug(600) << "removing from playbackdevicelist: " << listedDev.cardName();
dev = listedDev;
playbackdevicelist.removeAll(listedDev);
break;
}
}
if (dev.isValid()) {
kDebug(600) << "emit q.deviceUnplugged " << dev.cardName();
emit q.deviceUnplugged(dev);
}
}
AudioDeviceEnumerator::~AudioDeviceEnumerator()
{
}
QList<AudioDevice> AudioDeviceEnumerator::availablePlaybackDevices()
{
return audioDeviceEnumeratorPrivate->playbackdevicelist;
}
QList<AudioDevice> AudioDeviceEnumerator::availableCaptureDevices()
{
return audioDeviceEnumeratorPrivate->capturedevicelist;
}
} // namespace Phonon
#include "audiodeviceenumerator.moc"
// vim: sw=4 sts=4 et tw=100
<|endoftext|> |
<commit_before>//System includes
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#ifdef USE_KRATOS
// Ugly fixes
#include <assert.h>
#define KRATOS_ERROR std::cout
#include "interfaces/points_old_interface.h"
#include "interfaces/objects_old_interface.h"
#endif
// Containers
#include "containers.h"
// Interfaces
#include "interfaces/points_new_interface.h"
#ifdef USE_KRATOS
#include "interfaces/points_old_interface.h"
#include "interfaces/objects_old_interface.h"
#endif
int RunPointSearchComparison(std::string Filename, double Radius) {
// Input data
std::cout << std::setprecision(4) << std::fixed;
Point ** points;
Point point;
SphereObject<3> object;
std::ifstream input;
input.open(Filename.c_str());
if (!input) {
std::cout << "Cannot open data file" << std::endl;
return 1;
}
std::cout << "Comparison for " << Filename << std::endl;
std::size_t npoints;
input >> npoints;
points = new Point*[npoints];
std::vector<Entities::PtrObjectType> objects(npoints);
std::size_t pid;
for(std::size_t i = 0; i < npoints; i++) {
input >> pid;
input >> point;
for(std::size_t d = 0; d < 3; d++) {
object[d] = point[d];
}
object.radius = 0.5/npoints;
points[i] = new Point(point);
points[i]->id = pid;
objects[i] = new SphereObject<3>(object);
objects[i]->id = pid;
objects[i]->radius = 0.5/npoints;
}
Point min_point(*points[0]);
Point max_point(*points[0]);
Point mid_point;
SphereObject<3> mid_object;
min_point.id = 0;
max_point.id = 0;
mid_point.id = 0;
for (std::size_t i = 0; i < npoints; i++) {
for (std::size_t j = 0; j < 3; j++) {
if (min_point[j] > (*points[i])[j]) min_point[j] = (*points[i])[j];
if (max_point[j] < (*points[i])[j]) max_point[j] = (*points[i])[j];
}
}
for (std::size_t i = 0; i < Dim; i++) {
mid_point.coord[i] = (max_point[i] + min_point[i]) / 2.00;
mid_object.coord[i] = (max_point[i] + min_point[i]) / 2.00;
}
mid_object.radius = 0.5/npoints;
// Output data Info
Point & search_point = mid_point;
SphereObject<3> & search_object = mid_object;
std::size_t numsearch = 1000000;
std::size_t numsearch_nearest = numsearch * 10;
std::cout << " min point : " << min_point << std::endl;
std::cout << " max point : " << max_point << std::endl;
std::cout << " search_point : " << search_point << std::endl;
std::cout << " search radius : " << Radius << std::endl;
std::cout << std::endl;
std::cout << " Number of Points : " << npoints << std::endl;
std::cout << " Number of Repetitions : " << numsearch << std::endl;
std::cout << std::endl;
std::cout << "SS\t\tGEN\tSIROMP\tSIRSER\tSNPOMP\tSNPSER\tNOFR\tNP" << std::endl;
// Data Setup
Point * allPoints = new Point[numsearch];
SphereObject<3> * allSpheres = new SphereObject<3>[numsearch];
std::size_t max_results = npoints;
for (std::size_t i = 0; i < 1; i++) {
allPoints[i] = search_point;
allSpheres[i] = search_object;
}
//Prepare the search point, search radius and resut arrays
std::vector<Entities::PtrObjectType> objectResults(max_results);
std::vector<double> resultDistances(max_results);
double * distances = new double[npoints];
Entities::PointIterator p_results = new Entities::PtrPointType[max_results];
// Point-Based Search Structures
std::vector<Point> points_vector;
for (std::size_t i = 0; i < npoints; i++) {
points_vector.push_back(*(points[i]));
}
// Point Interfaces
// - New Interface
PointsNew::RunTests<PointsBins<Point>>("PointBins", points_vector, search_point, Radius, numsearch, numsearch_nearest);
// - Old Interface
#ifdef USE_KRATOS
PointsOld::RunTests<Containers::BinsStaticType>("StaticBins", points, points + npoints, p_results, resultDistances.begin(), max_results, allPoints, Radius, numsearch, 1);
PointsOld::RunTests<Containers::BinsDynamicType>("DynamicBins", points, points + npoints, p_results, resultDistances.begin(), max_results, allPoints, Radius, numsearch, 1);
PointsOld::RunTests<Containers::OctreeType>("OctTree\t", points, points + npoints, p_results, resultDistances.begin(), max_results, allPoints, Radius, numsearch, 10);
PointsOld::RunTests<Containers::BinsDynamicOctreeType>("OcTreeDynamic\t", points, points + npoints, p_results, resultDistances.begin(), max_results, allPoints, Radius, numsearch, 10);
#endif
// Object Interfaces
// - New Interface
// TO BE FILLED
// - Old Interface
#ifdef USE_KRATOS
ObjectsOld::RunTests<Containers::BinsObjectStaticType>("StaticObjects", objects.begin(), objects.end(), objectResults.begin(), resultDistances.begin(), max_results, allSpheres, Radius, numsearch, 1);
ObjectsOld::RunTests<Containers::BinsObjectDynamicType>("DynamicObjects", objects.begin(), objects.end(), objectResults.begin(), resultDistances.begin(), max_results, allSpheres, Radius, numsearch, 1);
#endif
// RunTestsOldInterface<BinsObjectDynamicType>
return 0;
}
int main(int arg, char* argv[]) {
std::string filename;
// Default filename
filename = "../cases/genericCube2x2x2.500000.pts";
// filename = "../cases/genericCube100x100x100.5051.pts";
// filename = "../cases/randomCube2000000.pts";
// Default radius
double radius = 0.0102;
if (arg > 1) {
if ( !strncasecmp( argv[ 1], "-h", 2) || !strncasecmp( argv[ 1], "--h", 2)) {
std::cout << "Usage: " << argv[ 0] << " [ filename [ radius ] ]" << std::endl;
std::cout << " filename default value = " << filename << std::endl;
std::cout << " radius default value = " << radius << std::endl;
return 0;
}
filename = argv[1];
if (arg == 3) {
radius = atof(argv[2]) / 1000000;
}
}
RunPointSearchComparison(filename, radius);
// filename = "../cases/offsetCube79x79x79.1603.pts";
// RunPointSearchComparison(filename, radius);
// filename = "../cases/clusterCube6x6x6X4913.490.pts";
// RunPointSearchComparison(filename, radius);
// filename = "../cases/line100000.5.pts";
// RunPointSearchComparison(filename, radius);
return 0;
}
<commit_msg>verify that there are points<commit_after>// System includes
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#ifdef USE_KRATOS
// Ugly fixes
#include <assert.h>
#define KRATOS_ERROR std::cout
#include "interfaces/points_old_interface.h"
#include "interfaces/objects_old_interface.h"
#endif
// Containers
#include "containers.h"
// Interfaces
#include "interfaces/points_new_interface.h"
int RunPointSearchComparison( std::string Filename, double Radius ) {
// Input data
std::cout << std::setprecision( 4 ) << std::fixed;
Point **points;
Point point;
SphereObject< 3 > object;
std::ifstream input;
input.open( Filename.c_str() );
if ( !input ) {
std::cout << "Cannot open data file" << std::endl;
return 1;
}
std::cout << "Comparison for " << Filename << std::endl;
std::size_t npoints;
input >> npoints;
if ( npoints <= 0) {
std::cout << "ERROR: no points information read, nothing to do!!!" << std::endl;
return 1;
}
points = new Point *[ npoints ];
std::vector< Entities::PtrObjectType > objects( npoints );
std::size_t pid;
for ( std::size_t i = 0; i < npoints; i++ ) {
input >> pid;
input >> point;
for ( std::size_t d = 0; d < 3; d++ ) {
object[ d ] = point[ d ];
}
object.radius = 0.5 / npoints;
points[ i ] = new Point( point );
points[ i ]->id = pid;
objects[ i ] = new SphereObject< 3 >( object );
objects[ i ]->id = pid;
objects[ i ]->radius = 0.5 / npoints;
}
Point min_point( *points[ 0 ] );
Point max_point( *points[ 0 ] );
Point mid_point;
SphereObject< 3 > mid_object;
min_point.id = 0;
max_point.id = 0;
mid_point.id = 0;
for ( std::size_t i = 0; i < npoints; i++ ) {
for ( std::size_t j = 0; j < 3; j++ ) {
if ( min_point[ j ] > ( *points[ i ] )[ j ] )
min_point[ j ] = ( *points[ i ] )[ j ];
if ( max_point[ j ] < ( *points[ i ] )[ j ] )
max_point[ j ] = ( *points[ i ] )[ j ];
}
}
for ( std::size_t i = 0; i < Dim; i++ ) {
mid_point.coord[ i ] = ( max_point[ i ] + min_point[ i ] ) / 2.00;
mid_object.coord[ i ] = ( max_point[ i ] + min_point[ i ] ) / 2.00;
}
mid_object.radius = 0.5 / npoints;
// Output data Info
Point &search_point = mid_point;
SphereObject< 3 > &search_object = mid_object;
std::size_t numsearch = 1000000;
std::size_t numsearch_nearest = numsearch * 10;
std::cout << " min point : " << min_point << std::endl;
std::cout << " max point : " << max_point << std::endl;
std::cout << " search_point : " << search_point << std::endl;
std::cout << " search radius : " << Radius << std::endl;
std::cout << std::endl;
std::cout << " Number of Points : " << npoints << std::endl;
std::cout << " Number of Repetitions : " << numsearch << std::endl;
std::cout << std::endl;
std::cout << "SS\t\tGEN\tSIROMP\tSIRSER\tSNPOMP\tSNPSER\tNOFR\tNP" << std::endl;
// Data Setup
Point *allPoints = new Point[ numsearch ];
SphereObject< 3 > *allSpheres = new SphereObject< 3 >[ numsearch ];
std::size_t max_results = npoints;
for ( std::size_t i = 0; i < 1; i++ ) {
allPoints[ i ] = search_point;
allSpheres[ i ] = search_object;
}
// Prepare the search point, search radius and resut arrays
std::vector< Entities::PtrObjectType > objectResults( max_results );
std::vector< double > resultDistances( max_results );
double *distances = new double[ npoints ];
Entities::PointIterator p_results = new Entities::PtrPointType[ max_results ];
// Point-Based Search Structures
std::vector< Point > points_vector;
for ( std::size_t i = 0; i < npoints; i++ ) {
points_vector.push_back( *( points[ i ] ) );
}
// Point Interfaces
// - New Interface
PointsNew::RunTests< PointsBins< Point > >( "PointBins", points_vector, search_point, Radius,
numsearch, numsearch_nearest );
// - Old Interface
#ifdef USE_KRATOS
PointsOld::RunTests< Containers::BinsStaticType >( "StaticBins", points, points + npoints,
p_results, resultDistances.begin(),
max_results, allPoints, Radius, numsearch, 1 );
PointsOld::RunTests< Containers::BinsDynamicType >(
"DynamicBins", points, points + npoints, p_results, resultDistances.begin(), max_results,
allPoints, Radius, numsearch, 1 );
PointsOld::RunTests< Containers::OctreeType >( "OctTree\t", points, points + npoints, p_results,
resultDistances.begin(), max_results, allPoints,
Radius, numsearch, 10 );
PointsOld::RunTests< Containers::BinsDynamicOctreeType >(
"OcTreeDynamic\t", points, points + npoints, p_results, resultDistances.begin(), max_results,
allPoints, Radius, numsearch, 10 );
#endif
// Object Interfaces
// - New Interface
// TO BE FILLED
// - Old Interface
#ifdef USE_KRATOS
ObjectsOld::RunTests< Containers::BinsObjectStaticType >(
"StaticObjects", objects.begin(), objects.end(), objectResults.begin(),
resultDistances.begin(), max_results, allSpheres, Radius, numsearch, 1 );
ObjectsOld::RunTests< Containers::BinsObjectDynamicType >(
"DynamicObjects", objects.begin(), objects.end(), objectResults.begin(),
resultDistances.begin(), max_results, allSpheres, Radius, numsearch, 1 );
#endif
// RunTestsOldInterface<BinsObjectDynamicType>
return 0;
}
int main( int arg, char *argv[] ) {
std::string filename;
// Default filename
filename = "../cases/genericCube2x2x2.500000.pts";
// filename = "../cases/genericCube100x100x100.5051.pts";
// filename = "../cases/randomCube2000000.pts";
// Default radius
double radius = 0.0102;
if ( arg > 1 ) {
if ( !strncasecmp( argv[ 1 ], "-h", 2 ) || !strncasecmp( argv[ 1 ], "--h", 2 ) ) {
std::cout << "Usage: " << argv[ 0 ] << " [ filename [ radius ] ]" << std::endl;
std::cout << " filename default value = " << filename << std::endl;
std::cout << " radius default value = " << radius << std::endl;
return 0;
}
filename = argv[ 1 ];
if ( arg == 3 ) {
radius = atof( argv[ 2 ] ) / 1000000;
}
}
RunPointSearchComparison( filename, radius );
// filename = "../cases/offsetCube79x79x79.1603.pts";
// RunPointSearchComparison(filename, radius);
// filename = "../cases/clusterCube6x6x6X4913.490.pts";
// RunPointSearchComparison(filename, radius);
// filename = "../cases/line100000.5.pts";
// RunPointSearchComparison(filename, radius);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <set>
#include "debug.h"
#include "util.h"
#include "snapshotindex.h"
using namespace std;
SnapshotIndex::SnapshotIndex()
{
fd = -1;
}
SnapshotIndex::~SnapshotIndex()
{
close();
}
void
SnapshotIndex::open(const string &indexFile)
{
struct stat sb;
fileName = indexFile;
// Read index
fd = ::open(indexFile.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0) {
perror("open");
cout << "Could not open the index file!" << endl;
assert(false);
return;
};
if (::fstat(fd, &sb) < 0) {
perror("fstat");
return;
}
int len = sb.st_size;
char *buf = new char[len];
int status = read(fd, &buf, len);
assert(status == len);
string blob = string().assign(buf, len);
string line;
stringstream ss(blob);
while (getline(ss, line, '\n')) {
string hash, name;
hash = line.substr(0, 64);
name = line.substr(65);
snapshots[name] = hash;
}
::close(fd);
// Reopen append only
fd = ::open(indexFile.c_str(), O_WRONLY | O_APPEND);
assert(fd >= 0); // Assume that the repository lock protects the index
// Delete temporary index if present
if (Util_FileExists(indexFile + ".tmp")) {
Util_DeleteFile(indexFile + ".tmp");
}
}
void
SnapshotIndex::close()
{
if (fd != -1) {
::fsync(fd);
::close(fd);
fd = -1;
}
}
void
SnapshotIndex::rewrite()
{
int fdNew, tmpFd;
string newIndex = fileName + ".tmp";
map<string, string>::iterator it;
fdNew = ::open(newIndex.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fdNew < 0) {
perror("open");
cout << "Could not open a temporary index file!" << endl;
return;
};
// Write new index
for (it = snapshots.begin(); it != snapshots.end(); it++)
{
int status;
string indexLine;
indexLine = (*it).second + " " + (*it).second + "\n";
status = write(fdNew, indexLine.data(), indexLine.size());
assert(status == indexLine.size());
}
Util_RenameFile(newIndex, fileName);
tmpFd = fd;
fd = fdNew;
::close(tmpFd);
}
void
SnapshotIndex::addSnapshot(const string &name, const string &commitId)
{
string indexLine;
assert(commitId.size() == 64);
/*
* XXX: Extra sanity checking for the hash string
* for (int i = 0; i < 64; i++) {
* char c = objId[i];
* assert((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'));
* }
*/
indexLine = commitId + " " + name + "\n";
write(fd, indexLine.data(), indexLine.size());
}
void
SnapshotIndex::delSnapshot(const std::string &name)
{
// delete in map
rewrite();
}
const string &
SnapshotIndex::getSnapshot(const string &name) const
{
map<string, string>::const_iterator it = snapshots.find(name);
assert(it != snapshots.end());
return (*it).second;
}
map<string, string>
SnapshotIndex::getList()
{
return snapshots;
}
<commit_msg>Fixing bug in SnapshotIndex class.<commit_after>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <set>
#include "debug.h"
#include "util.h"
#include "snapshotindex.h"
using namespace std;
SnapshotIndex::SnapshotIndex()
{
fd = -1;
}
SnapshotIndex::~SnapshotIndex()
{
close();
}
void
SnapshotIndex::open(const string &indexFile)
{
struct stat sb;
fileName = indexFile;
// Read index
fd = ::open(indexFile.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0) {
perror("open");
cout << "Could not open the index file!" << endl;
assert(false);
return;
};
if (::fstat(fd, &sb) < 0) {
perror("fstat");
return;
}
int len = sb.st_size;
char *buf = new char[len];
int status = read(fd, buf, len);
assert(status == len);
string blob = string().assign(buf, len);
string line;
stringstream ss(blob);
while (getline(ss, line, '\n')) {
string hash, name;
hash = line.substr(0, 64);
name = line.substr(65);
snapshots[name] = hash;
}
::close(fd);
// Reopen append only
fd = ::open(indexFile.c_str(), O_WRONLY | O_APPEND);
assert(fd >= 0); // Assume that the repository lock protects the index
// Delete temporary index if present
if (Util_FileExists(indexFile + ".tmp")) {
Util_DeleteFile(indexFile + ".tmp");
}
}
void
SnapshotIndex::close()
{
if (fd != -1) {
::fsync(fd);
::close(fd);
fd = -1;
}
}
void
SnapshotIndex::rewrite()
{
int fdNew, tmpFd;
string newIndex = fileName + ".tmp";
map<string, string>::iterator it;
fdNew = ::open(newIndex.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fdNew < 0) {
perror("open");
cout << "Could not open a temporary index file!" << endl;
return;
};
// Write new index
for (it = snapshots.begin(); it != snapshots.end(); it++)
{
int status;
string indexLine;
indexLine = (*it).second + " " + (*it).second + "\n";
status = write(fdNew, indexLine.data(), indexLine.size());
assert(status == indexLine.size());
}
Util_RenameFile(newIndex, fileName);
tmpFd = fd;
fd = fdNew;
::close(tmpFd);
}
void
SnapshotIndex::addSnapshot(const string &name, const string &commitId)
{
string indexLine;
assert(commitId.size() == 64);
/*
* XXX: Extra sanity checking for the hash string
* for (int i = 0; i < 64; i++) {
* char c = objId[i];
* assert((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'));
* }
*/
indexLine = commitId + " " + name + "\n";
write(fd, indexLine.data(), indexLine.size());
}
void
SnapshotIndex::delSnapshot(const std::string &name)
{
// delete in map
rewrite();
}
const string &
SnapshotIndex::getSnapshot(const string &name) const
{
map<string, string>::const_iterator it = snapshots.find(name);
assert(it != snapshots.end());
return (*it).second;
}
map<string, string>
SnapshotIndex::getList()
{
return snapshots;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX600 グループ LVDA 定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 電圧検出回路(LVDA)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct lvda_t {
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 1 回路制御レジスタ 1(LVD1CR1)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd1cr1_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> LVD1IDTSEL;
bit_rw_t <io_, bitpos::B2> LVD1IRQSEL;
};
static lvd1cr1_t<0x000800E0> LVD1CR1;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 1 回路ステータスレジスタ(LVD1SR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd1sr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD1DET;
bit_ro_t <io_, bitpos::B1> LVD1MON;
};
static lvd1sr_t<0x000800E1> LVD1SR;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 2 回路制御レジスタ 1(LVD2CR1)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd2cr1_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> LVD2IDTSEL;
bit_rw_t <io_, bitpos::B2> LVD2IRQSEL;
};
static lvd2cr1_t<0x000800E2> LVD2CR1;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 2 回路ステータスレジスタ(LVD2SR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd2sr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD2DET;
bit_ro_t <io_, bitpos::B1> LVD2MON;
};
static lvd2sr_t<0x000800E3> LVD2SR;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視回路制御レジスタ(LVCMPCR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvcmpcr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t<io_, bitpos::B5> LVD1E;
bit_rw_t<io_, bitpos::B6> LVD2E;
};
static lvcmpcr_t<0x0008C297> LVCMPCR;
//-----------------------------------------------------------------//
/*!
@brief 電圧検出レベル選択レジスタ(LVDLVLR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvdlvlr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 4> LVD1LVL;
#if defined(SIG_RX24T)
bits_rw_t<io_, bitpos::B4, 2> LVD2LVL;
#else
bits_rw_t<io_, bitpos::B4, 4> LVD2LVL;
#endif
};
static lvdlvlr_t<0x0008C298> LVDLVLR;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 1 回路制御レジスタ 0(LVD1CR0)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd1cr0_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD1RIE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T)
bit_rw_t <io_, bitpos::B1> LVD1DFDIS;
#endif
bit_rw_t <io_, bitpos::B2> LVD1CMPE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T)
bits_rw_t<io_, bitpos::B4, 2> LVD1FSAMP;
#endif
bit_rw_t <io_, bitpos::B6> LVD1RI;
bit_rw_t <io_, bitpos::B7> LVD1RN;
};
static lvd1cr0_t<0x0008C29A> LVD1CR0;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 2 回路制御レジスタ 0(LVD2CR0)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd2cr0_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD2RIE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T)
bit_rw_t <io_, bitpos::B1> LVD2DFDIS;
#endif
bit_rw_t <io_, bitpos::B2> LVD2CMPE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T)
bits_rw_t<io_, bitpos::B4, 2> LVD2FSAMP;
#endif
bit_rw_t <io_, bitpos::B6> LVD2RI;
bit_rw_t <io_, bitpos::B7> LVD2RN;
};
static lvd2cr0_t<0x0008C29B> LVD2CR0;
};
typedef lvda_t LVDA;
}
<commit_msg>Update: The reality of the template when it is not optimized<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX24T/RX64M/RX71M/RX65N/RX66T/RX72M/RX72N グループ LVDA 定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 電圧検出回路(LVDA)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class _>
struct lvda_t {
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 1 回路制御レジスタ 1(LVD1CR1)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd1cr1_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> LVD1IDTSEL;
bit_rw_t <io_, bitpos::B2> LVD1IRQSEL;
};
typedef lvd1cr1_t<0x000800E0> LVD1CR1_;
static LVD1CR1_ LVD1CR1;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 1 回路ステータスレジスタ(LVD1SR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd1sr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD1DET;
bit_ro_t <io_, bitpos::B1> LVD1MON;
};
typedef lvd1sr_t<0x000800E1> LVD1SR_;
static LVD1SR_ LVD1SR;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 2 回路制御レジスタ 1(LVD2CR1)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd2cr1_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> LVD2IDTSEL;
bit_rw_t <io_, bitpos::B2> LVD2IRQSEL;
};
typedef lvd2cr1_t<0x000800E2> LVD2CR1_;
static LVD2CR1_ LVD2CR1;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 2 回路ステータスレジスタ(LVD2SR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd2sr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD2DET;
bit_ro_t <io_, bitpos::B1> LVD2MON;
};
typedef lvd2sr_t<0x000800E3> LVD2SR_;
static LVD2SR_ LVD2SR;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視回路制御レジスタ(LVCMPCR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvcmpcr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t<io_, bitpos::B5> LVD1E;
bit_rw_t<io_, bitpos::B6> LVD2E;
};
typedef lvcmpcr_t<0x0008C297> LVCMPCR_;
static LVCMPCR_ LVCMPCR;
//-----------------------------------------------------------------//
/*!
@brief 電圧検出レベル選択レジスタ(LVDLVLR)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvdlvlr_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 4> LVD1LVL;
#if defined(SIG_RX24T)
bits_rw_t<io_, bitpos::B4, 2> LVD2LVL;
#else
bits_rw_t<io_, bitpos::B4, 4> LVD2LVL;
#endif
};
typedef lvdlvlr_t<0x0008C298> LVDLVLR_;
static LVDLVLR_ LVDLVLR;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 1 回路制御レジスタ 0(LVD1CR0)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd1cr0_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD1RIE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72N)
bit_rw_t <io_, bitpos::B1> LVD1DFDIS;
#endif
bit_rw_t <io_, bitpos::B2> LVD1CMPE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72N)
bits_rw_t<io_, bitpos::B4, 2> LVD1FSAMP;
#endif
bit_rw_t <io_, bitpos::B6> LVD1RI;
bit_rw_t <io_, bitpos::B7> LVD1RN;
};
typedef lvd1cr0_t<0x0008C29A> LVD1CR0_;
static LVD1CR0_ LVD1CR0;
//-----------------------------------------------------------------//
/*!
@brief 電圧監視 2 回路制御レジスタ 0(LVD2CR0)
@param[in] base ベース・アドレス
*/
//-----------------------------------------------------------------//
template <uint32_t base>
struct lvd2cr0_t : public rw8_t<base> {
typedef rw8_t<base> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> LVD2RIE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72N)
bit_rw_t <io_, bitpos::B1> LVD2DFDIS;
#endif
bit_rw_t <io_, bitpos::B2> LVD2CMPE;
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72N)
bits_rw_t<io_, bitpos::B4, 2> LVD2FSAMP;
#endif
bit_rw_t <io_, bitpos::B6> LVD2RI;
bit_rw_t <io_, bitpos::B7> LVD2RN;
};
typedef lvd2cr0_t<0x0008C29B> LVD2CR0_;
static LVD2CR0_ LVD2CR0;
};
template <class _> typename lvda_t<_>::LVD1CR1_ lvda_t<_>::LVD1CR1;
template <class _> typename lvda_t<_>::LVD1SR_ lvda_t<_>::LVD1SR;
template <class _> typename lvda_t<_>::LVD2CR1_ lvda_t<_>::LVD2CR1;
template <class _> typename lvda_t<_>::LVD2SR_ lvda_t<_>::LVD2SR;
template <class _> typename lvda_t<_>::LVCMPCR_ lvda_t<_>::LVCMPCR;
template <class _> typename lvda_t<_>::LVDLVLR_ lvda_t<_>::LVDLVLR;
template <class _> typename lvda_t<_>::LVD1CR0_ lvda_t<_>::LVD1CR0;
template <class _> typename lvda_t<_>::LVD2CR0_ lvda_t<_>::LVD2CR0;
typedef lvda_t<void> LVDA;
}
<|endoftext|> |
<commit_before>/*
* SDLBackend.cpp
* openc2e
*
* Created by Alyssa Milburn on Sun Oct 24 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "SDLBackend.h"
#include "SDL_gfxPrimitives.h"
#include "openc2e.h"
#include "Agent.h"
SDLBackend *g_backend;
void SoundSlot::play() {
soundchannel = Mix_PlayChannel(-1, sound, 0);
}
void SoundSlot::playLooped() {
soundchannel = Mix_PlayChannel(-1, sound, -1);
}
void SoundSlot::adjustPanning(int angle, int distance) {
Mix_SetPosition(soundchannel, angle, distance);
}
void SoundSlot::fadeOut() {
Mix_FadeOutChannel(soundchannel, 500); // TODO: is 500 a good value?
}
void SoundSlot::stop() {
Mix_HaltChannel(soundchannel);
sound = 0;
}
void SDLBackend::resizeNotify(int _w, int _h) {
width = _w;
height = _h;
screen = SDL_SetVideoMode(width, height, 0, SDL_RESIZABLE);
assert(screen != 0);
}
void SDLBackend::init(bool enable_sound) {
int init = SDL_INIT_VIDEO;
if (enable_sound) init |= SDL_INIT_AUDIO;
if (SDL_Init(init) < 0) {
std::cerr << "SDL init failed: " << SDL_GetError() << std::endl;
assert(false);
}
if (!enable_sound) {
std::cerr << "Sound disabled per user request." << std::endl;
soundenabled = false;
} else if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096) < 0) {
std::cerr << "SDL_mixer init failed, disabling sound: " << Mix_GetError() << std::endl;
soundenabled = false;
} else soundenabled = true;
resizeNotify(640, 480);
SDL_WM_SetCaption("openc2e - Creatures 3 (development build)", "openc2e");
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
SDL_ShowCursor(false);
}
SoundSlot *SDLBackend::getAudioSlot(std::string filename) {
if (!soundenabled) return 0;
unsigned int i = 0;
while (i < nosounds) {
if (sounddata[i].sound == 0) break;
if (!Mix_Playing(sounddata[i].soundchannel)) {
sounddata[i].sound = 0;
if (sounddata[i].agent)
sounddata[i].agent->soundslot = 0;
break;
}
i++;
}
if (i == nosounds) return 0; // no free slots, so return
sounddata[i].agent = 0;
std::map<std::string, Mix_Chunk *>::iterator it = soundcache.find(filename);
if (it != soundcache.end()) {
sounddata[i].sound = (*it).second;
} else {
std::string fname = datapath + "/Sounds/" + filename + ".wav"; // TODO: case sensitivity stuff
//std::cout << "trying to load " << fname << std::endl;
sounddata[i].sound = Mix_LoadWAV(fname.c_str());
if (!sounddata[i].sound) return 0; // TODO: spout error
soundcache[filename] = sounddata[i].sound;
}
return &sounddata[i];
}
void SDLBackend::renderLine(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int colour) {
aalineColor(screen, x1, y1, x2, y2, colour);
}
void SDLBackend::render(creaturesImage *image, unsigned int frame, unsigned int x, unsigned int y, bool trans, unsigned char transparency) {
SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(image->data(frame),
image->width(frame),
image->height(frame),
16, // depth
image->width(frame) * 2, // pitch
0xF800, 0x07E0, 0x001F, 0); // RGBA mask
SDL_SetColorKey(surf, SDL_SRCCOLORKEY, 0);
if (trans) SDL_SetAlpha(surf, SDL_SRCALPHA, 255 - transparency);
SDL_Rect destrect;
destrect.x = x; destrect.y = y;
SDL_BlitSurface(surf, 0, screen, &destrect);
SDL_FreeSurface(surf);
}
<commit_msg>default to 800x600<commit_after>/*
* SDLBackend.cpp
* openc2e
*
* Created by Alyssa Milburn on Sun Oct 24 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "SDLBackend.h"
#include "SDL_gfxPrimitives.h"
#include "openc2e.h"
#include "Agent.h"
SDLBackend *g_backend;
void SoundSlot::play() {
soundchannel = Mix_PlayChannel(-1, sound, 0);
}
void SoundSlot::playLooped() {
soundchannel = Mix_PlayChannel(-1, sound, -1);
}
void SoundSlot::adjustPanning(int angle, int distance) {
Mix_SetPosition(soundchannel, angle, distance);
}
void SoundSlot::fadeOut() {
Mix_FadeOutChannel(soundchannel, 500); // TODO: is 500 a good value?
}
void SoundSlot::stop() {
Mix_HaltChannel(soundchannel);
sound = 0;
}
void SDLBackend::resizeNotify(int _w, int _h) {
width = _w;
height = _h;
screen = SDL_SetVideoMode(width, height, 0, SDL_RESIZABLE);
assert(screen != 0);
}
void SDLBackend::init(bool enable_sound) {
int init = SDL_INIT_VIDEO;
if (enable_sound) init |= SDL_INIT_AUDIO;
if (SDL_Init(init) < 0) {
std::cerr << "SDL init failed: " << SDL_GetError() << std::endl;
assert(false);
}
if (!enable_sound) {
std::cerr << "Sound disabled per user request." << std::endl;
soundenabled = false;
} else if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096) < 0) {
std::cerr << "SDL_mixer init failed, disabling sound: " << Mix_GetError() << std::endl;
soundenabled = false;
} else soundenabled = true;
resizeNotify(800, 600);
SDL_WM_SetCaption("openc2e - Creatures 3 (development build)", "openc2e");
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
SDL_ShowCursor(false);
}
SoundSlot *SDLBackend::getAudioSlot(std::string filename) {
if (!soundenabled) return 0;
unsigned int i = 0;
while (i < nosounds) {
if (sounddata[i].sound == 0) break;
if (!Mix_Playing(sounddata[i].soundchannel)) {
sounddata[i].sound = 0;
if (sounddata[i].agent)
sounddata[i].agent->soundslot = 0;
break;
}
i++;
}
if (i == nosounds) return 0; // no free slots, so return
sounddata[i].agent = 0;
std::map<std::string, Mix_Chunk *>::iterator it = soundcache.find(filename);
if (it != soundcache.end()) {
sounddata[i].sound = (*it).second;
} else {
std::string fname = datapath + "/Sounds/" + filename + ".wav"; // TODO: case sensitivity stuff
//std::cout << "trying to load " << fname << std::endl;
sounddata[i].sound = Mix_LoadWAV(fname.c_str());
if (!sounddata[i].sound) return 0; // TODO: spout error
soundcache[filename] = sounddata[i].sound;
}
return &sounddata[i];
}
void SDLBackend::renderLine(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int colour) {
aalineColor(screen, x1, y1, x2, y2, colour);
}
void SDLBackend::render(creaturesImage *image, unsigned int frame, unsigned int x, unsigned int y, bool trans, unsigned char transparency) {
SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(image->data(frame),
image->width(frame),
image->height(frame),
16, // depth
image->width(frame) * 2, // pitch
0xF800, 0x07E0, 0x001F, 0); // RGBA mask
SDL_SetColorKey(surf, SDL_SRCCOLORKEY, 0);
if (trans) SDL_SetAlpha(surf, SDL_SRCALPHA, 255 - transparency);
SDL_Rect destrect;
destrect.x = x; destrect.y = y;
SDL_BlitSurface(surf, 0, screen, &destrect);
SDL_FreeSurface(surf);
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
// Returns aligned image
Mat alignImage( Mat image) {
Mat org = imread( "template-blank.jpg", CV_LOAD_IMAGE_GRAYSCALE );
if(!org.data) std::cout << "unable to read template image";
// Detect the keypoints using SURF Detector
int minHessian = 400;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypointsOrg, keypointsImage;
detector.detect( org, keypointsOrg );
detector.detect( image, keypointsImage );
// Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;
Mat descriptorsOrg, descriptorsImage;
extractor.compute( org, keypointsOrg, descriptorsOrg );
extractor.compute( image, keypointsImage, descriptorsImage );
// Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptorsOrg, descriptorsImage, matches );
double max_dist = 0;
double min_dist = 100;
// Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptorsOrg.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
// Use "good" matches (i.e. whose distance is less than ((399*min_dist)+max_dist)/400 )
std::vector< DMatch > good_matches;
for( int i = 0; i < descriptorsOrg.rows; i++ )
{ if( matches[i].distance < ((399*min_dist)+max_dist)/400 )
{ good_matches.push_back( matches[i]); }
}
// Localize the object
std::vector<Point2f> kptsOrg;
std::vector<Point2f> kptsImage;
for( int i = 0; i < good_matches.size(); i++ )
{
// Get the keypoints from the good matches
kptsOrg.push_back( keypointsOrg[ good_matches[i].queryIdx ].pt );
kptsImage.push_back( keypointsImage[ good_matches[i].trainIdx ].pt );
}
Mat H = findHomography( kptsImage, kptsOrg, CV_RANSAC );
warpPerspective( image, org, H, org.size() );
// imshow( "img_object", org);
// waitKey(0);
return org;
}
Mat definePtns ( int numQues, int numOpts, int numQuesRow, int centerX, int centerY, int distRow, int distCol, int distOpts ) {
Mat optsPtns( numQues, numOpts, CV_16UC2 );
unsigned int colNum = 0;
unsigned int rowNum = 0;
for (int i = 0; i < numQues; ++i)
{
for (int j = 0; j < numOpts; ++j)
{
colNum = i/numQuesRow;
rowNum = i%numQuesRow;
optsPtns.at<Vec2s>(i,j)[0] = 221 + (182*colNum) + (28*j);
optsPtns.at<Vec2s>(i,j)[1] = 176 + (42*rowNum);
}
}
return optsPtns;
}
Mat readOpts( Mat image ) {
// define constants
int numQues = 60;
int numQuesRow = 21;
int numOpts = 5;
int distRow = 42;
int distCol = 182;
int distOpts = 28;
int centerX = 221;
int centerY = 176;
int radius = 11;
Mat opts( numQues, numOpts, CV_8UC1, 0 );
Mat optsPtns = definePtns( numQues, numOpts, numQuesRow, centerX, centerY, distRow, distCol, distOpts );
std::cout << optsPtns.at<Vec2s>(0,0) << "\n";
std::cout << optsPtns.at<Vec2s>(59,4) << "\n";
return optsPtns;
}
// Main function
int main(int argc, char** argv) {
Mat image = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
if(!image.data) std::cout << "unable to read argument image";
Mat imageAligned = alignImage( image );
Mat markedOpts = readOpts( imageAligned );
}
<commit_msg>Implemented option reading and marked identifying function in the kernel<commit_after>#include <stdio.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
// Returns aligned image
Mat alignImage( Mat image) {
Mat org = imread( "template-blank.jpg", CV_LOAD_IMAGE_GRAYSCALE );
if(!org.data) std::cout << "unable to read template image";
// Detect the keypoints using SURF Detector
int minHessian = 400;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypointsOrg, keypointsImage;
detector.detect( org, keypointsOrg );
detector.detect( image, keypointsImage );
// Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;
Mat descriptorsOrg, descriptorsImage;
extractor.compute( org, keypointsOrg, descriptorsOrg );
extractor.compute( image, keypointsImage, descriptorsImage );
// Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptorsOrg, descriptorsImage, matches );
double max_dist = 0;
double min_dist = 100;
// Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptorsOrg.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
// Use "good" matches (i.e. whose distance is less than ((399*min_dist)+max_dist)/400 )
std::vector< DMatch > good_matches;
for( int i = 0; i < descriptorsOrg.rows; i++ )
{ if( matches[i].distance < ((399*min_dist)+max_dist)/400 )
{ good_matches.push_back( matches[i]); }
}
// Localize the object
std::vector<Point2f> kptsOrg;
std::vector<Point2f> kptsImage;
for( int i = 0; i < good_matches.size(); i++ )
{
// Get the keypoints from the good matches
kptsOrg.push_back( keypointsOrg[ good_matches[i].queryIdx ].pt );
kptsImage.push_back( keypointsImage[ good_matches[i].trainIdx ].pt );
}
Mat H = findHomography( kptsImage, kptsOrg, CV_RANSAC );
warpPerspective( image, org, H, org.size() );
// imshow( "img_object", org);
// waitKey(0);
return org;
}
Mat definePtns ( int numQues, int numOpts, int numQuesRow, int centerX, int centerY, int distRow, int distCol, int distOpts ) {
Mat optsPtns( numQues, numOpts, CV_16UC2 );
unsigned int colNum = 0;
unsigned int rowNum = 0;
for (int i = 0; i < numQues; ++i)
{
for (int j = 0; j < numOpts; ++j)
{
colNum = i/numQuesRow;
rowNum = i%numQuesRow;
optsPtns.at<Vec2s>(i,j)[0] = 221 + (182*colNum) + (28*j);
optsPtns.at<Vec2s>(i,j)[1] = 176 + (42*rowNum);
}
}
return optsPtns;
}
short isOptMarked(Vec2s optCenter, Mat& image, int radius) {
float X = 0.0;
float Y = 0.0;
float effRadius = radius - 0.5;
unsigned int counter = 0;
unsigned int sum = 0;
unsigned int threshold = 80;
short isMarked = 0;
for (int j = optCenter[1]-radius+1; j <= optCenter[1]+radius ; ++j)
{
for (int i = optCenter[0]-radius+1; i <= optCenter[0]+radius; ++i)
{
X = i - (optCenter[0] + 0.5);
Y = j - (optCenter[1] + 0.5);
if ((X*X) + (Y*Y) <= (effRadius*effRadius))
{
counter = counter + 1;
sum = sum + image.at<uchar>(j,i);
}
}
}
if (sum/counter < threshold)
{
isMarked = 1;
std::cout << isMarked <<"\n" << sum/counter << "\n";
}
return isMarked;
}
Mat readOpts( Mat image ) {
// define constants
int numQues = 60;
int numQuesRow = 21;
int numOpts = 5;
int distRow = 42;
int distCol = 182;
int distOpts = 28;
int centerX = 221;
int centerY = 176;
int optRadius = 10;
Mat opts( numQues, numOpts, CV_8SC1);
Mat optsPtns = definePtns( numQues, numOpts, numQuesRow, centerX, centerY, distRow, distCol, distOpts );
for (int i = 0; i < optsPtns.rows; ++i)
{
for (int j = 0; j < optsPtns.cols; ++j)
{
Vec2s optCenter = optsPtns.at<Vec2s>(i,j);
opts.at<short>(i,j) = isOptMarked(optCenter, image, optRadius);
}
}
return opts;
}
// Main function
int main(int argc, char** argv) {
Mat image = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
if(!image.data) std::cout << "unable to read argument image";
Mat imageAligned = alignImage( image );
Mat markedOpts = readOpts( imageAligned );
}
<|endoftext|> |
<commit_before>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Host.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include <memory>
using namespace llvm;
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
// Determine optimization level.
static cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));
static cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
static cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
static cl::opt<bool>
RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
cl::desc("Choose a file type (not all types are supported by all targets):"),
cl::values(
clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
"Emit an assembly ('.s') file"),
clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
"Emit a native object ('.o') file [experimental]"),
clEnumValN(TargetMachine::CGFT_Null, "null",
"Emit nothing, for performance testing"),
clEnumValEnd));
cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
static cl::opt<bool>
DisableRedZone("disable-red-zone",
cl::desc("Do not emit code that uses the red zone."),
cl::init(false));
static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
cl::desc("Don't generate implicit floating point instructions (x86-only)"),
cl::init(false));
// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if ((Len > 2) &&
IFN[Len-3] == '.' &&
((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
(IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
static formatted_raw_ostream *GetOutputStream(const char *TargetName,
Triple::OSType OS,
const char *ProgName) {
if (OutputFilename != "") {
if (OutputFilename == "-")
return new formatted_raw_ostream(outs(),
formatted_raw_ostream::PRESERVE_STREAM);
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
std::string error;
raw_fd_ostream *FDOut =
new raw_fd_ostream(OutputFilename.c_str(), error,
raw_fd_ostream::F_Binary);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
formatted_raw_ostream *Out =
new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
return Out;
}
if (InputFilename == "-") {
OutputFilename = "-";
return new formatted_raw_ostream(outs(),
formatted_raw_ostream::PRESERVE_STREAM);
}
OutputFilename = GetFileNameRoot(InputFilename);
bool Binary = false;
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
if (TargetName[0] == 'c') {
if (TargetName[1] == 0)
OutputFilename += ".cbe.c";
else if (TargetName[1] == 'p' && TargetName[2] == 'p')
OutputFilename += ".cpp";
else
OutputFilename += ".s";
} else
OutputFilename += ".s";
break;
case TargetMachine::CGFT_ObjectFile:
if (OS == Triple::Win32)
OutputFilename += ".obj";
else
OutputFilename += ".o";
Binary = true;
break;
case TargetMachine::CGFT_Null:
OutputFilename += ".null";
Binary = true;
break;
}
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
std::string error;
unsigned OpenFlags = 0;
if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
OpenFlags);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
formatted_raw_ostream *Out =
new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
return Out;
}
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets first, so that --version shows registered targets.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
// Load the module to be compiled...
SMDiagnostic Err;
std::auto_ptr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
Module &mod = *M.get();
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
mod.setTargetTriple(TargetTriple);
Triple TheTriple(mod.getTargetTriple());
if (TheTriple.getTriple().empty())
TheTriple.setTriple(sys::getHostTriple());
// Allocate target machine. First, check whether the user has explicitly
// specified an architecture to compile for. If so we have to look it up by
// name, because it might be a backend that has no mapping to a target triple.
const Target *TheTarget = 0;
if (!MArch.empty()) {
for (TargetRegistry::iterator it = TargetRegistry::begin(),
ie = TargetRegistry::end(); it != ie; ++it) {
if (MArch == it->getName()) {
TheTarget = &*it;
break;
}
}
if (!TheTarget) {
errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
return 1;
}
// Adjust the triple to match (if known), otherwise stick with the
// module/host triple.
Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
if (Type != Triple::UnknownArch)
TheTriple.setArch(Type);
} else {
std::string Err;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
if (TheTarget == 0) {
errs() << argv[0] << ": error auto-selecting target for module '"
<< Err << "'. Please use the -march option to explicitly "
<< "pick a target.\n";
return 1;
}
}
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MCPU.size() || MAttrs.size()) {
SubtargetFeatures Features;
Features.setCPU(MCPU);
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Figure out where we are going to send the output...
formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(),
TheTriple.getOS(), argv[0]);
if (Out == 0) return 1;
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << argv[0] << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
// Request that addPassesToEmitFile run the Verifier after running
// passes which modify the IR.
#ifndef NDEBUG
bool DisableVerify = false;
#else
bool DisableVerify = true;
#endif
// Build up all of the passes that we want to do to the module.
PassManager PM;
// Add the target data from the target machine, if it exists, or the module.
if (const TargetData *TD = Target.getTargetData())
PM.add(new TargetData(*TD));
else
PM.add(new TargetData(&mod));
if (!NoVerify)
PM.add(createVerifierPass());
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
if (RelaxAll) {
if (FileType != TargetMachine::CGFT_ObjectFile)
errs() << argv[0]
<< ": warning: ignoring -mc-relax-all because filetype != obj";
else
Target.setMCRelaxAll(true);
}
// Ask the target to add backend passes as necessary.
if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl,
DisableVerify)) {
errs() << argv[0] << ": target does not support generation of this"
<< " file type!\n";
delete Out;
// And the Out file is empty and useless, so remove it now.
sys::Path(OutputFilename).eraseFromDisk();
return 1;
}
PM.run(mod);
// Delete the ostream.
delete Out;
return 0;
}
<commit_msg>llc: Clarify -mc-relax-all description.<commit_after>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Host.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include <memory>
using namespace llvm;
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
// Determine optimization level.
static cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));
static cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
static cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
static cl::opt<bool>
RelaxAll("mc-relax-all",
cl::desc("When used with filetype=obj, "
"relax all fixups in the emited object file"));
cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
cl::desc("Choose a file type (not all types are supported by all targets):"),
cl::values(
clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
"Emit an assembly ('.s') file"),
clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
"Emit a native object ('.o') file [experimental]"),
clEnumValN(TargetMachine::CGFT_Null, "null",
"Emit nothing, for performance testing"),
clEnumValEnd));
cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
static cl::opt<bool>
DisableRedZone("disable-red-zone",
cl::desc("Do not emit code that uses the red zone."),
cl::init(false));
static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
cl::desc("Don't generate implicit floating point instructions (x86-only)"),
cl::init(false));
// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if ((Len > 2) &&
IFN[Len-3] == '.' &&
((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
(IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
static formatted_raw_ostream *GetOutputStream(const char *TargetName,
Triple::OSType OS,
const char *ProgName) {
if (OutputFilename != "") {
if (OutputFilename == "-")
return new formatted_raw_ostream(outs(),
formatted_raw_ostream::PRESERVE_STREAM);
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
std::string error;
raw_fd_ostream *FDOut =
new raw_fd_ostream(OutputFilename.c_str(), error,
raw_fd_ostream::F_Binary);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
formatted_raw_ostream *Out =
new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
return Out;
}
if (InputFilename == "-") {
OutputFilename = "-";
return new formatted_raw_ostream(outs(),
formatted_raw_ostream::PRESERVE_STREAM);
}
OutputFilename = GetFileNameRoot(InputFilename);
bool Binary = false;
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
if (TargetName[0] == 'c') {
if (TargetName[1] == 0)
OutputFilename += ".cbe.c";
else if (TargetName[1] == 'p' && TargetName[2] == 'p')
OutputFilename += ".cpp";
else
OutputFilename += ".s";
} else
OutputFilename += ".s";
break;
case TargetMachine::CGFT_ObjectFile:
if (OS == Triple::Win32)
OutputFilename += ".obj";
else
OutputFilename += ".o";
Binary = true;
break;
case TargetMachine::CGFT_Null:
OutputFilename += ".null";
Binary = true;
break;
}
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
std::string error;
unsigned OpenFlags = 0;
if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
OpenFlags);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
formatted_raw_ostream *Out =
new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
return Out;
}
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets first, so that --version shows registered targets.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
// Load the module to be compiled...
SMDiagnostic Err;
std::auto_ptr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
Module &mod = *M.get();
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
mod.setTargetTriple(TargetTriple);
Triple TheTriple(mod.getTargetTriple());
if (TheTriple.getTriple().empty())
TheTriple.setTriple(sys::getHostTriple());
// Allocate target machine. First, check whether the user has explicitly
// specified an architecture to compile for. If so we have to look it up by
// name, because it might be a backend that has no mapping to a target triple.
const Target *TheTarget = 0;
if (!MArch.empty()) {
for (TargetRegistry::iterator it = TargetRegistry::begin(),
ie = TargetRegistry::end(); it != ie; ++it) {
if (MArch == it->getName()) {
TheTarget = &*it;
break;
}
}
if (!TheTarget) {
errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
return 1;
}
// Adjust the triple to match (if known), otherwise stick with the
// module/host triple.
Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
if (Type != Triple::UnknownArch)
TheTriple.setArch(Type);
} else {
std::string Err;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
if (TheTarget == 0) {
errs() << argv[0] << ": error auto-selecting target for module '"
<< Err << "'. Please use the -march option to explicitly "
<< "pick a target.\n";
return 1;
}
}
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MCPU.size() || MAttrs.size()) {
SubtargetFeatures Features;
Features.setCPU(MCPU);
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
// Figure out where we are going to send the output...
formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(),
TheTriple.getOS(), argv[0]);
if (Out == 0) return 1;
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << argv[0] << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
// Request that addPassesToEmitFile run the Verifier after running
// passes which modify the IR.
#ifndef NDEBUG
bool DisableVerify = false;
#else
bool DisableVerify = true;
#endif
// Build up all of the passes that we want to do to the module.
PassManager PM;
// Add the target data from the target machine, if it exists, or the module.
if (const TargetData *TD = Target.getTargetData())
PM.add(new TargetData(*TD));
else
PM.add(new TargetData(&mod));
if (!NoVerify)
PM.add(createVerifierPass());
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
if (RelaxAll) {
if (FileType != TargetMachine::CGFT_ObjectFile)
errs() << argv[0]
<< ": warning: ignoring -mc-relax-all because filetype != obj";
else
Target.setMCRelaxAll(true);
}
// Ask the target to add backend passes as necessary.
if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl,
DisableVerify)) {
errs() << argv[0] << ": target does not support generation of this"
<< " file type!\n";
delete Out;
// And the Out file is empty and useless, so remove it now.
sys::Path(OutputFilename).eraseFromDisk();
return 1;
}
PM.run(mod);
// Delete the ostream.
delete Out;
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "AutoPacket.h"
#include "Autowired.h"
#include "AutoPacketFactory.h"
#include "AutoPacketProfiler.h"
#include "SatCounter.h"
#include <list>
AutoPacket::AutoPacket(AutoPacketFactory& factory):
m_satCounters(
factory.GetSubscriberVector().begin(),
factory.GetSubscriberVector().end()
)
{
// Prime the satisfaction graph for each element:
for(auto& autoFilter : m_satCounters)
for(
auto pCur = autoFilter.GetAutoFilterInput();
*pCur;
pCur++
) {
DecorationDisposition& entry = m_decorations[*pCur->ti];
// Decide what to do with this entry:
switch(pCur->subscriberType) {
case inTypeInvalid:
// Should never happen--trivially ignore this entry
break;
case inTypeRequired:
entry.m_subscribers.push_back(std::make_pair(&autoFilter, true));
break;
case inTypeOptional:
entry.m_subscribers.push_back(std::make_pair(&autoFilter, false));
break;
case outTypeRef:
case outTypeRefAutoReady:
// We don't do anything with these types.
// Optionally, we might want to register them as outputs, or do some kind
// of runtime detection that a multi-satisfaction case exists--but for now,
// we just trivially ignore them.
break;
}
}
// Initial reset, required to get into a valid initial state
Reset();
}
AutoPacket::~AutoPacket() {
// Last chance for AutoFilter call
ResolveOptions();
{
boost::lock_guard<boost::mutex> lk(m_lock);
m_decorations.clear();
m_satCounters.clear();
}
}
void AutoPacket::ResolveOptions(void) {
// Queue calls to ensure that calls to Decorate inside of AutoFilter methods
// will NOT effect the resolution of optional arguments.
std::list<SatCounter*> callQueue;
{
boost::lock_guard<boost::mutex> lk(m_lock);
for(auto& decoration : m_decorations)
for(auto& satCounter : decoration.second.m_subscribers)
if(!satCounter.second)
if(satCounter.first->Resolve())
callQueue.emplace_back(satCounter.first);
}
for (SatCounter* call : callQueue)
call->CallAutoFilter(*this);
}
void AutoPacket::MarkUnsatisfiable(const std::type_info& info) {
DecorationDisposition* decoration;
{
boost::lock_guard<boost::mutex> lk(m_lock);
auto dFind = m_decorations.find(info);
if(dFind == m_decorations.end())
// Trivial return, there's no subscriber to this decoration and so we have nothing to do
return;
decoration = &dFind->second;
}
// Update everything
for(auto& satCounter : decoration->m_subscribers) {
if(satCounter.second)
// Entry is mandatory, leave it unsatisfaible
continue;
// Entry is optional, we will call if we're satisfied after decrementing this optional field
if(satCounter.first->Decrement(false))
satCounter.first->CallAutoFilter(*this);
}
}
void AutoPacket::UpdateSatisfaction(const std::type_info& info) {
DecorationDisposition* decoration;
{
boost::lock_guard<boost::mutex> lk(m_lock);
auto dFind = m_decorations.find(info);
if(dFind == m_decorations.end())
// Trivial return, there's no subscriber to this decoration and so we have nothing to do
return;
decoration = &dFind->second;
}
// Update everything
for(auto& satCounter : decoration->m_subscribers)
if(satCounter.first->Decrement(satCounter.second))
satCounter.first->CallAutoFilter(*this);
}
void AutoPacket::PulseSatisfaction(DecorationDisposition* pTypeSubs[], size_t nInfos) {
// First pass, decrement what we can:
for(size_t i = nInfos; i--;) {
for(auto& satCounter : pTypeSubs[i]->m_subscribers) {
auto& cur = satCounter.first;
if (satCounter.second) {
--cur->remaining;
if(!cur->remaining)
//Call only when required data is decremented to zero
cur->CallAutoFilter(*this);
}
}
}
// Reset all counters
// since data in this call will not be available subsequently
for(size_t i = nInfos; i--;) {
for(auto& satCounter : pTypeSubs[i]->m_subscribers) {
auto& cur = satCounter.first;
if (satCounter.second) {
++cur->remaining;
}
}
}
}
void AutoPacket::Reset(void) {
// Last chance for AutoFilter call
ResolveOptions();
// Reset all counters:
{
boost::lock_guard<boost::mutex> lk(m_lock);
for(auto& satCounter : m_satCounters)
satCounter.Reset();
for(auto& decoration : m_decorations)
decoration.second.Reset();
}
// Initial satisfaction of the AutoPacket:
UpdateSatisfaction(typeid(AutoPacket));
}
bool AutoPacket::HasSubscribers(const std::type_info& ti) const {
return m_decorations.count(ti) != 0;
}
<commit_msg>Unfortunately, no such method as emplace_back on libstdc++<commit_after>#include "stdafx.h"
#include "AutoPacket.h"
#include "Autowired.h"
#include "AutoPacketFactory.h"
#include "AutoPacketProfiler.h"
#include "SatCounter.h"
#include <list>
AutoPacket::AutoPacket(AutoPacketFactory& factory):
m_satCounters(
factory.GetSubscriberVector().begin(),
factory.GetSubscriberVector().end()
)
{
// Prime the satisfaction graph for each element:
for(auto& autoFilter : m_satCounters)
for(
auto pCur = autoFilter.GetAutoFilterInput();
*pCur;
pCur++
) {
DecorationDisposition& entry = m_decorations[*pCur->ti];
// Decide what to do with this entry:
switch(pCur->subscriberType) {
case inTypeInvalid:
// Should never happen--trivially ignore this entry
break;
case inTypeRequired:
entry.m_subscribers.push_back(std::make_pair(&autoFilter, true));
break;
case inTypeOptional:
entry.m_subscribers.push_back(std::make_pair(&autoFilter, false));
break;
case outTypeRef:
case outTypeRefAutoReady:
// We don't do anything with these types.
// Optionally, we might want to register them as outputs, or do some kind
// of runtime detection that a multi-satisfaction case exists--but for now,
// we just trivially ignore them.
break;
}
}
// Initial reset, required to get into a valid initial state
Reset();
}
AutoPacket::~AutoPacket() {
// Last chance for AutoFilter call
ResolveOptions();
{
boost::lock_guard<boost::mutex> lk(m_lock);
m_decorations.clear();
m_satCounters.clear();
}
}
void AutoPacket::ResolveOptions(void) {
// Queue calls to ensure that calls to Decorate inside of AutoFilter methods
// will NOT effect the resolution of optional arguments.
std::list<SatCounter*> callQueue;
{
boost::lock_guard<boost::mutex> lk(m_lock);
for(auto& decoration : m_decorations)
for(auto& satCounter : decoration.second.m_subscribers)
if(!satCounter.second)
if(satCounter.first->Resolve())
callQueue.push_back(satCounter.first);
}
for (SatCounter* call : callQueue)
call->CallAutoFilter(*this);
}
void AutoPacket::MarkUnsatisfiable(const std::type_info& info) {
DecorationDisposition* decoration;
{
boost::lock_guard<boost::mutex> lk(m_lock);
auto dFind = m_decorations.find(info);
if(dFind == m_decorations.end())
// Trivial return, there's no subscriber to this decoration and so we have nothing to do
return;
decoration = &dFind->second;
}
// Update everything
for(auto& satCounter : decoration->m_subscribers) {
if(satCounter.second)
// Entry is mandatory, leave it unsatisfaible
continue;
// Entry is optional, we will call if we're satisfied after decrementing this optional field
if(satCounter.first->Decrement(false))
satCounter.first->CallAutoFilter(*this);
}
}
void AutoPacket::UpdateSatisfaction(const std::type_info& info) {
DecorationDisposition* decoration;
{
boost::lock_guard<boost::mutex> lk(m_lock);
auto dFind = m_decorations.find(info);
if(dFind == m_decorations.end())
// Trivial return, there's no subscriber to this decoration and so we have nothing to do
return;
decoration = &dFind->second;
}
// Update everything
for(auto& satCounter : decoration->m_subscribers)
if(satCounter.first->Decrement(satCounter.second))
satCounter.first->CallAutoFilter(*this);
}
void AutoPacket::PulseSatisfaction(DecorationDisposition* pTypeSubs[], size_t nInfos) {
// First pass, decrement what we can:
for(size_t i = nInfos; i--;) {
for(auto& satCounter : pTypeSubs[i]->m_subscribers) {
auto& cur = satCounter.first;
if (satCounter.second) {
--cur->remaining;
if(!cur->remaining)
//Call only when required data is decremented to zero
cur->CallAutoFilter(*this);
}
}
}
// Reset all counters
// since data in this call will not be available subsequently
for(size_t i = nInfos; i--;) {
for(auto& satCounter : pTypeSubs[i]->m_subscribers) {
auto& cur = satCounter.first;
if (satCounter.second) {
++cur->remaining;
}
}
}
}
void AutoPacket::Reset(void) {
// Last chance for AutoFilter call
ResolveOptions();
// Reset all counters:
{
boost::lock_guard<boost::mutex> lk(m_lock);
for(auto& satCounter : m_satCounters)
satCounter.Reset();
for(auto& decoration : m_decorations)
decoration.second.Reset();
}
// Initial satisfaction of the AutoPacket:
UpdateSatisfaction(typeid(AutoPacket));
}
bool AutoPacket::HasSubscribers(const std::type_info& ti) const {
return m_decorations.count(ti) != 0;
}
<|endoftext|> |
<commit_before>//
// Simulation.cpp
// MobileDetectorSim
//
// Created by Jonas Nilsson on 2016-05-11.
// Copyright © 2016 Jonas Nilsson. All rights reserved.
//
#include "Simulation.hpp"
ListModeSimulator::ListModeSimulator(unsigned int iterations, bool use_multiple_threads) : iterations(iterations), use_multiple_threads(use_multiple_threads) {
int numberOfThreads = thread::hardware_concurrency();
PRINT("Starting simulation threads.");
for (int i = 0; i < numberOfThreads; i++) {
SimulatorThread calcThread(i, &threadIn);
threads.push_back(boost::thread(calcThread));
}
}
ListModeSimulator::~ListModeSimulator() {
if (threads.size() > 0) {
CloseThreads();
}
}
void ListModeSimulator::CloseThreads() {
PRINT("Closing simulation threads.");
SimulationParams par;
par.exit = true;
for (int i = 0; i < threads.size(); i++) {
threadIn.push(par);
}
while (threads.size() > 0) {
threads[threads.size() - 1].join();
threads.pop_back();
}
}
double ListModeSimulator::PerformSimulation(SimulationParams par) {
concurrent_queue<ReturnData> threadOut;
par.threadOut = &threadOut;
if (use_multiple_threads) {
for (int j = 0; j < threads.size() - 1; j++) {
par.iterations = iterations / threads.size();
threadIn.push(par);
}
par.iterations = iterations / threads.size() + iterations % threads.size();
threadIn.push(par);
} else {
par.iterations = iterations;
threadIn.push(par);
}
unsigned int finishedCtr = 0;
unsigned int truePositives = 0;
ReturnData retVal;
while (finishedCtr < iterations) {
threadOut.wait_and_pop(retVal);
finishedCtr += retVal.iterations;
truePositives += retVal.value;
}
return 1.0 - double(truePositives) / double(finishedCtr);
}
SimulatorThread::SimulatorThread(int threadId, concurrent_queue<SimulationParams> *threadIn) : threadId(threadId), threadIn(threadIn) {
}
void SimulatorThread::operator()() {
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now) + threadId};
double maxRate;
double cTime, pTime;
double cStopTime;
unsigned int truePositiveProb = 0;
SimulationParams cParams;
ReturnData ret;
while (true) {
threadIn->wait_and_pop(cParams);
if (cParams.exit) {
break;
}
{
auto dist = [&cParams] (double t) {return sqrt((cParams.velocity * t) * (cParams.velocity * t) + cParams.distance * cParams.distance);};
auto ang = [&cParams, &dist] (double t) {return asin(cParams.distance / dist(t));};
auto S = [&cParams, &dist, &ang] (double t) {return cParams.distResp(dist(t)) * cParams.angResp(ang(t));};
maxRate = S(0.0) * cParams.activityFactor + cParams.background;
boost::random::exponential_distribution<> expDist(maxRate);
boost::random::uniform_real_distribution<> rejectDist(0, maxRate);
boost::circular_buffer<double> eventQueue(cParams.critical_limit);
truePositiveProb = 0;
for (int i = 0; i < cParams.iterations; i++) {
if (cParams.startTime > -cParams.integrationTime) {
cTime = -cParams.integrationTime + expDist(gen);
cStopTime = cParams.integrationTime;
} else {
cTime = cParams.startTime + expDist(gen);
cStopTime = cParams.stopTime;
}
eventQueue.clear(); //Clear the queue
do {
if (rejectDist(gen) <= S(cTime) * cParams.activityFactor + cParams.background) {
eventQueue.push_back(cTime);
pTime = cTime - cParams.integrationTime;
while (eventQueue.front() < pTime) {
eventQueue.pop_front();
}
if (eventQueue.size() >= cParams.critical_limit) {
truePositiveProb++;
break;
}
}
cTime += expDist(gen);
} while (cTime < cStopTime);
}
}
ret.iterations = cParams.iterations;
ret.value = truePositiveProb;
cParams.threadOut->push(ret);
}
}
<commit_msg>Cleaned up the simulation loop slightly.<commit_after>//
// Simulation.cpp
// MobileDetectorSim
//
// Created by Jonas Nilsson on 2016-05-11.
// Copyright © 2016 Jonas Nilsson. All rights reserved.
//
#include "Simulation.hpp"
ListModeSimulator::ListModeSimulator(unsigned int iterations, bool use_multiple_threads) : iterations(iterations), use_multiple_threads(use_multiple_threads) {
int numberOfThreads = thread::hardware_concurrency();
PRINT("Starting simulation threads.");
for (int i = 0; i < numberOfThreads; i++) {
SimulatorThread calcThread(i, &threadIn);
threads.push_back(boost::thread(calcThread));
}
}
ListModeSimulator::~ListModeSimulator() {
if (threads.size() > 0) {
CloseThreads();
}
}
void ListModeSimulator::CloseThreads() {
PRINT("Closing simulation threads.");
SimulationParams par;
par.exit = true;
for (int i = 0; i < threads.size(); i++) {
threadIn.push(par);
}
while (threads.size() > 0) {
threads[threads.size() - 1].join();
threads.pop_back();
}
}
double ListModeSimulator::PerformSimulation(SimulationParams par) {
concurrent_queue<ReturnData> threadOut;
par.threadOut = &threadOut;
if (use_multiple_threads) {
for (int j = 0; j < threads.size() - 1; j++) {
par.iterations = iterations / threads.size();
threadIn.push(par);
}
par.iterations = iterations / threads.size() + iterations % threads.size();
threadIn.push(par);
} else {
par.iterations = iterations;
threadIn.push(par);
}
unsigned int finishedCtr = 0;
unsigned int truePositives = 0;
ReturnData retVal;
while (finishedCtr < iterations) {
threadOut.wait_and_pop(retVal);
finishedCtr += retVal.iterations;
truePositives += retVal.value;
}
return 1.0 - double(truePositives) / double(finishedCtr);
}
SimulatorThread::SimulatorThread(int threadId, concurrent_queue<SimulationParams> *threadIn) : threadId(threadId), threadIn(threadIn) {
}
void SimulatorThread::operator()() {
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now) + threadId};
double maxRate;
double cTime, pTime;
double cStartTime, cStopTime;
unsigned int truePositiveProb = 0;
SimulationParams cParams;
ReturnData ret;
while (true) {
threadIn->wait_and_pop(cParams);
if (cParams.exit) {
break;
}
{
auto dist = [&cParams] (double t) {return sqrt((cParams.velocity * t) * (cParams.velocity * t) + cParams.distance * cParams.distance);};
auto ang = [&cParams, &dist] (double t) {return asin(cParams.distance / dist(t));};
auto S = [&cParams, &dist, &ang] (double t) {return cParams.distResp(dist(t)) * cParams.angResp(ang(t));};
maxRate = S(0.0) * cParams.activityFactor + cParams.background;
boost::random::exponential_distribution<> expDist(maxRate);
boost::random::uniform_real_distribution<> rejectDist(0, maxRate);
boost::circular_buffer<double> eventQueue(cParams.critical_limit);
truePositiveProb = 0;
if (cParams.startTime > -cParams.integrationTime) {
cStartTime = -cParams.integrationTime;
cStopTime = cParams.integrationTime;
} else {
cStartTime = cParams.startTime;
cStopTime = cParams.stopTime;
}
for (int i = 0; i < cParams.iterations; i++) {
cTime = cStartTime + expDist(gen);
eventQueue.clear(); //Clear the queue
do {
if (rejectDist(gen) <= S(cTime) * cParams.activityFactor + cParams.background) {
eventQueue.push_back(cTime);
pTime = cTime - cParams.integrationTime;
while (eventQueue.front() < pTime) {
eventQueue.pop_front();
}
if (eventQueue.size() >= cParams.critical_limit) {
truePositiveProb++;
break;
}
}
cTime += expDist(gen);
} while (cTime < cStopTime);
}
}
ret.iterations = cParams.iterations;
ret.value = truePositiveProb;
cParams.threadOut->push(ret);
}
}
<|endoftext|> |
<commit_before>AliAnalysisTaskLambdaNNRun2* AddMyTaskLNRun2(Bool_t isMC=kFALSE)
{
// get the manager via the static access member. since it's static, you don't need
// to create an instance of the class here to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":MyTask"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskLambdaNNRun2* task = new AliAnalysisTaskLambdaNNRun2("LambdaNNRun2Ntuple",isMC);
if (!task) return 0x0;
// task->SetMC(isMC);
//task->SelectCollisionCandidates(AliVEvent::kAnyINT);
//task->SelectCollisionCandidates(AliVEvent::kAny);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task, 1, mgr->CreateContainer("MyOutputContainer", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
mgr->ConnectOutput(task, 2, mgr->CreateContainer("Data", TTree::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<commit_msg>Fix addtask name<commit_after>AliAnalysisTaskLambdaNNRun2* AddMyTaskLNNRun2(Bool_t isMC=kFALSE)
{
// get the manager via the static access member. since it's static, you don't need
// to create an instance of the class here to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":MyTask"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskLambdaNNRun2* task = new AliAnalysisTaskLambdaNNRun2("LambdaNNRun2Ntuple",isMC);
if (!task) return 0x0;
// task->SetMC(isMC);
//task->SelectCollisionCandidates(AliVEvent::kAnyINT);
//task->SelectCollisionCandidates(AliVEvent::kAny);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task, 1, mgr->CreateContainer("MyOutputContainer", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
mgr->ConnectOutput(task, 2, mgr->CreateContainer("Data", TTree::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<|endoftext|> |
<commit_before>#include "SoftModem.h"
#define TX_PIN (3)
#define RX_PIN1 (6) // AIN0
#define RX_PIN2 (7) // AIN1
SoftModem *SoftModem::activeObject = 0;
SoftModem::SoftModem() {
}
SoftModem::~SoftModem() {
end();
}
#if F_CPU == 16000000
#if SOFT_MODEM_BAUD_RATE <= 126
#define TIMER_CLOCK_SELECT (7)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(1024))
#elif SOFT_MODEM_BAUD_RATE <= 315
#define TIMER_CLOCK_SELECT (6)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(256))
#elif SOFT_MODEM_BAUD_RATE <= 630
#define TIMER_CLOCK_SELECT (5)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(128))
#elif SOFT_MODEM_BAUD_RATE <= 1225
#define TIMER_CLOCK_SELECT (4)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(64))
#else
#define TIMER_CLOCK_SELECT (3)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(32))
#endif
#else
#if SOFT_MODEM_BAUD_RATE <= 126
#define TIMER_CLOCK_SELECT (6)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(256))
#elif SOFT_MODEM_BAUD_RATE <= 315
#define TIMER_CLOCK_SELECT (5)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(128))
#elif SOFT_MODEM_BAUD_RATE <= 630
#define TIMER_CLOCK_SELECT (4)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(64))
#else
#define TIMER_CLOCK_SELECT (3)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(32))
#endif
#endif
#define BIT_PERIOD (1000000/SOFT_MODEM_BAUD_RATE)
#define HIGH_FREQ_MICROS (1000000/SOFT_MODEM_HIGH_FREQ)
#define LOW_FREQ_MICROS (1000000/SOFT_MODEM_LOW_FREQ)
#define HIGH_FREQ_CNT (BIT_PERIOD/HIGH_FREQ_MICROS)
#define LOW_FREQ_CNT (BIT_PERIOD/LOW_FREQ_MICROS)
#define MAX_CARRIR_BITS (40000/BIT_PERIOD)
#define TCNT_BIT_PERIOD (BIT_PERIOD/MICROS_PER_TIMER_COUNT)
#define TCNT_HIGH_FREQ (HIGH_FREQ_MICROS/MICROS_PER_TIMER_COUNT)
#define TCNT_LOW_FREQ (LOW_FREQ_MICROS/MICROS_PER_TIMER_COUNT)
#define TCNT_HIGH_TH_L (TCNT_HIGH_FREQ * 0.90)
#define TCNT_HIGH_TH_H (TCNT_HIGH_FREQ * 1.15)
#define TCNT_LOW_TH_L (TCNT_LOW_FREQ * 0.85)
#define TCNT_LOW_TH_H (TCNT_LOW_FREQ * 1.10)
#if SOFT_MODEM_DEBUG_ENABLE
static volatile uint8_t *_portLEDReg;
static uint8_t _portLEDMask;
#endif
enum { START_BIT = 0, DATA_BIT = 8, STOP_BIT = 9, INACTIVE = 0xff };
void SoftModem::begin(void)
{
pinMode(RX_PIN1, INPUT);
digitalWrite(RX_PIN1, LOW);
pinMode(RX_PIN2, INPUT);
digitalWrite(RX_PIN2, LOW);
pinMode(TX_PIN, OUTPUT);
digitalWrite(TX_PIN, LOW);
_txPortReg = portOutputRegister(digitalPinToPort(TX_PIN));
_txPortMask = digitalPinToBitMask(TX_PIN);
#if SOFT_MODEM_DEBUG_ENABLE
_portLEDReg = portOutputRegister(digitalPinToPort(13));
_portLEDMask = digitalPinToBitMask(13);
pinMode(13, OUTPUT);
#endif
_recvStat = INACTIVE;
_recvBufferHead = _recvBufferTail = 0;
SoftModem::activeObject = this;
_lastTCNT = TCNT2;
_lastDiff = _lowCount = _highCount = 0;
TCCR2A = 0;
TCCR2B = TIMER_CLOCK_SELECT;
ACSR = _BV(ACIE) | _BV(ACIS1);
DIDR1 = _BV(AIN1D) | _BV(AIN0D);
}
void SoftModem::end(void)
{
ACSR &= ~(_BV(ACIE));
TIMSK2 &= ~(_BV(OCIE2A));
DIDR1 &= ~(_BV(AIN1D) | _BV(AIN0D));
SoftModem::activeObject = 0;
}
void SoftModem::demodulate(void)
{
uint8_t t = TCNT2;
uint8_t diff;
diff = t - _lastTCNT;
if(diff < 4)
return;
_lastTCNT = t;
if(diff > (uint8_t)(TCNT_LOW_TH_H))
return;
// 移動平均
_lastDiff = (diff >> 1) + (diff >> 2) + (_lastDiff >> 2);
if(_lastDiff >= (uint8_t)(TCNT_LOW_TH_L)){
_lowCount += _lastDiff;
if(_recvStat == INACTIVE){
// スタートビット検出
if(_lowCount >= (uint8_t)(TCNT_BIT_PERIOD * 0.5)){
_recvStat = START_BIT;
_highCount = 0;
_recvBits = 0;
OCR2A = t + (uint8_t)(TCNT_BIT_PERIOD) - _lowCount;
TIFR2 |= _BV(OCF2A);
TIMSK2 |= _BV(OCIE2A);
}
}
}
else if(_lastDiff <= (uint8_t)(TCNT_HIGH_TH_H)){
if(_recvStat == INACTIVE){
_lowCount = 0;
_highCount = 0;
}
else{
_highCount += _lastDiff;
}
}
}
// アナログコンパレータ割り込み
ISR(ANALOG_COMP_vect)
{
SoftModem::activeObject->demodulate();
}
void SoftModem::recv(void)
{
uint8_t high;
// ビット論理判定
if(_highCount > _lowCount){
_highCount = 0;
high = 0x80;
}
else{
_lowCount = 0;
high = 0x00;
}
// スタートビット受信
if(_recvStat == START_BIT){
if(!high){
_recvStat++;
}
else{
goto end_recv;
}
}
// データビット受信
else if(_recvStat <= DATA_BIT) {
_recvBits >>= 1;
_recvBits |= high;
_recvStat++;
}
// ストップビット受信
else if(_recvStat == STOP_BIT){
if(high){
// 受信バッファに格納
uint8_t new_tail = (_recvBufferTail + 1) & (SOFT_MODEM_RX_BUF_SIZE - 1);
if(new_tail != _recvBufferHead){
_recvBuffer[_recvBufferTail] = _recvBits;
_recvBufferTail = new_tail;
}
else{
;// オーバーランエラー
}
}
else{
;// フレミングエラー
}
goto end_recv;
}
else{
end_recv:
_recvStat = INACTIVE;
TIMSK2 &= ~_BV(OCIE2A);
}
}
// タイマー2比較一致割り込みA
ISR(TIMER2_COMPA_vect)
{
OCR2A += (uint8_t)TCNT_BIT_PERIOD;
SoftModem::activeObject->recv();
#if SOFT_MODEM_DEBUG_ENABLE
*_portLEDReg ^= _portLEDMask;
#endif
}
int SoftModem::available()
{
return (_recvBufferTail + SOFT_MODEM_RX_BUF_SIZE - _recvBufferHead) & (SOFT_MODEM_RX_BUF_SIZE - 1);
}
int SoftModem::read()
{
if(_recvBufferHead == _recvBufferTail)
return -1;
int d = _recvBuffer[_recvBufferHead];
_recvBufferHead = (_recvBufferHead + 1) & (SOFT_MODEM_RX_BUF_SIZE - 1);
return d;
}
int SoftModem::peek()
{
if(_recvBufferHead == _recvBufferTail)
return -1;
return _recvBuffer[_recvBufferHead];
}
void SoftModem::flush()
{
}
void SoftModem::modulate(uint8_t b)
{
uint8_t cnt,tcnt,tcnt2;
if(b){
cnt = (uint8_t)(HIGH_FREQ_CNT);
tcnt2 = (uint8_t)(TCNT_HIGH_FREQ / 2);
tcnt = (uint8_t)(TCNT_HIGH_FREQ) - tcnt2;
}else{
cnt = (uint8_t)(LOW_FREQ_CNT);
tcnt2 = (uint8_t)(TCNT_LOW_FREQ / 2);
tcnt = (uint8_t)(TCNT_LOW_FREQ) - tcnt2;
}
do {
cnt--;
{
OCR2B += tcnt;
TIFR2 |= _BV(OCF2B);
while(!(TIFR2 & _BV(OCF2B)));
}
*_txPortReg ^= _txPortMask;
{
OCR2B += tcnt2;
TIFR2 |= _BV(OCF2B);
while(!(TIFR2 & _BV(OCF2B)));
}
*_txPortReg ^= _txPortMask;
} while (cnt);
}
// Preamble bit before transmission
// 1 start bit (LOW)
// 8 data bits, LSB first
// 1 stop bit (HIGH)
// ...
// Postamble bit after transmission
size_t SoftModem::write(const uint8_t *buffer, size_t size)
{
// プリアンブルビット
uint8_t cnt = ((micros() - _lastWriteTime) / BIT_PERIOD) + 1;
if(cnt > MAX_CARRIR_BITS){
cnt = MAX_CARRIR_BITS;
}
for(uint8_t i = 0; i<cnt; i++){
modulate(HIGH);
}
size_t n = size;
while (size--) {
uint8_t data = *buffer++;
// スタート1ビット
modulate(LOW);
// データ8ビット
for(uint8_t mask = 1; mask; mask <<= 1){
if(data & mask){
modulate(HIGH);
}
else{
modulate(LOW);
}
}
// ストップ1ビット
modulate(HIGH);
}
// ポストアンブルビット
modulate(HIGH);
_lastWriteTime = micros();
return n;
}
size_t SoftModem::write(uint8_t data)
{
return write(&data, 1);
}
<commit_msg>add comments<commit_after>#include "SoftModem.h"
#define TX_PIN (3)
#define RX_PIN1 (6) // AIN0
#define RX_PIN2 (7) // AIN1
SoftModem *SoftModem::activeObject = 0;
SoftModem::SoftModem() {
}
SoftModem::~SoftModem() {
end();
}
#if F_CPU == 16000000
#if SOFT_MODEM_BAUD_RATE <= 126
#define TIMER_CLOCK_SELECT (7)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(1024))
#elif SOFT_MODEM_BAUD_RATE <= 315
#define TIMER_CLOCK_SELECT (6)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(256))
#elif SOFT_MODEM_BAUD_RATE <= 630
#define TIMER_CLOCK_SELECT (5)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(128))
#elif SOFT_MODEM_BAUD_RATE <= 1225
#define TIMER_CLOCK_SELECT (4)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(64))
#else
#define TIMER_CLOCK_SELECT (3)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(32))
#endif
#else
#if SOFT_MODEM_BAUD_RATE <= 126
#define TIMER_CLOCK_SELECT (6)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(256))
#elif SOFT_MODEM_BAUD_RATE <= 315
#define TIMER_CLOCK_SELECT (5)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(128))
#elif SOFT_MODEM_BAUD_RATE <= 630
#define TIMER_CLOCK_SELECT (4)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(64))
#else
#define TIMER_CLOCK_SELECT (3)
#define MICROS_PER_TIMER_COUNT (clockCyclesToMicroseconds(32))
#endif
#endif
#define BIT_PERIOD (1000000/SOFT_MODEM_BAUD_RATE)
#define HIGH_FREQ_MICROS (1000000/SOFT_MODEM_HIGH_FREQ)
#define LOW_FREQ_MICROS (1000000/SOFT_MODEM_LOW_FREQ)
#define HIGH_FREQ_CNT (BIT_PERIOD/HIGH_FREQ_MICROS)
#define LOW_FREQ_CNT (BIT_PERIOD/LOW_FREQ_MICROS)
#define MAX_CARRIR_BITS (40000/BIT_PERIOD) // 40ms
#define TCNT_BIT_PERIOD (BIT_PERIOD/MICROS_PER_TIMER_COUNT)
#define TCNT_HIGH_FREQ (HIGH_FREQ_MICROS/MICROS_PER_TIMER_COUNT)
#define TCNT_LOW_FREQ (LOW_FREQ_MICROS/MICROS_PER_TIMER_COUNT)
#define TCNT_HIGH_TH_L (TCNT_HIGH_FREQ * 0.80)
#define TCNT_HIGH_TH_H (TCNT_HIGH_FREQ * 1.15)
#define TCNT_LOW_TH_L (TCNT_LOW_FREQ * 0.85)
#define TCNT_LOW_TH_H (TCNT_LOW_FREQ * 1.20)
#if SOFT_MODEM_DEBUG_ENABLE
static volatile uint8_t *_portLEDReg;
static uint8_t _portLEDMask;
#endif
enum { START_BIT = 0, DATA_BIT = 8, STOP_BIT = 9, INACTIVE = 0xff };
void SoftModem::begin(void)
{
pinMode(RX_PIN1, INPUT);
digitalWrite(RX_PIN1, LOW);
pinMode(RX_PIN2, INPUT);
digitalWrite(RX_PIN2, LOW);
pinMode(TX_PIN, OUTPUT);
digitalWrite(TX_PIN, LOW);
_txPortReg = portOutputRegister(digitalPinToPort(TX_PIN));
_txPortMask = digitalPinToBitMask(TX_PIN);
#if SOFT_MODEM_DEBUG_ENABLE
_portLEDReg = portOutputRegister(digitalPinToPort(13));
_portLEDMask = digitalPinToBitMask(13);
pinMode(13, OUTPUT);
#endif
_recvStat = INACTIVE;
_recvBufferHead = _recvBufferTail = 0;
SoftModem::activeObject = this;
_lastTCNT = TCNT2;
_lastDiff = _lowCount = _highCount = 0;
TCCR2A = 0;
TCCR2B = TIMER_CLOCK_SELECT;
ACSR = _BV(ACIE) | _BV(ACIS1); // set Analog Comparator Interrupt Enable | trgger on falling edge
DIDR1 = _BV(AIN1D) | _BV(AIN0D); // digital port off
}
void SoftModem::end(void)
{
ACSR &= ~(_BV(ACIE));
TIMSK2 &= ~(_BV(OCIE2A));
DIDR1 &= ~(_BV(AIN1D) | _BV(AIN0D));
SoftModem::activeObject = 0;
}
void SoftModem::demodulate(void)
{
uint8_t t = TCNT2; //get time in Timer 2
uint8_t diff;
if(TIFR2 & _BV(TOV2)){ // Timer 2 overflow
TIFR2 |= _BV(TOV2);
diff = (255 - _lastTCNT) + t + 1;
}
else{
diff = t - _lastTCNT;
}
if(diff < (uint8_t)(TCNT_HIGH_TH_L)) // Noise?
return;
_lastTCNT = t;
if(diff > (uint8_t)(TCNT_LOW_TH_H))
return;
// _lastDiff = (diff >> 1) + (diff >> 2) + (_lastDiff >> 2);
_lastDiff = diff;
if(_lastDiff >= (uint8_t)(TCNT_LOW_TH_L)){ // recv low frequency signal
_lowCount += _lastDiff;
if((_recvStat == INACTIVE) && (_lowCount >= (uint8_t)(TCNT_BIT_PERIOD * 0.5))){ // maybe Start-Bit , now at half of start bit
_recvStat = START_BIT;
_highCount = 0;
_recvBits = 0;
OCR2A = t + (uint8_t)(TCNT_BIT_PERIOD) - _lowCount; // 1 bit period after detected, set next timer2 interrupt at half TCNT_BIT_PERIOD later
TIFR2 |= _BV(OCF2A);
TIMSK2 |= _BV(OCIE2A);
}
}
else if(_lastDiff <= (uint8_t)(TCNT_HIGH_TH_H)){ // recv high frequency signal
_highCount += _lastDiff;
if((_recvStat == INACTIVE) && (_highCount >= (uint8_t)(TCNT_BIT_PERIOD))){
_lowCount = _highCount = 0;
}
}
}
//analog voltage compare interrupt (AIN0 and AIN1)
ISR(ANALOG_COMP_vect)
{
SoftModem::activeObject->demodulate();
}
void SoftModem::recv(void)
{
uint8_t high;
if(_highCount > _lowCount){
if(_highCount >= (uint8_t)TCNT_BIT_PERIOD)
_highCount -= (uint8_t)TCNT_BIT_PERIOD;
else
_highCount = 0;
high = 0x80;
}
else{
if(_lowCount >= (uint8_t)TCNT_BIT_PERIOD)
_lowCount -= (uint8_t)TCNT_BIT_PERIOD;
else
_lowCount = 0;
high = 0x00;
}
if(_recvStat == START_BIT){ // Start bit
if(!high){
_recvStat++;
}else{
goto end_recv;
}
}
else if(_recvStat <= DATA_BIT) { // Data bits
_recvBits >>= 1;
_recvBits |= high;
_recvStat++;
}
else if(_recvStat == STOP_BIT){ // Stop bit
uint8_t new_tail = (_recvBufferTail + 1) & (SOFT_MODEM_RX_BUF_SIZE - 1);
if(new_tail != _recvBufferHead){
_recvBuffer[_recvBufferTail] = _recvBits;
_recvBufferTail = new_tail;
}
goto end_recv;
}
else{
end_recv:
_recvStat = INACTIVE;
TIMSK2 &= ~_BV(OCIE2A);
}
}
//timer2 interrupt
ISR(TIMER2_COMPA_vect)
{
OCR2A += (uint8_t)TCNT_BIT_PERIOD;
SoftModem::activeObject->recv();
#if SOFT_MODEM_DEBUG_ENABLE
*_portLEDReg ^= _portLEDMask;
#endif
}
int SoftModem::available()
{
return (_recvBufferTail + SOFT_MODEM_RX_BUF_SIZE - _recvBufferHead) & (SOFT_MODEM_RX_BUF_SIZE - 1);
}
int SoftModem::read()
{
if(_recvBufferHead == _recvBufferTail)
return -1;
int d = _recvBuffer[_recvBufferHead];
_recvBufferHead = (_recvBufferHead + 1) & (SOFT_MODEM_RX_BUF_SIZE - 1);
return d;
}
int SoftModem::peek()
{
if(_recvBufferHead == _recvBufferTail)
return -1;
return _recvBuffer[_recvBufferHead];
}
void SoftModem::flush()
{
_recvBufferHead = _recvBufferTail = 0;
}
void SoftModem::modulate(uint8_t b)
{
uint8_t cnt,tcnt,tcnt2;
if(b){
cnt = (uint8_t)(HIGH_FREQ_CNT);
tcnt2 = (uint8_t)(TCNT_HIGH_FREQ / 2);
tcnt = (uint8_t)(TCNT_HIGH_FREQ) - tcnt2;
}else{
cnt = (uint8_t)(LOW_FREQ_CNT);
tcnt2 = (uint8_t)(TCNT_LOW_FREQ / 2);
tcnt = (uint8_t)(TCNT_LOW_FREQ) - tcnt2;
}
do {
cnt--;
{
OCR2B += tcnt;
TIFR2 |= _BV(OCF2B);
while(!(TIFR2 & _BV(OCF2B)));
}
*_txPortReg ^= _txPortMask;
{
OCR2B += tcnt2;
TIFR2 |= _BV(OCF2B);
while(!(TIFR2 & _BV(OCF2B)));
}
*_txPortReg ^= _txPortMask;
} while (cnt);
}
// Brief carrier tone before each transmission
// 1 start bit (LOW)
// 8 data bits, LSB first
// 1 stop bit (HIGH)
// ...
// 1 push bit (HIGH)
size_t SoftModem::write(const uint8_t *buffer, size_t size)
{
uint8_t cnt = ((micros() - _lastWriteTime) / BIT_PERIOD) + 1;
if(cnt > MAX_CARRIR_BITS)
cnt = MAX_CARRIR_BITS;
for(uint8_t i = 0; i<cnt; i++)
modulate(HIGH);
size_t n = size;
while (size--) {
uint8_t data = *buffer++;
modulate(LOW); // Start Bit
for(uint8_t mask = 1; mask; mask <<= 1){ // Data Bits
if(data & mask){
modulate(HIGH);
}
else{
modulate(LOW);
}
}
modulate(HIGH); // Stop Bit
}
modulate(HIGH); // Push Bit
_lastWriteTime = micros();
return n;
}
size_t SoftModem::write(uint8_t data)
{
return write(&data, 1);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "uiitem.h"
#include <framework/otml/otml.h>
#include <framework/graphics/graphics.h>
#include <framework/graphics/fontmanager.h>
UIItem::UIItem()
{
m_dragable = true;
}
void UIItem::drawSelf()
{
UIWidget::drawSelf();
if(m_item) {
Rect drawRect = getClippingRect();
float scaleFactor = std::min(drawRect.width() / 32.0f, drawRect.height() / 32.0f);
g_painter.setColor(Color::white);
m_item->draw(drawRect.topLeft(), scaleFactor, true);
if(m_font && m_item->isStackable() && m_item->getCount() > 1) {
std::string count = Fw::tostring(m_item->getCount());
g_painter.setColor(Color(231, 231, 231));
m_font->drawText(count, Rect(m_rect.topLeft(), m_rect.bottomRight() - Point(3, 0)), Fw::AlignBottomRight);
}
}
}
void UIItem::setItemId(int id)
{
if(!m_item && id != 0)
m_item = Item::create(id);
else {
// remove item
if(id == 0)
m_item = nullptr;
else
m_item->setId(id);
}
}
void UIItem::onStyleApply(const std::string& styleName, const OTMLNodePtr& styleNode)
{
UIWidget::onStyleApply(styleName, styleNode);
for(const OTMLNodePtr& node : styleNode->children()) {
if(node->tag() == "item-id")
setItemId(node->value<int>());
else if(node->tag() == "item-count")
setItemCount(node->value<int>());
else if(node->tag() == "virtual")
setVirtual(node->value<bool>());
}
}
<commit_msg>fix drawing of 2x2 items on UIItem<commit_after>/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "uiitem.h"
#include <framework/otml/otml.h>
#include <framework/graphics/graphics.h>
#include <framework/graphics/fontmanager.h>
UIItem::UIItem()
{
m_dragable = true;
}
void UIItem::drawSelf()
{
UIWidget::drawSelf();
if(m_item) {
Rect drawRect = getClippingRect();
Point dest = drawRect.topLeft();
float scaleFactor = std::min(drawRect.width() / (float)m_item->getExactSize(), drawRect.height() / (float)m_item->getExactSize());
dest += (1 - scaleFactor)*32;
dest += m_item->getDisplacement() * scaleFactor;
g_painter.setColor(Color::white);
m_item->draw(dest, scaleFactor, true);
if(m_font && m_item->isStackable() && m_item->getCount() > 1) {
std::string count = Fw::tostring(m_item->getCount());
g_painter.setColor(Color(231, 231, 231));
m_font->drawText(count, Rect(m_rect.topLeft(), m_rect.bottomRight() - Point(3, 0)), Fw::AlignBottomRight);
}
//m_font->drawText(Fw::tostring(m_item->getId()), m_rect, Fw::AlignBottomRight);
}
}
void UIItem::setItemId(int id)
{
if(!m_item && id != 0)
m_item = Item::create(id);
else {
// remove item
if(id == 0)
m_item = nullptr;
else
m_item->setId(id);
}
}
void UIItem::onStyleApply(const std::string& styleName, const OTMLNodePtr& styleNode)
{
UIWidget::onStyleApply(styleName, styleNode);
for(const OTMLNodePtr& node : styleNode->children()) {
if(node->tag() == "item-id")
setItemId(node->value<int>());
else if(node->tag() == "item-count")
setItemCount(node->value<int>());
else if(node->tag() == "virtual")
setVirtual(node->value<bool>());
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <entt/core/hashed_string.hpp>
#include <entt/meta/context.hpp>
#include <entt/meta/factory.hpp>
struct base {};
struct clazz: base {
clazz() = default;
clazz(int)
: clazz{} {}
clazz(char, int)
: clazz{} {}
int func(int v) {
return (value = v);
}
int cfunc(int v) const {
return v;
}
static void move_to_bucket(const clazz &instance) {
bucket = instance.value;
}
int value{};
static inline int bucket{};
};
struct local_only {};
struct argument {
argument(int val)
: value{val} {}
int get() const {
return value;
}
int get_mul() const {
return value * 2;
}
private:
int value{};
};
class MetaContext: public ::testing::Test {
void init_global_context() {
using namespace entt::literals;
entt::meta<int>()
.data<global_marker>("marker"_hs);
entt::meta<argument>()
.conv<&argument::get>();
entt::meta<clazz>()
.type("foo"_hs)
.ctor<int>()
.data<&clazz::value>("value"_hs)
.data<&clazz::value>("rw"_hs)
.func<&clazz::func>("func"_hs);
}
void init_local_context() {
using namespace entt::literals;
entt::meta<int>(context)
.data<local_marker>("marker"_hs);
entt::meta<local_only>(context)
.type("quux"_hs);
entt::meta<argument>(context)
.conv<&argument::get_mul>();
entt::meta<clazz>(context)
.type("bar"_hs)
.base<base>()
.ctor<char, int>()
.dtor<&clazz::move_to_bucket>()
.data<nullptr, &clazz::value>("value"_hs)
.data<&clazz::value>("rw"_hs)
.func<&clazz::cfunc>("func"_hs);
}
public:
void SetUp() override {
init_global_context();
init_local_context();
clazz::bucket = bucket_value;
}
void TearDown() override {
entt::meta_reset(context);
entt::meta_reset();
}
protected:
static constexpr int global_marker = 1;
static constexpr int local_marker = 42;
static constexpr int bucket_value = 99;
entt::meta_ctx context{};
};
TEST_F(MetaContext, Resolve) {
using namespace entt::literals;
ASSERT_TRUE(entt::resolve<clazz>());
ASSERT_TRUE(entt::resolve<clazz>(context));
ASSERT_TRUE(entt::resolve<local_only>());
ASSERT_TRUE(entt::resolve<local_only>(context));
ASSERT_TRUE(entt::resolve(entt::type_id<clazz>()));
ASSERT_TRUE(entt::resolve(context, entt::type_id<clazz>()));
ASSERT_FALSE(entt::resolve(entt::type_id<local_only>()));
ASSERT_TRUE(entt::resolve(context, entt::type_id<local_only>()));
ASSERT_TRUE(entt::resolve("foo"_hs));
ASSERT_FALSE(entt::resolve(context, "foo"_hs));
ASSERT_FALSE(entt::resolve("bar"_hs));
ASSERT_TRUE(entt::resolve(context, "bar"_hs));
ASSERT_FALSE(entt::resolve("quux"_hs));
ASSERT_TRUE(entt::resolve(context, "quux"_hs));
ASSERT_EQ((std::distance(entt::resolve().cbegin(), entt::resolve().cend())), 3);
ASSERT_EQ((std::distance(entt::resolve(context).cbegin(), entt::resolve(context).cend())), 4);
}
TEST_F(MetaContext, MetaType) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>();
const auto local = entt::resolve<clazz>(context);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_NE(global, local);
ASSERT_EQ(global, entt::resolve("foo"_hs));
ASSERT_EQ(local, entt::resolve(context, "bar"_hs));
ASSERT_EQ(global.id(), "foo"_hs);
ASSERT_EQ(local.id(), "bar"_hs);
}
TEST_F(MetaContext, MetaBase) {
const auto global = entt::resolve<clazz>();
const auto local = entt::resolve<clazz>(context);
ASSERT_EQ((std::distance(global.base().cbegin(), global.base().cend())), 0);
ASSERT_EQ((std::distance(local.base().cbegin(), local.base().cend())), 1);
ASSERT_EQ(local.base().cbegin()->second.info(), entt::type_id<base>());
ASSERT_FALSE(entt::resolve(entt::type_id<base>()));
ASSERT_FALSE(entt::resolve(context, entt::type_id<base>()));
}
TEST_F(MetaContext, MetaData) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>().data("value"_hs);
const auto local = entt::resolve<clazz>(context).data("value"_hs);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_FALSE(global.is_const());
ASSERT_TRUE(local.is_const());
ASSERT_EQ(global.type().data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.type().data("marker"_hs).get({}).cast<int>(), local_marker);
const auto grw = entt::resolve<clazz>().data("rw"_hs);
const auto lrw = entt::resolve<clazz>(context).data("rw"_hs);
ASSERT_EQ(grw.arg(0).data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(lrw.arg(0).data("marker"_hs).get({}).cast<int>(), local_marker);
clazz instance{};
const argument value{2};
grw.set(instance, value);
ASSERT_EQ(instance.value, value.get());
lrw.set(entt::meta_handle{context, instance}, entt::meta_any{context, value});
ASSERT_EQ(instance.value, value.get_mul());
}
TEST_F(MetaContext, MetaFunc) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>().func("func"_hs);
const auto local = entt::resolve<clazz>(context).func("func"_hs);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_FALSE(global.is_const());
ASSERT_TRUE(local.is_const());
ASSERT_EQ(global.arg(0).data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.arg(0).data("marker"_hs).get({}).cast<int>(), local_marker);
ASSERT_EQ(global.ret().data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.ret().data("marker"_hs).get({}).cast<int>(), local_marker);
clazz instance{};
const argument value{2};
ASSERT_NE(instance.value, value.get());
ASSERT_EQ(global.invoke(instance, value).cast<int>(), value.get());
ASSERT_EQ(instance.value, value.get());
ASSERT_NE(instance.value, value.get_mul());
ASSERT_EQ(local.invoke(entt::meta_handle{context, instance}, entt::meta_any{context, value}).cast<int>(), value.get_mul());
ASSERT_NE(instance.value, value.get_mul());
}
TEST_F(MetaContext, MetaCtor) {
const auto global = entt::resolve<clazz>();
const auto local = entt::resolve<clazz>(context);
ASSERT_TRUE(global.construct());
ASSERT_TRUE(local.construct());
ASSERT_TRUE(global.construct(0));
ASSERT_FALSE(local.construct(0));
ASSERT_FALSE(global.construct('c', 0));
ASSERT_TRUE(local.construct('c', 0));
}
TEST_F(MetaContext, MetaConv) {
argument value{2};
auto global = entt::forward_as_meta(value);
auto local = entt::forward_as_meta(context, value);
ASSERT_TRUE(global.allow_cast<int>());
ASSERT_TRUE(local.allow_cast<int>());
ASSERT_EQ(global.cast<int>(), value.get());
ASSERT_EQ(local.cast<int>(), value.get_mul());
}
TEST_F(MetaContext, MetaDtor) {
auto global = entt::resolve<clazz>().construct();
auto local = entt::resolve<clazz>(context).construct();
ASSERT_EQ(clazz::bucket, bucket_value);
global.reset();
ASSERT_EQ(clazz::bucket, bucket_value);
local.reset();
ASSERT_NE(clazz::bucket, bucket_value);
}
TEST_F(MetaContext, MetaProp) {
// TODO
}
TEST_F(MetaContext, MetaTemplate) {
// TODO
}
TEST_F(MetaContext, MetaPointer) {
// TODO
}
TEST_F(MetaContext, MetaAssociativeContainer) {
// TODO
}
TEST_F(MetaContext, MetaSequenceContainer) {
// TODO
}
TEST_F(MetaContext, MetaAny) {
// TODO
}
TEST_F(MetaContext, MetaHandle) {
// TODO
}
TEST_F(MetaContext, ForwardAsMeta) {
// TODO
}
TEST_F(MetaContext, ContextMix) {
// TODO
}
<commit_msg>test: context aware meta prop<commit_after>#include <gtest/gtest.h>
#include <entt/core/hashed_string.hpp>
#include <entt/meta/context.hpp>
#include <entt/meta/factory.hpp>
struct base {};
struct clazz: base {
clazz() = default;
clazz(int)
: clazz{} {}
clazz(char, int)
: clazz{} {}
int func(int v) {
return (value = v);
}
int cfunc(int v) const {
return v;
}
static void move_to_bucket(const clazz &instance) {
bucket = instance.value;
}
int value{};
static inline int bucket{};
};
struct local_only {};
struct argument {
argument(int val)
: value{val} {}
int get() const {
return value;
}
int get_mul() const {
return value * 2;
}
private:
int value{};
};
class MetaContext: public ::testing::Test {
void init_global_context() {
using namespace entt::literals;
entt::meta<int>()
.data<global_marker>("marker"_hs);
entt::meta<argument>()
.conv<&argument::get>();
entt::meta<clazz>()
.type("foo"_hs)
.prop("prop"_hs, prop_value)
.ctor<int>()
.data<&clazz::value>("value"_hs)
.data<&clazz::value>("rw"_hs)
.func<&clazz::func>("func"_hs);
}
void init_local_context() {
using namespace entt::literals;
entt::meta<int>(context)
.data<local_marker>("marker"_hs);
entt::meta<local_only>(context)
.type("quux"_hs);
entt::meta<argument>(context)
.conv<&argument::get_mul>();
entt::meta<clazz>(context)
.type("bar"_hs)
.prop("prop"_hs, prop_value)
.base<base>()
.ctor<char, int>()
.dtor<&clazz::move_to_bucket>()
.data<nullptr, &clazz::value>("value"_hs)
.data<&clazz::value>("rw"_hs)
.func<&clazz::cfunc>("func"_hs);
}
public:
void SetUp() override {
init_global_context();
init_local_context();
clazz::bucket = bucket_value;
}
void TearDown() override {
entt::meta_reset(context);
entt::meta_reset();
}
protected:
static constexpr int global_marker = 1;
static constexpr int local_marker = 42;
static constexpr int bucket_value = 99;
static constexpr int prop_value = 3;
entt::meta_ctx context{};
};
TEST_F(MetaContext, Resolve) {
using namespace entt::literals;
ASSERT_TRUE(entt::resolve<clazz>());
ASSERT_TRUE(entt::resolve<clazz>(context));
ASSERT_TRUE(entt::resolve<local_only>());
ASSERT_TRUE(entt::resolve<local_only>(context));
ASSERT_TRUE(entt::resolve(entt::type_id<clazz>()));
ASSERT_TRUE(entt::resolve(context, entt::type_id<clazz>()));
ASSERT_FALSE(entt::resolve(entt::type_id<local_only>()));
ASSERT_TRUE(entt::resolve(context, entt::type_id<local_only>()));
ASSERT_TRUE(entt::resolve("foo"_hs));
ASSERT_FALSE(entt::resolve(context, "foo"_hs));
ASSERT_FALSE(entt::resolve("bar"_hs));
ASSERT_TRUE(entt::resolve(context, "bar"_hs));
ASSERT_FALSE(entt::resolve("quux"_hs));
ASSERT_TRUE(entt::resolve(context, "quux"_hs));
ASSERT_EQ((std::distance(entt::resolve().cbegin(), entt::resolve().cend())), 3);
ASSERT_EQ((std::distance(entt::resolve(context).cbegin(), entt::resolve(context).cend())), 4);
}
TEST_F(MetaContext, MetaType) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>();
const auto local = entt::resolve<clazz>(context);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_NE(global, local);
ASSERT_EQ(global, entt::resolve("foo"_hs));
ASSERT_EQ(local, entt::resolve(context, "bar"_hs));
ASSERT_EQ(global.id(), "foo"_hs);
ASSERT_EQ(local.id(), "bar"_hs);
}
TEST_F(MetaContext, MetaBase) {
const auto global = entt::resolve<clazz>();
const auto local = entt::resolve<clazz>(context);
ASSERT_EQ((std::distance(global.base().cbegin(), global.base().cend())), 0);
ASSERT_EQ((std::distance(local.base().cbegin(), local.base().cend())), 1);
ASSERT_EQ(local.base().cbegin()->second.info(), entt::type_id<base>());
ASSERT_FALSE(entt::resolve(entt::type_id<base>()));
ASSERT_FALSE(entt::resolve(context, entt::type_id<base>()));
}
TEST_F(MetaContext, MetaData) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>().data("value"_hs);
const auto local = entt::resolve<clazz>(context).data("value"_hs);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_FALSE(global.is_const());
ASSERT_TRUE(local.is_const());
ASSERT_EQ(global.type().data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.type().data("marker"_hs).get({}).cast<int>(), local_marker);
const auto grw = entt::resolve<clazz>().data("rw"_hs);
const auto lrw = entt::resolve<clazz>(context).data("rw"_hs);
ASSERT_EQ(grw.arg(0).data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(lrw.arg(0).data("marker"_hs).get({}).cast<int>(), local_marker);
clazz instance{};
const argument value{2};
grw.set(instance, value);
ASSERT_EQ(instance.value, value.get());
lrw.set(entt::meta_handle{context, instance}, entt::meta_any{context, value});
ASSERT_EQ(instance.value, value.get_mul());
}
TEST_F(MetaContext, MetaFunc) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>().func("func"_hs);
const auto local = entt::resolve<clazz>(context).func("func"_hs);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_FALSE(global.is_const());
ASSERT_TRUE(local.is_const());
ASSERT_EQ(global.arg(0).data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.arg(0).data("marker"_hs).get({}).cast<int>(), local_marker);
ASSERT_EQ(global.ret().data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.ret().data("marker"_hs).get({}).cast<int>(), local_marker);
clazz instance{};
const argument value{2};
ASSERT_NE(instance.value, value.get());
ASSERT_EQ(global.invoke(instance, value).cast<int>(), value.get());
ASSERT_EQ(instance.value, value.get());
ASSERT_NE(instance.value, value.get_mul());
ASSERT_EQ(local.invoke(entt::meta_handle{context, instance}, entt::meta_any{context, value}).cast<int>(), value.get_mul());
ASSERT_NE(instance.value, value.get_mul());
}
TEST_F(MetaContext, MetaCtor) {
const auto global = entt::resolve<clazz>();
const auto local = entt::resolve<clazz>(context);
ASSERT_TRUE(global.construct());
ASSERT_TRUE(local.construct());
ASSERT_TRUE(global.construct(0));
ASSERT_FALSE(local.construct(0));
ASSERT_FALSE(global.construct('c', 0));
ASSERT_TRUE(local.construct('c', 0));
}
TEST_F(MetaContext, MetaConv) {
argument value{2};
auto global = entt::forward_as_meta(value);
auto local = entt::forward_as_meta(context, value);
ASSERT_TRUE(global.allow_cast<int>());
ASSERT_TRUE(local.allow_cast<int>());
ASSERT_EQ(global.cast<int>(), value.get());
ASSERT_EQ(local.cast<int>(), value.get_mul());
}
TEST_F(MetaContext, MetaDtor) {
auto global = entt::resolve<clazz>().construct();
auto local = entt::resolve<clazz>(context).construct();
ASSERT_EQ(clazz::bucket, bucket_value);
global.reset();
ASSERT_EQ(clazz::bucket, bucket_value);
local.reset();
ASSERT_NE(clazz::bucket, bucket_value);
}
TEST_F(MetaContext, MetaProp) {
using namespace entt::literals;
const auto global = entt::resolve<clazz>().prop("prop"_hs);
const auto local = entt::resolve<clazz>(context).prop("prop"_hs);
ASSERT_TRUE(global);
ASSERT_TRUE(local);
ASSERT_EQ(global.value().type(), entt::resolve<int>());
ASSERT_EQ(local.value().type(), entt::resolve<int>(context));
ASSERT_EQ(global.value().cast<int>(), prop_value);
ASSERT_EQ(local.value().cast<int>(), prop_value);
ASSERT_EQ(global.value().type().data("marker"_hs).get({}).cast<int>(), global_marker);
ASSERT_EQ(local.value().type().data("marker"_hs).get({}).cast<int>(), local_marker);
}
TEST_F(MetaContext, MetaTemplate) {
// TODO
}
TEST_F(MetaContext, MetaPointer) {
// TODO
}
TEST_F(MetaContext, MetaAssociativeContainer) {
// TODO
}
TEST_F(MetaContext, MetaSequenceContainer) {
// TODO
}
TEST_F(MetaContext, MetaAny) {
// TODO
}
TEST_F(MetaContext, MetaHandle) {
// TODO
}
TEST_F(MetaContext, ForwardAsMeta) {
// TODO
}
TEST_F(MetaContext, ContextMix) {
// TODO
}
<|endoftext|> |
<commit_before>/*
* Author(s):
* - Nicolas Cornu <ncornu@aldebaran-robotics.com>
*
* Copyright (C) 2012-2013 Aldebaran Robotics
*/
#include "dataperfsuite_p.hpp"
#include <iostream>
#include <iomanip>
namespace qi
{
DataPerfSuite::DataPerfSuite(const std::string& projectName, const std::string& executableName, OutputData outputData, const std::string& filename)
:_p(new DataPerfSuitePrivate)
{
_p->projectName = projectName;
_p->executableName = executableName;
_p->outputData = outputData;
if (!filename.empty() && outputData != OutputData_None) {
_p->out.open(filename.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!(_p->out.is_open())) {
std::cerr << "Can't open file " << filename << "." << std::endl
<< "Using stdout instead." << std::endl;
}
}
if (_p->out.is_open()) {
_p->out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" << std::endl
<< "<perf_results project=\"" << projectName << "\" executable=\""
<< executableName << "\">" << std::endl;
}
std::cout << projectName << ": " << executableName << std::endl
<< "Name: bytes, msg/s, MB/s, period (us), cpu/total" << std::endl;
}
DataPerfSuite::~DataPerfSuite()
{
close();
delete _p;
}
DataPerfSuite& DataPerfSuite::operator<<(const DataPerf& data) {
if (_p->out.is_open()) {
std::string resultType;
float resultValue;
switch (_p->outputData)
{
case OutputData_Cpu:
resultType = "Cpu";
resultValue = data.getCpu();
break;
case OutputData_Period:
resultType = "Period";
resultValue = data.getPeriod();
break;
case OutputData_MsgPerSecond:
resultType = "MsgPerSecond";
resultValue = data.getMsgPerSecond();
break;
case OutputData_MsgMBPerSecond:
default:
resultType = "MsgMBPerSecond";
resultValue = data.getMegaBytePerSecond();
break;
}
_p->out << "\t<perf_result "
<< "benchmark=\"" << data.getBenchmarkName() << "_" << resultType << "\" "
<< "result_value=\"" << std::fixed << std::setprecision(6) << resultValue << "\" "
<< "result_type=\"" << resultType << "\" "
<< "test_name=\"" << data.getBenchmarkName() << "\" ";
if (data.getVariable() != "")
_p->out << "result_variable=\"" << data.getVariable() << "\" ";
else if (data.getMsgSize() != 0)
_p->out << "result_variable=\"" << data.getMsgSize() << "\" ";
_p->out << "/>" << std::endl;
}
std::cout << data.getBenchmarkName() << "-" << data.getVariable() << ": ";
if (data.getMsgSize() > 0) {
std::cout
<< std::fixed << std::setprecision(2) << data.getMsgSize() << " b, "
<< data.getMsgPerSecond() << " msg/s, "
<< std::setprecision(12) << data.getMegaBytePerSecond() << " MB/s, "
<< std::setprecision(0) << data.getPeriod() << " us, "
<< std::setprecision(1) << data.getCpu() << " %"
<< std::endl;
} else {
std::cout
<< std::setprecision(12) << data.getMsgPerSecond() << " msg/s, "
<< data.getPeriod() << " us, "
<< data.getCpu() << " %"
<< std::endl;
}
return *this;
}
void DataPerfSuite::flush()
{
if (_p->out.is_open())
_p->out.flush();
else
std::cout.flush();
}
void DataPerfSuite::close()
{
if (_p->out.is_open()) {
_p->out << "</perf_results>" << std::endl;
}
flush();
if (_p->out.is_open())
_p->out.close();
}
}
<commit_msg>Fix some build warnings<commit_after>/*
* Author(s):
* - Nicolas Cornu <ncornu@aldebaran-robotics.com>
*
* Copyright (C) 2012-2013 Aldebaran Robotics
*/
#include "dataperfsuite_p.hpp"
#include <iostream>
#include <iomanip>
namespace qi
{
DataPerfSuite::DataPerfSuite(const std::string& projectName, const std::string& executableName, OutputData outputData, const std::string& filename)
:_p(new DataPerfSuitePrivate)
{
_p->projectName = projectName;
_p->executableName = executableName;
_p->outputData = outputData;
if (!filename.empty() && outputData != OutputData_None) {
_p->out.open(filename.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!(_p->out.is_open())) {
std::cerr << "Can't open file " << filename << "." << std::endl
<< "Using stdout instead." << std::endl;
}
}
if (_p->out.is_open()) {
_p->out << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" << std::endl
<< "<perf_results project=\"" << projectName << "\" executable=\""
<< executableName << "\">" << std::endl;
}
std::cout << projectName << ": " << executableName << std::endl
<< "Name: bytes, msg/s, MB/s, period (us), cpu/total" << std::endl;
}
DataPerfSuite::~DataPerfSuite()
{
close();
delete _p;
}
DataPerfSuite& DataPerfSuite::operator<<(const DataPerf& data) {
if (_p->out.is_open()) {
std::string resultType;
float resultValue;
switch (_p->outputData)
{
case OutputData_Cpu:
resultType = "Cpu";
resultValue = static_cast<float>(data.getCpu());
break;
case OutputData_Period:
resultType = "Period";
resultValue = static_cast<float>(data.getPeriod());
break;
case OutputData_MsgPerSecond:
resultType = "MsgPerSecond";
resultValue = static_cast<float>(data.getMsgPerSecond());
break;
case OutputData_MsgMBPerSecond:
default:
resultType = "MsgMBPerSecond";
resultValue = static_cast<float>(data.getMegaBytePerSecond());
break;
}
_p->out << "\t<perf_result "
<< "benchmark=\"" << data.getBenchmarkName() << "_" << resultType << "\" "
<< "result_value=\"" << std::fixed << std::setprecision(6) << resultValue << "\" "
<< "result_type=\"" << resultType << "\" "
<< "test_name=\"" << data.getBenchmarkName() << "\" ";
if (data.getVariable() != "")
_p->out << "result_variable=\"" << data.getVariable() << "\" ";
else if (data.getMsgSize() != 0)
_p->out << "result_variable=\"" << data.getMsgSize() << "\" ";
_p->out << "/>" << std::endl;
}
std::cout << data.getBenchmarkName() << "-" << data.getVariable() << ": ";
if (data.getMsgSize() > 0) {
std::cout
<< std::fixed << std::setprecision(2) << data.getMsgSize() << " b, "
<< data.getMsgPerSecond() << " msg/s, "
<< std::setprecision(12) << data.getMegaBytePerSecond() << " MB/s, "
<< std::setprecision(0) << data.getPeriod() << " us, "
<< std::setprecision(1) << data.getCpu() << " %"
<< std::endl;
} else {
std::cout
<< std::setprecision(12) << data.getMsgPerSecond() << " msg/s, "
<< data.getPeriod() << " us, "
<< data.getCpu() << " %"
<< std::endl;
}
return *this;
}
void DataPerfSuite::flush()
{
if (_p->out.is_open())
_p->out.flush();
else
std::cout.flush();
}
void DataPerfSuite::close()
{
if (_p->out.is_open()) {
_p->out << "</perf_results>" << std::endl;
}
flush();
if (_p->out.is_open())
_p->out.close();
}
}
<|endoftext|> |
<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "distbench_utils.h"
#include "protocol_driver_allocator.h"
#include "gtest/gtest.h"
#include "gtest_utils.h"
#include "benchmark/benchmark.h"
#include "glog/logging.h"
namespace distbench {
class ProtocolDriverTest
: public testing::TestWithParam<ProtocolDriverOptions> {
};
TEST_P(ProtocolDriverTest, ctor) {
auto pd = AllocateProtocolDriver(GetParam()).value();
}
TEST_P(ProtocolDriverTest, initialize) {
auto pd = AllocateProtocolDriver(GetParam()).value();
pd->SetNumPeers(1);
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetHandler([](ServerRpcState *s) {
ADD_FAILURE() << "should not get here";
});
}
TEST_P(ProtocolDriverTest, get_addr) {
auto pd = AllocateProtocolDriver(GetParam()).value();
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_EQ(server_rpc_count, 0);
}
TEST_P(ProtocolDriverTest, get_set_addr) {
auto pd = AllocateProtocolDriver(GetParam()).value();
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_OK(pd->HandleConnect(addr, 0));
ASSERT_EQ(server_rpc_count, 0);
}
TEST_P(ProtocolDriverTest, invoke) {
auto pd = AllocateProtocolDriver(GetParam()).value();
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->send_response();
});
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_OK(pd->HandleConnect(addr, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state[10];
for (int i = 0; i < 10; ++i) {
pd->InitiateRpc(0, &rpc_state[i], [&]() { ++client_rpc_count; });
}
pd->ShutdownClient();
EXPECT_EQ(server_rpc_count, 10);
EXPECT_EQ(client_rpc_count, 10);
}
TEST_P(ProtocolDriverTest, self_echo) {
auto pd = AllocateProtocolDriver(GetParam()).value();
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->response.set_payload(s->request->payload());
s->send_response();
});
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_OK(pd->HandleConnect(addr, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state;
rpc_state.request.set_payload("ping!");
pd->InitiateRpc(0, &rpc_state, [&]() {
++client_rpc_count;
EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
EXPECT_EQ(rpc_state.response.payload(), "ping!");
});
pd->ShutdownClient();
EXPECT_EQ(server_rpc_count, 1);
EXPECT_EQ(client_rpc_count, 1);
}
TEST_P(ProtocolDriverTest, echo) {
auto pd1 = AllocateProtocolDriver(GetParam()).value();
auto pd2 = AllocateProtocolDriver(GetParam()).value();
std::atomic<int> server_rpc_count = 0;
int port1 = 0;
ASSERT_OK(pd2->Initialize(ProtocolDriverOptions(), &port1));
pd2->SetNumPeers(1);
pd2->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->response.set_payload(s->request->payload());
s->send_response();
});
int port2 = 0;
ASSERT_OK(pd1->Initialize(ProtocolDriverOptions(), &port2));
pd1->SetNumPeers(1);
pd1->SetHandler([&](ServerRpcState *s) {
ADD_FAILURE() << "should not get here";
});
std::string addr1 = pd1->HandlePreConnect("", 0).value();
std::string addr2 = pd2->HandlePreConnect("", 0).value();
ASSERT_OK(pd1->HandleConnect(addr2, 0));
ASSERT_OK(pd2->HandleConnect(addr1, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state;
rpc_state.request.set_payload("ping!");
pd1->InitiateRpc(0, &rpc_state, [&]() {
++client_rpc_count;
EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
EXPECT_EQ(rpc_state.response.payload(), "ping!");
});
pd1->ShutdownClient();
EXPECT_EQ(server_rpc_count, 1);
EXPECT_EQ(client_rpc_count, 1);
}
void Echo(benchmark::State &state, ProtocolDriverOptions opts) {
auto pd1 = AllocateProtocolDriver(opts).value();
auto pd2 = AllocateProtocolDriver(opts).value();
std::atomic<int> server_rpc_count = 0;
int port1 = 0;
ASSERT_OK(pd2->Initialize(ProtocolDriverOptions(), &port1));
pd2->SetNumPeers(1);
pd2->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->response.set_payload(s->request->payload());
s->send_response();
});
int port2 = 0;
ASSERT_OK(pd1->Initialize(ProtocolDriverOptions(), &port2));
pd1->SetNumPeers(1);
pd1->SetHandler([&](ServerRpcState *s) {
ADD_FAILURE() << "should not get here";
});
std::string addr1 = pd1->HandlePreConnect("", 0).value();
std::string addr2 = pd2->HandlePreConnect("", 0).value();
ASSERT_OK(pd1->HandleConnect(addr2, 0));
ASSERT_OK(pd2->HandleConnect(addr1, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state;
rpc_state.request.set_payload("ping!");
for (auto s : state) {
pd1->InitiateRpc(0, &rpc_state, [&]() {
++client_rpc_count;
EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
EXPECT_EQ(rpc_state.response.payload(), "ping!");
});
pd1->ShutdownClient();
}
}
ProtocolDriverOptions GrpcOptions() {
ProtocolDriverOptions ret;
ret.set_protocol_name("grpc");
return ret;
}
ProtocolDriverOptions GrpcCallbackOptions() {
ProtocolDriverOptions ret;
ret.set_protocol_name("grpc_async_callback");
return ret;
}
void BM_GrpcEcho(benchmark::State &state) {
Echo(state, GrpcOptions());
}
void BM_GrpcCallbackEcho(benchmark::State &state) {
Echo(state, GrpcCallbackOptions());
}
BENCHMARK(BM_GrpcEcho);
BENCHMARK(BM_GrpcCallbackEcho);
INSTANTIATE_TEST_SUITE_P(
ProtocolDriverTests, ProtocolDriverTest,
testing::Values(GrpcOptions(), GrpcCallbackOptions()));
} // namespace distbench
<commit_msg>Fix unit tests. Don't call SetNumPeers before Initialize.<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "distbench_utils.h"
#include "protocol_driver_allocator.h"
#include "gtest/gtest.h"
#include "gtest_utils.h"
#include "benchmark/benchmark.h"
#include "glog/logging.h"
namespace distbench {
class ProtocolDriverTest
: public testing::TestWithParam<ProtocolDriverOptions> {
};
TEST_P(ProtocolDriverTest, ctor) {
auto pd = AllocateProtocolDriver(GetParam()).value();
}
TEST_P(ProtocolDriverTest, initialize) {
auto pd = AllocateProtocolDriver(GetParam()).value();
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetNumPeers(1);
pd->SetHandler([](ServerRpcState *s) {
ADD_FAILURE() << "should not get here";
});
}
TEST_P(ProtocolDriverTest, get_addr) {
auto pd = AllocateProtocolDriver(GetParam()).value();
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_EQ(server_rpc_count, 0);
}
TEST_P(ProtocolDriverTest, get_set_addr) {
auto pd = AllocateProtocolDriver(GetParam()).value();
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_OK(pd->HandleConnect(addr, 0));
ASSERT_EQ(server_rpc_count, 0);
}
TEST_P(ProtocolDriverTest, invoke) {
auto pd = AllocateProtocolDriver(GetParam()).value();
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
pd->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->send_response();
});
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_OK(pd->HandleConnect(addr, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state[10];
for (int i = 0; i < 10; ++i) {
pd->InitiateRpc(0, &rpc_state[i], [&]() { ++client_rpc_count; });
}
pd->ShutdownClient();
EXPECT_EQ(server_rpc_count, 10);
EXPECT_EQ(client_rpc_count, 10);
}
TEST_P(ProtocolDriverTest, self_echo) {
auto pd = AllocateProtocolDriver(GetParam()).value();
int port = 0;
ASSERT_OK(pd->Initialize(ProtocolDriverOptions(), &port));
pd->SetNumPeers(1);
std::atomic<int> server_rpc_count = 0;
pd->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->response.set_payload(s->request->payload());
s->send_response();
});
std::string addr = pd->HandlePreConnect("", 0).value();
ASSERT_OK(pd->HandleConnect(addr, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state;
rpc_state.request.set_payload("ping!");
pd->InitiateRpc(0, &rpc_state, [&]() {
++client_rpc_count;
EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
EXPECT_EQ(rpc_state.response.payload(), "ping!");
});
pd->ShutdownClient();
EXPECT_EQ(server_rpc_count, 1);
EXPECT_EQ(client_rpc_count, 1);
}
TEST_P(ProtocolDriverTest, echo) {
auto pd1 = AllocateProtocolDriver(GetParam()).value();
auto pd2 = AllocateProtocolDriver(GetParam()).value();
std::atomic<int> server_rpc_count = 0;
int port1 = 0;
ASSERT_OK(pd2->Initialize(ProtocolDriverOptions(), &port1));
pd2->SetNumPeers(1);
pd2->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->response.set_payload(s->request->payload());
s->send_response();
});
int port2 = 0;
ASSERT_OK(pd1->Initialize(ProtocolDriverOptions(), &port2));
pd1->SetNumPeers(1);
pd1->SetHandler([&](ServerRpcState *s) {
ADD_FAILURE() << "should not get here";
});
std::string addr1 = pd1->HandlePreConnect("", 0).value();
std::string addr2 = pd2->HandlePreConnect("", 0).value();
ASSERT_OK(pd1->HandleConnect(addr2, 0));
ASSERT_OK(pd2->HandleConnect(addr1, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state;
rpc_state.request.set_payload("ping!");
pd1->InitiateRpc(0, &rpc_state, [&]() {
++client_rpc_count;
EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
EXPECT_EQ(rpc_state.response.payload(), "ping!");
});
pd1->ShutdownClient();
EXPECT_EQ(server_rpc_count, 1);
EXPECT_EQ(client_rpc_count, 1);
}
void Echo(benchmark::State &state, ProtocolDriverOptions opts) {
auto pd1 = AllocateProtocolDriver(opts).value();
auto pd2 = AllocateProtocolDriver(opts).value();
std::atomic<int> server_rpc_count = 0;
int port1 = 0;
ASSERT_OK(pd2->Initialize(ProtocolDriverOptions(), &port1));
pd2->SetNumPeers(1);
pd2->SetHandler([&](ServerRpcState *s) {
++server_rpc_count;
s->response.set_payload(s->request->payload());
s->send_response();
});
int port2 = 0;
ASSERT_OK(pd1->Initialize(ProtocolDriverOptions(), &port2));
pd1->SetNumPeers(1);
pd1->SetHandler([&](ServerRpcState *s) {
ADD_FAILURE() << "should not get here";
});
std::string addr1 = pd1->HandlePreConnect("", 0).value();
std::string addr2 = pd2->HandlePreConnect("", 0).value();
ASSERT_OK(pd1->HandleConnect(addr2, 0));
ASSERT_OK(pd2->HandleConnect(addr1, 0));
std::atomic<int> client_rpc_count = 0;
ClientRpcState rpc_state;
rpc_state.request.set_payload("ping!");
for (auto s : state) {
pd1->InitiateRpc(0, &rpc_state, [&]() {
++client_rpc_count;
EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());
EXPECT_EQ(rpc_state.response.payload(), "ping!");
});
pd1->ShutdownClient();
}
}
ProtocolDriverOptions GrpcOptions() {
ProtocolDriverOptions ret;
ret.set_protocol_name("grpc");
return ret;
}
ProtocolDriverOptions GrpcCallbackOptions() {
ProtocolDriverOptions ret;
ret.set_protocol_name("grpc_async_callback");
return ret;
}
void BM_GrpcEcho(benchmark::State &state) {
Echo(state, GrpcOptions());
}
void BM_GrpcCallbackEcho(benchmark::State &state) {
Echo(state, GrpcCallbackOptions());
}
BENCHMARK(BM_GrpcEcho);
BENCHMARK(BM_GrpcCallbackEcho);
INSTANTIATE_TEST_SUITE_P(
ProtocolDriverTests, ProtocolDriverTest,
testing::Values(GrpcOptions(), GrpcCallbackOptions()));
} // namespace distbench
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include <ophidian/geometry/Distance.h>
using namespace ophidian::geometry;
TEST_CASE("Geometry: manhattan distance between two points", "[geometry][distance]") {
Point<double> point1(5, 10);
Point<double> point2(3, 7);
double distance = ManhattanDistance(point1, point2);
double expected_distance = 5;
REQUIRE(distance == Approx(expected_distance));
}
TEST_CASE("Geometry: euclidean distance between two points", "[geometry][distance]") {
Point<double> point1(5, 10);
Point<double> point2(3, 7);
double distance = EuclideanDistance(point1, point2);
double expected_distance = std::sqrt(13);
REQUIRE(distance == Approx(expected_distance));
}
<commit_msg>refactor distance test<commit_after>#include <catch.hpp>
#include <ophidian/geometry/Distance.h>
#include <ophidian/util/Units.h>
using namespace ophidian::geometry;
template <typename T>
void test_manhattan_distance(T&& x1, T&& y1, T&& x2, T&& y2, T&& result)
{
auto point_1 = Point<T>(x1, y1);
auto point_2 = Point<T>(x2, y2);
CHECK(ManhattanDistance(point_1, point_2) == result);
}
TEST_CASE("Geometry: manhattan distance between two points", "[geometry][distance]")
{
SECTION("Test distance from points of double")
{
test_manhattan_distance(0.0d, 0.0d, 0.0d, 0.0d, 0.0d);
test_manhattan_distance(5.0d, 10.0d, 3.0d, 7.0d, 5.0d);
test_manhattan_distance(-5.0d, -10.0d, -3.0d, -7.0d, 5.0d);
}
SECTION("Test distance from points of database_unit_t")
{
using dbu = ophidian::util::database_unit_t;
test_manhattan_distance(dbu{0}, dbu{0}, dbu{0}, dbu{0}, dbu{0});
test_manhattan_distance(dbu{5}, dbu{10}, dbu{3}, dbu{7}, dbu{5});
test_manhattan_distance(dbu{-5}, dbu{-10}, dbu{-3}, dbu{-7}, dbu{5});
}
}
template <typename T>
void test_euclidean_distance(T&& x1, T&& y1, T&& x2, T&& y2, T&& result)
{
auto point_1 = Point<T>(x1, y1);
auto point_2 = Point<T>(x2, y2);
CHECK(EuclideanDistance(point_1, point_2) == result);
}
TEST_CASE("Geometry: euclidean distance between two points", "[geometry][distance]")
{
SECTION("Test distance from points of double")
{
test_euclidean_distance(0.0d, 0.0d, 0.0d, 0.0d, 0.0d);
test_euclidean_distance(5.0d, 10.0d, 3.0d, 7.0d, std::sqrt(13));
test_euclidean_distance(-5.0d, -10.0d, -3.0d, -7.0d, std::sqrt(13));
}
}
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef ENABLE_INTEGRATION_TESTS
# include <cppunit/extensions/TestFactoryRegistry.h>
# include <cppunit/extensions/HelperMacros.h>
#include "base/fscapi.h"
#include "base/globalsdef.h"
#include "base/messages.h"
#include "base/Log.h"
#include "base/util/StringBuffer.h"
#include "base/adapter/PlatformAdapter.h"
#include "client/DMTClientConfig.h"
#include "client/SyncClient.h"
#include "LOSyncSource.h"
#include "LOItemTest.h"
#include "spds/SyncManager.h"
#include "testUtils.h"
#include "client/FileSyncSource.h"
USE_NAMESPACE
LOItemTest::LOItemTest() {
LOG.setLogName("LOItemTest.log");
LOG.reset();
}
bool isSuccessful(const int status) {
if (status == 201 || status == 200)
return true;
else
return false;
}
int getOperationSuccessful(SyncSourceReport *ssr, const char* target, const char* command) {
ArrayList* list = ssr->getList(target, command);
ItemReport* e;
// Scan for successful codes
int good = 0;
if (list->size() > 0) {
e = (ItemReport*)list->front();
if ( isSuccessful(e->getStatus()) ) {
good++;
}
for (int i=1; i<list->size(); i++) {
e = (ItemReport*)list->next();
if ( isSuccessful(e->getStatus())) {
good++;
}
}
}
return good;
}
int getSuccessfullyAdded(SyncSourceReport *ssr) {
return getOperationSuccessful(ssr, SERVER, COMMAND_ADD);
}
int getSuccessfullyReplaced(SyncSourceReport *ssr) {
return getOperationSuccessful(ssr, SERVER, COMMAND_REPLACE);
}
int getSuccessfullyDeleted(SyncSourceReport *ssr) {
return getOperationSuccessful(ssr, SERVER, COMMAND_DELETE);
}
DMTClientConfig* LOItemTest::resetItemOnServer(const char* sourceURI) {
ArrayList asources;
StringBuffer contact("contact");
asources.add(contact);
DMTClientConfig* config = getNewDMTClientConfig("funambol_LOItem", true, &asources);
CPPUNIT_ASSERT(config);
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("refresh-from-client");
conf->setURI(sourceURI);
config->getAccessConfig().setMaxMsgSize(5500);
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = 0;
ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
config->save();
delete scontact;
return config;
}
void LOItemTest::testLOItem() {
DMTClientConfig* config = resetItemOnServer("card");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseAdd(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemDES() {
DMTClientConfig* config = resetItemOnServer("scard");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setEncoding("b64");
conf->setEncryption("des");
conf->setType("text/x-s4j-sifc");
conf->setURI("scard");
conf->setVersion("1.0");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSif(true);
scontact->setUseAdd(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemWithItemEncoding() {
DMTClientConfig* config = resetItemOnServer("card");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseAdd(true);
scontact->setUseDataEncoding(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemb64() {
DMTClientConfig* config = resetItemOnServer("scard");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setEncoding("b64");
conf->setType("text/x-s4j-sifc");
conf->setURI("scard");
conf->setVersion("1.0");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSif(true);
scontact->setUseAdd(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
config->save();
}
void LOItemTest::testLOItemReplaceb64() {
testLOItemb64();
initAdapter("funambol_LOItem");
DMTClientConfig* config = new DMTClientConfig();
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setEncoding("b64");
conf->setType("text/x-s4j-sifc");
conf->setURI("scard");
conf->setVersion("1.0");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSif(true);
scontact->setUseAdd(false);
scontact->setUseUpdate(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemSlowSync() {
DMTClientConfig* config = resetItemOnServer("card");
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("slow");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSlowSync(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int replaced = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(2, replaced);
}
void LOItemTest::testLOItemSlowSyncb64() {
DMTClientConfig* config = resetItemOnServer("scard");
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("slow");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSlowSync(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int replaced = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(2, replaced);
}
void LOItemTest::testFileSyncSource() {
StringBuffer test_dir("./FileToSync");
StringBuffer test_name("LOItemTest");
// empty the test dir if exists
removeFileInDir(test_dir.c_str());
ArrayList asources;
StringBuffer briefcase("briefcase");
asources.add(briefcase);
DMTClientConfig* config = getNewDMTClientConfig("funambol_LOItem", true, &asources);
CPPUNIT_ASSERT(config);
config->getAccessConfig().setMaxMsgSize(5500);
SyncSourceConfig *conf = config->getSyncSourceConfig(briefcase.c_str());
conf->setSync("refresh-from-client");
conf->setURI(briefcase.c_str());
// put 4 files inside the test dir
createFolder(test_dir.c_str());
for (int i = 0; i < 4; i++) {
StringBuffer s; s.sprintf("sif%i.txt", i);
StringBuffer& path = getTestFileFullPath(test_name.c_str(), s.c_str());
char* content = loadTestFile(test_name.c_str(), s.c_str(), true);
struct stat st;
stat(path.c_str(), &st);
int size = st.st_size;
StringBuffer name(test_dir);
name.append("/");
name.append(s);
bool written = saveFile(name.c_str(), content, size, true) ;
delete [] content;
}
FileSyncSource* fsss = new FileSyncSource(TEXT("briefcase"), conf, test_dir);
SyncSource* sources[2];
sources[0] = fsss;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = fsss->getReport();
int replaced = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(4, replaced);
config->save();
delete fsss;
// remove 2 items and add a new one
removeFileInDir(test_dir.c_str(), "sif0.txt");
removeFileInDir(test_dir.c_str(), "sif1.txt");
StringBuffer& path = getTestFileFullPath(test_name.c_str(), "vcard0.txt");
char* content = loadTestFile(test_name.c_str(), "vcard0.txt", true);
struct stat st;
stat(path.c_str(), &st);
int size = st.st_size;
StringBuffer name(test_dir);
name.append("/");
name.append("vcard0.txt");
bool written = saveFile(name.c_str(), content, size, true) ;
delete [] content;
config->read();
conf = config->getSyncSourceConfig(briefcase.c_str());
conf->setSync("two-way");
fsss = new FileSyncSource(TEXT("briefcase"), conf, test_dir);
sources[0] = fsss;
sources[1] = NULL;
ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
ssr = fsss->getReport();
int added = getSuccessfullyAdded(ssr);
int deleted = getSuccessfullyDeleted(ssr);
CPPUNIT_ASSERT_EQUAL(1, added);
CPPUNIT_ASSERT_EQUAL(2, deleted);
}
#endif // ENABLE_INTEGRATION_TESTS
<commit_msg>removed reference type in variable assign<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef ENABLE_INTEGRATION_TESTS
# include <cppunit/extensions/TestFactoryRegistry.h>
# include <cppunit/extensions/HelperMacros.h>
#include "base/fscapi.h"
#include "base/globalsdef.h"
#include "base/messages.h"
#include "base/Log.h"
#include "base/util/StringBuffer.h"
#include "base/adapter/PlatformAdapter.h"
#include "client/DMTClientConfig.h"
#include "client/SyncClient.h"
#include "LOSyncSource.h"
#include "LOItemTest.h"
#include "spds/SyncManager.h"
#include "testUtils.h"
#include "client/FileSyncSource.h"
USE_NAMESPACE
LOItemTest::LOItemTest() {
LOG.setLogName("LOItemTest.log");
LOG.reset();
}
bool isSuccessful(const int status) {
if (status == 201 || status == 200)
return true;
else
return false;
}
int getOperationSuccessful(SyncSourceReport *ssr, const char* target, const char* command) {
ArrayList* list = ssr->getList(target, command);
ItemReport* e;
// Scan for successful codes
int good = 0;
if (list->size() > 0) {
e = (ItemReport*)list->front();
if ( isSuccessful(e->getStatus()) ) {
good++;
}
for (int i=1; i<list->size(); i++) {
e = (ItemReport*)list->next();
if ( isSuccessful(e->getStatus())) {
good++;
}
}
}
return good;
}
int getSuccessfullyAdded(SyncSourceReport *ssr) {
return getOperationSuccessful(ssr, SERVER, COMMAND_ADD);
}
int getSuccessfullyReplaced(SyncSourceReport *ssr) {
return getOperationSuccessful(ssr, SERVER, COMMAND_REPLACE);
}
int getSuccessfullyDeleted(SyncSourceReport *ssr) {
return getOperationSuccessful(ssr, SERVER, COMMAND_DELETE);
}
DMTClientConfig* LOItemTest::resetItemOnServer(const char* sourceURI) {
ArrayList asources;
StringBuffer contact("contact");
asources.add(contact);
DMTClientConfig* config = getNewDMTClientConfig("funambol_LOItem", true, &asources);
CPPUNIT_ASSERT(config);
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("refresh-from-client");
conf->setURI(sourceURI);
config->getAccessConfig().setMaxMsgSize(5500);
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = 0;
ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
config->save();
delete scontact;
return config;
}
void LOItemTest::testLOItem() {
DMTClientConfig* config = resetItemOnServer("card");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseAdd(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemDES() {
DMTClientConfig* config = resetItemOnServer("scard");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setEncoding("b64");
conf->setEncryption("des");
conf->setType("text/x-s4j-sifc");
conf->setURI("scard");
conf->setVersion("1.0");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSif(true);
scontact->setUseAdd(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemWithItemEncoding() {
DMTClientConfig* config = resetItemOnServer("card");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseAdd(true);
scontact->setUseDataEncoding(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemb64() {
DMTClientConfig* config = resetItemOnServer("scard");
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setEncoding("b64");
conf->setType("text/x-s4j-sifc");
conf->setURI("scard");
conf->setVersion("1.0");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSif(true);
scontact->setUseAdd(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyAdded(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
config->save();
}
void LOItemTest::testLOItemReplaceb64() {
testLOItemb64();
initAdapter("funambol_LOItem");
DMTClientConfig* config = new DMTClientConfig();
CPPUNIT_ASSERT(config);
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setEncoding("b64");
conf->setType("text/x-s4j-sifc");
conf->setURI("scard");
conf->setVersion("1.0");
conf->setSync("two-way");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSif(true);
scontact->setUseAdd(false);
scontact->setUseUpdate(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int added = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(2, added);
}
void LOItemTest::testLOItemSlowSync() {
DMTClientConfig* config = resetItemOnServer("card");
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("slow");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSlowSync(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int replaced = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(2, replaced);
}
void LOItemTest::testLOItemSlowSyncb64() {
DMTClientConfig* config = resetItemOnServer("scard");
config->read();
SyncSourceConfig *conf = config->getSyncSourceConfig("contact");
conf->setSync("slow");
LOSyncSource* scontact = new LOSyncSource(TEXT("contact"), conf);
scontact->setUseSlowSync(true);
SyncSource* sources[2];
sources[0] = scontact;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = scontact->getReport();
int replaced = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(2, replaced);
}
void LOItemTest::testFileSyncSource() {
StringBuffer test_dir("./FileToSync");
StringBuffer test_name("LOItemTest");
// empty the test dir if exists
removeFileInDir(test_dir.c_str());
ArrayList asources;
StringBuffer briefcase("briefcase");
asources.add(briefcase);
DMTClientConfig* config = getNewDMTClientConfig("funambol_LOItem", true, &asources);
CPPUNIT_ASSERT(config);
config->getAccessConfig().setMaxMsgSize(5500);
SyncSourceConfig *conf = config->getSyncSourceConfig(briefcase.c_str());
conf->setSync("refresh-from-client");
conf->setURI(briefcase.c_str());
// put 4 files inside the test dir
createFolder(test_dir.c_str());
for (int i = 0; i < 4; i++) {
StringBuffer s; s.sprintf("sif%i.txt", i);
StringBuffer path = getTestFileFullPath(test_name.c_str(), s.c_str());
char* content = loadTestFile(test_name.c_str(), s.c_str(), true);
struct stat st;
stat(path.c_str(), &st);
int size = st.st_size;
StringBuffer name(test_dir);
name.append("/");
name.append(s);
bool written = saveFile(name.c_str(), content, size, true) ;
delete [] content;
}
FileSyncSource* fsss = new FileSyncSource(TEXT("briefcase"), conf, test_dir);
SyncSource* sources[2];
sources[0] = fsss;
sources[1] = NULL;
SyncClient client;
int ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
SyncSourceReport *ssr = fsss->getReport();
int replaced = getSuccessfullyReplaced(ssr);
CPPUNIT_ASSERT_EQUAL(4, replaced);
config->save();
delete fsss;
// remove 2 items and add a new one
removeFileInDir(test_dir.c_str(), "sif0.txt");
removeFileInDir(test_dir.c_str(), "sif1.txt");
StringBuffer path = getTestFileFullPath(test_name.c_str(), "vcard0.txt");
char* content = loadTestFile(test_name.c_str(), "vcard0.txt", true);
struct stat st;
stat(path.c_str(), &st);
int size = st.st_size;
StringBuffer name(test_dir);
name.append("/");
name.append("vcard0.txt");
bool written = saveFile(name.c_str(), content, size, true) ;
delete [] content;
config->read();
conf = config->getSyncSourceConfig(briefcase.c_str());
conf->setSync("two-way");
fsss = new FileSyncSource(TEXT("briefcase"), conf, test_dir);
sources[0] = fsss;
sources[1] = NULL;
ret = client.sync(*config, sources);
CPPUNIT_ASSERT(!ret);
ssr = fsss->getReport();
int added = getSuccessfullyAdded(ssr);
int deleted = getSuccessfullyDeleted(ssr);
CPPUNIT_ASSERT_EQUAL(1, added);
CPPUNIT_ASSERT_EQUAL(2, deleted);
}
#endif // ENABLE_INTEGRATION_TESTS
<|endoftext|> |
<commit_before>/*
* structs.h
*
* Created on: 28.01.2015
* Author: fnolden
*/
#include <assert.h>
#ifndef INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
#define INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
namespace search
{
struct Value{
float min;
float max;
int steps_max;
float step_width;
Value(){
init_range(0, 0, 1);
};
Value( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_range( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_min_max(float min, float max, int steps_max = 3){
assert(min <= max);
assert(steps_max > 0);
this->min = min;
this->max = max;
this->steps_max = steps_max;
if(steps_max != 1){
step_width = (max - min)/(steps_max-1); // First step = min, last step = max
}
else{
step_width = 0;
}
}
float at(int step){
assert(step < steps_max);
return min + (step_width*step);
}
std::string to_string(){
std::stringstream ss;
ss << "min: " << min << " max: " << max << " steps: " << steps_max << " step_width: " << step_width << "\n";
return ss.str();
}
};
struct Search_setup{
Value x;
Value y;
Value z;
Value roll;
Value pitch;
Value yaw;
std::string to_string(){
std::stringstream ss;
ss << "x: " << x.to_string();
ss << "y: " << y.to_string();
ss << "z: " << z.to_string();
ss << "roll: " << roll.to_string();
ss << "pitch: " << pitch.to_string();
ss << "yaw: " << yaw.to_string();
return ss.str();
}
};
struct Search_value{
Search_value(){
init(0, 0, 0, 0, 0, 0, 0);
}
Search_value(tf::Transform tf, long unsigned int result = 0){
init(tf, result);
}
Search_value( float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0){
init(x, y, z, roll, pitch, yaw, result);
}
void init(float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0)
{
this->x = x;
this->y = y;
this->z = z;
this->roll = roll;
this->pitch = pitch;
this->yaw = yaw;
this->result = result;
}
void init(tf::Transform tf, long unsigned int result = 0)
{
this->x = tf.getOrigin()[0];
this->y = tf.getOrigin()[1];
this->z = tf.getOrigin()[2];
double r,p,y;
tf.getBasis().getRPY(r, p, y);
this->roll = r;
this->pitch = p;
this->yaw = y;
this->result = result;
}
std::string to_string(){
std::stringstream ss;
ss << "x: " << x << " y: " << y <<" z: " << z;
ss << " roll: " << roll << " pitch: " << pitch << " yaw: " << yaw;
ss << " result: " << result << "\n";
return ss.str();
}
void get_transform(tf::Transform &tf){
tf.setOrigin( tf::Vector3( x, y, z ) );
tf::Quaternion q;
q.setRPY(roll, pitch, yaw );
tf.setRotation( q );
}
float x;
float y;
float z;
float roll;
float pitch;
float yaw;
long unsigned int result;
};
struct Window{
int window_size;
std::deque<cv::Mat> images;
std::deque<pcl::PointCloud<pcl::PointXYZI> > pointclouds;
void check(){
assert(images.size() == pointclouds.size());
if(size() > window_size){
pop_front();
}
}
size_t size(){
check();
return images.size();
}
void pop_front(){
images.pop_front();
pointclouds.pop_front();
check();
}
void push_back(cv::Mat image, pcl::PointCloud<pcl::PointXYZI> pointcloud){
images.push_back(image);
pointclouds.push_back(pointcloud);
check();
}
};
}
#endif /* INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_ */
<commit_msg>renamed struct, added struct for multi search results<commit_after>/*
* structs.h
*
* Created on: 28.01.2015
* Author: fnolden
*/
#include <assert.h>
#ifndef INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
#define INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_
namespace search
{
const std::string spacer = " \t";
struct Value_calculator{
float min;
float max;
int steps_max;
float step_width;
Value_calculator(){
init_range(0, 0, 1);
};
Value_calculator( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_range( float value, float range, int steps_max = 3){
init_min_max(value - range/2, value + range/2, steps_max);
}
void init_min_max(float min, float max, int steps_max = 3){
assert(min <= max);
assert(steps_max > 0);
this->min = min;
this->max = max;
this->steps_max = steps_max;
if(steps_max != 1){
step_width = (max - min)/(steps_max-1); // First step = min, last step = max
}
else{
step_width = 0;
}
}
float at(int step){
assert(step < steps_max);
return min + (step_width*step);
}
std::string to_string(){
std::stringstream ss;
ss << "min:" << spacer << min << spacer;
ss << "max:" << spacer << max << spacer;
ss << "steps:" << spacer << steps_max << spacer;
ss << "step_width:"<< spacer << step_width << spacer;
return ss.str();
}
};
struct Search_setup{
Value_calculator x;
Value_calculator y;
Value_calculator z;
Value_calculator roll;
Value_calculator pitch;
Value_calculator yaw;
Search_setup(){
init(0,0,0,0,0,0,0,1);
}
Search_setup(float x, float y, float z, float roll, float pitch, float yaw, float range, int steps){
init( x, y, z, roll, pitch, yaw, range, steps);
}
void init(float x, float y, float z, float roll, float pitch, float yaw, float range, int steps){
this->x.init_range(x, range, steps);
this->y.init_range(y, range, steps);
this->z.init_range(z, range, steps);
this->roll.init_range(roll, range, steps);
this->pitch.init_range(pitch, range, steps);
this->yaw.init_range(yaw, range, steps);
}
std::string to_string(){
std::stringstream ss;
ss << "x:" << spacer << x.to_string() << spacer;
ss << "y:" << spacer << y.to_string() << spacer;
ss << "z:" << spacer << z.to_string() << spacer;
ss << "roll:" << spacer << roll.to_string() << spacer;
ss << "pitch:" << spacer << pitch.to_string() << spacer;
ss << "yaw:" << spacer << yaw.to_string() << spacer;
return ss.str();
}
};
struct Search_value{
Search_value(){
init(0, 0, 0, 0, 0, 0, 0);
}
Search_value(tf::Transform tf, long unsigned int result = 0){
init(tf, result);
}
Search_value( float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0){
init(x, y, z, roll, pitch, yaw, result);
}
void init(float x, float y, float z, float roll, float pitch, float yaw, long unsigned int result = 0)
{
this->x = x;
this->y = y;
this->z = z;
this->roll = roll;
this->pitch = pitch;
this->yaw = yaw;
this->result = result;
}
void init(tf::Transform tf, long unsigned int result = 0)
{
this->x = tf.getOrigin()[0];
this->y = tf.getOrigin()[1];
this->z = tf.getOrigin()[2];
double r,p,y;
tf.getBasis().getRPY(r, p, y);
this->roll = r;
this->pitch = p;
this->yaw = y;
this->result = result;
}
std::string to_string(){
std::stringstream ss;
ss << "x:" << spacer << x << spacer;
ss << "y:" << spacer << y << spacer;
ss <<" z:" << spacer << z << spacer;
ss << "roll:" << spacer << roll << spacer;
ss << "pitch:" << spacer << pitch << spacer;
ss << "yaw:" << spacer << yaw << spacer;
ss << "result:" << spacer << result;
return ss.str();
}
void get_transform(tf::Transform &tf){
tf.setOrigin( tf::Vector3( x, y, z ) );
tf::Quaternion q;
q.setRPY(roll, pitch, yaw );
tf.setRotation( q );
}
float x;
float y;
float z;
float roll;
float pitch;
float yaw;
long unsigned int result;
};
struct Multi_search_result{
Search_value in;
Search_value best;
long unsigned int nr_total;
long unsigned int nr_worse;
Multi_search_result(){
init();
}
void init(Search_value in, Search_value best, long unsigned int nr_total, long unsigned int nr_worse){
this->nr_total = nr_total;
this->nr_worse = nr_worse;
this->in = in;
this->best = best;
}
void init(){
nr_total = 0;
nr_worse = 0;
Search_value empty;
empty.init(0,0,0,0,0,0,0);
in = empty;
best = empty;
}
float get_fc(){
if(nr_total > 0){
return (float)nr_worse/(float)nr_total;
}
return 0;
}
Search_value get_delta_best(){
Search_value delta = in;
delta.x-=best.x;
delta.y-=best.y;
delta.z-=best.z;
delta.roll-=best.roll;
delta.pitch-=best.pitch;
delta.yaw-=best.yaw;
delta.result-=best.result;
return delta;
}
std::string to_string(){
std::stringstream ss;
ss << "total:" << spacer << nr_total << spacer;
ss << "worse:" << spacer << nr_worse << spacer;
ss << "fc:" << spacer << get_fc() << spacer;
ss << "in:" <<spacer << in.to_string() << spacer;
ss << "out:" << spacer << best.to_string() << spacer;
ss << "delta:" << spacer << get_delta_best().to_string() << spacer;
return ss.str();
}
};
struct Window{
int window_size;
std::deque<cv::Mat> images;
std::deque<pcl::PointCloud<pcl::PointXYZI> > pointclouds;
void check(){
assert(images.size() == pointclouds.size());
if(size() > window_size){
pop_front();
}
}
size_t size(){
check();
return images.size();
}
void pop_front(){
images.pop_front();
pointclouds.pop_front();
check();
}
void push_back(cv::Mat image, pcl::PointCloud<pcl::PointXYZI> pointcloud){
images.push_back(image);
pointclouds.push_back(pointcloud);
check();
}
};
}
#endif /* INCLUDE_IMAGE_CLOUD_COMMON_CALIBRATION_STRUCTS_H_ */
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/kernel/terminate.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2018 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <kernel/hbdescriptor.H>
#include <kernel/hbterminatetypes.H>
#include <kernel/terminate.H>
#ifndef BOOTLOADER
#include <stdint.h>
#include <kernel/console.H>
#include <kernel/ipc.H>
#include <builtins.h>
#include <kernel/kernel_reasoncodes.H>
#endif // BOOTLOADER
extern "C" void p8_force_attn() NO_RETURN;
#ifndef BOOTLOADER
/* Instance of the TI Data Area */
HB_TI_DataArea kernel_TIDataArea;
/* Instance of the HB descriptor struct */
HB_Descriptor kernel_hbDescriptor =
{
&kernel_TIDataArea,
&KernelIpc::ipc_data_area,
0
};
#endif // BOOTLOADER
void terminateExecuteTI()
{
// Call the function that actually executes the TI code.
p8_force_attn();
}
#ifndef BOOTLOADER
void termWritePlid(uint16_t i_source, uint32_t plid)
{
kernel_TIDataArea.type = TI_WITH_PLID;
kernel_TIDataArea.source = i_source;
kernel_TIDataArea.plid = plid;
}
#endif // BOOTLOADER
void termWriteSRC(uint16_t i_source, uint16_t i_reasoncode,uint64_t i_failAddr,
uint32_t i_error_data)
{
// Update the TI structure with the type of TI, who called,
// and indicator flag for doing HB dump
// and extra error data (if applicable, otherwise 0)
kernel_TIDataArea.type = TI_WITH_SRC;
kernel_TIDataArea.source = i_source;
kernel_TIDataArea.hbDumpFlag = 1;
kernel_TIDataArea.error_data = i_error_data;
// Update TID data area with the SRC info we have avail
kernel_TIDataArea.src.ID = 0xBC;
kernel_TIDataArea.src.subsystem = 0x8A;
kernel_TIDataArea.src.reasoncode = i_reasoncode;
kernel_TIDataArea.src.moduleID = 0;
kernel_TIDataArea.src.iType = TI_WITH_SRC;
kernel_TIDataArea.src.iSource = i_source;
// Update User Data with address of fail location
kernel_TIDataArea.src.word6 = i_failAddr;
}
void termModifySRC(uint8_t i_moduleID, uint32_t i_word7, uint32_t i_word8)
{
// Update module ID
kernel_TIDataArea.src.moduleID = i_moduleID;
// Update User Data with anything supplied for word7 or word8
kernel_TIDataArea.src.word7 = i_word7;
kernel_TIDataArea.src.word8 = i_word8;
}
#ifndef BOOTLOADER
void termSetHbDump(void)
{
// Set indicator flag for doing HB dump
kernel_TIDataArea.hbDumpFlag = 1;
return;
}
#endif // BOOTLOADER
<commit_msg>Revert "Set HB Dump Flag in TI Data on any TI with SRC"<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/kernel/terminate.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2018 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <kernel/hbdescriptor.H>
#include <kernel/hbterminatetypes.H>
#include <kernel/terminate.H>
#ifndef BOOTLOADER
#include <stdint.h>
#include <kernel/console.H>
#include <kernel/ipc.H>
#include <builtins.h>
#include <kernel/kernel_reasoncodes.H>
#endif // BOOTLOADER
extern "C" void p8_force_attn() NO_RETURN;
#ifndef BOOTLOADER
/* Instance of the TI Data Area */
HB_TI_DataArea kernel_TIDataArea;
/* Instance of the HB descriptor struct */
HB_Descriptor kernel_hbDescriptor =
{
&kernel_TIDataArea,
&KernelIpc::ipc_data_area,
0
};
#endif // BOOTLOADER
void terminateExecuteTI()
{
// Call the function that actually executes the TI code.
p8_force_attn();
}
#ifndef BOOTLOADER
void termWritePlid(uint16_t i_source, uint32_t plid)
{
kernel_TIDataArea.type = TI_WITH_PLID;
kernel_TIDataArea.source = i_source;
kernel_TIDataArea.plid = plid;
}
#endif // BOOTLOADER
void termWriteSRC(uint16_t i_source, uint16_t i_reasoncode,uint64_t i_failAddr,
uint32_t i_error_data)
{
// Update the TI structure with the type of TI, who called,
// and extra error data (if applicable, otherwise 0)
kernel_TIDataArea.type = TI_WITH_SRC;
kernel_TIDataArea.source = i_source;
kernel_TIDataArea.error_data = i_error_data;
// Update TID data area with the SRC info we have avail
kernel_TIDataArea.src.ID = 0xBC;
kernel_TIDataArea.src.subsystem = 0x8A;
kernel_TIDataArea.src.reasoncode = i_reasoncode;
kernel_TIDataArea.src.moduleID = 0;
kernel_TIDataArea.src.iType = TI_WITH_SRC;
kernel_TIDataArea.src.iSource = i_source;
// Update User Data with address of fail location
kernel_TIDataArea.src.word6 = i_failAddr;
}
void termModifySRC(uint8_t i_moduleID, uint32_t i_word7, uint32_t i_word8)
{
// Update module ID
kernel_TIDataArea.src.moduleID = i_moduleID;
// Update User Data with anything supplied for word7 or word8
kernel_TIDataArea.src.word7 = i_word7;
kernel_TIDataArea.src.word8 = i_word8;
}
#ifndef BOOTLOADER
void termSetHbDump(void)
{
// Set indicator flag for doing HB dump
kernel_TIDataArea.hbDumpFlag = 1;
return;
}
#endif // BOOTLOADER
<|endoftext|> |
<commit_before>#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <map>
#include <list>
using namespace std;
// this function takes a line that may contain a name and/or email address,
// and returns just the name, while fixing the "bad cases".
std::string contributor_name(const std::string& line)
{
string result;
// let's first take care of the case of isolated email addresses, like
// "user@localhost.localdomain" entries
if(line.find("markb@localhost.localdomain") != string::npos)
{
return "Mark Borgerding";
}
// from there on we assume that we have a entry of the form
// either:
// Bla bli Blurp
// or:
// Bla bli Blurp <bblurp@email.com>
size_t position_of_email_address = line.find_first_of('<');
if(position_of_email_address != string::npos)
{
// there is an e-mail address in <...>.
// Hauke once committed as "John Smith", fix that.
if(line.find("hauke.heibel") != string::npos)
result = "Hauke Heibel";
else
{
// just remove the e-mail address
result = line.substr(0, position_of_email_address);
}
}
else
{
// there is no e-mail address in <...>.
if(line.find("convert-repo") != string::npos)
result = "";
else
result = line;
}
// remove trailing spaces
size_t length = result.length();
while(length >= 1 && result[length-1] == ' ') result.erase(--length);
return result;
}
// parses hg churn output to generate a contributors map.
map<string,int> contributors_map_from_churn_output(const char *filename)
{
map<string,int> contributors_map;
string line;
ifstream churn_out;
churn_out.open(filename, ios::in);
while(!getline(churn_out,line).eof())
{
// remove the histograms "******" that hg churn may draw at the end of some lines
size_t first_star = line.find_first_of('*');
if(first_star != string::npos) line.erase(first_star);
// remove trailing spaces
size_t length = line.length();
while(length >= 1 && line[length-1] == ' ') line.erase(--length);
// now the last space indicates where the number starts
size_t last_space = line.find_last_of(' ');
// get the number (of changesets or of modified lines for each contributor)
int number;
istringstream(line.substr(last_space+1)) >> number;
// get the name of the contributor
line.erase(last_space);
string name = contributor_name(line);
map<string,int>::iterator it = contributors_map.find(name);
// if new contributor, insert
if(it == contributors_map.end())
contributors_map.insert(pair<string,int>(name, number));
// if duplicate, just add the number
else
it->second += number;
}
churn_out.close();
return contributors_map;
}
// find the last name, i.e. the last word.
// for "van den Schbling" types of last names, that's not a problem, that's actually what we want.
string lastname(const string& name)
{
size_t last_space = name.find_last_of(' ');
if(last_space >= name.length()-1) return name;
else return name.substr(last_space+1);
}
struct contributor
{
string name;
int changedlines;
int changesets;
string url;
string misc;
contributor() : changedlines(0), changesets(0) {}
bool operator < (const contributor& other)
{
return lastname(name).compare(lastname(other.name)) < 0;
}
};
void add_online_info_into_contributors_list(list<contributor>& contributors_list, const char *filename)
{
string line;
ifstream online_info;
online_info.open(filename, ios::in);
while(!getline(online_info,line).eof())
{
string hgname, realname, url, misc;
size_t last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
misc = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
url = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
realname = line.substr(last_bar+1);
line.erase(last_bar);
hgname = line;
// remove the example line
if(hgname.find("MercurialName") != string::npos) continue;
list<contributor>::iterator it;
for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it)
{}
if(it == contributors_list.end())
{
contributor c;
c.name = realname;
c.url = url;
c.misc = misc;
contributors_list.push_back(c);
}
else
{
it->name = realname;
it->url = url;
it->misc = misc;
}
}
}
int main()
{
// parse the hg churn output files
map<string,int> contributors_map_for_changedlines = contributors_map_from_churn_output("churn-changedlines.out");
//map<string,int> contributors_map_for_changesets = contributors_map_from_churn_output("churn-changesets.out");
// merge into the contributors list
list<contributor> contributors_list;
map<string,int>::iterator it;
for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it)
{
contributor c;
c.name = it->first;
c.changedlines = it->second;
c.changesets = 0; //contributors_map_for_changesets.find(it->first)->second;
contributors_list.push_back(c);
}
add_online_info_into_contributors_list(contributors_list, "online-info.out");
contributors_list.sort();
cout << "{| cellpadding=\"5\"\n";
cout << "!\n";
cout << "! Lines changed\n";
cout << "!\n";
list<contributor>::iterator itc;
int i = 0;
for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc)
{
if(itc->name.length() == 0) continue;
if(i%2) cout << "|-\n";
else cout << "|- style=\"background:#FFFFD0\"\n";
if(itc->url.length())
cout << "| [" << itc->url << " " << itc->name << "]\n";
else
cout << "| " << itc->name << "\n";
if(itc->changedlines)
cout << "| " << itc->changedlines << "\n";
else
cout << "| (no information)\n";
cout << "| " << itc->misc << "\n";
i++;
}
cout << "|}" << endl;
}
<commit_msg>add workaround for Guillaume<commit_after>#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <map>
#include <list>
using namespace std;
// this function takes a line that may contain a name and/or email address,
// and returns just the name, while fixing the "bad cases".
std::string contributor_name(const std::string& line)
{
string result;
// let's first take care of the case of isolated email addresses, like
// "user@localhost.localdomain" entries
if(line.find("markb@localhost.localdomain") != string::npos)
{
return "Mark Borgerding";
}
if(line.find("kayhman@contact.intra.cea.fr") != string::npos)
{
return "Guillaume Saupin";
}
// from there on we assume that we have a entry of the form
// either:
// Bla bli Blurp
// or:
// Bla bli Blurp <bblurp@email.com>
size_t position_of_email_address = line.find_first_of('<');
if(position_of_email_address != string::npos)
{
// there is an e-mail address in <...>.
// Hauke once committed as "John Smith", fix that.
if(line.find("hauke.heibel") != string::npos)
result = "Hauke Heibel";
else
{
// just remove the e-mail address
result = line.substr(0, position_of_email_address);
}
}
else
{
// there is no e-mail address in <...>.
if(line.find("convert-repo") != string::npos)
result = "";
else
result = line;
}
// remove trailing spaces
size_t length = result.length();
while(length >= 1 && result[length-1] == ' ') result.erase(--length);
return result;
}
// parses hg churn output to generate a contributors map.
map<string,int> contributors_map_from_churn_output(const char *filename)
{
map<string,int> contributors_map;
string line;
ifstream churn_out;
churn_out.open(filename, ios::in);
while(!getline(churn_out,line).eof())
{
// remove the histograms "******" that hg churn may draw at the end of some lines
size_t first_star = line.find_first_of('*');
if(first_star != string::npos) line.erase(first_star);
// remove trailing spaces
size_t length = line.length();
while(length >= 1 && line[length-1] == ' ') line.erase(--length);
// now the last space indicates where the number starts
size_t last_space = line.find_last_of(' ');
// get the number (of changesets or of modified lines for each contributor)
int number;
istringstream(line.substr(last_space+1)) >> number;
// get the name of the contributor
line.erase(last_space);
string name = contributor_name(line);
map<string,int>::iterator it = contributors_map.find(name);
// if new contributor, insert
if(it == contributors_map.end())
contributors_map.insert(pair<string,int>(name, number));
// if duplicate, just add the number
else
it->second += number;
}
churn_out.close();
return contributors_map;
}
// find the last name, i.e. the last word.
// for "van den Schbling" types of last names, that's not a problem, that's actually what we want.
string lastname(const string& name)
{
size_t last_space = name.find_last_of(' ');
if(last_space >= name.length()-1) return name;
else return name.substr(last_space+1);
}
struct contributor
{
string name;
int changedlines;
int changesets;
string url;
string misc;
contributor() : changedlines(0), changesets(0) {}
bool operator < (const contributor& other)
{
return lastname(name).compare(lastname(other.name)) < 0;
}
};
void add_online_info_into_contributors_list(list<contributor>& contributors_list, const char *filename)
{
string line;
ifstream online_info;
online_info.open(filename, ios::in);
while(!getline(online_info,line).eof())
{
string hgname, realname, url, misc;
size_t last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
misc = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
url = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
realname = line.substr(last_bar+1);
line.erase(last_bar);
hgname = line;
// remove the example line
if(hgname.find("MercurialName") != string::npos) continue;
list<contributor>::iterator it;
for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it)
{}
if(it == contributors_list.end())
{
contributor c;
c.name = realname;
c.url = url;
c.misc = misc;
contributors_list.push_back(c);
}
else
{
it->name = realname;
it->url = url;
it->misc = misc;
}
}
}
int main()
{
// parse the hg churn output files
map<string,int> contributors_map_for_changedlines = contributors_map_from_churn_output("churn-changedlines.out");
//map<string,int> contributors_map_for_changesets = contributors_map_from_churn_output("churn-changesets.out");
// merge into the contributors list
list<contributor> contributors_list;
map<string,int>::iterator it;
for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it)
{
contributor c;
c.name = it->first;
c.changedlines = it->second;
c.changesets = 0; //contributors_map_for_changesets.find(it->first)->second;
contributors_list.push_back(c);
}
add_online_info_into_contributors_list(contributors_list, "online-info.out");
contributors_list.sort();
cout << "{| cellpadding=\"5\"\n";
cout << "!\n";
cout << "! Lines changed\n";
cout << "!\n";
list<contributor>::iterator itc;
int i = 0;
for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc)
{
if(itc->name.length() == 0) continue;
if(i%2) cout << "|-\n";
else cout << "|- style=\"background:#FFFFD0\"\n";
if(itc->url.length())
cout << "| [" << itc->url << " " << itc->name << "]\n";
else
cout << "| " << itc->name << "\n";
if(itc->changedlines)
cout << "| " << itc->changedlines << "\n";
else
cout << "| (no information)\n";
cout << "| " << itc->misc << "\n";
i++;
}
cout << "|}" << endl;
}
<|endoftext|> |
<commit_before>#include "./labeller.h"
#include <Eigen/Geometry>
#include <QLoggingCategory>
#include <vector>
#include <map>
#include "../utils/cuda_array_provider.h"
#include "./summed_area_table.h"
#include "./apollonius.h"
#include "./occupancy_updater.h"
#include "./constraint_updater.h"
#include "./persistent_constraint_updater.h"
#include "../utils/memory.h"
namespace Placement
{
QLoggingCategory plChan("Placement.Labeller");
Labeller::Labeller(std::shared_ptr<LabelsContainer> labels) : labels(labels)
{
}
void Labeller::initialize(
std::shared_ptr<CudaArrayProvider> occupancyTextureMapper,
std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper,
std::shared_ptr<CudaArrayProvider> constraintTextureMapper,
std::shared_ptr<PersistentConstraintUpdater> constraintUpdater)
{
qCInfo(plChan) << "Initialize";
if (!occupancySummedAreaTable.get())
occupancySummedAreaTable =
std::make_shared<SummedAreaTable>(occupancyTextureMapper);
occupancyUpdater = std::make_shared<OccupancyUpdater>(occupancyTextureMapper);
this->distanceTransformTextureMapper = distanceTransformTextureMapper;
this->apolloniusTextureMapper = apolloniusTextureMapper;
this->constraintUpdater = constraintUpdater;
costFunctionCalculator =
std::make_unique<CostFunctionCalculator>(constraintTextureMapper);
costFunctionCalculator->resize(size.x(), size.y());
costFunctionCalculator->setTextureSize(occupancyTextureMapper->getWidth(),
occupancyTextureMapper->getHeight());
}
void Labeller::cleanup()
{
occupancySummedAreaTable.reset();
apolloniusTextureMapper.reset();
occupancyUpdater.reset();
costFunctionCalculator.reset();
}
std::map<int, Eigen::Vector3f>
Labeller::update(const LabellerFrameData &frameData)
{
if (labels->count() == 0)
return std::map<int, Eigen::Vector3f>();
newPositions.clear();
if (!occupancySummedAreaTable.get())
return newPositions;
Eigen::Vector2i bufferSize(distanceTransformTextureMapper->getWidth(),
distanceTransformTextureMapper->getHeight());
auto insertionOrder = calculateInsertionOrder(frameData, bufferSize);
Eigen::Matrix4f inverseViewProjection = frameData.viewProjection.inverse();
occupancySummedAreaTable->runKernel();
for (size_t i = 0; i < insertionOrder.size(); ++i)
{
int id = insertionOrder[i];
auto label = labels->getById(id);
auto anchor2D = frameData.project(label.anchorPosition);
Eigen::Vector2i labelSizeForBuffer =
label.size.cast<int>().cwiseProduct(bufferSize).cwiseQuotient(size);
Eigen::Vector2f anchorPixels = toPixel(anchor2D, size);
Eigen::Vector2i anchorForBuffer = toPixel(anchor2D, bufferSize).cast<int>();
constraintUpdater->updateConstraints(id, anchorForBuffer, labelSizeForBuffer);
auto newPos = costFunctionCalculator->calculateForLabel(
occupancySummedAreaTable->getResults(), label.id, anchorPixels.x(),
anchorPixels.y(), label.size.x(), label.size.y());
Eigen::Vector2i newPosition(std::get<0>(newPos), std::get<1>(newPos));
constraintUpdater->setPosition(id, newPosition);
// occupancyUpdater->addLabel(newXPosition, newYPosition,
// labelSizeForBuffer.x(),
// labelSizeForBuffer.y());
newPositions[label.id] = reprojectTo3d(newPosition, anchor2D.z(),
bufferSize, inverseViewProjection);
}
return newPositions;
}
void Labeller::resize(int width, int height)
{
size = Eigen::Vector2i(width, height);
if (costFunctionCalculator.get())
costFunctionCalculator->resize(width, height);
}
std::map<int, Eigen::Vector3f> Labeller::getLastPlacementResult()
{
return newPositions;
}
std::vector<Eigen::Vector4f>
Labeller::createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection)
{
std::vector<Eigen::Vector4f> result;
for (auto &label : labels->getLabels())
{
Eigen::Vector4f pos =
viewProjection * Eigen::Vector4f(label.anchorPosition.x(),
label.anchorPosition.y(),
label.anchorPosition.z(), 1);
float x = (pos.x() / pos.w() * 0.5f + 0.5f) * size.x();
float y = (pos.y() / pos.w() * 0.5f + 0.5f) * size.y();
result.push_back(Eigen::Vector4f(label.id, x, y, 1));
}
return result;
}
std::vector<int>
Labeller::calculateInsertionOrder(const LabellerFrameData &frameData,
Eigen::Vector2i bufferSize)
{
if (labels->count() == 1)
return std::vector<int>{ labels->getLabels()[0].id };
std::vector<Eigen::Vector4f> labelsSeed =
createLabelSeeds(bufferSize, frameData.viewProjection);
Apollonius apollonius(distanceTransformTextureMapper, apolloniusTextureMapper,
labelsSeed, labels->count());
apollonius.run();
return apollonius.calculateOrdering();
}
Eigen::Vector3f Labeller::reprojectTo3d(Eigen::Vector2i newPosition,
float anchorZValue,
Eigen::Vector2i bufferSize,
Eigen::Matrix4f inverseViewProjection)
{
Eigen::Vector2f newNDC2d =
2.0f * newPosition.cast<float>().cwiseQuotient(bufferSize.cast<float>()) -
Eigen::Vector2f(1.0f, 1.0f);
Eigen::Vector4f newNDC(newNDC2d.x(), newNDC2d.y(), anchorZValue, 1);
Eigen::Vector4f reprojected = inverseViewProjection * newNDC;
reprojected /= reprojected.w();
return toVector3f(reprojected);
}
Eigen::Vector2f Labeller::toPixel(Eigen::Vector3f ndc, Eigen::Vector2i size)
{
const Eigen::Vector2f half(0.5f, 0.5f);
auto zeroToOne = ndc.head<2>().cwiseProduct(half) + half;
return zeroToOne.cwiseProduct(size.cast<float>());
}
} // namespace Placement
<commit_msg>Add profiling for SAT in Labeller.<commit_after>#include "./labeller.h"
#include <Eigen/Geometry>
#include <QLoggingCategory>
#include <vector>
#include <map>
#include <chrono>
#include "../utils/cuda_array_provider.h"
#include "../utils/logging.h"
#include "./summed_area_table.h"
#include "./apollonius.h"
#include "./occupancy_updater.h"
#include "./constraint_updater.h"
#include "./persistent_constraint_updater.h"
#include "../utils/memory.h"
namespace Placement
{
QLoggingCategory plChan("Placement.Labeller");
Labeller::Labeller(std::shared_ptr<LabelsContainer> labels) : labels(labels)
{
}
void Labeller::initialize(
std::shared_ptr<CudaArrayProvider> occupancyTextureMapper,
std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper,
std::shared_ptr<CudaArrayProvider> constraintTextureMapper,
std::shared_ptr<PersistentConstraintUpdater> constraintUpdater)
{
qCInfo(plChan) << "Initialize";
if (!occupancySummedAreaTable.get())
occupancySummedAreaTable =
std::make_shared<SummedAreaTable>(occupancyTextureMapper);
occupancyUpdater = std::make_shared<OccupancyUpdater>(occupancyTextureMapper);
this->distanceTransformTextureMapper = distanceTransformTextureMapper;
this->apolloniusTextureMapper = apolloniusTextureMapper;
this->constraintUpdater = constraintUpdater;
costFunctionCalculator =
std::make_unique<CostFunctionCalculator>(constraintTextureMapper);
costFunctionCalculator->resize(size.x(), size.y());
costFunctionCalculator->setTextureSize(occupancyTextureMapper->getWidth(),
occupancyTextureMapper->getHeight());
}
void Labeller::cleanup()
{
occupancySummedAreaTable.reset();
apolloniusTextureMapper.reset();
occupancyUpdater.reset();
costFunctionCalculator.reset();
}
std::map<int, Eigen::Vector3f>
Labeller::update(const LabellerFrameData &frameData)
{
if (labels->count() == 0)
return std::map<int, Eigen::Vector3f>();
newPositions.clear();
if (!occupancySummedAreaTable.get())
return newPositions;
Eigen::Vector2i bufferSize(distanceTransformTextureMapper->getWidth(),
distanceTransformTextureMapper->getHeight());
auto insertionOrder = calculateInsertionOrder(frameData, bufferSize);
Eigen::Matrix4f inverseViewProjection = frameData.viewProjection.inverse();
auto startTime = std::chrono::high_resolution_clock::now();
occupancySummedAreaTable->runKernel();
qCDebug(plChan) << "SAT took" << calculateDurationSince(startTime) << "ms";
for (size_t i = 0; i < insertionOrder.size(); ++i)
{
int id = insertionOrder[i];
auto label = labels->getById(id);
auto anchor2D = frameData.project(label.anchorPosition);
Eigen::Vector2i labelSizeForBuffer =
label.size.cast<int>().cwiseProduct(bufferSize).cwiseQuotient(size);
Eigen::Vector2f anchorPixels = toPixel(anchor2D, size);
Eigen::Vector2i anchorForBuffer = toPixel(anchor2D, bufferSize).cast<int>();
constraintUpdater->updateConstraints(id, anchorForBuffer,
labelSizeForBuffer);
auto newPos = costFunctionCalculator->calculateForLabel(
occupancySummedAreaTable->getResults(), label.id, anchorPixels.x(),
anchorPixels.y(), label.size.x(), label.size.y());
Eigen::Vector2i newPosition(std::get<0>(newPos), std::get<1>(newPos));
constraintUpdater->setPosition(id, newPosition);
// occupancyUpdater->addLabel(newXPosition, newYPosition,
// labelSizeForBuffer.x(),
// labelSizeForBuffer.y());
newPositions[label.id] = reprojectTo3d(newPosition, anchor2D.z(),
bufferSize, inverseViewProjection);
}
return newPositions;
}
void Labeller::resize(int width, int height)
{
size = Eigen::Vector2i(width, height);
if (costFunctionCalculator.get())
costFunctionCalculator->resize(width, height);
}
std::map<int, Eigen::Vector3f> Labeller::getLastPlacementResult()
{
return newPositions;
}
std::vector<Eigen::Vector4f>
Labeller::createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection)
{
std::vector<Eigen::Vector4f> result;
for (auto &label : labels->getLabels())
{
Eigen::Vector4f pos =
viewProjection * Eigen::Vector4f(label.anchorPosition.x(),
label.anchorPosition.y(),
label.anchorPosition.z(), 1);
float x = (pos.x() / pos.w() * 0.5f + 0.5f) * size.x();
float y = (pos.y() / pos.w() * 0.5f + 0.5f) * size.y();
result.push_back(Eigen::Vector4f(label.id, x, y, 1));
}
return result;
}
std::vector<int>
Labeller::calculateInsertionOrder(const LabellerFrameData &frameData,
Eigen::Vector2i bufferSize)
{
if (labels->count() == 1)
return std::vector<int>{ labels->getLabels()[0].id };
std::vector<Eigen::Vector4f> labelsSeed =
createLabelSeeds(bufferSize, frameData.viewProjection);
Apollonius apollonius(distanceTransformTextureMapper, apolloniusTextureMapper,
labelsSeed, labels->count());
apollonius.run();
return apollonius.calculateOrdering();
}
Eigen::Vector3f Labeller::reprojectTo3d(Eigen::Vector2i newPosition,
float anchorZValue,
Eigen::Vector2i bufferSize,
Eigen::Matrix4f inverseViewProjection)
{
Eigen::Vector2f newNDC2d =
2.0f * newPosition.cast<float>().cwiseQuotient(bufferSize.cast<float>()) -
Eigen::Vector2f(1.0f, 1.0f);
Eigen::Vector4f newNDC(newNDC2d.x(), newNDC2d.y(), anchorZValue, 1);
Eigen::Vector4f reprojected = inverseViewProjection * newNDC;
reprojected /= reprojected.w();
return toVector3f(reprojected);
}
Eigen::Vector2f Labeller::toPixel(Eigen::Vector3f ndc, Eigen::Vector2i size)
{
const Eigen::Vector2f half(0.5f, 0.5f);
auto zeroToOne = ndc.head<2>().cwiseProduct(half) + half;
return zeroToOne.cwiseProduct(size.cast<float>());
}
} // namespace Placement
<|endoftext|> |
<commit_before>// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <set>
#include <vector>
#include <shared_mutex>
#include <atomic>
int egis = 0;
class AsmLock {
public:
void Lock()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jnz retry;
}
}
void Lock2()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jz done;
retry_mov:
mov ebx, [egis];
test ebx, ebx;
jnz retry_mov;
jmp retry;
done:
}
}
void Unlock()
{
__asm {
mov eax, 0;
xchg eax, [egis];
}
}
void Unlock2()
{
__asm {
mov[egis], 0;
}
}
};
class SharedMutex {
std::shared_timed_mutex mutex;
public:
void Lock()
{
mutex.lock();
}
void Unlock()
{
mutex.unlock();
}
};
class Atomic {
std::atomic<int> val = 0;
static const int writeLockBit = 0x40000000;
void LockInternal(int delta, int testBits)
{
int expected;
do {
do {
expected = val;
} while (expected & testBits);
} while (!std::atomic_compare_exchange_weak(&val, &expected, expected + delta));
}
public:
void ReadLock()
{
LockInternal(1, writeLockBit);
}
void WriteLock()
{
LockInternal(writeLockBit, 0xffffffff);
}
void WriteUnlock()
{
std::atomic_fetch_sub(&val, writeLockBit);
}
void ReadUnlock()
{
std::atomic_fetch_sub(&val, 1);
}
};
//static AsmLock lock;
//static SharedMutex lock;
static Atomic lock;
void IncDecThreadMain()
{
static int a = 0;
for (int i = 0; i < 1000000; i++) {
lock.WriteLock();
a++;
if (a != 1)
{
printf("%d ", a);
}
a--;
lock.WriteUnlock();
printf("");
}
}
void StlContainerThreadMain(int id)
{
static std::set<int> c;
int readFound = 0;
int readNotFound = 0;
for (int i = 0; i < 1000000; i++) {
int r = rand() % 1000;
if (i % 10 == 0) {
lock.WriteLock();
auto it = c.find(r);
if (it == c.end()) {
c.insert(r);
} else {
c.erase(it);
}
lock.WriteUnlock();
} else {
lock.ReadLock();
auto it = c.find(r);
if (it == c.end()) {
readNotFound++;
} else {
readFound++;
}
lock.ReadUnlock();
}
printf("");
}
printf("threadId=%d readFound=%d readNotFound=%d\n", id, readFound, readNotFound);
}
double GetTime()
{
static auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count();
}
void IncDecTest()
{
printf("IncDecTest\n");
double begin = GetTime();
std::thread t1(IncDecThreadMain);
std::thread t2(IncDecThreadMain);
std::thread t3(IncDecThreadMain);
t1.join();
t2.join();
t3.join();
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
void StlContainerTest()
{
printf("StlContainerTest\n");
double begin = GetTime();
std::vector<std::thread> t;
for (int i = 0; i < 10; i++) {
t.emplace_back(std::thread(StlContainerThreadMain, i));
}
for (int i = 0; i < 10; i++) {
t[i].join();
}
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
int main()
{
IncDecTest();
StlContainerTest();
return 0;
}
<commit_msg>to prevent writer's long wait, allocate write waiter bits to exclude readers<commit_after>// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <set>
#include <vector>
#include <shared_mutex>
#include <atomic>
int egis = 0;
class AsmLock {
public:
void Lock()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jnz retry;
}
}
void Lock2()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jz done;
retry_mov:
mov ebx, [egis];
test ebx, ebx;
jnz retry_mov;
jmp retry;
done:
}
}
void Unlock()
{
__asm {
mov eax, 0;
xchg eax, [egis];
}
}
void Unlock2()
{
__asm {
mov[egis], 0;
}
}
};
class SharedMutex {
std::shared_timed_mutex mutex;
public:
void Lock()
{
mutex.lock();
}
void Unlock()
{
mutex.unlock();
}
};
class Atomic {
std::atomic<int> val = 0;
static const int writeLockBit = 0x40000000;
static const int writeWaiterBit = 0x00010000;
static const int writeBits = 0x7fff0000;
static const int readerBits = 0x0000ffff;
void LockInternal(int delta, int testBits)
{
int expected;
do {
do {
expected = val;
} while (expected & testBits);
} while (!std::atomic_compare_exchange_weak(&val, &expected, expected + delta));
}
public:
void ReadLock()
{
LockInternal(1, writeBits);
}
void WriteLock()
{
std::atomic_fetch_add(&val, writeWaiterBit);
LockInternal(writeLockBit, readerBits | 0x40000000);
}
void WriteUnlock()
{
std::atomic_fetch_sub(&val, writeLockBit + writeWaiterBit);
}
void ReadUnlock()
{
std::atomic_fetch_sub(&val, 1);
}
};
//static AsmLock lock;
//static SharedMutex lock;
static Atomic lock;
void IncDecThreadMain()
{
static int a = 0;
for (int i = 0; i < 1000000; i++) {
lock.WriteLock();
a++;
if (a != 1)
{
printf("%d ", a);
}
a--;
lock.WriteUnlock();
printf("");
}
}
void StlContainerThreadMain(int id)
{
static std::set<int> c;
int readFound = 0;
int readNotFound = 0;
for (int i = 0; i < 1000000; i++) {
int r = rand() % 1000;
if (i % 10 == 0) {
lock.WriteLock();
auto it = c.find(r);
if (it == c.end()) {
c.insert(r);
} else {
c.erase(it);
}
lock.WriteUnlock();
} else {
lock.ReadLock();
auto it = c.find(r);
if (it == c.end()) {
readNotFound++;
} else {
readFound++;
}
lock.ReadUnlock();
}
printf("");
}
printf("threadId=%d readFound=%d readNotFound=%d\n", id, readFound, readNotFound);
}
double GetTime()
{
static auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count();
}
void IncDecTest()
{
printf("IncDecTest\n");
double begin = GetTime();
std::thread t1(IncDecThreadMain);
std::thread t2(IncDecThreadMain);
std::thread t3(IncDecThreadMain);
t1.join();
t2.join();
t3.join();
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
void StlContainerTest()
{
printf("StlContainerTest\n");
double begin = GetTime();
std::vector<std::thread> t;
for (int i = 0; i < 10; i++) {
t.emplace_back(std::thread(StlContainerThreadMain, i));
}
for (int i = 0; i < 10; i++) {
t[i].join();
}
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
int main()
{
IncDecTest();
StlContainerTest();
return 0;
}
<|endoftext|> |
<commit_before>/*
* KeyListOpsMethods.cpp
*
* Created on: Feb 6, 2014
* Author: nek3d
*/
#include "KeyListOpsMethods.h"
#include <cfloat>
#include <cmath>
#include <algorithm>
#include "ParseTools.h" //to get the isNumeric function
KeyListOpsMethods::KeyListOpsMethods()
: _keyList(&_nullKeyList),
_column(1),
_nullVal("."),
_delimStr(","),
_iter(_nullKeyList.begin()),
_nonNumErrFlag(false),
_isBam(false)
{
}
KeyListOpsMethods::KeyListOpsMethods(RecordKeyVector *keyList, int column)
: _keyList(keyList),
_column(column),
_nullVal("."),
_delimStr(","),
_iter(keyList->begin())
{
}
KeyListOpsMethods::~KeyListOpsMethods() {
}
// return the total of the values in the vector
double KeyListOpsMethods::getSum() {
if (empty()) return NAN;
double theSum = 0.0;
for (begin(); !end(); next()) {
theSum += getColValNum();
}
return theSum;
}
// return the average value in the vector
double KeyListOpsMethods::getMean() {
if (empty()) return NAN;
return getSum() / (float)getCount();
}
// return the standard deviation
double KeyListOpsMethods::getStddev() {
if (empty()) return NAN;
double avg = getMean();
double squareDiffSum = 0.0;
for (begin(); !end(); next()) {
double val = getColValNum();
double diff = val - avg;
squareDiffSum += diff * diff;
}
return squareDiffSum / (float)getCount();
}
// return the standard deviation
double KeyListOpsMethods::getSampleStddev() {
if (empty()) return NAN;
double avg = getMean();
double squareDiffSum = 0.0;
for (begin(); !end(); next()) {
double val = getColValNum();
double diff = val - avg;
squareDiffSum += diff * diff;
}
return squareDiffSum / ((float)getCount() - 1.0);
}
// return the median value in the vector
double KeyListOpsMethods::getMedian() {
if (empty()) return NAN;
//get sorted vector. if even number of elems, return middle val.
//if odd, average of two.
toArray(true, ASC);
size_t count = getCount();
if (count % 2) {
//odd number of elements. Take middle one.
return _numArray[count/2];
} else {
//even numnber of elements. Take average of middle 2.
double sum = _numArray[count/2 -1] + _numArray[count/2];
return sum / 2.0;
}
}
// return the most common value in the vector
const QuickString &KeyListOpsMethods::getMode() {
if (empty()) return _nullVal;
makeFreqMap();
//now pass through the freq map and keep track of which key has the highest occurance.
freqMapType::iterator maxIter = _freqMap.begin();
int maxVal = 0;
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter->second > maxVal) {
maxIter = _freqIter;
maxVal = _freqIter->second;
}
}
_retStr = maxIter->first;
return _retStr;
}
// return the least common value in the vector
const QuickString &KeyListOpsMethods::getAntiMode() {
if (empty()) return _nullVal;
makeFreqMap();
//now pass through the freq map and keep track of which key has the highest occurance.
freqMapType::iterator minIter = _freqMap.begin();
int minVal = INT_MAX;
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter->second < minVal) {
minIter = _freqIter;
minVal = _freqIter->second;
}
}
_retStr = minIter->first;
return _retStr;
}
// return the minimum element of the vector
double KeyListOpsMethods::getMin() {
if (empty()) return NAN;
double minVal = DBL_MAX;
for (begin(); !end(); next()) {
double currVal = getColValNum();
minVal = (currVal < minVal) ? currVal : minVal;
}
return minVal;
}
// return the maximum element of the vector
double KeyListOpsMethods::getMax() {
if (empty()) return NAN;
double maxVal = DBL_MIN;
for (begin(); !end(); next()) {
double currVal = getColValNum();
maxVal = (currVal > maxVal) ? currVal : maxVal;
}
return maxVal;
}
// return the minimum absolute value of the vector
double KeyListOpsMethods::getAbsMin() {
if (empty()) return NAN;
double minVal = DBL_MAX;
for (begin(); !end(); next()) {
double currVal = abs(getColValNum());
minVal = (currVal < minVal) ? currVal : minVal;
}
return minVal;
}
// return the maximum absolute value of the vector
double KeyListOpsMethods::getAbsMax() {
if (empty()) return NAN;
double maxVal = DBL_MIN;
for (begin(); !end(); next()) {
double currVal = abs(getColValNum());
maxVal = (currVal > maxVal) ? currVal : maxVal;
}
return maxVal;
}
// return the count of element in the vector
uint32_t KeyListOpsMethods::getCount() {
return _keyList->size();
}
// return a delimited list of the unique elements
const QuickString &KeyListOpsMethods::getDistinct() {
if (empty()) return _nullVal;
// separated list of unique values. If something repeats, only report once.
makeFreqMap();
_retStr.clear();
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter != _freqMap.begin()) _retStr += _delimStr;
_retStr.append(_freqIter->first);
}
return _retStr;
}
const QuickString &KeyListOpsMethods::getDistinctOnly() {
if (empty()) return _nullVal;
// separated list of unique values. If something repeats, don't report.
makeFreqMap();
_retStr.clear();
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter->second > 1) continue;
if (_freqIter != _freqMap.begin()) _retStr += _delimStr;
_retStr.append(_freqIter->first);
}
return _retStr;
}
const QuickString &KeyListOpsMethods::getDistinctSortNum(bool asc) {
toArray(true, asc ? ASC : DESC);
vector<double>::iterator endIter = std::unique(_numArray.begin(), _numArray.end());
_retStr.clear();
for (vector<double>::iterator iter = _numArray.begin(); iter != endIter; iter++) {
if (iter != _numArray.begin()) _retStr += _delimStr;
_retStr.append(*iter);
}
return _retStr;
}
// return a the count of _unique_ elements in the vector
uint32_t KeyListOpsMethods::getCountDistinct() {
if (empty()) return 0;
makeFreqMap();
return _freqMap.size();
}
// return a delimiter-separated list of elements
const QuickString &KeyListOpsMethods::getCollapse(const QuickString &delimiter) {
if (empty()) return _nullVal;
//just put all items in one big separated list.
_retStr.clear();
int i=0;
for (begin(); !end(); next()) {
if (i > 0) _retStr += _delimStr;
_retStr.append(getColVal());
i++;
}
return _retStr;
}
// return a concatenation of all elements in the vector
const QuickString &KeyListOpsMethods::getConcat() {
if (empty()) return _nullVal;
//like collapse but w/o commas. Just a true concat of all vals.
//just swap out the delimChar with '' and call collapse, then
//restore the delimChar.
QuickString oldDelimStr(_delimStr);
_delimStr = "";
getCollapse(); //this will store it's results in the _retStr method.
_delimStr = oldDelimStr;
return _retStr;
}
// return a histogram of values and their freqs. in desc. order of frequency
const QuickString &KeyListOpsMethods::getFreqDesc() {
if (empty()) return _nullVal;
//for each uniq val, report # occurances, in desc order.
makeFreqMap();
//put freq map into multimap where key is the freq and val is the item. In other words, basically a reverse freq map.
histDescType hist;
for (; _freqIter != _freqMap.end(); _freqIter++) {
hist.insert(pair<int, QuickString>(_freqIter->second, _freqIter->first));
}
//now iterate through the reverse map we just made and output it's pairs in val:key format.
_retStr.clear();
for (histDescType::iterator histIter = hist.begin(); histIter != hist.end(); histIter++) {
if (histIter != hist.begin()) _retStr += _delimStr;
_retStr.append(histIter->second);
_retStr += ":";
_retStr.append(histIter->first);
}
return _retStr;
}
// return a histogram of values and their freqs. in asc. order of frequency
const QuickString &KeyListOpsMethods::getFreqAsc() {
if (empty()) return _nullVal;
//for each uniq val, report # occurances, in asc order.
makeFreqMap();
//put freq map into multimap where key is the freq and val is the item. In other words, basically a reverse freq map.
histAscType hist;
for (; _freqIter != _freqMap.end(); _freqIter++) {
hist.insert(pair<int, QuickString>(_freqIter->second, _freqIter->first));
// hist[*(_freqIter->second)] = _freqIter->first;
}
//now iterate through the reverse map we just made and output it's pairs in val:key format.
_retStr.clear();
for (histAscType::iterator histIter = hist.begin(); histIter != hist.end(); histIter++) {
if (histIter != hist.begin()) _retStr += _delimStr;
_retStr.append(histIter->second);
_retStr += ":";
_retStr.append(histIter->first);
}
return _retStr;
}
// return the first value in the list
const QuickString &KeyListOpsMethods::getFirst() {
if (empty()) return _nullVal;
//just the first item.
begin();
return getColVal();
}
// return the last value in the list
const QuickString &KeyListOpsMethods::getLast() {
if (empty()) return _nullVal;
//just the last item.
begin();
for (size_t i = 0; i < getCount() -1; i++) {
next();
}
return getColVal();
}
const QuickString &KeyListOpsMethods::getColVal() {
const QuickString &retVal = (*_iter)->getField(_column);
if (_isBam && retVal.empty()) return _nullVal;
return retVal;
}
double KeyListOpsMethods::getColValNum() {
const QuickString &strVal = (*_iter)->getField(_column);
if (!isNumeric(strVal)) {
_nonNumErrFlag = true;
_errMsg = " ***** WARNING: Non numeric value ";
_errMsg.append(strVal);
_errMsg.append(" in ");
_errMsg.append(_column);
_errMsg.append(".");
return NAN;
}
return atof(strVal.c_str());
}
void KeyListOpsMethods::toArray(bool useNum, SORT_TYPE sortVal) {
//TBD: optimize performance with better memory management.
if (useNum) {
_numArray.resize(_keyList->size());
int i=0;
for (begin(); !end(); next()) {
_numArray[i] = getColValNum();
i++;
}
} else {
_qsArray.resize(_keyList->size());
int i=0;
for (begin(); !end(); next()) {
_qsArray[i] = getColVal();
i++;
}
}
if (sortVal != UNSORTED) {
sortArray(useNum, sortVal == ASC);
}
}
void KeyListOpsMethods::sortArray(bool useNum, bool ascOrder)
{
if (useNum) {
if (ascOrder) {
sort(_numArray.begin(), _numArray.end(), less<double>());
} else {
sort(_numArray.begin(), _numArray.end(), greater<double>());
}
} else {
if (ascOrder) {
sort(_qsArray.begin(), _qsArray.end(), less<QuickString>());
} else {
sort(_qsArray.begin(), _qsArray.end(), greater<QuickString>());
}
}
}
void KeyListOpsMethods::makeFreqMap() {
_freqMap.clear();
//make a map of values to their number of times occuring.
for (begin(); !end(); next()) {
_freqMap[getColVal()]++;
}
_freqIter = _freqMap.begin();
}
<commit_msg>fix double comparisons to zero<commit_after>/*
* KeyListOpsMethods.cpp
*
* Created on: Feb 6, 2014
* Author: nek3d
*/
#include "KeyListOpsMethods.h"
#include <cfloat>
#include <cmath>
#include <algorithm>
#include "ParseTools.h" //to get the isNumeric function
KeyListOpsMethods::KeyListOpsMethods()
: _keyList(&_nullKeyList),
_column(1),
_nullVal("."),
_delimStr(","),
_iter(_nullKeyList.begin()),
_nonNumErrFlag(false),
_isBam(false)
{
}
KeyListOpsMethods::KeyListOpsMethods(RecordKeyVector *keyList, int column)
: _keyList(keyList),
_column(column),
_nullVal("."),
_delimStr(","),
_iter(keyList->begin())
{
}
KeyListOpsMethods::~KeyListOpsMethods() {
}
// return the total of the values in the vector
double KeyListOpsMethods::getSum() {
if (empty()) return NAN;
double theSum = 0.0;
for (begin(); !end(); next()) {
theSum += getColValNum();
}
return theSum;
}
// return the average value in the vector
double KeyListOpsMethods::getMean() {
if (empty()) return NAN;
return getSum() / (float)getCount();
}
// return the standard deviation
double KeyListOpsMethods::getStddev() {
if (empty()) return NAN;
double avg = getMean();
double squareDiffSum = 0.0;
for (begin(); !end(); next()) {
double val = getColValNum();
double diff = val - avg;
squareDiffSum += diff * diff;
}
return squareDiffSum / (float)getCount();
}
// return the standard deviation
double KeyListOpsMethods::getSampleStddev() {
if (empty()) return NAN;
double avg = getMean();
double squareDiffSum = 0.0;
for (begin(); !end(); next()) {
double val = getColValNum();
double diff = val - avg;
squareDiffSum += diff * diff;
}
return squareDiffSum / ((float)getCount() - 1.0);
}
// return the median value in the vector
double KeyListOpsMethods::getMedian() {
if (empty()) return NAN;
//get sorted vector. if even number of elems, return middle val.
//if odd, average of two.
toArray(true, ASC);
size_t count = getCount();
if (count % 2) {
//odd number of elements. Take middle one.
return _numArray[count/2];
} else {
//even numnber of elements. Take average of middle 2.
double sum = _numArray[count/2 -1] + _numArray[count/2];
return sum / 2.0;
}
}
// return the most common value in the vector
const QuickString &KeyListOpsMethods::getMode() {
if (empty()) return _nullVal;
makeFreqMap();
//now pass through the freq map and keep track of which key has the highest occurance.
freqMapType::iterator maxIter = _freqMap.begin();
int maxVal = 0;
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter->second > maxVal) {
maxIter = _freqIter;
maxVal = _freqIter->second;
}
}
_retStr = maxIter->first;
return _retStr;
}
// return the least common value in the vector
const QuickString &KeyListOpsMethods::getAntiMode() {
if (empty()) return _nullVal;
makeFreqMap();
//now pass through the freq map and keep track of which key has the highest occurance.
freqMapType::iterator minIter = _freqMap.begin();
int minVal = INT_MAX;
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter->second < minVal) {
minIter = _freqIter;
minVal = _freqIter->second;
}
}
_retStr = minIter->first;
return _retStr;
}
// return the minimum element of the vector
double KeyListOpsMethods::getMin() {
if (empty()) return NAN;
double minVal = DBL_MAX;
for (begin(); !end(); next()) {
double currVal = getColValNum();
minVal = ((float) currVal <= (float) minVal) ? currVal : minVal;
}
return minVal;
}
// return the maximum element of the vector
double KeyListOpsMethods::getMax() {
if (empty()) return NAN;
double maxVal = DBL_MIN;
for (begin(); !end(); next()) {
double currVal = getColValNum();
maxVal = ((float) currVal >= (float) maxVal) ? currVal : maxVal;
}
return maxVal;
}
// return the minimum absolute value of the vector
double KeyListOpsMethods::getAbsMin() {
if (empty()) return NAN;
double minVal = DBL_MAX;
for (begin(); !end(); next()) {
double currVal = abs(getColValNum());
minVal = ((float)currVal <= (float)minVal) ? currVal : minVal;
}
return minVal;
}
// return the maximum absolute value of the vector
double KeyListOpsMethods::getAbsMax() {
if (empty()) return NAN;
double maxVal = DBL_MIN;
for (begin(); !end(); next()) {
double currVal = abs(getColValNum());
maxVal = ((float)currVal >= (float)maxVal) ? currVal : maxVal;
}
return maxVal;
}
// return the count of element in the vector
uint32_t KeyListOpsMethods::getCount() {
return _keyList->size();
}
// return a delimited list of the unique elements
const QuickString &KeyListOpsMethods::getDistinct() {
if (empty()) return _nullVal;
// separated list of unique values. If something repeats, only report once.
makeFreqMap();
_retStr.clear();
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter != _freqMap.begin()) _retStr += _delimStr;
_retStr.append(_freqIter->first);
}
return _retStr;
}
const QuickString &KeyListOpsMethods::getDistinctOnly() {
if (empty()) return _nullVal;
// separated list of unique values. If something repeats, don't report.
makeFreqMap();
_retStr.clear();
for (; _freqIter != _freqMap.end(); _freqIter++) {
if (_freqIter->second > 1) continue;
if (_freqIter != _freqMap.begin()) _retStr += _delimStr;
_retStr.append(_freqIter->first);
}
return _retStr;
}
const QuickString &KeyListOpsMethods::getDistinctSortNum(bool asc) {
toArray(true, asc ? ASC : DESC);
vector<double>::iterator endIter = std::unique(_numArray.begin(), _numArray.end());
_retStr.clear();
for (vector<double>::iterator iter = _numArray.begin(); iter != endIter; iter++) {
if (iter != _numArray.begin()) _retStr += _delimStr;
_retStr.append(*iter);
}
return _retStr;
}
// return a the count of _unique_ elements in the vector
uint32_t KeyListOpsMethods::getCountDistinct() {
if (empty()) return 0;
makeFreqMap();
return _freqMap.size();
}
// return a delimiter-separated list of elements
const QuickString &KeyListOpsMethods::getCollapse(const QuickString &delimiter) {
if (empty()) return _nullVal;
//just put all items in one big separated list.
_retStr.clear();
int i=0;
for (begin(); !end(); next()) {
if (i > 0) _retStr += _delimStr;
_retStr.append(getColVal());
i++;
}
return _retStr;
}
// return a concatenation of all elements in the vector
const QuickString &KeyListOpsMethods::getConcat() {
if (empty()) return _nullVal;
//like collapse but w/o commas. Just a true concat of all vals.
//just swap out the delimChar with '' and call collapse, then
//restore the delimChar.
QuickString oldDelimStr(_delimStr);
_delimStr = "";
getCollapse(); //this will store it's results in the _retStr method.
_delimStr = oldDelimStr;
return _retStr;
}
// return a histogram of values and their freqs. in desc. order of frequency
const QuickString &KeyListOpsMethods::getFreqDesc() {
if (empty()) return _nullVal;
//for each uniq val, report # occurances, in desc order.
makeFreqMap();
//put freq map into multimap where key is the freq and val is the item. In other words, basically a reverse freq map.
histDescType hist;
for (; _freqIter != _freqMap.end(); _freqIter++) {
hist.insert(pair<int, QuickString>(_freqIter->second, _freqIter->first));
}
//now iterate through the reverse map we just made and output it's pairs in val:key format.
_retStr.clear();
for (histDescType::iterator histIter = hist.begin(); histIter != hist.end(); histIter++) {
if (histIter != hist.begin()) _retStr += _delimStr;
_retStr.append(histIter->second);
_retStr += ":";
_retStr.append(histIter->first);
}
return _retStr;
}
// return a histogram of values and their freqs. in asc. order of frequency
const QuickString &KeyListOpsMethods::getFreqAsc() {
if (empty()) return _nullVal;
//for each uniq val, report # occurances, in asc order.
makeFreqMap();
//put freq map into multimap where key is the freq and val is the item. In other words, basically a reverse freq map.
histAscType hist;
for (; _freqIter != _freqMap.end(); _freqIter++) {
hist.insert(pair<int, QuickString>(_freqIter->second, _freqIter->first));
// hist[*(_freqIter->second)] = _freqIter->first;
}
//now iterate through the reverse map we just made and output it's pairs in val:key format.
_retStr.clear();
for (histAscType::iterator histIter = hist.begin(); histIter != hist.end(); histIter++) {
if (histIter != hist.begin()) _retStr += _delimStr;
_retStr.append(histIter->second);
_retStr += ":";
_retStr.append(histIter->first);
}
return _retStr;
}
// return the first value in the list
const QuickString &KeyListOpsMethods::getFirst() {
if (empty()) return _nullVal;
//just the first item.
begin();
return getColVal();
}
// return the last value in the list
const QuickString &KeyListOpsMethods::getLast() {
if (empty()) return _nullVal;
//just the last item.
begin();
for (size_t i = 0; i < getCount() -1; i++) {
next();
}
return getColVal();
}
const QuickString &KeyListOpsMethods::getColVal() {
const QuickString &retVal = (*_iter)->getField(_column);
if (_isBam && retVal.empty()) return _nullVal;
return retVal;
}
double KeyListOpsMethods::getColValNum() {
const QuickString &strVal = (*_iter)->getField(_column);
if (!isNumeric(strVal)) {
_nonNumErrFlag = true;
_errMsg = " ***** WARNING: Non numeric value ";
_errMsg.append(strVal);
_errMsg.append(" in ");
_errMsg.append(_column);
_errMsg.append(".");
return NAN;
}
return atof(strVal.c_str());
}
void KeyListOpsMethods::toArray(bool useNum, SORT_TYPE sortVal) {
//TBD: optimize performance with better memory management.
if (useNum) {
_numArray.resize(_keyList->size());
int i=0;
for (begin(); !end(); next()) {
_numArray[i] = getColValNum();
i++;
}
} else {
_qsArray.resize(_keyList->size());
int i=0;
for (begin(); !end(); next()) {
_qsArray[i] = getColVal();
i++;
}
}
if (sortVal != UNSORTED) {
sortArray(useNum, sortVal == ASC);
}
}
void KeyListOpsMethods::sortArray(bool useNum, bool ascOrder)
{
if (useNum) {
if (ascOrder) {
sort(_numArray.begin(), _numArray.end(), less<double>());
} else {
sort(_numArray.begin(), _numArray.end(), greater<double>());
}
} else {
if (ascOrder) {
sort(_qsArray.begin(), _qsArray.end(), less<QuickString>());
} else {
sort(_qsArray.begin(), _qsArray.end(), greater<QuickString>());
}
}
}
void KeyListOpsMethods::makeFreqMap() {
_freqMap.clear();
//make a map of values to their number of times occuring.
for (begin(); !end(); next()) {
_freqMap[getColVal()]++;
}
_freqIter = _freqMap.begin();
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "ObjectCameraController.h"
#include "EventManager.h"
#include "InputEvents.h"
#include "SceneEvents.h"
#include "Renderer.h"
#include "Frame.h"
#include "Entity.h"
#include <QApplication>
#include <SceneManager.h>
#include <EC_OgrePlaceable.h>
#include <EC_OgreCamera.h>
#include <EC_OgreMesh.h>
#include <EC_OgreCustomObject.h>
#include <Ogre.h>
#include <QDebug>
namespace RexLogic
{
ObjectCameraController::ObjectCameraController(RexLogicModule* rex_logic, CameraControllable* camera_controllable, QObject *parent) :
QObject(parent),
rex_logic_(rex_logic),
framework_(rex_logic->GetFramework()),
camera_controllable_(camera_controllable),
camera_count_(0),
last_dir_(Vector3df::ZERO),
selected_entity_(0),
alt_key_pressed_(false),
zoom_close_(false),
left_mousebutton_pressed_(false),
object_selected_(false)
{
event_query_categories_ << "Input" << "Action" << "Framework" << "NetworkState" << "Scene";
timeline_ = new QTimeLine(1000, this);
timeline_->setFrameRange(0, 100);
}
ObjectCameraController::~ObjectCameraController()
{
}
void ObjectCameraController::SubscribeToEventCategories()
{
service_category_identifiers_.clear();
foreach (QString category, event_query_categories_)
service_category_identifiers_[category] = framework_->GetEventManager()->QueryEventCategory(category.toStdString());
}
void ObjectCameraController::PostInitialize()
{
// Get all category id's that we are interested in
SubscribeToEventCategories();
// Register building key context
input_context_ = framework_->Input()->RegisterInputContext("ObjectCameraContext", 100);
connect(input_context_.get(), SIGNAL(KeyPressed(KeyEvent*)), this, SLOT(KeyPressed(KeyEvent*)));
connect(input_context_.get(), SIGNAL(KeyReleased(KeyEvent*)), this, SLOT(KeyReleased(KeyEvent*)));
connect(input_context_.get(), SIGNAL(MouseMove(MouseEvent*)), this, SLOT(MouseMove(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseLeftPressed(MouseEvent*)), this, SLOT(MouseLeftPressed(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseLeftReleased(MouseEvent*)), this, SLOT(MouseLeftReleased(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseScroll(MouseEvent*)), this, SLOT(MouseScroll(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseDoubleClicked(MouseEvent*)), this, SLOT(MouseDoubleClicked(MouseEvent*)));
connect(framework_->GetFrame(), SIGNAL(Updated(float)), this, SLOT(Update(float)));
connect(timeline_, SIGNAL(frameChanged(int)), this, SLOT(FrameChanged(int)));
connect(timeline_, SIGNAL(finished()), this, SLOT(TimeLineFinished()));
}
bool ObjectCameraController::HandleInputEvent(event_id_t event_id, IEventData* data)
{
return false;
}
bool ObjectCameraController::HandleSceneEvent(event_id_t event_id, IEventData* data)
{
return false;
}
bool ObjectCameraController::HandleFrameworkEvent(event_id_t event_id, IEventData* data)
{
if (event_id == Foundation::WORLD_STREAM_READY)
{
CreateCustomCamera();
}
return false;
}
void ObjectCameraController::EntityClicked(Scene::Entity* entity)
{
if (!entity || !camera_entity_)
return;
if (timeline_->state() == QTimeLine::Running)
return;
if (alt_key_pressed_)
{
ec_camera_ = camera_entity_->GetComponent<OgreRenderer::EC_OgreCamera>().get();
cam_ec_placable_ = camera_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
OgreRenderer::EC_OgrePlaceable *camera_placeable = 0;
vectors_position_.first = Vector3df::ZERO;
vectors_position_.second = Vector3df::ZERO;
if (!selected_entity_)
{
cam_ec_placable_->SetPosition(camera_controllable_->GetCameraEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>().get()->GetPosition());
vectors_lookat_.first = camera_controllable_->GetThirdPersonLookAt();
avatar_camera_position_ = cam_ec_placable_->GetPosition();
avatar_camera_lookat_ = camera_controllable_->GetThirdPersonLookAt();
}
else
{
camera_placeable = selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
vectors_lookat_.first = camera_placeable->GetPosition();
}
OgreRenderer::EC_OgrePlaceable *entity_ec_placable = entity->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (entity_ec_placable)
{
cam_ec_placable_->LookAt(vectors_lookat_.first);
ec_camera_->SetActive();
object_selected_ = true;
selected_entity_ = entity;
QCursor *current_cur = QApplication::overrideCursor();
if (current_cur)
if (current_cur->shape() != Qt::SizeAllCursor)
QApplication::setOverrideCursor(Qt::SizeAllCursor);
vectors_lookat_.second = entity_ec_placable->GetPosition();
timeline_->start();
}
}
}
void ObjectCameraController::KeyPressed(KeyEvent* key_event)
{
if (key_event->keyCode == Qt::Key_Alt)
{
alt_key_pressed_ = true;
QApplication::setOverrideCursor(Qt::PointingHandCursor);
}
if (key_event->keyCode == Qt::Key_Left || key_event->keyCode == Qt::Key_Right || key_event->keyCode == Qt::Key_Up || key_event->keyCode == Qt::Key_Down)
{
if (object_selected_)
{
ReturnToAvatarCamera();
}
}
}
void ObjectCameraController::MouseMove(MouseEvent* mouse)
{
if (object_selected_ && left_mousebutton_pressed_)
{
float width = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowWidth();
float height = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowHeight();
RotateObject(2*PI*mouse->relativeX/width, 2*PI*mouse->relativeY/height);
}
}
void ObjectCameraController::MouseLeftPressed(MouseEvent* mouse)
{
left_mousebutton_pressed_ = true;
}
void ObjectCameraController::MouseLeftReleased(MouseEvent* mouse)
{
left_mousebutton_pressed_ = false;
}
void ObjectCameraController::KeyReleased(KeyEvent* key_event)
{
if (key_event->keyCode == Qt::Key_Alt)
{
QCursor *current_cur = QApplication::overrideCursor();
if (!object_selected_)
{
while (current_cur)
{
QApplication::restoreOverrideCursor();
current_cur = QApplication::overrideCursor();
}
}
else
{
if (current_cur)
if (current_cur->shape() == Qt::PointingHandCursor)
QApplication::restoreOverrideCursor();
}
alt_key_pressed_ = false;
}
}
void ObjectCameraController::MouseScroll(MouseEvent* mouse)
{
if (object_selected_)
{
if (! selected_entity_)
return;
OgreRenderer::EC_OgrePlaceable *entity_ec_placable = selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (!entity_ec_placable)
return;
ZoomRelativeToPoint(entity_ec_placable->GetPosition(), mouse->RelativeZ());
}
}
void ObjectCameraController::MouseDoubleClicked(MouseEvent *mouse)
{
if (object_selected_)
{
if (! selected_entity_)
return;
zoom_close_ = true;
}
}
void ObjectCameraController::RotateObject(qreal x, qreal y)
{
if (selected_entity_)
{
OgreRenderer::EC_OgrePlaceable *entity_ec_placable = selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (entity_ec_placable)
{
qreal acceleration_x = 1;
qreal acceleration_y = 1;
RotateCamera(entity_ec_placable->GetPosition(),selected_camera_id_,x*acceleration_x,y*acceleration_y);
}
}
}
void ObjectCameraController::RotateCamera(Vector3df pivot, CameraID id, qreal x, qreal y)
{
if (!ec_camera_ || !cam_ec_placable_)
return;
Ogre::Camera* cam = ec_camera_->GetCamera();
Vector3df pos = cam_ec_placable_->GetPosition();
Vector3df dir(pos-pivot);
Quaternion quat(-x,cam_ec_placable_->GetLocalYAxis());
quat *= Quaternion(-y, cam_ec_placable_->GetLocalXAxis());
dir = quat * dir;
Vector3df new_pos(pivot+dir);
cam_ec_placable_->SetPosition(new_pos);
cam_ec_placable_->LookAt(pivot);
last_dir_=pivot - cam_ec_placable_->GetPosition();
}
void ObjectCameraController::CreateCustomCamera()
{
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
if (!scene)
return;
Scene::EntityPtr cam_entity = scene->CreateEntity(scene->GetNextFreeId());
if (!cam_entity.get())
return;
cam_entity->AddComponent(framework_->GetComponentManager()->CreateComponent(OgreRenderer::EC_OgrePlaceable::TypeNameStatic()));
cam_entity->AddComponent(framework_->GetComponentManager()->CreateComponent(OgreRenderer::EC_OgreCamera::TypeNameStatic()));
scene->EmitEntityCreated(cam_entity);
ComponentPtr component_placable = cam_entity->GetComponent(OgreRenderer::EC_OgrePlaceable::TypeNameStatic());
OgreRenderer::EC_OgreCamera *ec_camera = cam_entity->GetComponent<OgreRenderer::EC_OgreCamera>().get();
if (!component_placable.get() || !ec_camera)
return;
ec_camera->SetPlaceable(component_placable);
camera_entity_ = cam_entity;
}
void ObjectCameraController::ZoomRelativeToPoint(Vector3df point, qreal delta, qreal min, qreal max)
{
bool zoomed = false;
if (!camera_entity_)
return;
if (!cam_ec_placable_)
return;
Vector3df pos = cam_ec_placable_->GetPosition();
Vector3df dir = point-pos;
Vector3df distance = dir;
dir.normalize();
qreal acceleration = 0.01;
dir *= (delta * acceleration);
if (delta>0 && (distance.getLength()+dir.getLength() > min))
{
zoomed = true;
}
if (delta<0 && (distance.getLength()+dir.getLength() <max))
{
zoomed = true;
}
if (zoomed)
{
cam_ec_placable_->SetPosition(cam_ec_placable_->GetPosition() + dir);
}
}
void ObjectCameraController::Update(float frametime)
{
if(zoom_close_)
{
ZoomCloseToPoint(selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get()->GetPosition());
}
}
void ObjectCameraController::FrameChanged(int frame)
{
qreal step = frame;
step /= 100;
if (vectors_position_.first != Vector3df::ZERO && vectors_position_.second != Vector3df::ZERO)
{
Vector3df position_start = vectors_position_.first;
Vector3df position_end = vectors_position_.second;
Vector3df position;
position.x = (position_end.x - position_start.x) * step + position_start.x;
position.y = (position_end.y - position_start.y) * step + position_start.y;
position.z = (position_end.z - position_start.z) * step + position_start.z;
cam_ec_placable_->SetPosition(position);
}
if (vectors_lookat_.first != Vector3df::ZERO && vectors_lookat_.second != Vector3df::ZERO)
{
Vector3df lookat_start = vectors_lookat_.first;
Vector3df lookat_end = vectors_lookat_.second;
Vector3df look_at;
look_at.x = (lookat_end.x - lookat_start.x) * step + lookat_start.x;
look_at.y = (lookat_end.y - lookat_start.y) * step + lookat_start.y;
look_at.z = (lookat_end.z - lookat_start.z) * step + lookat_start.z;
cam_ec_placable_->LookAt(look_at);
}
}
void ObjectCameraController::TimeLineFinished()
{
if (vectors_position_.first != Vector3df::ZERO && vectors_position_.second != Vector3df::ZERO)
{
camera_controllable_->GetCameraEntity()->GetComponent<OgreRenderer::EC_OgreCamera>().get()->SetActive();
event_category_id_t event_category = framework_->GetEventManager()->QueryEventCategory("Input");
framework_->GetEventManager()->SendEvent(event_category, Input::Events::INPUTSTATE_THIRDPERSON, 0);
object_selected_ = false;
selected_entity_ = 0;
QCursor *current_cur = QApplication::overrideCursor();
while (current_cur)
{
QApplication::restoreOverrideCursor();
current_cur = QApplication::overrideCursor();
}
}
}
void ObjectCameraController::ReturnToAvatarCamera()
{
OgreRenderer::EC_OgrePlaceable *cam_placable = camera_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (!cam_placable)
return;
if (timeline_->state() == QTimeLine::Running)
return;
vectors_position_.first = cam_placable->GetPosition();
vectors_position_.second = avatar_camera_position_;
vectors_lookat_.first = vectors_lookat_.second;
vectors_lookat_.second = avatar_camera_lookat_;
timeline_->start();
}
void ObjectCameraController::ZoomCloseToPoint(Vector3df point, qreal delta, qreal min)
{
if (!camera_entity_)
return;
if (!cam_ec_placable_)
return;
Vector3df pos = cam_ec_placable_->GetPosition();
Vector3df dir = point-pos;
Vector3df distance = dir;
dir.normalize();
qreal acceleration = 0.005;
dir *= (delta * acceleration);
if (distance.getLength()+dir.getLength() > min)
{
cam_ec_placable_->SetPosition(cam_ec_placable_->GetPosition() + dir);
} else
{
zoom_close_ = false;
}
}
}
<commit_msg>Going to avatar camera after doubleclick zooming is finished<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "ObjectCameraController.h"
#include "EventManager.h"
#include "InputEvents.h"
#include "SceneEvents.h"
#include "Renderer.h"
#include "Frame.h"
#include "Entity.h"
#include <QApplication>
#include <SceneManager.h>
#include <EC_OgrePlaceable.h>
#include <EC_OgreCamera.h>
#include <EC_OgreMesh.h>
#include <EC_OgreCustomObject.h>
#include <Ogre.h>
#include <QDebug>
namespace RexLogic
{
ObjectCameraController::ObjectCameraController(RexLogicModule* rex_logic, CameraControllable* camera_controllable, QObject *parent) :
QObject(parent),
rex_logic_(rex_logic),
framework_(rex_logic->GetFramework()),
camera_controllable_(camera_controllable),
camera_count_(0),
last_dir_(Vector3df::ZERO),
selected_entity_(0),
alt_key_pressed_(false),
zoom_close_(false),
left_mousebutton_pressed_(false),
object_selected_(false)
{
event_query_categories_ << "Input" << "Action" << "Framework" << "NetworkState" << "Scene";
timeline_ = new QTimeLine(1000, this);
timeline_->setFrameRange(0, 100);
}
ObjectCameraController::~ObjectCameraController()
{
}
void ObjectCameraController::SubscribeToEventCategories()
{
service_category_identifiers_.clear();
foreach (QString category, event_query_categories_)
service_category_identifiers_[category] = framework_->GetEventManager()->QueryEventCategory(category.toStdString());
}
void ObjectCameraController::PostInitialize()
{
// Get all category id's that we are interested in
SubscribeToEventCategories();
// Register building key context
input_context_ = framework_->Input()->RegisterInputContext("ObjectCameraContext", 100);
connect(input_context_.get(), SIGNAL(KeyPressed(KeyEvent*)), this, SLOT(KeyPressed(KeyEvent*)));
connect(input_context_.get(), SIGNAL(KeyReleased(KeyEvent*)), this, SLOT(KeyReleased(KeyEvent*)));
connect(input_context_.get(), SIGNAL(MouseMove(MouseEvent*)), this, SLOT(MouseMove(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseLeftPressed(MouseEvent*)), this, SLOT(MouseLeftPressed(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseLeftReleased(MouseEvent*)), this, SLOT(MouseLeftReleased(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseScroll(MouseEvent*)), this, SLOT(MouseScroll(MouseEvent*)));
connect(input_context_.get(), SIGNAL(MouseDoubleClicked(MouseEvent*)), this, SLOT(MouseDoubleClicked(MouseEvent*)));
connect(framework_->GetFrame(), SIGNAL(Updated(float)), this, SLOT(Update(float)));
connect(timeline_, SIGNAL(frameChanged(int)), this, SLOT(FrameChanged(int)));
connect(timeline_, SIGNAL(finished()), this, SLOT(TimeLineFinished()));
}
bool ObjectCameraController::HandleInputEvent(event_id_t event_id, IEventData* data)
{
return false;
}
bool ObjectCameraController::HandleSceneEvent(event_id_t event_id, IEventData* data)
{
return false;
}
bool ObjectCameraController::HandleFrameworkEvent(event_id_t event_id, IEventData* data)
{
if (event_id == Foundation::WORLD_STREAM_READY)
{
CreateCustomCamera();
}
return false;
}
void ObjectCameraController::EntityClicked(Scene::Entity* entity)
{
if (!entity || !camera_entity_)
return;
if (timeline_->state() == QTimeLine::Running)
return;
if (alt_key_pressed_)
{
ec_camera_ = camera_entity_->GetComponent<OgreRenderer::EC_OgreCamera>().get();
cam_ec_placable_ = camera_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
OgreRenderer::EC_OgrePlaceable *camera_placeable = 0;
vectors_position_.first = Vector3df::ZERO;
vectors_position_.second = Vector3df::ZERO;
if (!selected_entity_)
{
cam_ec_placable_->SetPosition(camera_controllable_->GetCameraEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>().get()->GetPosition());
vectors_lookat_.first = camera_controllable_->GetThirdPersonLookAt();
avatar_camera_position_ = cam_ec_placable_->GetPosition();
avatar_camera_lookat_ = camera_controllable_->GetThirdPersonLookAt();
}
else
{
camera_placeable = selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
vectors_lookat_.first = camera_placeable->GetPosition();
}
OgreRenderer::EC_OgrePlaceable *entity_ec_placable = entity->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (entity_ec_placable)
{
cam_ec_placable_->LookAt(vectors_lookat_.first);
ec_camera_->SetActive();
object_selected_ = true;
selected_entity_ = entity;
QCursor *current_cur = QApplication::overrideCursor();
if (current_cur)
if (current_cur->shape() != Qt::SizeAllCursor)
QApplication::setOverrideCursor(Qt::SizeAllCursor);
vectors_lookat_.second = entity_ec_placable->GetPosition();
timeline_->start();
}
}
}
void ObjectCameraController::KeyPressed(KeyEvent* key_event)
{
if (key_event->keyCode == Qt::Key_Alt)
{
alt_key_pressed_ = true;
QApplication::setOverrideCursor(Qt::PointingHandCursor);
}
if (key_event->keyCode == Qt::Key_Left || key_event->keyCode == Qt::Key_Right || key_event->keyCode == Qt::Key_Up || key_event->keyCode == Qt::Key_Down)
{
if (object_selected_)
{
if (zoom_close_)
return;
ReturnToAvatarCamera();
}
}
}
void ObjectCameraController::MouseMove(MouseEvent* mouse)
{
if (object_selected_ && left_mousebutton_pressed_)
{
float width = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowWidth();
float height = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowHeight();
RotateObject(2*PI*mouse->relativeX/width, 2*PI*mouse->relativeY/height);
}
}
void ObjectCameraController::MouseLeftPressed(MouseEvent* mouse)
{
left_mousebutton_pressed_ = true;
}
void ObjectCameraController::MouseLeftReleased(MouseEvent* mouse)
{
left_mousebutton_pressed_ = false;
}
void ObjectCameraController::KeyReleased(KeyEvent* key_event)
{
if (key_event->keyCode == Qt::Key_Alt)
{
QCursor *current_cur = QApplication::overrideCursor();
if (!object_selected_)
{
while (current_cur)
{
QApplication::restoreOverrideCursor();
current_cur = QApplication::overrideCursor();
}
}
else
{
if (current_cur)
if (current_cur->shape() == Qt::PointingHandCursor)
QApplication::restoreOverrideCursor();
}
alt_key_pressed_ = false;
}
}
void ObjectCameraController::MouseScroll(MouseEvent* mouse)
{
if (object_selected_)
{
if (! selected_entity_)
return;
OgreRenderer::EC_OgrePlaceable *entity_ec_placable = selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (!entity_ec_placable)
return;
ZoomRelativeToPoint(entity_ec_placable->GetPosition(), mouse->RelativeZ());
}
}
void ObjectCameraController::MouseDoubleClicked(MouseEvent *mouse)
{
if (object_selected_)
{
if (! selected_entity_)
return;
zoom_close_ = true;
}
}
void ObjectCameraController::RotateObject(qreal x, qreal y)
{
if (selected_entity_)
{
OgreRenderer::EC_OgrePlaceable *entity_ec_placable = selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (entity_ec_placable)
{
qreal acceleration_x = 1;
qreal acceleration_y = 1;
RotateCamera(entity_ec_placable->GetPosition(),selected_camera_id_,x*acceleration_x,y*acceleration_y);
}
}
}
void ObjectCameraController::RotateCamera(Vector3df pivot, CameraID id, qreal x, qreal y)
{
if (!ec_camera_ || !cam_ec_placable_)
return;
Ogre::Camera* cam = ec_camera_->GetCamera();
Vector3df pos = cam_ec_placable_->GetPosition();
Vector3df dir(pos-pivot);
Quaternion quat(-x,cam_ec_placable_->GetLocalYAxis());
quat *= Quaternion(-y, cam_ec_placable_->GetLocalXAxis());
dir = quat * dir;
Vector3df new_pos(pivot+dir);
cam_ec_placable_->SetPosition(new_pos);
cam_ec_placable_->LookAt(pivot);
last_dir_=pivot - cam_ec_placable_->GetPosition();
}
void ObjectCameraController::CreateCustomCamera()
{
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
if (!scene)
return;
Scene::EntityPtr cam_entity = scene->CreateEntity(scene->GetNextFreeId());
if (!cam_entity.get())
return;
cam_entity->AddComponent(framework_->GetComponentManager()->CreateComponent(OgreRenderer::EC_OgrePlaceable::TypeNameStatic()));
cam_entity->AddComponent(framework_->GetComponentManager()->CreateComponent(OgreRenderer::EC_OgreCamera::TypeNameStatic()));
scene->EmitEntityCreated(cam_entity);
ComponentPtr component_placable = cam_entity->GetComponent(OgreRenderer::EC_OgrePlaceable::TypeNameStatic());
OgreRenderer::EC_OgreCamera *ec_camera = cam_entity->GetComponent<OgreRenderer::EC_OgreCamera>().get();
if (!component_placable.get() || !ec_camera)
return;
ec_camera->SetPlaceable(component_placable);
camera_entity_ = cam_entity;
}
void ObjectCameraController::ZoomRelativeToPoint(Vector3df point, qreal delta, qreal min, qreal max)
{
bool zoomed = false;
if (!camera_entity_)
return;
if (!cam_ec_placable_)
return;
Vector3df pos = cam_ec_placable_->GetPosition();
Vector3df dir = point-pos;
Vector3df distance = dir;
dir.normalize();
qreal acceleration = 0.01;
dir *= (delta * acceleration);
if (delta>0 && (distance.getLength()+dir.getLength() > min))
{
zoomed = true;
}
if (delta<0 && (distance.getLength()+dir.getLength() <max))
{
zoomed = true;
}
if (zoomed)
{
cam_ec_placable_->SetPosition(cam_ec_placable_->GetPosition() + dir);
}
}
void ObjectCameraController::Update(float frametime)
{
if(zoom_close_)
{
ZoomCloseToPoint(selected_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get()->GetPosition());
}
}
void ObjectCameraController::FrameChanged(int frame)
{
qreal step = frame;
step /= 100;
if (vectors_position_.first != Vector3df::ZERO && vectors_position_.second != Vector3df::ZERO)
{
Vector3df position_start = vectors_position_.first;
Vector3df position_end = vectors_position_.second;
Vector3df position;
position.x = (position_end.x - position_start.x) * step + position_start.x;
position.y = (position_end.y - position_start.y) * step + position_start.y;
position.z = (position_end.z - position_start.z) * step + position_start.z;
cam_ec_placable_->SetPosition(position);
}
if (vectors_lookat_.first != Vector3df::ZERO && vectors_lookat_.second != Vector3df::ZERO)
{
Vector3df lookat_start = vectors_lookat_.first;
Vector3df lookat_end = vectors_lookat_.second;
Vector3df look_at;
look_at.x = (lookat_end.x - lookat_start.x) * step + lookat_start.x;
look_at.y = (lookat_end.y - lookat_start.y) * step + lookat_start.y;
look_at.z = (lookat_end.z - lookat_start.z) * step + lookat_start.z;
cam_ec_placable_->LookAt(look_at);
}
}
void ObjectCameraController::TimeLineFinished()
{
if (vectors_position_.first != Vector3df::ZERO && vectors_position_.second != Vector3df::ZERO)
{
camera_controllable_->GetCameraEntity()->GetComponent<OgreRenderer::EC_OgreCamera>().get()->SetActive();
event_category_id_t event_category = framework_->GetEventManager()->QueryEventCategory("Input");
framework_->GetEventManager()->SendEvent(event_category, Input::Events::INPUTSTATE_THIRDPERSON, 0);
object_selected_ = false;
selected_entity_ = 0;
QCursor *current_cur = QApplication::overrideCursor();
while (current_cur)
{
QApplication::restoreOverrideCursor();
current_cur = QApplication::overrideCursor();
}
}
}
void ObjectCameraController::ReturnToAvatarCamera()
{
OgreRenderer::EC_OgrePlaceable *cam_placable = camera_entity_->GetComponent<OgreRenderer::EC_OgrePlaceable>().get();
if (!cam_placable)
return;
if (timeline_->state() == QTimeLine::Running)
return;
vectors_position_.first = cam_placable->GetPosition();
vectors_position_.second = avatar_camera_position_;
vectors_lookat_.first = vectors_lookat_.second;
vectors_lookat_.second = avatar_camera_lookat_;
timeline_->start();
}
void ObjectCameraController::ZoomCloseToPoint(Vector3df point, qreal delta, qreal min)
{
if (!camera_entity_)
return;
if (!cam_ec_placable_)
return;
Vector3df pos = cam_ec_placable_->GetPosition();
Vector3df dir = point-pos;
Vector3df distance = dir;
dir.normalize();
qreal acceleration = 0.005;
dir *= (delta * acceleration);
if (distance.getLength()+dir.getLength() > min)
{
cam_ec_placable_->SetPosition(cam_ec_placable_->GetPosition() + dir);
} else
{
zoom_close_ = false;
}
}
}
<|endoftext|> |
<commit_before>///
/// @file EratBig.cpp
/// @brief Segmented sieve of Eratosthenes optimized for big sieving
/// primes. This is an optimized implementation of Tomas
/// Oliveira e Silva's cache-friendly bucket sieve algorithm:
/// http://www.ieeta.pt/~tos/software/prime_sieve.html
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/EratBig.hpp>
#include <primesieve/pmath.hpp>
#include <primesieve/primesieve_error.hpp>
#include <primesieve/Wheel.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <memory>
#include <vector>
namespace primesieve {
/// @param stop Upper bound for sieving.
/// @param sieveSize Sieve size in bytes.
/// @param limit Sieving primes must be <= limit,
/// usually limit = sqrt(stop).
///
EratBig::EratBig(uint64_t stop, uint_t sieveSize, uint_t limit) :
Modulo210Wheel_t(stop, sieveSize),
limit_(limit),
log2SieveSize_(ilog2(sieveSize)),
moduloSieveSize_(sieveSize - 1),
stock_(nullptr)
{
// '>> log2SieveSize' requires a power of 2 sieveSize
if (!isPowerOf2(sieveSize))
throw primesieve_error("EratBig: sieveSize must be a power of 2");
init(sieveSize);
}
void EratBig::init(uint_t sieveSize)
{
uint_t maxSievingPrime = limit_ / NUMBERS_PER_BYTE;
uint_t maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor();
uint_t maxMultipleIndex = sieveSize - 1 + maxNextMultiple;
uint_t maxSegmentCount = maxMultipleIndex >> log2SieveSize_;
uint_t size = maxSegmentCount + 1;
// EratBig uses up to 1.6 gigabytes of memory
memory_.reserve(((1u << 30) * 2) / config::BYTES_PER_ALLOC);
lists_.resize(size, nullptr);
for (uint_t i = 0; i < size; i++)
pushBucket(i);
}
/// Add a new sieving prime to EratBig
void EratBig::storeSievingPrime(uint_t prime, uint_t multipleIndex, uint_t wheelIndex)
{
assert(prime <= limit_);
uint_t sievingPrime = prime / NUMBERS_PER_BYTE;
uint_t segment = multipleIndex >> log2SieveSize_;
multipleIndex &= moduloSieveSize_;
if (!lists_[segment]->store(sievingPrime, multipleIndex, wheelIndex))
pushBucket(segment);
}
/// Add an empty bucket to the front of lists_[segment]
void EratBig::pushBucket(uint_t segment)
{
// allocate new buckets
if (!stock_)
{
int N = config::BYTES_PER_ALLOC / sizeof(Bucket);
memory_.emplace_back(std::unique_ptr<Bucket[]>(new Bucket[N]));
Bucket* bucket = memory_.back().get();
for (int i = 0; i < N - 1; i++)
bucket[i].setNext(&bucket[i + 1]);
bucket[N-1].setNext(nullptr);
stock_ = bucket;
}
Bucket* emptyBucket = stock_;
stock_ = stock_->next();
moveBucket(*emptyBucket, lists_[segment]);
}
void EratBig::moveBucket(Bucket& src, Bucket*& dest)
{
src.setNext(dest);
dest = &src;
}
/// Cross-off the multiples of big sieving primes
/// from the sieve array.
///
void EratBig::crossOff(byte_t* sieve)
{
// process the buckets in lists_[0] which hold the sieving primes
// that have multiple(s) in the current segment
while (lists_[0]->hasNext() || !lists_[0]->empty())
{
Bucket* bucket = lists_[0];
lists_[0] = nullptr;
pushBucket(0);
do {
crossOff(sieve, bucket->begin(), bucket->end());
Bucket* processed = bucket;
bucket = bucket->next();
processed->reset();
moveBucket(*processed, stock_);
} while (bucket);
}
// move the list corresponding to the next segment
// i.e. lists_[1] to lists_[0] ...
std::rotate(lists_.begin(), lists_.begin() + 1, lists_.end());
}
/// Cross-off the next multiple of each sieving prime within the
/// current bucket. This is an implementation of the segmented sieve
/// of Eratosthenes with wheel factorization optimized for big sieving
/// primes that have very few multiples per segment. This algorithm
/// uses a modulo 210 wheel that skips multiples of 2, 3, 5 and 7.
///
void EratBig::crossOff(byte_t* sieve, SievingPrime* sPrime, SievingPrime* sEnd)
{
Bucket** lists = &lists_[0];
uint_t moduloSieveSize = moduloSieveSize_;
uint_t log2SieveSize = log2SieveSize_;
// 2 sieving primes are processed per loop iteration
// to increase instruction level parallelism
for (; sPrime + 2 <= sEnd; sPrime += 2)
{
uint_t multipleIndex0 = sPrime[0].getMultipleIndex();
uint_t wheelIndex0 = sPrime[0].getWheelIndex();
uint_t sievingPrime0 = sPrime[0].getSievingPrime();
uint_t multipleIndex1 = sPrime[1].getMultipleIndex();
uint_t wheelIndex1 = sPrime[1].getWheelIndex();
uint_t sievingPrime1 = sPrime[1].getSievingPrime();
// cross-off the current multiple (unset bit)
// and calculate the next multiple
unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
uint_t segment0 = multipleIndex0 >> log2SieveSize;
uint_t segment1 = multipleIndex1 >> log2SieveSize;
multipleIndex0 &= moduloSieveSize;
multipleIndex1 &= moduloSieveSize;
// move the 2 sieving primes to the list related
// to their next multiple
if (!lists[segment0]->store(sievingPrime0, multipleIndex0, wheelIndex0))
pushBucket(segment0);
if (!lists[segment1]->store(sievingPrime1, multipleIndex1, wheelIndex1))
pushBucket(segment1);
}
if (sPrime != sEnd)
{
uint_t multipleIndex = sPrime->getMultipleIndex();
uint_t wheelIndex = sPrime->getWheelIndex();
uint_t sievingPrime = sPrime->getSievingPrime();
unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex);
uint_t segment = multipleIndex >> log2SieveSize;
multipleIndex &= moduloSieveSize;
if (!lists[segment]->store(sievingPrime, multipleIndex, wheelIndex))
pushBucket(segment);
}
}
} // namespace
<commit_msg>Update comments<commit_after>///
/// @file EratBig.cpp
/// @brief Segmented sieve of Eratosthenes optimized for big sieving
/// primes. This is an optimized implementation of Tomas
/// Oliveira e Silva's cache-friendly bucket sieve algorithm:
/// http://www.ieeta.pt/~tos/software/prime_sieve.html
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/EratBig.hpp>
#include <primesieve/pmath.hpp>
#include <primesieve/primesieve_error.hpp>
#include <primesieve/Wheel.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <memory>
#include <vector>
namespace primesieve {
/// @stop: Upper bound for sieving
/// @sieveSize: Sieve size in bytes
/// @limit: Sieving primes must be <= limit,
/// usually limit = sqrt(stop)
///
EratBig::EratBig(uint64_t stop, uint_t sieveSize, uint_t limit) :
Modulo210Wheel_t(stop, sieveSize),
limit_(limit),
log2SieveSize_(ilog2(sieveSize)),
moduloSieveSize_(sieveSize - 1),
stock_(nullptr)
{
// '>> log2SieveSize' requires power of 2 sieveSize
if (!isPowerOf2(sieveSize))
throw primesieve_error("EratBig: sieveSize must be a power of 2");
init(sieveSize);
}
void EratBig::init(uint_t sieveSize)
{
uint_t maxSievingPrime = limit_ / NUMBERS_PER_BYTE;
uint_t maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor();
uint_t maxMultipleIndex = sieveSize - 1 + maxNextMultiple;
uint_t maxSegmentCount = maxMultipleIndex >> log2SieveSize_;
uint_t size = maxSegmentCount + 1;
// EratBig uses up to 1.6 gigabytes of memory
memory_.reserve(((1u << 30) * 2) / config::BYTES_PER_ALLOC);
lists_.resize(size, nullptr);
for (uint_t i = 0; i < size; i++)
pushBucket(i);
}
/// Add a new sieving prime to EratBig
void EratBig::storeSievingPrime(uint_t prime, uint_t multipleIndex, uint_t wheelIndex)
{
assert(prime <= limit_);
uint_t sievingPrime = prime / NUMBERS_PER_BYTE;
uint_t segment = multipleIndex >> log2SieveSize_;
multipleIndex &= moduloSieveSize_;
if (!lists_[segment]->store(sievingPrime, multipleIndex, wheelIndex))
pushBucket(segment);
}
/// Add an empty bucket to the front of lists_[segment]
void EratBig::pushBucket(uint_t segment)
{
// allocate new buckets
if (!stock_)
{
int N = config::BYTES_PER_ALLOC / sizeof(Bucket);
memory_.emplace_back(unique_ptr<Bucket[]>(new Bucket[N]));
Bucket* bucket = memory_.back().get();
for (int i = 0; i < N - 1; i++)
bucket[i].setNext(&bucket[i + 1]);
bucket[N-1].setNext(nullptr);
stock_ = bucket;
}
Bucket* emptyBucket = stock_;
stock_ = stock_->next();
moveBucket(*emptyBucket, lists_[segment]);
}
void EratBig::moveBucket(Bucket& src, Bucket*& dest)
{
src.setNext(dest);
dest = &src;
}
/// Cross-off the multiples of big sieving
/// primes from the sieve array
///
void EratBig::crossOff(byte_t* sieve)
{
while (lists_[0]->hasNext() || !lists_[0]->empty())
{
Bucket* bucket = lists_[0];
lists_[0] = nullptr;
pushBucket(0);
do {
crossOff(sieve, bucket->begin(), bucket->end());
Bucket* processed = bucket;
bucket = bucket->next();
processed->reset();
moveBucket(*processed, stock_);
} while (bucket);
}
rotate(lists_.begin(), lists_.begin() + 1, lists_.end());
}
/// Cross-off the next multiple of each sieving prime in the
/// current bucket. This is an implementation of the segmented
/// sieve of Eratosthenes with wheel factorization optimized for
/// big sieving primes that have very few multiples per segment
///
void EratBig::crossOff(byte_t* sieve, SievingPrime* sPrime, SievingPrime* sEnd)
{
Bucket** lists = &lists_[0];
uint_t moduloSieveSize = moduloSieveSize_;
uint_t log2SieveSize = log2SieveSize_;
// 2 sieving primes are processed per loop iteration
// to increase instruction level parallelism
for (; sPrime + 2 <= sEnd; sPrime += 2)
{
uint_t multipleIndex0 = sPrime[0].getMultipleIndex();
uint_t wheelIndex0 = sPrime[0].getWheelIndex();
uint_t sievingPrime0 = sPrime[0].getSievingPrime();
uint_t multipleIndex1 = sPrime[1].getMultipleIndex();
uint_t wheelIndex1 = sPrime[1].getWheelIndex();
uint_t sievingPrime1 = sPrime[1].getSievingPrime();
// cross-off the current multiple (unset bit)
// and calculate the next multiple
unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
uint_t segment0 = multipleIndex0 >> log2SieveSize;
uint_t segment1 = multipleIndex1 >> log2SieveSize;
multipleIndex0 &= moduloSieveSize;
multipleIndex1 &= moduloSieveSize;
// move the 2 sieving primes to the list related
// to their next multiple
if (!lists[segment0]->store(sievingPrime0, multipleIndex0, wheelIndex0))
pushBucket(segment0);
if (!lists[segment1]->store(sievingPrime1, multipleIndex1, wheelIndex1))
pushBucket(segment1);
}
if (sPrime != sEnd)
{
uint_t multipleIndex = sPrime->getMultipleIndex();
uint_t wheelIndex = sPrime->getWheelIndex();
uint_t sievingPrime = sPrime->getSievingPrime();
unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex);
uint_t segment = multipleIndex >> log2SieveSize;
multipleIndex &= moduloSieveSize;
if (!lists[segment]->store(sievingPrime, multipleIndex, wheelIndex))
pushBucket(segment);
}
}
} // namespace
<|endoftext|> |
<commit_before>#ifndef INCLUDED_EMPLACE_INSERT_ITERATOR
#define INCLUDED_EMPLACE_INSERT_ITERATOR
#include<iterator>
#ifdef __GXX_EXPERIMENTAL_CXX0X__
namespace srook{
inline namespace v1{
template<class Container>
class emplace_insert_iterator:
public std::iterator<std::output_iterator_tag,void,void,void,void>{
protected:
Container* container;
typename Container::iterator iter;
public:
typedef Container container_type;
emplace_insert_iterator(Container& x,typename Container::iterator i)
:container(&x),iter(i)
{}
emplace_insert_iterator&
operator=(typename Container::value_type& value)
{
iter=container->emplace(iter,value);
++iter;
return *this;
}
emplace_insert_iterator&
operator=(typename Container::value_type&& value)
{
iter=container->emplace(iter,std::move(value));
++iter;
return *this;
}
emplace_insert_iterator&
operator*()
{
return *this;
}
emplace_insert_iterator&
operator++()
{
return *this;
}
emplace_insert_iterator&
operator++(int)
{
return *this;
}
};
template<class Container,class Iterator>
inline emplace_insert_iterator<Container>
emplace_inserter(Container& x,Iterator i)
{
return emplace_insert_iterator<Container>(x,typename Container::iterator(i));
}
}
}
#endif
#endif
<commit_msg>Update emplace_insert_iterator.hpp<commit_after>#ifndef INCLUDED_EMPLACE_INSERT_ITERATOR
#define INCLUDED_EMPLACE_INSERT_ITERATOR
#include<iterator>
#ifdef __GXX_EXPERIMENTAL_CXX0X__
namespace srook{
inline namespace v1{
template<class Container>
class emplace_insert_iterator:
public std::iterator<std::output_iterator_tag,void,void,void,void>{
protected:
Container* container;
typename Container::iterator iter;
public:
typedef Container container_type;
emplace_insert_iterator(Container& x,typename Container::iterator i)
:container(&x),iter(i)
{}
emplace_insert_iterator&
operator=(const typename Container::value_type& value)
{
iter=container->emplace(iter,value);
++iter;
return *this;
}
emplace_insert_iterator&
operator=(const typename Container::value_type&& value)
{
iter=container->emplace(iter,std::move(value));
++iter;
return *this;
}
emplace_insert_iterator&
operator*()
{
return *this;
}
emplace_insert_iterator&
operator++()
{
return *this;
}
emplace_insert_iterator&
operator++(int)
{
return *this;
}
};
template<class Container,class Iterator>
inline emplace_insert_iterator<Container>
emplace_inserter(Container& x,Iterator i)
{
return emplace_insert_iterator<Container>(x,typename Container::iterator(i));
}
}
}
#endif
#endif
<|endoftext|> |
<commit_before>#include <itkImageRegionConstIterator.h>
#include <itkPasteImageFilter.h>
#include <itksys/SystemTools.hxx>
#include <itkJoinSeriesImageFilter.h>
#include "rtkTestConfiguration.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
#include "rtkFourDROOSTERConeBeamReconstructionFilter.h"
#include "rtkPhasesToInterpolationWeights.h"
template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
ImageIteratorType itRef( ref, ref->GetBufferedRegion() );
typedef double ErrorType;
ErrorType TestError = 0.;
ErrorType EnerError = 0.;
itTest.GoToBegin();
itRef.GoToBegin();
while( !itRef.IsAtEnd() )
{
typename TImage::PixelType TestVal = itTest.Get();
typename TImage::PixelType RefVal = itRef.Get();
TestError += vcl_abs(RefVal - TestVal);
EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
++itTest;
++itRef;
}
// Error per Pixel
ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
// MSE
ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "MSE = " << MSE << std::endl;
// PSNR
ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
std::cout << "PSNR = " << PSNR << "dB" << std::endl;
// QI
ErrorType QI = (2.0-ErrorPerPixel)/2.0;
std::cout << "QI = " << QI << std::endl;
// Checking results
if (ErrorPerPixel > 0.25)
{
std::cerr << "Test Failed, Error per pixel not valid! "
<< ErrorPerPixel << " instead of 0.25." << std::endl;
exit( EXIT_FAILURE);
}
if (PSNR < 15.)
{
std::cerr << "Test Failed, PSNR not valid! "
<< PSNR << " instead of 15" << std::endl;
exit( EXIT_FAILURE);
}
}
#endif
/**
* \file rtkfourdconjugategradienttest.cxx
*
* \brief Functional test for classes performing 4D conjugate gradient-based
* reconstruction.
*
* This test generates the projections of a phantom, which consists of two
* ellipsoids (one of them moving). The resulting moving phantom is
* reconstructed using 4D conjugate gradient and the generated
* result is compared to the expected results (analytical computation).
*
* \author Cyril Mory
*/
int main(int, char** )
{
typedef float OutputPixelType;
#ifdef RTK_USE_CUDA
typedef itk::CudaImage< OutputPixelType, 4 > VolumeSeriesType;
typedef itk::CudaImage< OutputPixelType, 3 > ProjectionStackType;
typedef itk::CudaImage< OutputPixelType, 3 > VolumeType;
#else
typedef itk::Image< OutputPixelType, 4 > VolumeSeriesType;
typedef itk::Image< OutputPixelType, 3 > ProjectionStackType;
typedef itk::Image< OutputPixelType, 3 > VolumeType;
#endif
#if FAST_TESTS_NO_CHECKS
const unsigned int NumberOfProjectionImages = 5;
#else
const unsigned int NumberOfProjectionImages = 64;
#endif
// Constant image sources
typedef rtk::ConstantImageSource< VolumeType > ConstantImageSourceType;
ConstantImageSourceType::PointType origin;
ConstantImageSourceType::SizeType size;
ConstantImageSourceType::SpacingType spacing;
typedef rtk::ConstantImageSource< VolumeSeriesType > FourDSourceType;
FourDSourceType::PointType fourDOrigin;
FourDSourceType::SizeType fourDSize;
FourDSourceType::SpacingType fourdDSpacing;
ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();
origin[0] = -63.;
origin[1] = -31.;
origin[2] = -63.;
#if FAST_TESTS_NO_CHECKS
size[0] = 8;
size[1] = 8;
size[2] = 8;
spacing[0] = 16.;
spacing[1] = 8.;
spacing[2] = 16.;
#else
size[0] = 32;
size[1] = 16;
size[2] = 32;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
#endif
tomographySource->SetOrigin( origin );
tomographySource->SetSpacing( spacing );
tomographySource->SetSize( size );
tomographySource->SetConstant( 0. );
FourDSourceType::Pointer fourdSource = FourDSourceType::New();
fourDOrigin[0] = -63.;
fourDOrigin[1] = -31.;
fourDOrigin[2] = -63.;
fourDOrigin[3] = 0;
#if FAST_TESTS_NO_CHECKS
fourDSize[0] = 8;
fourDSize[1] = 8;
fourDSize[2] = 8;
fourDSize[3] = 2;
fourdDSpacing[0] = 16.;
fourdDSpacing[1] = 8.;
fourdDSpacing[2] = 16.;
fourdDSpacing[3] = 1.;
#else
fourDSize[0] = 32;
fourDSize[1] = 16;
fourDSize[2] = 32;
fourDSize[3] = 8;
fourdDSpacing[0] = 4.;
fourdDSpacing[1] = 4.;
fourdDSpacing[2] = 4.;
fourdDSpacing[3] = 1.;
#endif
fourdSource->SetOrigin( fourDOrigin );
fourdSource->SetSpacing( fourdDSpacing );
fourdSource->SetSize( fourDSize );
fourdSource->SetConstant( 0. );
ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
origin[0] = -254.;
origin[1] = -254.;
origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
size[0] = 32;
size[1] = 32;
size[2] = NumberOfProjectionImages;
spacing[0] = 32.;
spacing[1] = 32.;
spacing[2] = 32.;
#else
size[0] = 64;
size[1] = 64;
size[2] = NumberOfProjectionImages;
spacing[0] = 8.;
spacing[1] = 8.;
spacing[2] = 1.;
#endif
projectionsSource->SetOrigin( origin );
projectionsSource->SetSpacing( spacing );
projectionsSource->SetSize( size );
projectionsSource->SetConstant( 0. );
ConstantImageSourceType::Pointer oneProjectionSource = ConstantImageSourceType::New();
size[2] = 1;
oneProjectionSource->SetOrigin( origin );
oneProjectionSource->SetSpacing( spacing );
oneProjectionSource->SetSize( size );
oneProjectionSource->SetConstant( 0. );
// Geometry object
typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
GeometryType::Pointer geometry = GeometryType::New();
// Projections
typedef rtk::RayEllipsoidIntersectionImageFilter<VolumeType, ProjectionStackType> REIType;
typedef itk::PasteImageFilter <ProjectionStackType, ProjectionStackType, ProjectionStackType > PasteImageFilterType;
ProjectionStackType::IndexType destinationIndex;
destinationIndex[0] = 0;
destinationIndex[1] = 0;
destinationIndex[2] = 0;
PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();
std::ofstream signalFile("signal.txt");
ProjectionStackType::Pointer wholeImage = projectionsSource->GetOutput();
for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
{
geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Geometry object
GeometryType::Pointer oneProjGeometry = GeometryType::New();
oneProjGeometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Ellipse 1
REIType::Pointer e1 = REIType::New();
REIType::VectorType semiprincipalaxis, center;
semiprincipalaxis.Fill(60.);
semiprincipalaxis[1]=30;
center.Fill(0.);
e1->SetInput(oneProjectionSource->GetOutput());
e1->SetGeometry(oneProjGeometry);
e1->SetDensity(2.);
e1->SetAxis(semiprincipalaxis);
e1->SetCenter(center);
e1->SetAngle(0.);
e1->InPlaceOff();
e1->Update();
// Ellipse 2
REIType::Pointer e2 = REIType::New();
semiprincipalaxis.Fill(8.);
center[0] = 4*(vcl_abs( (4+noProj) % 8 - 4.) - 2.);
center[1] = 0.;
center[2] = 0.;
e2->SetInput(e1->GetOutput());
e2->SetGeometry(oneProjGeometry);
e2->SetDensity(-1.);
e2->SetAxis(semiprincipalaxis);
e2->SetCenter(center);
e2->SetAngle(0.);
e2->Update();
// Adding each projection to the projection stack
pasteFilter->SetSourceImage(e2->GetOutput());
pasteFilter->SetDestinationImage(wholeImage);
pasteFilter->SetSourceRegion(e2->GetOutput()->GetLargestPossibleRegion());
pasteFilter->SetDestinationIndex(destinationIndex);
pasteFilter->Update();
wholeImage = pasteFilter->GetOutput();
wholeImage->DisconnectPipeline();
destinationIndex[2]++;
// Signal
signalFile << (noProj % 8) / 8. << std::endl;
}
// Ground truth
VolumeType::Pointer * Volumes = new VolumeType::Pointer[fourDSize[3]];
typedef itk::JoinSeriesImageFilter<VolumeType, VolumeSeriesType> JoinFilterType;
JoinFilterType::Pointer join = JoinFilterType::New();
for (itk::SizeValueType n = 0; n < fourDSize[3]; n++)
{
// Ellipse 1
typedef rtk::DrawEllipsoidImageFilter<VolumeType, VolumeType> DEType;
DEType::Pointer de1 = DEType::New();
de1->SetInput( tomographySource->GetOutput() );
de1->SetDensity(2.);
DEType::VectorType axis;
axis.Fill(60.);
axis[1]=30;
de1->SetAxis(axis);
DEType::VectorType center;
center.Fill(0.);
de1->SetCenter(center);
de1->SetAngle(0.);
de1->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( de1->Update() )
// Ellipse 2
DEType::Pointer de2 = DEType::New();
de2->SetInput(de1->GetOutput());
de2->SetDensity(-1.);
DEType::VectorType axis2;
axis2.Fill(8.);
de2->SetAxis(axis2);
DEType::VectorType center2;
center2[0] = 4*(vcl_abs( (4+n) % 8 - 4.) - 2.);
center2[1] = 0.;
center2[2] = 0.;
de2->SetCenter(center2);
de2->SetAngle(0.);
de2->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( de2->Update() );
Volumes[n] = de2->GetOutput();
Volumes[n]->DisconnectPipeline();
join->SetInput(n, Volumes[n]);
}
join->Update();
// ROI
typedef rtk::DrawEllipsoidImageFilter<VolumeType, VolumeType> DEType;
DEType::Pointer roi = DEType::New();
roi->SetInput( tomographySource->GetOutput() );
roi->SetDensity(1.);
DEType::VectorType axis;
axis.Fill(15.);
axis[0]=20;
roi->SetAxis(axis);
DEType::VectorType center;
center.Fill(0.);
roi->SetCenter(center);
roi->SetAngle(0.);
roi->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( roi->Update() )
// Read the phases file
rtk::PhasesToInterpolationWeights::Pointer phaseReader = rtk::PhasesToInterpolationWeights::New();
phaseReader->SetFileName("signal.txt");
phaseReader->SetNumberOfReconstructedPhases( fourDSize[3] );
phaseReader->Update();
// Set the forward and back projection filters to be used
typedef rtk::FourDROOSTERConeBeamReconstructionFilter<VolumeSeriesType, ProjectionStackType> ROOSTERFilterType;
ROOSTERFilterType::Pointer rooster = ROOSTERFilterType::New();
rooster->SetInputVolumeSeries(fourdSource->GetOutput() );
rooster->SetInputProjectionStack(wholeImage);
rooster->SetGeometry(geometry);
rooster->SetWeights(phaseReader->GetOutput());
rooster->SetInputROI(roi->GetOutput());
rooster->SetGeometry( geometry );
rooster->SetCG_iterations( 2 );
rooster->SetMainLoop_iterations( 2);
rooster->SetTV_iterations( 3 );
rooster->SetGammaSpace(1);
rooster->SetGammaTime(0.1);
std::cout << "\n\n****** Case 1: Voxel-Based Backprojector ******" << std::endl;
rooster->SetBackProjectionFilter( 0 ); // Voxel based
rooster->SetForwardProjectionFilter( 0 ); // Joseph
TRY_AND_EXIT_ON_ITK_EXCEPTION( rooster->Update() );
CheckImageQuality<VolumeSeriesType>(rooster->GetOutput(), join->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
#ifdef USE_CUDA
std::cout << "\n\n****** Case 2: CUDA Voxel-Based Backprojector ******" << std::endl;
rooster->SetBackProjectionFilter( 2 ); // Cuda voxel based
rooster->SetForwardProjectionFilter( 2 ); // Cuda ray cast
TRY_AND_EXIT_ON_ITK_EXCEPTION( rooster->Update() );
CheckImageQuality<VolumeSeriesType>(rooster->GetOutput(), join->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
#endif
itksys::SystemTools::RemoveFile("signal.txt");
return EXIT_SUCCESS;
}
<commit_msg>Modified the rtkfourdroostertest to detect NaN results<commit_after>#include <itkImageRegionConstIterator.h>
#include <itkPasteImageFilter.h>
#include <itksys/SystemTools.hxx>
#include <itkJoinSeriesImageFilter.h>
#include "rtkTestConfiguration.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
#include "rtkFourDROOSTERConeBeamReconstructionFilter.h"
#include "rtkPhasesToInterpolationWeights.h"
template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
ImageIteratorType itRef( ref, ref->GetBufferedRegion() );
typedef double ErrorType;
ErrorType TestError = 0.;
ErrorType EnerError = 0.;
itTest.GoToBegin();
itRef.GoToBegin();
while( !itRef.IsAtEnd() )
{
typename TImage::PixelType TestVal = itTest.Get();
typename TImage::PixelType RefVal = itRef.Get();
TestError += vcl_abs(RefVal - TestVal);
EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
++itTest;
++itRef;
}
// Error per Pixel
ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
// MSE
ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "MSE = " << MSE << std::endl;
// PSNR
ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
std::cout << "PSNR = " << PSNR << "dB" << std::endl;
// QI
ErrorType QI = (2.0-ErrorPerPixel)/2.0;
std::cout << "QI = " << QI << std::endl;
// Checking results. As a comparison with NaN always returns false,
// this design allows to detect NaN results and cause test failure
if (ErrorPerPixel < 0.25);
else
{
std::cerr << "Test Failed, Error per pixel not valid! "
<< ErrorPerPixel << " instead of 0.25." << std::endl;
exit( EXIT_FAILURE);
}
if (PSNR > 15.);
else
{
std::cerr << "Test Failed, PSNR not valid! "
<< PSNR << " instead of 15" << std::endl;
exit( EXIT_FAILURE);
}
}
#endif
/**
* \file rtkfourdconjugategradienttest.cxx
*
* \brief Functional test for classes performing 4D conjugate gradient-based
* reconstruction.
*
* This test generates the projections of a phantom, which consists of two
* ellipsoids (one of them moving). The resulting moving phantom is
* reconstructed using 4D conjugate gradient and the generated
* result is compared to the expected results (analytical computation).
*
* \author Cyril Mory
*/
int main(int, char** )
{
typedef float OutputPixelType;
#ifdef RTK_USE_CUDA
typedef itk::CudaImage< OutputPixelType, 4 > VolumeSeriesType;
typedef itk::CudaImage< OutputPixelType, 3 > ProjectionStackType;
typedef itk::CudaImage< OutputPixelType, 3 > VolumeType;
#else
typedef itk::Image< OutputPixelType, 4 > VolumeSeriesType;
typedef itk::Image< OutputPixelType, 3 > ProjectionStackType;
typedef itk::Image< OutputPixelType, 3 > VolumeType;
#endif
#if FAST_TESTS_NO_CHECKS
const unsigned int NumberOfProjectionImages = 5;
#else
const unsigned int NumberOfProjectionImages = 64;
#endif
// Constant image sources
typedef rtk::ConstantImageSource< VolumeType > ConstantImageSourceType;
ConstantImageSourceType::PointType origin;
ConstantImageSourceType::SizeType size;
ConstantImageSourceType::SpacingType spacing;
typedef rtk::ConstantImageSource< VolumeSeriesType > FourDSourceType;
FourDSourceType::PointType fourDOrigin;
FourDSourceType::SizeType fourDSize;
FourDSourceType::SpacingType fourdDSpacing;
ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();
origin[0] = -63.;
origin[1] = -31.;
origin[2] = -63.;
#if FAST_TESTS_NO_CHECKS
size[0] = 8;
size[1] = 8;
size[2] = 8;
spacing[0] = 16.;
spacing[1] = 8.;
spacing[2] = 16.;
#else
size[0] = 32;
size[1] = 16;
size[2] = 32;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
#endif
tomographySource->SetOrigin( origin );
tomographySource->SetSpacing( spacing );
tomographySource->SetSize( size );
tomographySource->SetConstant( 0. );
FourDSourceType::Pointer fourdSource = FourDSourceType::New();
fourDOrigin[0] = -63.;
fourDOrigin[1] = -31.;
fourDOrigin[2] = -63.;
fourDOrigin[3] = 0;
#if FAST_TESTS_NO_CHECKS
fourDSize[0] = 8;
fourDSize[1] = 8;
fourDSize[2] = 8;
fourDSize[3] = 2;
fourdDSpacing[0] = 16.;
fourdDSpacing[1] = 8.;
fourdDSpacing[2] = 16.;
fourdDSpacing[3] = 1.;
#else
fourDSize[0] = 32;
fourDSize[1] = 16;
fourDSize[2] = 32;
fourDSize[3] = 8;
fourdDSpacing[0] = 4.;
fourdDSpacing[1] = 4.;
fourdDSpacing[2] = 4.;
fourdDSpacing[3] = 1.;
#endif
fourdSource->SetOrigin( fourDOrigin );
fourdSource->SetSpacing( fourdDSpacing );
fourdSource->SetSize( fourDSize );
fourdSource->SetConstant( 0. );
ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
origin[0] = -254.;
origin[1] = -254.;
origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
size[0] = 32;
size[1] = 32;
size[2] = NumberOfProjectionImages;
spacing[0] = 32.;
spacing[1] = 32.;
spacing[2] = 32.;
#else
size[0] = 64;
size[1] = 64;
size[2] = NumberOfProjectionImages;
spacing[0] = 8.;
spacing[1] = 8.;
spacing[2] = 1.;
#endif
projectionsSource->SetOrigin( origin );
projectionsSource->SetSpacing( spacing );
projectionsSource->SetSize( size );
projectionsSource->SetConstant( 0. );
ConstantImageSourceType::Pointer oneProjectionSource = ConstantImageSourceType::New();
size[2] = 1;
oneProjectionSource->SetOrigin( origin );
oneProjectionSource->SetSpacing( spacing );
oneProjectionSource->SetSize( size );
oneProjectionSource->SetConstant( 0. );
// Geometry object
typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
GeometryType::Pointer geometry = GeometryType::New();
// Projections
typedef rtk::RayEllipsoidIntersectionImageFilter<VolumeType, ProjectionStackType> REIType;
typedef itk::PasteImageFilter <ProjectionStackType, ProjectionStackType, ProjectionStackType > PasteImageFilterType;
ProjectionStackType::IndexType destinationIndex;
destinationIndex[0] = 0;
destinationIndex[1] = 0;
destinationIndex[2] = 0;
PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();
std::ofstream signalFile("signal.txt");
ProjectionStackType::Pointer wholeImage = projectionsSource->GetOutput();
for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
{
geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Geometry object
GeometryType::Pointer oneProjGeometry = GeometryType::New();
oneProjGeometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Ellipse 1
REIType::Pointer e1 = REIType::New();
REIType::VectorType semiprincipalaxis, center;
semiprincipalaxis.Fill(60.);
semiprincipalaxis[1]=30;
center.Fill(0.);
e1->SetInput(oneProjectionSource->GetOutput());
e1->SetGeometry(oneProjGeometry);
e1->SetDensity(2.);
e1->SetAxis(semiprincipalaxis);
e1->SetCenter(center);
e1->SetAngle(0.);
e1->InPlaceOff();
e1->Update();
// Ellipse 2
REIType::Pointer e2 = REIType::New();
semiprincipalaxis.Fill(8.);
center[0] = 4*(vcl_abs( (4+noProj) % 8 - 4.) - 2.);
center[1] = 0.;
center[2] = 0.;
e2->SetInput(e1->GetOutput());
e2->SetGeometry(oneProjGeometry);
e2->SetDensity(-1.);
e2->SetAxis(semiprincipalaxis);
e2->SetCenter(center);
e2->SetAngle(0.);
e2->Update();
// Adding each projection to the projection stack
pasteFilter->SetSourceImage(e2->GetOutput());
pasteFilter->SetDestinationImage(wholeImage);
pasteFilter->SetSourceRegion(e2->GetOutput()->GetLargestPossibleRegion());
pasteFilter->SetDestinationIndex(destinationIndex);
pasteFilter->Update();
wholeImage = pasteFilter->GetOutput();
wholeImage->DisconnectPipeline();
destinationIndex[2]++;
// Signal
signalFile << (noProj % 8) / 8. << std::endl;
}
// Ground truth
VolumeType::Pointer * Volumes = new VolumeType::Pointer[fourDSize[3]];
typedef itk::JoinSeriesImageFilter<VolumeType, VolumeSeriesType> JoinFilterType;
JoinFilterType::Pointer join = JoinFilterType::New();
for (itk::SizeValueType n = 0; n < fourDSize[3]; n++)
{
// Ellipse 1
typedef rtk::DrawEllipsoidImageFilter<VolumeType, VolumeType> DEType;
DEType::Pointer de1 = DEType::New();
de1->SetInput( tomographySource->GetOutput() );
de1->SetDensity(2.);
DEType::VectorType axis;
axis.Fill(60.);
axis[1]=30;
de1->SetAxis(axis);
DEType::VectorType center;
center.Fill(0.);
de1->SetCenter(center);
de1->SetAngle(0.);
de1->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( de1->Update() )
// Ellipse 2
DEType::Pointer de2 = DEType::New();
de2->SetInput(de1->GetOutput());
de2->SetDensity(-1.);
DEType::VectorType axis2;
axis2.Fill(8.);
de2->SetAxis(axis2);
DEType::VectorType center2;
center2[0] = 4*(vcl_abs( (4+n) % 8 - 4.) - 2.);
center2[1] = 0.;
center2[2] = 0.;
de2->SetCenter(center2);
de2->SetAngle(0.);
de2->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( de2->Update() );
Volumes[n] = de2->GetOutput();
Volumes[n]->DisconnectPipeline();
join->SetInput(n, Volumes[n]);
}
join->Update();
// ROI
typedef rtk::DrawEllipsoidImageFilter<VolumeType, VolumeType> DEType;
DEType::Pointer roi = DEType::New();
roi->SetInput( tomographySource->GetOutput() );
roi->SetDensity(1.);
DEType::VectorType axis;
axis.Fill(15.);
axis[0]=20;
roi->SetAxis(axis);
DEType::VectorType center;
center.Fill(0.);
roi->SetCenter(center);
roi->SetAngle(0.);
roi->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( roi->Update() )
// Read the phases file
rtk::PhasesToInterpolationWeights::Pointer phaseReader = rtk::PhasesToInterpolationWeights::New();
phaseReader->SetFileName("signal.txt");
phaseReader->SetNumberOfReconstructedPhases( fourDSize[3] );
phaseReader->Update();
// Set the forward and back projection filters to be used
typedef rtk::FourDROOSTERConeBeamReconstructionFilter<VolumeSeriesType, ProjectionStackType> ROOSTERFilterType;
ROOSTERFilterType::Pointer rooster = ROOSTERFilterType::New();
rooster->SetInputVolumeSeries(fourdSource->GetOutput() );
rooster->SetInputProjectionStack(wholeImage);
rooster->SetGeometry(geometry);
rooster->SetWeights(phaseReader->GetOutput());
rooster->SetInputROI(roi->GetOutput());
rooster->SetGeometry( geometry );
rooster->SetCG_iterations( 2 );
rooster->SetMainLoop_iterations( 2);
rooster->SetTV_iterations( 3 );
rooster->SetGammaSpace(1);
rooster->SetGammaTime(0.1);
std::cout << "\n\n****** Case 1: Voxel-Based Backprojector ******" << std::endl;
rooster->SetBackProjectionFilter( 0 ); // Voxel based
rooster->SetForwardProjectionFilter( 0 ); // Joseph
TRY_AND_EXIT_ON_ITK_EXCEPTION( rooster->Update() );
CheckImageQuality<VolumeSeriesType>(rooster->GetOutput(), join->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
#ifdef USE_CUDA
std::cout << "\n\n****** Case 2: CUDA Voxel-Based Backprojector ******" << std::endl;
rooster->SetBackProjectionFilter( 2 ); // Cuda voxel based
rooster->SetForwardProjectionFilter( 2 ); // Cuda ray cast
TRY_AND_EXIT_ON_ITK_EXCEPTION( rooster->Update() );
CheckImageQuality<VolumeSeriesType>(rooster->GetOutput(), join->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
#endif
itksys::SystemTools::RemoveFile("signal.txt");
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <USB.h>
#define CDC_ACT_SET_LINE_CODING 1
uint8_t CDCACM::getDescriptorLength() {
return 58;
}
uint8_t CDCACM::getInterfaceCount() {
return 2;
}
uint32_t CDCACM::populateConfigurationDescriptor(uint8_t *buf) {
uint8_t i = 0;
buf[i++] = 9; // length
buf[i++] = 0x04; // interface descriptor
buf[i++] = _ifControl; // interface number
buf[i++] = 0x00; // alternate
buf[i++] = 0x01; // num endpoints
buf[i++] = 0x02; // interface class (comm)
buf[i++] = 0x02; // subclass (acm)
buf[i++] = 0x01; // protocol (at)
buf[i++] = 0x00; // interface (string)
buf[i++] = 5; // length
buf[i++] = 0x24; // header functional descriptor
buf[i++] = 0x00;
buf[i++] = 0x10;
buf[i++] = 0x01;
buf[i++] = 4; // length
buf[i++] = 0x24; // abstract control model descriptor
buf[i++] = 0x02;
buf[i++] = 0x06;
buf[i++] = 5; // length
buf[i++] = 0x24; // union functional descriptor
buf[i++] = 0x06;
buf[i++] = 0x00; // comm
buf[i++] = 0x01; // data
buf[i++] = 5; // length
buf[i++] = 0x24; // call management functional descriptor
buf[i++] = 0x01;
buf[i++] = 0x00;
buf[i++] = 0x01;
buf[i++] = 7; // length
buf[i++] = 0x05; // endpoint descriptor
buf[i++] = 0x80 | _epControl; // endpoint IN address
buf[i++] = 0x03; // attributes: interrupt
buf[i++] = 0x08;
buf[i++] = 0x00; // packet size
buf[i++] = 0x10; // interval (ms)
buf[i++] = 9; // length
buf[i++] = 0x04; // interface descriptor
buf[i++] = _ifBulk; // interface number
buf[i++] = 0x00; // alternate
buf[i++] = 0x02; // num endpoints
buf[i++] = 0x0a; // interface class (data)
buf[i++] = 0x00; // subclass
buf[i++] = 0x00; // protocol
buf[i++] = 0x00; // interface (string)
buf[i++] = 7; // length
buf[i++] = 0x05; // endpoint descriptor
buf[i++] = 0x80 | _epBulk; // endpoint IN address
buf[i++] = 0x02; // attributes: bulk
buf[i++] = 0x40;
buf[i++] = 0x00; // packet size
buf[i++] = 0x00; // interval (ms)
buf[i++] = 7; // length
buf[i++] = 0x05; // endpoint descriptor
buf[i++] = _epBulk; // endpoint OUT address
buf[i++] = 0x02; // attributes: bulk
buf[i++] = 0x40;
buf[i++] = 0x00; // packet size
buf[i++] = 0x00; // interval (ms)
return i;
}
void CDCACM::initDevice(USBManager *manager) {
_manager = manager;
_ifControl = _manager->allocateInterface();
_ifBulk = _manager->allocateInterface();
_epControl = _manager->allocateEndpoint();
_epBulk = _manager->allocateEndpoint();
}
bool CDCACM::getDescriptor(uint8_t ep, uint8_t target, uint8_t id, uint8_t maxlen) {
return false;
}
void CDCACM::configureEndpoints() {
_manager->addEndpoint(_epControl, EP_OUT, EP_CTL, 8);
_manager->addEndpoint(_epBulk, EP_IN, EP_BLK, 64);
_manager->addEndpoint(_epBulk, EP_OUT, EP_BLK, 64);
}
bool CDCACM::onSetupPacket(uint8_t ep, uint8_t target, uint8_t *data, uint32_t l) {
if (target == _ifControl) {
uint16_t signature = (data[0] << 8) | data[1];
switch (signature) {
case 0x2120:
_outAction = CDC_ACT_SET_LINE_CODING;
return true;
case 0x2122:
_lineState = data[2];
_manager->sendBuffer(0, NULL, 0);
return true;
}
}
return false;
}
bool CDCACM::onInPacket(uint8_t ep, uint8_t target, uint8_t *data, uint32_t l) {
if ((ep == 0) && (target == _ifControl)) {
return true;
}
if (ep == _epBulk) {
if (_txPos > 0) {
_manager->sendBuffer(_epBulk, _txBuffer, _txPos);
_txPos = 0;
}
}
return false;
}
struct CDCLineCoding {
uint32_t dwDTERate;
uint8_t bCharFormat;
uint8_t bParityType;
uint8_t bDataBits;
} __attribute__((packed));
bool CDCACM::onOutPacket(uint8_t ep, uint8_t target, uint8_t *data, uint32_t l) {
if (ep == 0) {
if (target == _ifControl) {
switch(_outAction) {
case CDC_ACT_SET_LINE_CODING:
struct CDCLineCoding *coding = (struct CDCLineCoding *)data;
_baud = coding->dwDTERate;
_stopBits = coding->bCharFormat;
_parity = coding->bParityType;
_dataBits = coding->bDataBits;
_manager->sendBuffer(0, NULL, 0);
return true;
}
}
}
if (ep == _epBulk) {
for (int i = 0; i < l; i++) {
int bufIndex = (_rxHead + 1) % 64;
if (bufIndex != _rxTail) {
_rxBuffer[_rxHead] = data[i];
_rxHead = bufIndex;
}
}
return true;
}
return false;
}
size_t CDCACM::write(uint8_t b) {
if (_lineState == 0) return 0;
while (_txPos >= 64);
_txBuffer[_txPos++] = b;
if (_manager->sendBuffer(_epBulk, _txBuffer, _txPos)) {
_txPos = 0;
}
return 1;
}
int CDCACM::available() {
return (64 + _rxHead - _rxTail) % 64;
}
int CDCACM::read() {
if (_rxHead == _rxTail) return -1;
uint8_t ch = _rxBuffer[_rxTail];
_rxTail = (_rxTail + 1) % 64;
return ch;
}
void CDCACM::flush() {
}
CDCACM::operator int() {
return _lineState > 0;
}
int CDCACM::peek() {
if (_rxHead == _rxTail) return -1;
return _rxBuffer[_rxTail];
}
<commit_msg>Set correct interface linking parameters<commit_after>#include <USB.h>
#define CDC_ACT_SET_LINE_CODING 1
uint8_t CDCACM::getDescriptorLength() {
return 58;
}
uint8_t CDCACM::getInterfaceCount() {
return 2;
}
uint32_t CDCACM::populateConfigurationDescriptor(uint8_t *buf) {
uint8_t i = 0;
buf[i++] = 9; // length
buf[i++] = 0x04; // interface descriptor
buf[i++] = _ifControl; // interface number
buf[i++] = 0x00; // alternate
buf[i++] = 0x01; // num endpoints
buf[i++] = 0x02; // interface class (comm)
buf[i++] = 0x02; // subclass (acm)
buf[i++] = 0x01; // protocol (at)
buf[i++] = 0x00; // interface (string)
buf[i++] = 5; // length
buf[i++] = 0x24; // header functional descriptor
buf[i++] = 0x00;
buf[i++] = 0x10;
buf[i++] = 0x01;
buf[i++] = 4; // length
buf[i++] = 0x24; // abstract control model descriptor
buf[i++] = 0x02;
buf[i++] = 0x06;
buf[i++] = 5; // length
buf[i++] = 0x24; // union functional descriptor
buf[i++] = 0x06;
buf[i++] = _ifControl;
buf[i++] = _ifBulk;
buf[i++] = 5; // length
buf[i++] = 0x24; // call management functional descriptor
buf[i++] = 0x01;
buf[i++] = 0x00;
buf[i++] = _ifBulk;
buf[i++] = 7; // length
buf[i++] = 0x05; // endpoint descriptor
buf[i++] = 0x80 | _epControl; // endpoint IN address
buf[i++] = 0x03; // attributes: interrupt
buf[i++] = 0x08;
buf[i++] = 0x00; // packet size
buf[i++] = 0x10; // interval (ms)
buf[i++] = 9; // length
buf[i++] = 0x04; // interface descriptor
buf[i++] = _ifBulk; // interface number
buf[i++] = 0x00; // alternate
buf[i++] = 0x02; // num endpoints
buf[i++] = 0x0a; // interface class (data)
buf[i++] = 0x00; // subclass
buf[i++] = 0x00; // protocol
buf[i++] = 0x00; // interface (string)
buf[i++] = 7; // length
buf[i++] = 0x05; // endpoint descriptor
buf[i++] = 0x80 | _epBulk; // endpoint IN address
buf[i++] = 0x02; // attributes: bulk
buf[i++] = 0x40;
buf[i++] = 0x00; // packet size
buf[i++] = 0x00; // interval (ms)
buf[i++] = 7; // length
buf[i++] = 0x05; // endpoint descriptor
buf[i++] = _epBulk; // endpoint OUT address
buf[i++] = 0x02; // attributes: bulk
buf[i++] = 0x40;
buf[i++] = 0x00; // packet size
buf[i++] = 0x00; // interval (ms)
return i;
}
void CDCACM::initDevice(USBManager *manager) {
_manager = manager;
_ifControl = _manager->allocateInterface();
_ifBulk = _manager->allocateInterface();
_epControl = _manager->allocateEndpoint();
_epBulk = _manager->allocateEndpoint();
}
bool CDCACM::getDescriptor(uint8_t ep, uint8_t target, uint8_t id, uint8_t maxlen) {
return false;
}
void CDCACM::configureEndpoints() {
_manager->addEndpoint(_epControl, EP_OUT, EP_CTL, 8);
_manager->addEndpoint(_epBulk, EP_IN, EP_BLK, 64);
_manager->addEndpoint(_epBulk, EP_OUT, EP_BLK, 64);
}
bool CDCACM::onSetupPacket(uint8_t ep, uint8_t target, uint8_t *data, uint32_t l) {
if (target == _ifControl) {
uint16_t signature = (data[0] << 8) | data[1];
switch (signature) {
case 0x2120:
_outAction = CDC_ACT_SET_LINE_CODING;
return true;
case 0x2122:
_lineState = data[2];
_manager->sendBuffer(0, NULL, 0);
return true;
}
}
return false;
}
bool CDCACM::onInPacket(uint8_t ep, uint8_t target, uint8_t *data, uint32_t l) {
if ((ep == 0) && (target == _ifControl)) {
return true;
}
if (ep == _epBulk) {
if (_txPos > 0) {
_manager->sendBuffer(_epBulk, _txBuffer, _txPos);
_txPos = 0;
}
}
return false;
}
struct CDCLineCoding {
uint32_t dwDTERate;
uint8_t bCharFormat;
uint8_t bParityType;
uint8_t bDataBits;
} __attribute__((packed));
bool CDCACM::onOutPacket(uint8_t ep, uint8_t target, uint8_t *data, uint32_t l) {
if (ep == 0) {
if (target == _ifControl) {
switch(_outAction) {
case CDC_ACT_SET_LINE_CODING:
struct CDCLineCoding *coding = (struct CDCLineCoding *)data;
_baud = coding->dwDTERate;
_stopBits = coding->bCharFormat;
_parity = coding->bParityType;
_dataBits = coding->bDataBits;
_manager->sendBuffer(0, NULL, 0);
return true;
}
}
}
if (ep == _epBulk) {
for (int i = 0; i < l; i++) {
int bufIndex = (_rxHead + 1) % 64;
if (bufIndex != _rxTail) {
_rxBuffer[_rxHead] = data[i];
_rxHead = bufIndex;
}
}
return true;
}
return false;
}
size_t CDCACM::write(uint8_t b) {
if (_lineState == 0) return 0;
while (_txPos >= 64);
_txBuffer[_txPos++] = b;
if (_manager->sendBuffer(_epBulk, _txBuffer, _txPos)) {
_txPos = 0;
}
return 1;
}
int CDCACM::available() {
return (64 + _rxHead - _rxTail) % 64;
}
int CDCACM::read() {
if (_rxHead == _rxTail) return -1;
uint8_t ch = _rxBuffer[_rxTail];
_rxTail = (_rxTail + 1) % 64;
return ch;
}
void CDCACM::flush() {
}
CDCACM::operator int() {
return _lineState > 0;
}
int CDCACM::peek() {
if (_rxHead == _rxTail) return -1;
return _rxBuffer[_rxTail];
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file TuvokJPEG.cpp
\author Tom Fogal
SCI Institute
University of Utah
\brief Tuvok wrapper for JPEG loading code.
*/
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <vector>
#include "3rdParty/jpeglib/jpeglib.h"
#include "TuvokJPEG.h"
#include "Controller/Controller.h"
/// To read from something with a JPEG embedded, like a DICOM, we need to be
/// able to read from an arbitrary buffer. We support a typical file
/// interface, but we also need to support the former use case. Thus the file
/// interface works by opening the file, slurping in the entire buffer, and
/// then reading the data as if it had always been in memory. This unifies our
/// code paths, but requires more memory than is strictly necessary.
namespace tuvok {
// To do JPEG IO which isn't from a file, one has to set up a special object
// with a particular set of methods. We'll reuse most of the methods from
// what libjpeg thinks is a stdio src, which works because we've pre-populated
// the buffer. Thus libjpeg will never make a request to the source manager to
// read more data.
typedef struct {
jpeg_source_mgr pub; /* public fields */
JOCTET *buffer; /* start of buffer */
} incore_src_mgr;
// Well, mostly. Just to be sure, we override the `ask for more data' method
// to ensure it'll never be called. We'll also install our own error handler,
// because libjpeg's default terminates the process.
static boolean fill_input_buffer(j_decompress_ptr);
static void jpg_error(j_common_ptr);
static void fill_buffer_from_file(std::vector<char>& buf, const char *fn,
std::streamoff offset);
/// To avoid including jpeglib in the header, we create an opaque pointer to
/// the `jpeg implementation'. This is what we'll actually end up pointing to.
struct j_implementation : public JPEG::j_impl {
// Constructor just configures the objects we'll use later.
j_implementation() : started(false) {
struct jpeg_decompress_struct jpg;
jpg.err = jpeg_std_error(&(this->jerr));
jpg.err->error_exit = jpg_error;
jpeg_create_decompress(&jpg);
jpeg_stdio_src(&jpg, NULL);
this->jinfo = jpg;
};
// Expects to get the entire JPEG buffer, but only reads the header.
// After calling this, it is safe to query the JPEG metadata from
// this->jinfo.
// Copies the data from the argument.
void set_data(const std::vector<char>& mem) {
this->data = mem;
this->jinfo.src->bytes_in_buffer = this->data.size();
this->jinfo.src->next_input_byte = &(this->data.at(0));
if(jpeg_read_header(&(this->jinfo), TRUE) != JPEG_HEADER_OK) {
T_ERROR("Could not read JPEG header, bailing...");
return;
}
jpeg_start_decompress(&(this->jinfo));
started = true;
}
virtual ~j_implementation() {
// If the client didn't transfer any actual data (i.e. only read
// metadata), then this `finish' causes an `Application transferred too few
// scanlines' warning. Yet we've called start_decompress, so we must call
// finish. Just live with the warning, or fix the issue in libjpeg itself.
if(started) {
jpeg_finish_decompress(&this->jinfo);
jpeg_destroy_decompress(&this->jinfo);
}
}
std::vector<char> data; ///< hunk of memory we'll read the jpeg from.
bool started; ///< whether we've started decompressing
jpeg_error_mgr jerr; ///< how jpeg will report errors
jpeg_decompress_struct jinfo; ///< main interface for decompression
};
JPEG::JPEG(const std::string &fn, std::streamoff offset) :
w(0), h(0), bpp(0), jpeg_impl(new j_implementation)
{
fill_buffer_from_file(this->buffer, fn.c_str(), offset);
this->initialize();
}
JPEG::JPEG(const std::vector<char>& buf) :
w(0), h(0), bpp(0), jpeg_impl(new j_implementation)
{
this->buffer = buf;
this->initialize();
}
JPEG::~JPEG()
{
delete this->jpeg_impl;
}
bool JPEG::valid() const
{
return this->w != 0 &&
this->h != 0 &&
this->bpp != 0;
}
size_t JPEG::width() const { return this->w; }
size_t JPEG::height() const { return this->h; }
size_t JPEG::components() const {return this->bpp; }
size_t JPEG::size() const { return this->w * this->h * this->bpp; }
// Decode the JPEG data and give back the raw array.
const char* JPEG::data()
{
// If the JPEG isn't valid, we can't load anything from it; just bail.
if(!this->valid()) { return NULL; }
// Need a buffer for the image data.
this->buffer.resize(this->size());
j_implementation *jimpl = dynamic_cast<j_implementation*>(this->jpeg_impl);
{
void *jbuffer = NULL;
const size_t row_sz = this->w * this->bpp;
jbuffer = (*jimpl->jinfo.mem->alloc_sarray)(
(j_common_ptr) &(jimpl->jinfo),
JPOOL_IMAGE,
JDIMENSION(row_sz),
1
);
assert(this->h == jimpl->jinfo.output_height);
assert(this->height() == jimpl->jinfo.output_height);
assert(this->width() > 0);
assert(this->components() > 0);
char *data = &(this->buffer.at(0));
while(jimpl->jinfo.output_scanline < jimpl->jinfo.output_height) {
jpeg_read_scanlines(&(jimpl->jinfo), (JSAMPLE**)&jbuffer, 1);
// The -1 is because jpeg_read_scanlines implicitly incremented the
// output_scanline field, putting the current scanline after the call 1
// in front of the scanline we want to copy.
assert(jimpl->jinfo.output_scanline > 0);
std::memcpy(data + ((jimpl->jinfo.output_scanline-1)*row_sz),
jbuffer, row_sz);
}
}
return &this->buffer.at(0);
}
void JPEG::initialize()
{
j_implementation *jimpl = dynamic_cast<j_implementation*>(this->jpeg_impl);
jimpl->jinfo.src->fill_input_buffer = fill_input_buffer;
jimpl->set_data(this->buffer);
this->w = jimpl->jinfo.output_width;
this->h = jimpl->jinfo.output_height;
this->bpp = jimpl->jinfo.output_components;
}
/// Overly complex, too much so to be worth explaining. Basically JPEG will
/// call this when it runs out of data to process. In our case this should
/// never happen, because we read the whole JPEG before giving it to the
/// library -- all the data are already resident.
boolean fill_input_buffer(j_decompress_ptr)
{
T_ERROR("unexpected fill_input_buffer");
return TRUE;
}
// Just output the message and return. We override this method because libjpeg
// would kill our process with its default implementation.
static void
jpg_error(j_common_ptr jinfo)
{
// Unfortunately it seems pretty difficult to pull the actual error string
// out of the library. We'd like this to go to our debug logs, but it'll end
// up on stderr.
(*jinfo->err->output_message)(jinfo);
}
/// Exactly what it says; fill the contents of the buffer with the data in the
/// given filename. Not a great idea to do this with large files.
static void
fill_buffer_from_file(std::vector<char>& buf, const char *fn,
std::streamoff offset)
{
std::ifstream ifs(fn, std::ifstream::binary);
// get filesize.
ifs.seekg(0, std::ios::end);
std::ifstream::pos_type file_size = ifs.tellg() - offset;
ifs.seekg(offset, std::ios::beg);
MESSAGE("Reading %d byte file.", static_cast<unsigned int>(file_size));
// resize our buffer to be big enough for the file
try {
buf.resize(file_size);
} catch(std::bad_alloc &ba) {
T_ERROR("Could not allocate JPEG buffer (%s)",ba.what());
WARNING("Retrying with smaller buffer...");
file_size = 256*256*256;
buf.resize(file_size);
}
ifs.read(&buf.at(0), file_size);
assert(ifs.gcount() == file_size);
}
}; // namespace tuvok
<commit_msg>Fix some JPEG memory errors.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file TuvokJPEG.cpp
\author Tom Fogal
SCI Institute
University of Utah
\brief Tuvok wrapper for JPEG loading code.
*/
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <vector>
#include "3rdParty/jpeglib/jpeglib.h"
#include "TuvokJPEG.h"
#include "Controller/Controller.h"
/// To read from something with a JPEG embedded, like a DICOM, we need to be
/// able to read from an arbitrary buffer. We support a typical file
/// interface, but we also need to support the former use case. Thus the file
/// interface works by opening the file, slurping in the entire buffer, and
/// then reading the data as if it had always been in memory. This unifies our
/// code paths, but requires more memory than is strictly necessary.
namespace tuvok {
// To do JPEG IO which isn't from a file, one has to set up a special object
// with a particular set of methods. We'll reuse most of the methods from
// what libjpeg thinks is a stdio src, which works because we've pre-populated
// the buffer. Thus libjpeg will never make a request to the source manager to
// read more data.
typedef struct {
jpeg_source_mgr pub; /* public fields */
JOCTET *buffer; /* start of buffer */
} incore_src_mgr;
// Well, mostly. Just to be sure, we override the `ask for more data' method
// to ensure it'll never be called. We'll also install our own error handler,
// because libjpeg's default terminates the process.
static boolean fill_input_buffer(j_decompress_ptr);
static void jpg_error(j_common_ptr);
static void fill_buffer_from_file(std::vector<char>& buf, const char *fn,
std::streamoff offset);
/// To avoid including jpeglib in the header, we create an opaque pointer to
/// the `jpeg implementation'. This is what we'll actually end up pointing to.
struct j_implementation : public JPEG::j_impl {
// Constructor just configures the objects we'll use later.
j_implementation() : started(false) {
struct jpeg_decompress_struct jpg;
jpg.err = jpeg_std_error(&(this->jerr));
jpg.err->error_exit = jpg_error;
jpeg_create_decompress(&jpg);
jpeg_stdio_src(&jpg, NULL);
this->jinfo = jpg;
};
// Expects to get the entire JPEG buffer, but only reads the header.
// After calling this, it is safe to query the JPEG metadata from
// this->jinfo.
// Copies the data from the argument.
void set_data(const std::vector<char>& mem) {
this->data = mem;
this->jinfo.src->bytes_in_buffer = this->data.size();
this->jinfo.src->next_input_byte = &(this->data.at(0));
if(jpeg_read_header(&(this->jinfo), TRUE) != JPEG_HEADER_OK) {
T_ERROR("Could not read JPEG header, bailing...");
return;
}
if(jpeg_start_decompress(&(this->jinfo))) {
started = true;
}
}
virtual ~j_implementation() {
// If the client didn't transfer any actual data (i.e. only read
// metadata), then this `finish' causes an `Application transferred too few
// scanlines' warning. Yet we've called start_decompress, so we must call
// finish. Just live with the warning, or fix the issue in libjpeg itself.
if(started) {
jpeg_finish_decompress(&this->jinfo);
}
jpeg_destroy_decompress(&this->jinfo);
}
std::vector<char> data; ///< hunk of memory we'll read the jpeg from.
bool started; ///< whether we've started decompressing
jpeg_error_mgr jerr; ///< how jpeg will report errors
jpeg_decompress_struct jinfo; ///< main interface for decompression
};
JPEG::JPEG(const std::string &fn, std::streamoff offset) :
w(0), h(0), bpp(0), jpeg_impl(new j_implementation)
{
fill_buffer_from_file(this->buffer, fn.c_str(), offset);
this->initialize();
}
JPEG::JPEG(const std::vector<char>& buf) :
w(0), h(0), bpp(0), jpeg_impl(new j_implementation)
{
this->buffer = buf;
this->initialize();
}
JPEG::~JPEG()
{
delete this->jpeg_impl;
}
bool JPEG::valid() const
{
return this->w != 0 &&
this->h != 0 &&
this->bpp != 0;
}
size_t JPEG::width() const { return this->w; }
size_t JPEG::height() const { return this->h; }
size_t JPEG::components() const {return this->bpp; }
size_t JPEG::size() const { return this->w * this->h * this->bpp; }
// Decode the JPEG data and give back the raw array.
const char* JPEG::data()
{
// If the JPEG isn't valid, we can't load anything from it; just bail.
if(!this->valid()) { return NULL; }
// Need a buffer for the image data.
this->buffer.resize(this->size());
j_implementation *jimpl = dynamic_cast<j_implementation*>(this->jpeg_impl);
{
JSAMPLE *jbuffer = NULL;
const size_t row_sz = this->w * this->bpp;
jbuffer = new JSAMPLE[row_sz];
assert(this->h == jimpl->jinfo.output_height);
assert(this->height() == jimpl->jinfo.output_height);
assert(this->width() > 0);
assert(this->components() > 0);
char *data = &(this->buffer.at(0));
while(jimpl->jinfo.output_scanline < jimpl->jinfo.output_height) {
jpeg_read_scanlines(&(jimpl->jinfo), (JSAMPLE**)&jbuffer, 1);
// The -1 is because jpeg_read_scanlines implicitly incremented the
// output_scanline field, putting the current scanline after the call 1
// in front of the scanline we want to copy.
assert(jimpl->jinfo.output_scanline > 0);
std::memcpy(data + ((jimpl->jinfo.output_scanline-1)*row_sz),
jbuffer, row_sz);
}
delete[] jbuffer;
}
// This would happen in our destructor anyway, but we might as clean up ASAP.
delete this->jpeg_impl;
this->jpeg_impl = NULL;
return &this->buffer.at(0);
}
void JPEG::initialize()
{
j_implementation *jimpl = dynamic_cast<j_implementation*>(this->jpeg_impl);
jimpl->jinfo.src->fill_input_buffer = fill_input_buffer;
jimpl->set_data(this->buffer);
this->w = jimpl->jinfo.output_width;
this->h = jimpl->jinfo.output_height;
this->bpp = jimpl->jinfo.output_components;
}
/// Overly complex, too much so to be worth explaining. Basically JPEG will
/// call this when it runs out of data to process. In our case this should
/// never happen, because we read the whole JPEG before giving it to the
/// library -- all the data are already resident.
boolean fill_input_buffer(j_decompress_ptr)
{
T_ERROR("unexpected fill_input_buffer");
return TRUE;
}
// Just output the message and return. We override this method because libjpeg
// would kill our process with its default implementation.
static void
jpg_error(j_common_ptr jinfo)
{
// Unfortunately it seems pretty difficult to pull the actual error string
// out of the library. We'd like this to go to our debug logs, but it'll end
// up on stderr.
(*jinfo->err->output_message)(jinfo);
}
/// Exactly what it says; fill the contents of the buffer with the data in the
/// given filename. Not a great idea to do this with large files.
static void
fill_buffer_from_file(std::vector<char>& buf, const char *fn,
std::streamoff offset)
{
std::ifstream ifs(fn, std::ifstream::binary);
if(!ifs.is_open()) {
return;
}
// get filesize.
ifs.seekg(0, std::ios::end);
std::ifstream::pos_type file_size = ifs.tellg() - offset;
ifs.seekg(offset, std::ios::beg);
MESSAGE("Reading %u byte file.", static_cast<unsigned int>(file_size));
// resize our buffer to be big enough for the file
try {
buf.resize(file_size);
} catch(std::bad_alloc &ba) {
T_ERROR("Could not allocate JPEG buffer (%s)",ba.what());
WARNING("Retrying with smaller buffer...");
file_size = 256*256*256;
buf.resize(file_size);
}
ifs.read(&buf.at(0), file_size);
assert(ifs.gcount() == file_size);
}
}; // namespace tuvok
<|endoftext|> |
<commit_before>#include "mtao/logging/logger.hpp"
#include <iostream>
#include <chrono>
#include <iomanip>
namespace mtao { namespace logging {
std::map<std::string,Logger> active_loggers;
Logger* default_logger = &make_file_logger("default",Level::All,true);//Making this continue because multiple files might log to it over time
//Logger* default_logger = &make_file_logger("default","default.log",Level::All,true);//Making this continue because multiple files might log to it over time
const std::string level_strings[int(Level::All)+1] = {
std::string("Off"),
std::string("Fatal"),
std::string("Error"),
std::string("Warn"),
std::string("Info"),
std::string("Debug"),
std::string("Trace"),
std::string("All")
};
Level level_from_string(const std::string& str) {
static auto make_map = []() {
std::map<std::string,Level> mymap;
for(int i = 0; i < static_cast<int>(Level::All)+1; ++i) {
mymap[level_strings[i]] = static_cast<Level>(i);
}
return mymap;
};
static const std::map<std::string,Level> strmap = make_map();
return strmap.at(str);
}
Logger::Logger(const std::string& alias, Level l): m_alias(alias), m_level(l) {
write(Level::Info, "Beginning Log ", alias);
}
void Logger::add_file(const std::string& filename, Level level, bool continueFile) {
if(auto it = m_outputs.find(filename);
it == m_outputs.end()) {
std::ofstream outstream = continueFile?std::ofstream(filename,std::ios::app):std::ofstream(filename);
m_outputs[filename] = {std::move(outstream),level};
auto continuing = [&]() -> std::string {
if(continueFile) {
return "[append mode]";
} else {
return "";
}
};
write_cerr(Level::Info, "Adding log file ", filename, " to outputs of ", m_alias, " at level ", log_type_string(level), continuing());
write_output(m_outputs[filename],Level::Info, "Logging to log ", m_alias, " at level ", log_type_string(level));
}
}
Logger& make_logger(const std::string& alias, Level level) {
if(auto it = active_loggers.find(alias);
it != active_loggers.end()) {
it->second.set_level(level);
return it->second;
} else {
auto&& out = active_loggers[alias] = Logger(alias, level);
if(active_loggers.empty()) {//TODO: remember why this was something to be worried about?
}
return out;
}
}
Logger& make_file_logger(const std::string& alias, const std::string& filename, Level level, bool continueFile) {
Logger& logger = make_logger(alias,level);
logger.add_file(filename,level, continueFile);
return logger;
}
std::string Logger::decorator(Level l, bool humanReadable) const {
std::stringstream ss;
ss << "[";
if(humanReadable) {
std::time_t res = std::time(NULL);
ss << "\033[30;1m";
ss << std::put_time(std::localtime(&res), "%c");
ss << "\033[0m";
} else {
std::time_t res = std::time(NULL);
//ss << current_time();
ss << std::put_time(std::localtime(&res), "%c");
}
ss << "](" << log_type_string(l, humanReadable) << "): ";
return ss.str();
}
void Logger::write_line(Level l, const std::string& str) {
std::string dec = decorator(l);
for(auto&& op: m_outputs) {
write_line_nodec(op.second, l,dec + str);
}
write_line_cerr(l,str);
}
void Logger::write_line(Output& output, Level l,const std::string& str) {
if(l <= output.level) {
std::string dec = decorator(l);
write_line_nodec(output, l,dec+str);
}
}
void Logger::write_line_cerr(Level l,const std::string& str) {
if(l <= m_level) {
std::string dec = decorator(l,true);
write_line_cerr_nodec(l,dec+str);
}
}
void Logger::write_line_nodec(Output& output, Level l, const std::string& str) {
if(l <= output.level) {
output.out << str;
}
}
void Logger::write_line_cerr_nodec(Level l, const std::string& str) {
if(l <= m_level) {
std::cerr << str;
}
}
size_t Logger::current_time() const {
using ClockType = std::chrono::steady_clock;
auto now = ClockType::now();
return now.time_since_epoch().count();
}
const std::string& Logger::log_type_string(Level l, bool color) {
const static std::string col_strs[int(Level::All)+1] = {
std::string("\033[30mOff\033[0m"),
std::string("\033[31;1;7mFatal\033[0m"),
std::string("\033[31;1mError\033[0m"),
std::string("\033[33mWarn\033[0m"),
std::string("\033[32;7;1mInfo\033[0m"),
std::string("\033[32;1mDebug\033[0m"),
std::string("\033[0mTrace\033[0m"),
std::string("\033[30mAll\033[0m")
};
if(color) {
return col_strs[int(l)];
} else {
return level_strings[int(l)];
}
}
Logger::Instance::~Instance() {
m_ss << std::endl;
logger->write_line(level,m_ss.str());
}
LoggerContext get_logger(const std::pair<std::string,Level>& pr) {
return get_logger(pr.first,pr.second);
}
LoggerContext get_logger(const std::string& alias, Level level) {
if(auto it = active_loggers.find(alias);
it != active_loggers.end()) {
return LoggerContext(&it->second,level);
} else {
std::cerr << "Error: Logger " << alias << " not found! Making it" << std::endl;
return LoggerContext(&make_logger(alias),level);
return LoggerContext();
}
}
Logger::Instance fatal(){ return log(Level::Fatal); }
Logger::Instance error(){ return log(Level::Error); }
Logger::Instance warn(){ return log(Level::Warn); }
Logger::Instance info(){ return log(Level::Info); }
Logger::Instance debug(){ return log(Level::Debug); }
Logger::Instance trace(){ return log(Level::Trace); }
Logger::Instance log(Level l){ return default_logger->instance(l); }
}}
<commit_msg>typo?<commit_after>#include "mtao/logging/logger.hpp"
#include <iostream>
#include <chrono>
#include <iomanip>
namespace mtao { namespace logging {
std::map<std::string,Logger> active_loggers;
Logger* default_logger = &make_logger("default",Level::All,true);//Making this continue because multiple files might log to it over time
//Logger* default_logger = &make_file_logger("default","default.log",Level::All,true);//Making this continue because multiple files might log to it over time
const std::string level_strings[int(Level::All)+1] = {
std::string("Off"),
std::string("Fatal"),
std::string("Error"),
std::string("Warn"),
std::string("Info"),
std::string("Debug"),
std::string("Trace"),
std::string("All")
};
Level level_from_string(const std::string& str) {
static auto make_map = []() {
std::map<std::string,Level> mymap;
for(int i = 0; i < static_cast<int>(Level::All)+1; ++i) {
mymap[level_strings[i]] = static_cast<Level>(i);
}
return mymap;
};
static const std::map<std::string,Level> strmap = make_map();
return strmap.at(str);
}
Logger::Logger(const std::string& alias, Level l): m_alias(alias), m_level(l) {
write(Level::Info, "Beginning Log ", alias);
}
void Logger::add_file(const std::string& filename, Level level, bool continueFile) {
if(auto it = m_outputs.find(filename);
it == m_outputs.end()) {
std::ofstream outstream = continueFile?std::ofstream(filename,std::ios::app):std::ofstream(filename);
m_outputs[filename] = {std::move(outstream),level};
auto continuing = [&]() -> std::string {
if(continueFile) {
return "[append mode]";
} else {
return "";
}
};
write_cerr(Level::Info, "Adding log file ", filename, " to outputs of ", m_alias, " at level ", log_type_string(level), continuing());
write_output(m_outputs[filename],Level::Info, "Logging to log ", m_alias, " at level ", log_type_string(level));
}
}
Logger& make_logger(const std::string& alias, Level level) {
if(auto it = active_loggers.find(alias);
it != active_loggers.end()) {
it->second.set_level(level);
return it->second;
} else {
auto&& out = active_loggers[alias] = Logger(alias, level);
if(active_loggers.empty()) {//TODO: remember why this was something to be worried about?
}
return out;
}
}
Logger& make_file_logger(const std::string& alias, const std::string& filename, Level level, bool continueFile) {
Logger& logger = make_logger(alias,level);
logger.add_file(filename,level, continueFile);
return logger;
}
std::string Logger::decorator(Level l, bool humanReadable) const {
std::stringstream ss;
ss << "[";
if(humanReadable) {
std::time_t res = std::time(NULL);
ss << "\033[30;1m";
ss << std::put_time(std::localtime(&res), "%c");
ss << "\033[0m";
} else {
std::time_t res = std::time(NULL);
//ss << current_time();
ss << std::put_time(std::localtime(&res), "%c");
}
ss << "](" << log_type_string(l, humanReadable) << "): ";
return ss.str();
}
void Logger::write_line(Level l, const std::string& str) {
std::string dec = decorator(l);
for(auto&& op: m_outputs) {
write_line_nodec(op.second, l,dec + str);
}
write_line_cerr(l,str);
}
void Logger::write_line(Output& output, Level l,const std::string& str) {
if(l <= output.level) {
std::string dec = decorator(l);
write_line_nodec(output, l,dec+str);
}
}
void Logger::write_line_cerr(Level l,const std::string& str) {
if(l <= m_level) {
std::string dec = decorator(l,true);
write_line_cerr_nodec(l,dec+str);
}
}
void Logger::write_line_nodec(Output& output, Level l, const std::string& str) {
if(l <= output.level) {
output.out << str;
}
}
void Logger::write_line_cerr_nodec(Level l, const std::string& str) {
if(l <= m_level) {
std::cerr << str;
}
}
size_t Logger::current_time() const {
using ClockType = std::chrono::steady_clock;
auto now = ClockType::now();
return now.time_since_epoch().count();
}
const std::string& Logger::log_type_string(Level l, bool color) {
const static std::string col_strs[int(Level::All)+1] = {
std::string("\033[30mOff\033[0m"),
std::string("\033[31;1;7mFatal\033[0m"),
std::string("\033[31;1mError\033[0m"),
std::string("\033[33mWarn\033[0m"),
std::string("\033[32;7;1mInfo\033[0m"),
std::string("\033[32;1mDebug\033[0m"),
std::string("\033[0mTrace\033[0m"),
std::string("\033[30mAll\033[0m")
};
if(color) {
return col_strs[int(l)];
} else {
return level_strings[int(l)];
}
}
Logger::Instance::~Instance() {
m_ss << std::endl;
logger->write_line(level,m_ss.str());
}
LoggerContext get_logger(const std::pair<std::string,Level>& pr) {
return get_logger(pr.first,pr.second);
}
LoggerContext get_logger(const std::string& alias, Level level) {
if(auto it = active_loggers.find(alias);
it != active_loggers.end()) {
return LoggerContext(&it->second,level);
} else {
std::cerr << "Error: Logger " << alias << " not found! Making it" << std::endl;
return LoggerContext(&make_logger(alias),level);
return LoggerContext();
}
}
Logger::Instance fatal(){ return log(Level::Fatal); }
Logger::Instance error(){ return log(Level::Error); }
Logger::Instance warn(){ return log(Level::Warn); }
Logger::Instance info(){ return log(Level::Info); }
Logger::Instance debug(){ return log(Level::Debug); }
Logger::Instance trace(){ return log(Level::Trace); }
Logger::Instance log(Level l){ return default_logger->instance(l); }
}}
<|endoftext|> |
<commit_before>#include "Sketch.h"
#include "chr/gl/draw/Cube.h"
#include "chr/gl/draw/Rect.h"
using namespace std;
using namespace chr;
using namespace gl;
Sketch::Sketch()
{}
void Sketch::setup()
{
setupFramebuffer();
texture = Texture(Texture::ImageRequest("lys_32.png")
.setFlags(image::FLAGS_TRANSLUCENT_INVERSE)
.setMipmap(true)
.setWrap(GL_REPEAT, GL_REPEAT));
//
textureBatch
.setShader(textureShader)
.setShaderColor(1, 1, 1, 1)
.setTexture(fboColorTexture);
lightenBatch
.setShader(lambertShader)
.setShaderColor(0.25f, 0.25f, 0.25f, 1);
// ---
draw::Rect()
.setBounds(-200, -200, 400, 400)
.setTextureScale(400.0f / fboColorTexture.width)
.append(textureBatch, Matrix());
//
draw::Cube()
.setSize(150)
.append(lightenBatch, Matrix());
// ---
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void Sketch::draw()
{
glBindFramebuffer(GL_FRAMEBUFFER, fboId);
drawScene2();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// fboColorTexture.bind();
// glGenerateMipmap(GL_TEXTURE_2D);
// fboColorTexture.unbind();
drawScene1();
}
void Sketch::setupFramebuffer()
{
fboColorTexture = Texture(
Texture::EmptyRequest(512, 512));
fboDepthTexture = Texture(
Texture::EmptyRequest(512, 512)
.setFormat(GL_DEPTH_COMPONENT)
.setType(GL_FLOAT));
glGenFramebuffersEXT(1, &fboId);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER, fboId);
glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fboColorTexture.textureId, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fboDepthTexture.textureId, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
void Sketch::drawScene1()
{
glViewport(0, 0, windowInfo.width, windowInfo.height);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
glClearColor(1, 0.75f, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
// ---
auto projectionMatrix = glm::perspective(60 * D2R, windowInfo.width / windowInfo.height, 0.1f, 1000.0f);
Matrix mvMatrix;
mvMatrix
.scale(1, -1, 1)
.translate(0, 0, -400)
.rotateY(clock()->getTime() * 0.0f); // XXX
auto mvpMatrix = mvMatrix * projectionMatrix;
// ---
State()
.setShaderMatrix<MVP>(mvpMatrix)
.apply();
textureBatch.flush();
}
void Sketch::drawScene2()
{
glViewport(0, 0, fboColorTexture.width, fboColorTexture.height);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearColor(0.5f, 0.5f, 0.5f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// ---
auto projectionMatrix = glm::perspective(60 * D2R, windowInfo.width / windowInfo.height, 0.1f, 1000.0f);
Matrix mvMatrix;
mvMatrix
.scale(1, -1, 1)
.translate(0, 0, -300)
.rotateY(clock()->getTime())
.rotateZ(clock()->getTime() * 0.25f);
auto mvpMatrix = mvMatrix * projectionMatrix;
// ---
State()
.setShaderMatrix<MVP>(mvpMatrix)
.setShaderMatrix<NORMAL>(mvMatrix.getNormalMatrix())
.apply();
lightenBatch.flush();
}
<commit_msg>TestingFBO: Deformation problem solved!<commit_after>#include "Sketch.h"
#include "chr/gl/draw/Cube.h"
#include "chr/gl/draw/Rect.h"
using namespace std;
using namespace chr;
using namespace gl;
Sketch::Sketch()
{}
void Sketch::setup()
{
setupFramebuffer();
texture = Texture(Texture::ImageRequest("lys_32.png")
.setFlags(image::FLAGS_TRANSLUCENT_INVERSE)
.setMipmap(true)
.setWrap(GL_REPEAT, GL_REPEAT));
//
textureBatch
.setShader(textureShader)
.setShaderColor(1, 1, 1, 1)
.setTexture(fboColorTexture);
lightenBatch
.setShader(lambertShader)
.setShaderColor(0.25f, 0.25f, 0.25f, 1);
// ---
draw::Rect()
.setBounds(-200, -200, 400, 400)
.setTextureScale(400.0f / fboColorTexture.width)
.append(textureBatch, Matrix());
//
draw::Cube()
.setSize(150)
.append(lightenBatch, Matrix());
// ---
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void Sketch::draw()
{
glBindFramebuffer(GL_FRAMEBUFFER, fboId);
drawScene2();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// fboColorTexture.bind();
// glGenerateMipmap(GL_TEXTURE_2D);
// fboColorTexture.unbind();
drawScene1();
}
void Sketch::setupFramebuffer()
{
fboColorTexture = Texture(
Texture::EmptyRequest(512, 512));
fboDepthTexture = Texture(
Texture::EmptyRequest(512, 512)
.setFormat(GL_DEPTH_COMPONENT)
.setType(GL_FLOAT));
glGenFramebuffersEXT(1, &fboId);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER, fboId);
glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fboColorTexture.textureId, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fboDepthTexture.textureId, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
void Sketch::drawScene1()
{
glViewport(0, 0, windowInfo.width, windowInfo.height);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
glClearColor(1, 0.75f, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
// ---
auto projectionMatrix = glm::perspective(60 * D2R, windowInfo.width / windowInfo.height, 0.1f, 1000.0f);
Matrix mvMatrix;
mvMatrix
.scale(1, -1, 1)
.translate(0, 0, -400)
.rotateY(clock()->getTime() * 0.0f); // XXX
auto mvpMatrix = mvMatrix * projectionMatrix;
// ---
State()
.setShaderMatrix<MVP>(mvpMatrix)
.apply();
textureBatch.flush();
}
void Sketch::drawScene2()
{
glViewport(0, 0, fboColorTexture.width, fboColorTexture.height);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearColor(0.5f, 0.5f, 0.5f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// ---
auto projectionMatrix = glm::perspective(60 * D2R, fboColorTexture.width / fboColorTexture.height, 0.1f, 1000.0f);
Matrix mvMatrix;
mvMatrix
.scale(1, -1, 1)
.translate(0, 0, -300)
.rotateY(clock()->getTime())
.rotateZ(clock()->getTime() * 0.25f);
auto mvpMatrix = mvMatrix * projectionMatrix;
// ---
State()
.setShaderMatrix<MVP>(mvpMatrix)
.setShaderMatrix<NORMAL>(mvMatrix.getNormalMatrix())
.apply();
lightenBatch.flush();
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename T> bool isNotNaN(const T& x)
{
return x==x;
}
// workaround aggressive optimization in ICC
template<typename T> EIGEN_DONT_INLINE T sub(T a, T b) { return a - b; }
template<typename T> bool isFinite(const T& x)
{
return isNotNaN(sub(x,x));
}
template<typename T> EIGEN_DONT_INLINE T copy(const T& x)
{
return x;
}
template<typename MatrixType> void stable_norm(const MatrixType& m)
{
/* this test covers the following files:
StableNorm.h
*/
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
// Check the basic machine-dependent constants.
{
int ibeta, it, iemin, iemax;
ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers
it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa
iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent
iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent
VERIFY( (!(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5) || (it<=4 && ibeta <= 3 ) || it<2))
&& "the stable norm algorithm cannot be guaranteed on this computer");
}
Index rows = m.rows();
Index cols = m.cols();
Scalar big = internal::random<Scalar>() * (std::numeric_limits<RealScalar>::max() * RealScalar(1e-4));
Scalar small = static_cast<RealScalar>(1)/big;
MatrixType vzero = MatrixType::Zero(rows, cols),
vrand = MatrixType::Random(rows, cols),
vbig(rows, cols),
vsmall(rows,cols);
vbig.fill(big);
vsmall.fill(small);
VERIFY_IS_MUCH_SMALLER_THAN(vzero.norm(), static_cast<RealScalar>(1));
VERIFY_IS_APPROX(vrand.stableNorm(), vrand.norm());
VERIFY_IS_APPROX(vrand.blueNorm(), vrand.norm());
VERIFY_IS_APPROX(vrand.hypotNorm(), vrand.norm());
RealScalar size = static_cast<RealScalar>(m.size());
// test isFinite
VERIFY(!isFinite( std::numeric_limits<RealScalar>::infinity()));
VERIFY(!isFinite(internal::sqrt(-internal::abs(big))));
// test overflow
VERIFY(isFinite(internal::sqrt(size)*internal::abs(big)));
VERIFY_IS_NOT_APPROX(internal::sqrt(copy(vbig.squaredNorm())), internal::abs(internal::sqrt(size)*big)); // here the default norm must fail
VERIFY_IS_APPROX(vbig.stableNorm(), internal::sqrt(size)*internal::abs(big));
VERIFY_IS_APPROX(vbig.blueNorm(), internal::sqrt(size)*internal::abs(big));
VERIFY_IS_APPROX(vbig.hypotNorm(), internal::sqrt(size)*internal::abs(big));
// test underflow
VERIFY(isFinite(internal::sqrt(size)*internal::abs(small)));
VERIFY_IS_NOT_APPROX(internal::sqrt(copy(vsmall.squaredNorm())), internal::abs(internal::sqrt(size)*small)); // here the default norm must fail
VERIFY_IS_APPROX(vsmall.stableNorm(), internal::sqrt(size)*internal::abs(small));
VERIFY_IS_APPROX(vsmall.blueNorm(), internal::sqrt(size)*internal::abs(small));
VERIFY_IS_APPROX(vsmall.hypotNorm(), internal::sqrt(size)*internal::abs(small));
// Test compilation of cwise() version
VERIFY_IS_APPROX(vrand.colwise().stableNorm(), vrand.colwise().norm());
VERIFY_IS_APPROX(vrand.colwise().blueNorm(), vrand.colwise().norm());
VERIFY_IS_APPROX(vrand.colwise().hypotNorm(), vrand.colwise().norm());
VERIFY_IS_APPROX(vrand.rowwise().stableNorm(), vrand.rowwise().norm());
VERIFY_IS_APPROX(vrand.rowwise().blueNorm(), vrand.rowwise().norm());
VERIFY_IS_APPROX(vrand.rowwise().hypotNorm(), vrand.rowwise().norm());
}
void test_stable_norm()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( stable_norm(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( stable_norm(Vector4d()) );
CALL_SUBTEST_3( stable_norm(VectorXd(internal::random<int>(10,2000))) );
CALL_SUBTEST_4( stable_norm(VectorXf(internal::random<int>(10,2000))) );
CALL_SUBTEST_5( stable_norm(VectorXcd(internal::random<int>(10,2000))) );
}
}
<commit_msg>fix stable_norm test: the |small| value was 0 on clang with complex<float>.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename T> bool isNotNaN(const T& x)
{
return x==x;
}
// workaround aggressive optimization in ICC
template<typename T> EIGEN_DONT_INLINE T sub(T a, T b) { return a - b; }
template<typename T> bool isFinite(const T& x)
{
return isNotNaN(sub(x,x));
}
template<typename T> EIGEN_DONT_INLINE T copy(const T& x)
{
return x;
}
template<typename MatrixType> void stable_norm(const MatrixType& m)
{
/* this test covers the following files:
StableNorm.h
*/
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
// Check the basic machine-dependent constants.
{
int ibeta, it, iemin, iemax;
ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers
it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa
iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent
iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent
VERIFY( (!(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5) || (it<=4 && ibeta <= 3 ) || it<2))
&& "the stable norm algorithm cannot be guaranteed on this computer");
}
Index rows = m.rows();
Index cols = m.cols();
Scalar big = internal::random<Scalar>() * (std::numeric_limits<RealScalar>::max() * RealScalar(1e-4));
Scalar small = internal::random<Scalar>() * (std::numeric_limits<RealScalar>::min() * RealScalar(1e4));
MatrixType vzero = MatrixType::Zero(rows, cols),
vrand = MatrixType::Random(rows, cols),
vbig(rows, cols),
vsmall(rows,cols);
vbig.fill(big);
vsmall.fill(small);
VERIFY_IS_MUCH_SMALLER_THAN(vzero.norm(), static_cast<RealScalar>(1));
VERIFY_IS_APPROX(vrand.stableNorm(), vrand.norm());
VERIFY_IS_APPROX(vrand.blueNorm(), vrand.norm());
VERIFY_IS_APPROX(vrand.hypotNorm(), vrand.norm());
RealScalar size = static_cast<RealScalar>(m.size());
// test isFinite
VERIFY(!isFinite( std::numeric_limits<RealScalar>::infinity()));
VERIFY(!isFinite(internal::sqrt(-internal::abs(big))));
// test overflow
VERIFY(isFinite(internal::sqrt(size)*internal::abs(big)));
VERIFY_IS_NOT_APPROX(internal::sqrt(copy(vbig.squaredNorm())), internal::abs(internal::sqrt(size)*big)); // here the default norm must fail
VERIFY_IS_APPROX(vbig.stableNorm(), internal::sqrt(size)*internal::abs(big));
VERIFY_IS_APPROX(vbig.blueNorm(), internal::sqrt(size)*internal::abs(big));
VERIFY_IS_APPROX(vbig.hypotNorm(), internal::sqrt(size)*internal::abs(big));
// test underflow
VERIFY(isFinite(internal::sqrt(size)*internal::abs(small)));
VERIFY_IS_NOT_APPROX(internal::sqrt(copy(vsmall.squaredNorm())), internal::abs(internal::sqrt(size)*small)); // here the default norm must fail
VERIFY_IS_APPROX(vsmall.stableNorm(), internal::sqrt(size)*internal::abs(small));
VERIFY_IS_APPROX(vsmall.blueNorm(), internal::sqrt(size)*internal::abs(small));
VERIFY_IS_APPROX(vsmall.hypotNorm(), internal::sqrt(size)*internal::abs(small));
// Test compilation of cwise() version
VERIFY_IS_APPROX(vrand.colwise().stableNorm(), vrand.colwise().norm());
VERIFY_IS_APPROX(vrand.colwise().blueNorm(), vrand.colwise().norm());
VERIFY_IS_APPROX(vrand.colwise().hypotNorm(), vrand.colwise().norm());
VERIFY_IS_APPROX(vrand.rowwise().stableNorm(), vrand.rowwise().norm());
VERIFY_IS_APPROX(vrand.rowwise().blueNorm(), vrand.rowwise().norm());
VERIFY_IS_APPROX(vrand.rowwise().hypotNorm(), vrand.rowwise().norm());
}
void test_stable_norm()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( stable_norm(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( stable_norm(Vector4d()) );
CALL_SUBTEST_3( stable_norm(VectorXd(internal::random<int>(10,2000))) );
CALL_SUBTEST_4( stable_norm(VectorXf(internal::random<int>(10,2000))) );
CALL_SUBTEST_5( stable_norm(VectorXcd(internal::random<int>(10,2000))) );
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Novell, Inc.
* Copyright (c) [2016-2018] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied 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, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Utils/HumanString.h"
#include "storage/Devices/BlkDeviceImpl.h"
#include "storage/Filesystems/VfatImpl.h"
#include "storage/FreeInfo.h"
#include "storage/UsedFeatures.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Vfat>::classname = "Vfat";
Vfat::Impl::Impl(const xmlNode* node)
: BlkFilesystem::Impl(node)
{
}
string
Vfat::Impl::get_pretty_classname() const
{
// TRANSLATORS: name of object
return _("VFAT").translated;
}
ContentInfo
Vfat::Impl::detect_content_info_on_disk() const
{
EnsureMounted ensure_mounted(get_filesystem());
ContentInfo content_info;
if (detect_is_efi(ensure_mounted.get_any_mount_point()))
content_info.is_efi = true;
else
content_info.is_windows = detect_is_windows(ensure_mounted.get_any_mount_point());
return content_info;
}
uint64_t
Vfat::Impl::used_features() const
{
return UF_VFAT | BlkFilesystem::Impl::used_features();
}
void
Vfat::Impl::do_create()
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = MKFSFATBIN " -v " + get_mkfs_options() + " " + quote(blk_device->get_name());
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
// uuid is included in mkfs output
probe_uuid();
}
void
Vfat::Impl::do_set_label() const
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = FATLABELBIN " " + quote(blk_device->get_name()) + " " +
quote(get_label());
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
void
Vfat::Impl::do_resize(ResizeMode resize_mode, const Device* rhs) const
{
const BlkDevice* blk_device = get_blk_device();
const BlkDevice* blk_device_rhs = to_vfat(rhs)->get_impl().get_blk_device();
string cmd_line = FATRESIZEBIN " " + quote(blk_device->get_name());
if (resize_mode == ResizeMode::SHRINK)
cmd_line += " " + to_string(blk_device_rhs->get_size() / KiB);
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
}
<commit_msg>- removed unneeded include<commit_after>/*
* Copyright (c) 2015 Novell, Inc.
* Copyright (c) [2016-2018] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied 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, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Devices/BlkDeviceImpl.h"
#include "storage/Filesystems/VfatImpl.h"
#include "storage/FreeInfo.h"
#include "storage/UsedFeatures.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Vfat>::classname = "Vfat";
Vfat::Impl::Impl(const xmlNode* node)
: BlkFilesystem::Impl(node)
{
}
string
Vfat::Impl::get_pretty_classname() const
{
// TRANSLATORS: name of object
return _("VFAT").translated;
}
ContentInfo
Vfat::Impl::detect_content_info_on_disk() const
{
EnsureMounted ensure_mounted(get_filesystem());
ContentInfo content_info;
if (detect_is_efi(ensure_mounted.get_any_mount_point()))
content_info.is_efi = true;
else
content_info.is_windows = detect_is_windows(ensure_mounted.get_any_mount_point());
return content_info;
}
uint64_t
Vfat::Impl::used_features() const
{
return UF_VFAT | BlkFilesystem::Impl::used_features();
}
void
Vfat::Impl::do_create()
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = MKFSFATBIN " -v " + get_mkfs_options() + " " + quote(blk_device->get_name());
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
// uuid is included in mkfs output
probe_uuid();
}
void
Vfat::Impl::do_set_label() const
{
const BlkDevice* blk_device = get_blk_device();
string cmd_line = FATLABELBIN " " + quote(blk_device->get_name()) + " " +
quote(get_label());
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
void
Vfat::Impl::do_resize(ResizeMode resize_mode, const Device* rhs) const
{
const BlkDevice* blk_device = get_blk_device();
const BlkDevice* blk_device_rhs = to_vfat(rhs)->get_impl().get_blk_device();
string cmd_line = FATRESIZEBIN " " + quote(blk_device->get_name());
if (resize_mode == ResizeMode::SHRINK)
cmd_line += " " + to_string(blk_device_rhs->get_size() / KiB);
wait_for_devices();
SystemCmd cmd(cmd_line, SystemCmd::DoThrow);
}
}
<|endoftext|> |
<commit_before>#include "CppUTest/TestHarness.h"
extern "C"
{
#include "ciostack/ciostack.h"
}
TEST_GROUP(ciostack)
{
// global vars
void setup()
{
}
void teardown()
{
}
};
TEST(ciostack, init_buffer_object)
{
unsigned char buffer[32];
CIO_BUFFER_OBJECT bufferObject;
CIO_Buffer_Init(&bufferObject, buffer, sizeof(buffer));
CHECK_EQUAL(buffer, bufferObject.buffer);
CHECK_EQUAL(sizeof(buffer), bufferObject.size);
}
TEST(ciostack, init_frame_init)
{
CIO_FRAME frameIO;
COFFEEIO_VARIANT fieldsIO[5];
CIO_FrameInit(&frameIO, fieldsIO, sizeof(fieldsIO) / sizeof(fieldsIO[0]));
CHECK_EQUAL(5, frameIO.fieldsCount);
CHECK_EQUAL(fieldsIO, frameIO.fields);
}
TEST(ciostack, xy)
{
CIO_FRAME frameIO;
COFFEEIO_VARIANT fieldsIO[5];
CIO_FrameInit(&frameIO, fieldsIO, sizeof(fieldsIO) / sizeof(fieldsIO[0]));
frameIO.header.flags.byte = 0x12;
frameIO.fields[0].type = variant_u32;
frameIO.fields[0].value.u32 = 123;
frameIO.fields[1].type = variant_u32;
frameIO.fields[1].value.u32 = 987654321;
frameIO.fields[2].type = variant_u16;
frameIO.fields[2].value.u16 = 1234;
frameIO.fields[3].type = variant_f32;
frameIO.fields[3].value.f32 = 12.532;
frameIO.fields[4].type = variant_f32;
frameIO.fields[4].value.f32 = 15.5;
}
<commit_msg>Adding first tests<commit_after>#include "CppUTest/TestHarness.h"
extern "C"
{
#include "ciostack/ciostack.h"
}
TEST_GROUP(ciostack)
{
// global vars
void setup()
{
}
void teardown()
{
}
};
TEST(ciostack, init_buffer_object)
{
unsigned char buffer[32];
CIO_BUFFER_OBJECT bufferObject;
CIO_Buffer_Init(&bufferObject, buffer, sizeof(buffer));
CHECK_EQUAL(buffer, bufferObject.buffer);
CHECK_EQUAL(sizeof(buffer), bufferObject.size);
}
TEST(ciostack, init_frame_init)
{
CIO_FRAME frameIO;
COFFEEIO_VARIANT fieldsIO[5];
CIO_FrameInit(&frameIO, fieldsIO, sizeof(fieldsIO) / sizeof(fieldsIO[0]));
CHECK_EQUAL(5, frameIO.fieldsCount);
CHECK_EQUAL(fieldsIO, frameIO.fields);
}
TEST(ciostack, xy)
{
CIO_FRAME frameIO;
COFFEEIO_VARIANT fieldsIO[5];
CIO_FrameInit(&frameIO, fieldsIO, sizeof(fieldsIO) / sizeof(fieldsIO[0]));
frameIO.header.flags.byte = 0x12;
frameIO.fields[0].type = variant_u32;
frameIO.fields[0].value.u32 = 123;
frameIO.fields[1].type = variant_u32;
frameIO.fields[1].value.u32 = 987654321;
frameIO.fields[2].type = variant_u16;
frameIO.fields[2].value.u16 = 1234;
frameIO.fields[3].type = variant_f32;
frameIO.fields[3].value.f32 = 12.532;
frameIO.fields[4].type = variant_f32;
frameIO.fields[4].value.f32 = 15.5;
}
<|endoftext|> |
<commit_before>#include <pthread.h>
#include <vector>
#include <netdb.h>
#include "io.h"
#include "parse_args.h"
#include "cache.h"
#include "vw.h"
pthread_t* thread;
size_t d_1;
size_t d_2;
v_array<v_array<io_buf> > bufs;
bool second_of_pair[256];
bool pairs_exist=false;
size_t log_int_r(size_t v)
{
if (v > 1)
return 1+log_int_r(v >> 1);
else
return 0;
}
size_t log_int(size_t v)
{//find largest number n such that 2^n <= v
return log_int_r(v);
}
size_t find_split(size_t number)
{/* Breaks <number> things into a factor of 2 by a factor of 2, with the first dimension longest */
d_1 = 1;
d_2 = 1;
if (number > 1)
{
size_t log_2 = log_int(number);
if (!pairs_exist)
d_1 = 1 << log_2;
else
{
d_1 = 1 << (log_2 -1);
if (d_1 * d_1 > number)
d_2 = d_1 / 2;
else {
d_2 = d_1;
if (d_1 * 2 * d_2 < number)
d_1 *=2;
}
}
if (d_1 * d_2 < number)
cerr << "warning: number of remote hosts is not a factor of 2, so some are wasted" << endl;
return log_2;
}
return 0;
}
void open_sockets(vector<string>& hosts)
{
for (size_t i = 0; i < d_1; i++)
{
v_array<io_buf> t;
push(bufs,t);
for (size_t j = 0; j< d_2; j++)
{
size_t number = j + d_2*i;
hostent* he = gethostbyname(hosts[number].c_str());
if (he == NULL)
{
cerr << "can't resolve hostname: " << hosts[number] << endl;
exit(1);
}
int sd = socket(PF_INET, SOCK_STREAM, 0);
if (sd == -1)
{
cerr << "can't get socket " << endl;
exit(1);
}
sockaddr_in far_end;
far_end.sin_family = AF_INET;
far_end.sin_port = htons(39523);
far_end.sin_addr = *(in_addr*)(he->h_addr);
memset(&far_end.sin_zero, '\0',8);
if (connect(sd,(sockaddr*)&far_end, sizeof(far_end)) == -1)
{
cerr << "can't connect to: " << hosts[number] << endl;
exit(1);
}
io_buf b;
b.file = sd;
push(bufs[i], b);
}
}
}
void parse_send_args(po::variables_map& vm, vector<string> pairs, size_t& thread_bits)
{
if (vm.count("sendto"))
{
if (pairs.size() > 0)
{
pairs_exist=true;
for (int i = 0; i<256;i++)
second_of_pair[i]=false;
for (vector<string>::iterator i = pairs.begin(); i != pairs.end();i++)
second_of_pair[(int)(*i)[1]] = true;
}
vector<string> hosts = vm["sendto"].as< vector<string> >();
thread_bits = max(thread_bits,find_split(hosts.size()));
open_sockets(hosts);
}
}
void send_features(int i, int j, io_buf& b, example* ec)
{
output_int(bufs[i][j],ec->indices.index());
for (size_t* index = ec->indices.begin; index != ec->indices.end; index++)
if (second_of_pair[*index])
output_features(b, *index, ec->subsets[*index][j*d_1], ec->subsets[*index][(j+1)*d_1]);
else
output_features(b, *index, ec->subsets[*index][i*d_2], ec->subsets[*index][(i+1)*d_2]);
b.flush();
}
void* send_thread(void*)
{
example* ec = NULL;
while ( (ec = get_example(ec,0)) )
{
label_data* ld = (label_data*)ec->ld;
for (size_t i = 0; i < d_1; i++)
for (size_t j = 0; j < d_2; j++)
{
simple_label.cache_label(ld,bufs[i][j]);//send label information.
send_features(i,j,bufs[i][j],ec);
}
ec->threads_to_finish = 0;
}
return NULL;
}
void setup_send()
{
thread = (pthread_t*)calloc(1,sizeof(pthread_t));
pthread_create(thread, NULL, send_thread, NULL);
}
void destroy_send()
{
pthread_join(*thread, NULL);
}
<commit_msg>Removed deadlock in sender.<commit_after>#include <pthread.h>
#include <vector>
#include <netdb.h>
#include "io.h"
#include "parse_args.h"
#include "cache.h"
#include "vw.h"
pthread_t* thread;
size_t d_1;
size_t d_2;
v_array<v_array<io_buf> > bufs;
bool second_of_pair[256];
bool pairs_exist=false;
size_t log_int_r(size_t v)
{
if (v > 1)
return 1+log_int_r(v >> 1);
else
return 0;
}
size_t log_int(size_t v)
{//find largest number n such that 2^n <= v
return log_int_r(v);
}
size_t find_split(size_t number)
{/* Breaks <number> things into a factor of 2 by a factor of 2, with the first dimension longest */
d_1 = 1;
d_2 = 1;
if (number > 1)
{
size_t log_2 = log_int(number);
if (!pairs_exist)
d_1 = 1 << log_2;
else
{
d_1 = 1 << (log_2 -1);
if (d_1 * d_1 > number)
d_2 = d_1 / 2;
else {
d_2 = d_1;
if (d_1 * 2 * d_2 < number)
d_1 *=2;
}
}
if (d_1 * d_2 < number)
cerr << "warning: number of remote hosts is not a factor of 2, so some are wasted" << endl;
return log_2;
}
return 0;
}
void open_sockets(vector<string>& hosts)
{
for (size_t i = 0; i < d_1; i++)
{
v_array<io_buf> t;
push(bufs,t);
for (size_t j = 0; j< d_2; j++)
{
size_t number = j + d_2*i;
hostent* he = gethostbyname(hosts[number].c_str());
if (he == NULL)
{
cerr << "can't resolve hostname: " << hosts[number] << endl;
exit(1);
}
int sd = socket(PF_INET, SOCK_STREAM, 0);
if (sd == -1)
{
cerr << "can't get socket " << endl;
exit(1);
}
sockaddr_in far_end;
far_end.sin_family = AF_INET;
far_end.sin_port = htons(39523);
far_end.sin_addr = *(in_addr*)(he->h_addr);
memset(&far_end.sin_zero, '\0',8);
if (connect(sd,(sockaddr*)&far_end, sizeof(far_end)) == -1)
{
cerr << "can't connect to: " << hosts[number] << endl;
exit(1);
}
io_buf b;
b.file = sd;
push(bufs[i], b);
}
}
}
void parse_send_args(po::variables_map& vm, vector<string> pairs, size_t& thread_bits)
{
if (vm.count("sendto"))
{
if (pairs.size() > 0)
{
pairs_exist=true;
for (int i = 0; i<256;i++)
second_of_pair[i]=false;
for (vector<string>::iterator i = pairs.begin(); i != pairs.end();i++)
second_of_pair[(int)(*i)[1]] = true;
}
vector<string> hosts = vm["sendto"].as< vector<string> >();
thread_bits = max(thread_bits,find_split(hosts.size()));
open_sockets(hosts);
}
}
void send_features(int i, int j, io_buf& b, example* ec)
{
output_int(bufs[i][j],ec->indices.index());
for (size_t* index = ec->indices.begin; index != ec->indices.end; index++)
if (second_of_pair[*index])
output_features(b, *index, ec->subsets[*index][j*d_1], ec->subsets[*index][(j+1)*d_1]);
else
output_features(b, *index, ec->subsets[*index][i*d_2], ec->subsets[*index][(i+1)*d_2]);
b.flush();
}
void* send_thread(void*)
{
example* ec = NULL;
while ( (ec = get_example(ec,0)) )
{
label_data* ld = (label_data*)ec->ld;
for (size_t i = 0; i < d_1; i++)
for (size_t j = 0; j < d_2; j++)
{
simple_label.cache_label(ld,bufs[i][j]);//send label information.
send_features(i,j,bufs[i][j],ec);
}
ec->threads_to_finish = 1;
ec->done = true;
}
return NULL;
}
void setup_send()
{
thread = (pthread_t*)calloc(1,sizeof(pthread_t));
pthread_create(thread, NULL, send_thread, NULL);
}
void destroy_send()
{
pthread_join(*thread, NULL);
}
<|endoftext|> |
<commit_before>#include "transactionview.h"
#include "transactionfilterproxy.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "bitcoinunits.h"
#include "csvmodelwriter.h"
#include "transactiondescdialog.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QScrollBar>
#include <QComboBox>
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QTableView>
#include <QHeaderView>
#include <QPushButton>
#include <QMessageBox>
#include <QPoint>
#include <QMenu>
#include <QApplication>
#include <QClipboard>
#include <QLabel>
#include <QDateTimeEdit>
TransactionView::TransactionView(QWidget *parent) :
QWidget(parent), model(0), transactionProxyModel(0),
transactionView(0)
{
// Build filter row
setContentsMargins(0,0,0,0);
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->setContentsMargins(0,0,0,0);
#ifdef Q_WS_MAC
hlayout->setSpacing(5);
hlayout->addSpacing(26);
#else
hlayout->setSpacing(0);
hlayout->addSpacing(23);
#endif
dateWidget = new QComboBox(this);
#ifdef Q_WS_MAC
dateWidget->setFixedWidth(121);
#else
dateWidget->setFixedWidth(120);
#endif
dateWidget->addItem(tr("All"), All);
dateWidget->addItem(tr("Today"), Today);
dateWidget->addItem(tr("This week"), ThisWeek);
dateWidget->addItem(tr("This month"), ThisMonth);
dateWidget->addItem(tr("Last month"), LastMonth);
dateWidget->addItem(tr("This year"), ThisYear);
dateWidget->addItem(tr("Range..."), Range);
hlayout->addWidget(dateWidget);
typeWidget = new QComboBox(this);
#ifdef Q_WS_MAC
typeWidget->setFixedWidth(121);
#else
typeWidget->setFixedWidth(120);
#endif
typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other));
hlayout->addWidget(typeWidget);
addressWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
addressWidget->setPlaceholderText(tr("Enter address or label to search"));
#endif
hlayout->addWidget(addressWidget);
amountWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
amountWidget->setPlaceholderText(tr("Min amount"));
#endif
#ifdef Q_WS_MAC
amountWidget->setFixedWidth(97);
#else
amountWidget->setFixedWidth(100);
#endif
amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));
hlayout->addWidget(amountWidget);
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(0,0,0,0);
vlayout->setSpacing(0);
QTableView *view = new QTableView(this);
vlayout->addLayout(hlayout);
vlayout->addWidget(createDateRangeWidget());
vlayout->addWidget(view);
vlayout->setSpacing(0);
int width = view->verticalScrollBar()->sizeHint().width();
// Cover scroll bar width with spacing
#ifdef Q_WS_MAC
hlayout->addSpacing(width+2);
#else
hlayout->addSpacing(width);
#endif
// Always show scroll bar
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
view->setTabKeyNavigation(false);
view->setContextMenuPolicy(Qt::CustomContextMenu);
transactionView = view;
// Actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
QAction *editLabelAction = new QAction(tr("Edit label"), this);
QAction *showDetailsAction = new QAction(tr("Show transaction details"), this);
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(editLabelAction);
contextMenu->addAction(showDetailsAction);
// Connect actions
connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));
connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));
connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));
connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));
connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));
connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));
}
void TransactionView::setModel(WalletModel *model)
{
this->model = model;
if(model)
{
transactionProxyModel = new TransactionFilterProxy(this);
transactionProxyModel->setSourceModel(model->getTransactionTableModel());
transactionProxyModel->setDynamicSortFilter(true);
transactionProxyModel->setSortRole(Qt::EditRole);
transactionView->setModel(transactionProxyModel);
transactionView->setAlternatingRowColors(true);
transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);
transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);
transactionView->setSortingEnabled(true);
transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);
transactionView->verticalHeader()->hide();
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Status, 23);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Date, 120);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Type, 120);
transactionView->horizontalHeader()->setResizeMode(
TransactionTableModel::ToAddress, QHeaderView::Stretch);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Amount, 100);
}
}
void TransactionView::chooseDate(int idx)
{
if(!transactionProxyModel)
return;
QDate current = QDate::currentDate();
dateRangeWidget->setVisible(false);
switch(dateWidget->itemData(idx).toInt())
{
case All:
transactionProxyModel->setDateRange(
TransactionFilterProxy::MIN_DATE,
TransactionFilterProxy::MAX_DATE);
break;
case Today:
transactionProxyModel->setDateRange(
QDateTime(current),
TransactionFilterProxy::MAX_DATE);
break;
case ThisWeek: {
// Find last monday
QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
transactionProxyModel->setDateRange(
QDateTime(startOfWeek),
TransactionFilterProxy::MAX_DATE);
} break;
case ThisMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month(), 1)),
TransactionFilterProxy::MAX_DATE);
break;
case LastMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month()-1, 1)),
QDateTime(QDate(current.year(), current.month(), 1)));
break;
case ThisYear:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), 1, 1)),
TransactionFilterProxy::MAX_DATE);
break;
case Range:
dateRangeWidget->setVisible(true);
dateRangeChanged();
break;
}
}
void TransactionView::chooseType(int idx)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setTypeFilter(
typeWidget->itemData(idx).toInt());
}
void TransactionView::changedPrefix(const QString &prefix)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setAddressPrefix(prefix);
}
void TransactionView::changedAmount(const QString &amount)
{
if(!transactionProxyModel)
return;
qint64 amount_parsed = 0;
if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))
{
transactionProxyModel->setMinAmount(amount_parsed);
}
else
{
transactionProxyModel->setMinAmount(0);
}
}
void TransactionView::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Transaction Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(transactionProxyModel);
writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole);
writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole);
writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole);
writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void TransactionView::contextualMenu(const QPoint &point)
{
QModelIndex index = transactionView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void TransactionView::copyAddress()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);
}
void TransactionView::copyLabel()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);
}
void TransactionView::copyAmount()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);
}
void TransactionView::editLabel()
{
if(!transactionView->selectionModel() ||!model)
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
AddressTableModel *addressBook = model->getAddressTableModel();
if(!addressBook)
return;
QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();
if(address.isEmpty())
{
// If this transaction has no associated address, exit
return;
}
// Is address in address book? Address book can miss address when a transaction is
// sent from outside the UI.
int idx = addressBook->lookupAddress(address);
if(idx != -1)
{
// Edit sending / receiving address
QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());
// Determine type of address, launch appropriate editor dialog type
QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
EditAddressDialog dlg(type==AddressTableModel::Receive
? EditAddressDialog::EditReceivingAddress
: EditAddressDialog::EditSendingAddress,
this);
dlg.setModel(addressBook);
dlg.loadRow(idx);
dlg.exec();
}
else
{
// Add sending address
EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
this);
dlg.setModel(addressBook);
dlg.setAddress(address);
dlg.exec();
}
}
}
void TransactionView::showDetails()
{
if(!transactionView->selectionModel())
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
TransactionDescDialog dlg(selection.at(0));
dlg.exec();
}
}
QWidget *TransactionView::createDateRangeWidget()
{
dateRangeWidget = new QFrame();
dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
dateRangeWidget->setContentsMargins(1,1,1,1);
QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);
layout->setContentsMargins(0,0,0,0);
layout->addSpacing(23);
layout->addWidget(new QLabel(tr("Range:")));
dateFrom = new QDateTimeEdit(this);
dateFrom->setDisplayFormat("dd/MM/yy");
dateFrom->setCalendarPopup(true);
dateFrom->setMinimumWidth(100);
dateFrom->setDate(QDate::currentDate().addDays(-7));
layout->addWidget(dateFrom);
layout->addWidget(new QLabel(tr("to")));
dateTo = new QDateTimeEdit(this);
dateTo->setDisplayFormat("dd/MM/yy");
dateTo->setCalendarPopup(true);
dateTo->setMinimumWidth(100);
dateTo->setDate(QDate::currentDate());
layout->addWidget(dateTo);
layout->addStretch();
// Hide by default
dateRangeWidget->setVisible(false);
// Notify on change
connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
return dateRangeWidget;
}
void TransactionView::dateRangeChanged()
{
if(!transactionProxyModel)
return;
transactionProxyModel->setDateRange(
QDateTime(dateFrom->date()),
QDateTime(dateTo->date()).addDays(1));
}
<commit_msg>add 2 comments to transactionview.cpp to ensure no one moves setPlaceholderText to the XML file (after this all parts in the code that use setPlaceholderText have this comment<commit_after>#include "transactionview.h"
#include "transactionfilterproxy.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "bitcoinunits.h"
#include "csvmodelwriter.h"
#include "transactiondescdialog.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QScrollBar>
#include <QComboBox>
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QTableView>
#include <QHeaderView>
#include <QPushButton>
#include <QMessageBox>
#include <QPoint>
#include <QMenu>
#include <QApplication>
#include <QClipboard>
#include <QLabel>
#include <QDateTimeEdit>
TransactionView::TransactionView(QWidget *parent) :
QWidget(parent), model(0), transactionProxyModel(0),
transactionView(0)
{
// Build filter row
setContentsMargins(0,0,0,0);
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->setContentsMargins(0,0,0,0);
#ifdef Q_WS_MAC
hlayout->setSpacing(5);
hlayout->addSpacing(26);
#else
hlayout->setSpacing(0);
hlayout->addSpacing(23);
#endif
dateWidget = new QComboBox(this);
#ifdef Q_WS_MAC
dateWidget->setFixedWidth(121);
#else
dateWidget->setFixedWidth(120);
#endif
dateWidget->addItem(tr("All"), All);
dateWidget->addItem(tr("Today"), Today);
dateWidget->addItem(tr("This week"), ThisWeek);
dateWidget->addItem(tr("This month"), ThisMonth);
dateWidget->addItem(tr("Last month"), LastMonth);
dateWidget->addItem(tr("This year"), ThisYear);
dateWidget->addItem(tr("Range..."), Range);
hlayout->addWidget(dateWidget);
typeWidget = new QComboBox(this);
#ifdef Q_WS_MAC
typeWidget->setFixedWidth(121);
#else
typeWidget->setFixedWidth(120);
#endif
typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other));
hlayout->addWidget(typeWidget);
addressWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
addressWidget->setPlaceholderText(tr("Enter address or label to search"));
#endif
hlayout->addWidget(addressWidget);
amountWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
amountWidget->setPlaceholderText(tr("Min amount"));
#endif
#ifdef Q_WS_MAC
amountWidget->setFixedWidth(97);
#else
amountWidget->setFixedWidth(100);
#endif
amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));
hlayout->addWidget(amountWidget);
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(0,0,0,0);
vlayout->setSpacing(0);
QTableView *view = new QTableView(this);
vlayout->addLayout(hlayout);
vlayout->addWidget(createDateRangeWidget());
vlayout->addWidget(view);
vlayout->setSpacing(0);
int width = view->verticalScrollBar()->sizeHint().width();
// Cover scroll bar width with spacing
#ifdef Q_WS_MAC
hlayout->addSpacing(width+2);
#else
hlayout->addSpacing(width);
#endif
// Always show scroll bar
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
view->setTabKeyNavigation(false);
view->setContextMenuPolicy(Qt::CustomContextMenu);
transactionView = view;
// Actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
QAction *editLabelAction = new QAction(tr("Edit label"), this);
QAction *showDetailsAction = new QAction(tr("Show transaction details"), this);
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(editLabelAction);
contextMenu->addAction(showDetailsAction);
// Connect actions
connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));
connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));
connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));
connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));
connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));
connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));
}
void TransactionView::setModel(WalletModel *model)
{
this->model = model;
if(model)
{
transactionProxyModel = new TransactionFilterProxy(this);
transactionProxyModel->setSourceModel(model->getTransactionTableModel());
transactionProxyModel->setDynamicSortFilter(true);
transactionProxyModel->setSortRole(Qt::EditRole);
transactionView->setModel(transactionProxyModel);
transactionView->setAlternatingRowColors(true);
transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);
transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);
transactionView->setSortingEnabled(true);
transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);
transactionView->verticalHeader()->hide();
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Status, 23);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Date, 120);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Type, 120);
transactionView->horizontalHeader()->setResizeMode(
TransactionTableModel::ToAddress, QHeaderView::Stretch);
transactionView->horizontalHeader()->resizeSection(
TransactionTableModel::Amount, 100);
}
}
void TransactionView::chooseDate(int idx)
{
if(!transactionProxyModel)
return;
QDate current = QDate::currentDate();
dateRangeWidget->setVisible(false);
switch(dateWidget->itemData(idx).toInt())
{
case All:
transactionProxyModel->setDateRange(
TransactionFilterProxy::MIN_DATE,
TransactionFilterProxy::MAX_DATE);
break;
case Today:
transactionProxyModel->setDateRange(
QDateTime(current),
TransactionFilterProxy::MAX_DATE);
break;
case ThisWeek: {
// Find last monday
QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
transactionProxyModel->setDateRange(
QDateTime(startOfWeek),
TransactionFilterProxy::MAX_DATE);
} break;
case ThisMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month(), 1)),
TransactionFilterProxy::MAX_DATE);
break;
case LastMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month()-1, 1)),
QDateTime(QDate(current.year(), current.month(), 1)));
break;
case ThisYear:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), 1, 1)),
TransactionFilterProxy::MAX_DATE);
break;
case Range:
dateRangeWidget->setVisible(true);
dateRangeChanged();
break;
}
}
void TransactionView::chooseType(int idx)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setTypeFilter(
typeWidget->itemData(idx).toInt());
}
void TransactionView::changedPrefix(const QString &prefix)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setAddressPrefix(prefix);
}
void TransactionView::changedAmount(const QString &amount)
{
if(!transactionProxyModel)
return;
qint64 amount_parsed = 0;
if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))
{
transactionProxyModel->setMinAmount(amount_parsed);
}
else
{
transactionProxyModel->setMinAmount(0);
}
}
void TransactionView::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Transaction Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(transactionProxyModel);
writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole);
writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole);
writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole);
writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void TransactionView::contextualMenu(const QPoint &point)
{
QModelIndex index = transactionView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void TransactionView::copyAddress()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);
}
void TransactionView::copyLabel()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);
}
void TransactionView::copyAmount()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);
}
void TransactionView::editLabel()
{
if(!transactionView->selectionModel() ||!model)
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
AddressTableModel *addressBook = model->getAddressTableModel();
if(!addressBook)
return;
QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();
if(address.isEmpty())
{
// If this transaction has no associated address, exit
return;
}
// Is address in address book? Address book can miss address when a transaction is
// sent from outside the UI.
int idx = addressBook->lookupAddress(address);
if(idx != -1)
{
// Edit sending / receiving address
QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());
// Determine type of address, launch appropriate editor dialog type
QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
EditAddressDialog dlg(type==AddressTableModel::Receive
? EditAddressDialog::EditReceivingAddress
: EditAddressDialog::EditSendingAddress,
this);
dlg.setModel(addressBook);
dlg.loadRow(idx);
dlg.exec();
}
else
{
// Add sending address
EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
this);
dlg.setModel(addressBook);
dlg.setAddress(address);
dlg.exec();
}
}
}
void TransactionView::showDetails()
{
if(!transactionView->selectionModel())
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
TransactionDescDialog dlg(selection.at(0));
dlg.exec();
}
}
QWidget *TransactionView::createDateRangeWidget()
{
dateRangeWidget = new QFrame();
dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
dateRangeWidget->setContentsMargins(1,1,1,1);
QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);
layout->setContentsMargins(0,0,0,0);
layout->addSpacing(23);
layout->addWidget(new QLabel(tr("Range:")));
dateFrom = new QDateTimeEdit(this);
dateFrom->setDisplayFormat("dd/MM/yy");
dateFrom->setCalendarPopup(true);
dateFrom->setMinimumWidth(100);
dateFrom->setDate(QDate::currentDate().addDays(-7));
layout->addWidget(dateFrom);
layout->addWidget(new QLabel(tr("to")));
dateTo = new QDateTimeEdit(this);
dateTo->setDisplayFormat("dd/MM/yy");
dateTo->setCalendarPopup(true);
dateTo->setMinimumWidth(100);
dateTo->setDate(QDate::currentDate());
layout->addWidget(dateTo);
layout->addStretch();
// Hide by default
dateRangeWidget->setVisible(false);
// Notify on change
connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
return dateRangeWidget;
}
void TransactionView::dateRangeChanged()
{
if(!transactionProxyModel)
return;
transactionProxyModel->setDateRange(
QDateTime(dateFrom->date()),
QDateTime(dateTo->date()).addDays(1));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_BASIC_HPP
#define REALM_COLUMN_BASIC_HPP
#include <realm/column.hpp>
#include <realm/array_basic.hpp>
namespace realm {
template<class T> struct AggReturnType {
typedef T sum_type;
};
template<> struct AggReturnType<float> {
typedef double sum_type;
};
/// A basic column (BasicColumn<T>) is a single B+-tree, and the root
/// of the column is the root of the B+-tree. All leaf nodes are
/// single arrays of type BasicArray<T>.
///
/// A basic column can currently only be used for simple unstructured
/// types like float, double.
template<class T>
class BasicColumn : public ColumnBase, public ColumnTemplate<T> {
public:
typedef T value_type;
BasicColumn(Allocator&, ref_type);
std::size_t size() const REALM_NOEXCEPT;
bool is_empty() const REALM_NOEXCEPT { return size() == 0; }
T get(std::size_t ndx) const REALM_NOEXCEPT;
void add(T value = T());
void set(std::size_t ndx, T value);
void insert(std::size_t ndx, T value = T());
void erase(std::size_t row_ndx);
void move_last_over(std::size_t row_ndx);
void clear();
std::size_t count(T value) const;
typedef typename AggReturnType<T>::sum_type SumType;
SumType sum(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
double average(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
T maximum(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
T minimum(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
std::size_t find_first(T value, std::size_t begin = 0 , std::size_t end = npos) const;
void find_all(Column& result, T value, std::size_t begin = 0, std::size_t end = npos) const;
//@{
/// Find the lower/upper bound for the specified value assuming
/// that the elements are already sorted in ascending order.
std::size_t lower_bound(T value) const REALM_NOEXCEPT;
std::size_t upper_bound(T value) const REALM_NOEXCEPT;
//@{
/// Compare two columns for equality.
bool compare(const BasicColumn&) const;
static ref_type create(Allocator&, std::size_t size = 0);
// Overrriding method in ColumnBase
ref_type write(std::size_t, std::size_t, std::size_t,
_impl::OutputStream&) const override;
void insert(std::size_t, std::size_t, bool) override;
void erase(std::size_t, bool) override;
void move_last_over(std::size_t, std::size_t, bool) override;
void clear(std::size_t, bool) override;
void refresh_accessor_tree(std::size_t, const Spec&) override;
#ifdef REALM_DEBUG
void Verify() const;
void to_dot(std::ostream&, StringData title) const override;
void do_dump_node_structure(std::ostream&, int) const override;
#endif
protected:
T get_val(size_t row) const { return get(row); }
private:
std::size_t do_get_size() const REALM_NOEXCEPT override { return size(); }
/// \param row_ndx Must be `realm::npos` if appending.
void do_insert(std::size_t row_ndx, T value, std::size_t num_rows);
// Called by Array::bptree_insert().
static ref_type leaf_insert(MemRef leaf_mem, ArrayParent&, std::size_t ndx_in_parent,
Allocator&, std::size_t insert_ndx,
Array::TreeInsert<BasicColumn<T>>&);
template <typename R, Action action, class cond>
R aggregate(T target, std::size_t start, std::size_t end, std::size_t* return_ndx) const;
class SetLeafElem;
class EraseLeafElem;
class CreateHandler;
class SliceHandler;
void do_erase(std::size_t row_ndx, bool is_last);
void do_move_last_over(std::size_t row_ndx, std::size_t last_row_ndx);
void do_clear();
#ifdef REALM_DEBUG
static std::size_t verify_leaf(MemRef, Allocator&);
void leaf_to_dot(MemRef, ArrayParent*, std::size_t ndx_in_parent,
std::ostream&) const override;
static void leaf_dumper(MemRef, Allocator&, std::ostream&, int level);
#endif
friend class Array;
friend class ColumnBase;
};
} // namespace realm
// template implementation
#include <realm/column_basic_tpl.hpp>
#endif // REALM_COLUMN_BASIC_HPP
<commit_msg>BasicColumn<T>::get_leaf<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_BASIC_HPP
#define REALM_COLUMN_BASIC_HPP
#include <realm/column.hpp>
#include <realm/array_basic.hpp>
namespace realm {
template<class T> struct AggReturnType {
typedef T sum_type;
};
template<> struct AggReturnType<float> {
typedef double sum_type;
};
/// A basic column (BasicColumn<T>) is a single B+-tree, and the root
/// of the column is the root of the B+-tree. All leaf nodes are
/// single arrays of type BasicArray<T>.
///
/// A basic column can currently only be used for simple unstructured
/// types like float, double.
template<class T>
class BasicColumn : public ColumnBase, public ColumnTemplate<T> {
public:
typedef T value_type;
BasicColumn(Allocator&, ref_type);
std::size_t size() const REALM_NOEXCEPT;
bool is_empty() const REALM_NOEXCEPT { return size() == 0; }
const BasicArray<T>& get_leaf(std::size_t ndx, std::size_t& ndx_in_leaf,
BasicArray<T>& fallback) const REALM_NOEXCEPT;
T get(std::size_t ndx) const REALM_NOEXCEPT;
void add(T value = T());
void set(std::size_t ndx, T value);
void insert(std::size_t ndx, T value = T());
void erase(std::size_t row_ndx);
void move_last_over(std::size_t row_ndx);
void clear();
std::size_t count(T value) const;
typedef typename AggReturnType<T>::sum_type SumType;
SumType sum(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
double average(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
T maximum(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
T minimum(std::size_t begin = 0, std::size_t end = npos,
std::size_t limit = std::size_t(-1), size_t* return_ndx = nullptr) const;
std::size_t find_first(T value, std::size_t begin = 0 , std::size_t end = npos) const;
void find_all(Column& result, T value, std::size_t begin = 0, std::size_t end = npos) const;
//@{
/// Find the lower/upper bound for the specified value assuming
/// that the elements are already sorted in ascending order.
std::size_t lower_bound(T value) const REALM_NOEXCEPT;
std::size_t upper_bound(T value) const REALM_NOEXCEPT;
//@{
/// Compare two columns for equality.
bool compare(const BasicColumn&) const;
static ref_type create(Allocator&, std::size_t size = 0);
// Overrriding method in ColumnBase
ref_type write(std::size_t, std::size_t, std::size_t,
_impl::OutputStream&) const override;
void insert(std::size_t, std::size_t, bool) override;
void erase(std::size_t, bool) override;
void move_last_over(std::size_t, std::size_t, bool) override;
void clear(std::size_t, bool) override;
void refresh_accessor_tree(std::size_t, const Spec&) override;
#ifdef REALM_DEBUG
void Verify() const;
void to_dot(std::ostream&, StringData title) const override;
void do_dump_node_structure(std::ostream&, int) const override;
#endif
protected:
T get_val(size_t row) const { return get(row); }
private:
std::size_t do_get_size() const REALM_NOEXCEPT override { return size(); }
/// \param row_ndx Must be `realm::npos` if appending.
void do_insert(std::size_t row_ndx, T value, std::size_t num_rows);
// Called by Array::bptree_insert().
static ref_type leaf_insert(MemRef leaf_mem, ArrayParent&, std::size_t ndx_in_parent,
Allocator&, std::size_t insert_ndx,
Array::TreeInsert<BasicColumn<T>>&);
template <typename R, Action action, class cond>
R aggregate(T target, std::size_t start, std::size_t end, std::size_t* return_ndx) const;
class SetLeafElem;
class EraseLeafElem;
class CreateHandler;
class SliceHandler;
void do_erase(std::size_t row_ndx, bool is_last);
void do_move_last_over(std::size_t row_ndx, std::size_t last_row_ndx);
void do_clear();
#ifdef REALM_DEBUG
static std::size_t verify_leaf(MemRef, Allocator&);
void leaf_to_dot(MemRef, ArrayParent*, std::size_t ndx_in_parent,
std::ostream&) const override;
static void leaf_dumper(MemRef, Allocator&, std::ostream&, int level);
#endif
friend class Array;
friend class ColumnBase;
};
template <class T>
const BasicArray<T>& BasicColumn<T>::get_leaf(std::size_t ndx, std::size_t& ndx_in_leaf,
BasicArray<T>& fallback) const REALM_NOEXCEPT
{
if (!m_array->is_inner_bptree_node()) {
ndx_in_leaf = ndx;
return static_cast<const BasicArray<T>&>(*m_array);
}
std::pair<MemRef, std::size_t> p = m_array->get_bptree_leaf(ndx);
fallback.init_from_mem(p.first);
ndx_in_leaf = p.second;
return fallback;
}
} // namespace realm
// template implementation
#include <realm/column_basic_tpl.hpp>
#endif // REALM_COLUMN_BASIC_HPP
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <gl/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <cmath>
float WinWid=2000.0;
float WinHei=1000.0;
void drawCircle(float x, float y, float r, int amountSegments)
{
glBegin(GL_LINE_LOOP);
for(int i = 0; i < amountSegments; i++)
{
float angle = 2.0 * 3.1415926 * float(i) / float(amountSegments);
float dx = r * cosf(angle);
float dy = r * sinf(angle);
glVertex2f(x + dx, y + dy);
}
glEnd();
}
void Draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
//Steklyashka
glBegin(GL_QUADS);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(680, -500);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(700, -500);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(700, 250);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(680, 250);
glEnd();
//perekladina
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(500, 250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(880, 250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(880, 270);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(500, 270);
glEnd();
//punktir
//glEnable(GL_LINE_STIPPLE);
//glLineStipple(1,0x00FF);
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(680, -500);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(700, -500);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(700, 250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(680, 250);
glEnd();
//kulka
glColor3f(1.0, 0.0, 0.0);
drawCircle(689, 321, 50,60);
glBegin(GL_LINE_LOOP); //Romb
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-100, -325);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-175, -250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-100, -175);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-25, -250);
glEnd();
glBegin(GL_LINE_STRIP); //Garmata
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-770, -275);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-500, -275);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-500, -247);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-770, -247);
glEnd();
glColor3f(0.0, 0.0, 0.0); //koleso vid pushki
drawCircle(-700, -307, 30,60);
//Pidloga
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-999, -460);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-999, -499);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(999, -499);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(999,-460 );
glEnd();
//lovyshka 1
glBegin(GL_QUADS);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(445, -200);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(445, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(480, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(480,-200 );
glEnd();
//lovyshka 2
glBegin(GL_QUADS);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(195, -200);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(195, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(230, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(230,-200 );
glEnd();
glBegin(GL_LINE_LOOP);
glVertex2i(335, -400);
glVertex2i(295,-460);
glVertex2i(375,-460);
glEnd();
glFlush();
}
void Initialize()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-WinWid/2, WinWid/2, -WinHei/2, WinHei/2, -200.0, 200.0);
}
int main(int argc, char** argv)
{
//initialization
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(WinWid, WinHei);
glutInitWindowPosition(0,0);
glutCreateWindow("1ZAVDANNYA");
//registration
glutDisplayFunc(Draw);// painting
Initialize();
glutMainLoop();
return 0;
}
<commit_msg>dodav perhy user story<commit_after>#include "stdafx.h"
#include <gl/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <cmath>
float WinWid=2000.0;
float WinHei=1000.0;
void drawCircle(float x, float y, float r, int amountSegments)
{
glBegin(GL_LINE_LOOP);
for(int i = 0; i < amountSegments; i++)
{
float angle = 2.0 * 3.1415926 * float(i) / float(amountSegments);
float dx = r * cosf(angle);
float dy = r * sinf(angle);
glVertex2f(x + dx, y + dy);
}
glEnd();
}
void Draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
//Steklyashka
glBegin(GL_QUADS);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(680, -500);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(700, -500);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(700, 250);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(680, 250);
glEnd();
//perekladina
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(500, 250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(880, 250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(880, 270);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(500, 270);
glEnd();
//punktir
//glEnable(GL_LINE_STIPPLE);
//glLineStipple(1,0x00FF);
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(680, -500);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(700, -500);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(700, 250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(680, 250);
glEnd();
//kulka
glColor3f(1.0, 0.0, 0.0);
drawCircle(689, 321, 50,60);
glBegin(GL_LINE_LOOP); //Romb
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-100, -325);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-175, -250);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-100, -175);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-25, -250);
glEnd();
glBegin(GL_LINE_STRIP); //Garmata
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-770, -275);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-500, -275);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-500, -247);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-770, -247);
glEnd();
glColor3f(0.0, 0.0, 0.0); //koleso vid pushki
drawCircle(-700, -307, 30,60);
//Pidloga
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-999, -460);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(-999, -499);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(999, -499);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(999,-460 );
glEnd();
//lovyshka 1
glBegin(GL_QUADS);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(445, -200);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(445, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(480, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(480,-200 );
glEnd();
//lovyshka 2
glBegin(GL_QUADS);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(195, -200);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(195, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(230, -460);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(230,-200 );
glEnd();
glBegin(GL_LINE_LOOP);
glVertex2i(335, -400);
glVertex2i(295,-460);
glVertex2i(375,-460);
glEnd();
glFlush();
}
void Initialize()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-WinWid/2, WinWid/2, -WinHei/2, WinHei/2, -200.0, 200.0);
}
int main(int argc, char** argv)
{
//initialization
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(WinWid, WinHei);
glutInitWindowPosition(0,0);
glutCreateWindow("1ZAVDANNYA");
//registration
glutDisplayFunc(Draw);// painting
Initialize();
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>#include "finder-sync/finder-sync-host.h"
#include <vector>
#include <mutex>
#include <memory>
#include <QDir>
#include <QFileInfo>
#include "account.h"
#include "account-mgr.h"
#include "auto-login-service.h"
#include "settings-mgr.h"
#include "seafile-applet.h"
#include "rpc/local-repo.h"
#include "rpc/rpc-client.h"
#include "filebrowser/file-browser-requests.h"
#include "filebrowser/sharedlink-dialog.h"
#include "filebrowser/seafilelink-dialog.h"
#include "utils/utils.h"
enum PathStatus {
SYNC_STATUS_NONE = 0,
SYNC_STATUS_SYNCING,
SYNC_STATUS_ERROR,
SYNC_STATUS_IGNORED,
SYNC_STATUS_SYNCED,
SYNC_STATUS_READONLY,
SYNC_STATUS_PAUSED,
SYNC_STATUS_LOCKED,
SYNC_STATUS_LOCKED_BY_ME,
MAX_SYNC_STATUS,
};
namespace {
struct QtLaterDeleter {
public:
void operator()(QObject *ptr) {
ptr->deleteLater();
}
};
} // anonymous namespace
static const char *const kPathStatus[] = {
"none", "syncing", "error", "ignored", "synced", "readonly", "paused", "locked", "locked_by_me", NULL,
};
static inline PathStatus getPathStatusFromString(const QString &status) {
for (int p = SYNC_STATUS_NONE; p < MAX_SYNC_STATUS; ++p)
if (kPathStatus[p] == status)
return static_cast<PathStatus>(p);
return SYNC_STATUS_NONE;
}
inline static bool isContainsPrefix(const QString &path,
const QString &prefix) {
if (prefix.size() > path.size())
return false;
if (!path.startsWith(prefix))
return false;
if (prefix.size() < path.size() && path[prefix.size()] != '/')
return false;
return true;
}
static std::mutex update_mutex_;
static std::vector<LocalRepo> watch_set_;
static std::unique_ptr<GetSharedLinkRequest, QtLaterDeleter> get_shared_link_req_;
static std::unique_ptr<LockFileRequest, QtLaterDeleter> lock_file_req_;
FinderSyncHost::FinderSyncHost() : rpc_client_(new SeafileRpcClient) {
rpc_client_->connectDaemon();
}
FinderSyncHost::~FinderSyncHost() {
get_shared_link_req_.reset();
lock_file_req_.reset();
}
utils::BufferArray FinderSyncHost::getWatchSet(size_t header_size,
int max_size) {
updateWatchSet(); // lock is inside
std::unique_lock<std::mutex> lock(update_mutex_);
std::vector<QByteArray> array;
size_t byte_count = header_size;
unsigned count = (max_size >= 0 && watch_set_.size() > (unsigned)max_size)
? max_size
: watch_set_.size();
for (unsigned i = 0; i < count; ++i) {
array.emplace_back(watch_set_[i].worktree.toUtf8());
byte_count += 36 + array.back().size() + 3;
}
// rount byte_count to longword-size
size_t round_end = byte_count & 3;
if (round_end)
byte_count += 4 - round_end;
utils::BufferArray retval;
retval.resize(byte_count);
// zeroize rounds
switch (round_end) {
case 1:
retval[byte_count - 3] = '\0';
case 2:
retval[byte_count - 2] = '\0';
case 3:
retval[byte_count - 1] = '\0';
default:
break;
}
assert(retval.size() == byte_count);
char *pos = retval.data() + header_size;
for (unsigned i = 0; i != count; ++i) {
// copy repo_id
memcpy(pos, watch_set_[i].id.toUtf8().data(), 36);
pos += 36;
// copy worktree
memcpy(pos, array[i].data(), array[i].size() + 1);
pos += array[i].size() + 1;
// copy status
*pos++ = watch_set_[i].sync_state;
*pos++ = '\0';
}
return retval;
}
void FinderSyncHost::updateWatchSet() {
std::unique_lock<std::mutex> lock(update_mutex_);
// update watch_set_
if (rpc_client_->listLocalRepos(&watch_set_)) {
qWarning("[FinderSync] update watch set failed");
watch_set_.clear();
return;
}
for (LocalRepo &repo : watch_set_)
rpc_client_->getSyncStatus(repo);
lock.unlock();
}
uint32_t FinderSyncHost::getFileStatus(const char *repo_id, const char *path) {
std::unique_lock<std::mutex> lock(update_mutex_);
QString repo = QString::fromUtf8(repo_id, 36);
QString path_in_repo = path;
QString status;
bool isDirectory = path_in_repo.endsWith('/');
if (isDirectory)
path_in_repo.resize(path_in_repo.size() - 1);
if (rpc_client_->getRepoFileStatus(
repo,
path_in_repo,
isDirectory, &status) != 0) {
return PathStatus::SYNC_STATUS_NONE;
}
return getPathStatusFromString(status);
}
void FinderSyncHost::doShareLink(const QString &path) {
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
get_shared_link_req_.reset(new GetSharedLinkRequest(
account, repo_id, QString("/").append(path_in_repo),
QFileInfo(path).isFile()));
connect(get_shared_link_req_.get(), SIGNAL(success(const QString &)), this,
SLOT(onShareLinkGenerated(const QString &)));
get_shared_link_req_->send();
}
void FinderSyncHost::doInternalLink(const QString &path)
{
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
SeafileLinkDialog(repo_id, account, path_in_repo).exec();
}
void FinderSyncHost::doLockFile(const QString &path, bool lock)
{
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
lock_file_req_.reset(new LockFileRequest(account, repo_id, path_in_repo, lock));
connect(lock_file_req_.get(), SIGNAL(success()),
this, SLOT(onLockFileSuccess()));
lock_file_req_->send();
}
void FinderSyncHost::onShareLinkGenerated(const QString &link)
{
SharedLinkDialog *dialog = new SharedLinkDialog(link, NULL);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
dialog->raise();
dialog->activateWindow();
}
void FinderSyncHost::onLockFileSuccess()
{
LockFileRequest* req = qobject_cast<LockFileRequest*>(sender());
if (!req)
return;
rpc_client_->markFileLockState(req->repoId(), req->path(), req->lock());
}
bool FinderSyncHost::lookUpFileInformation(const QString &path, QString *repo_id, Account *account, QString *path_in_repo)
{
QString worktree;
// work in a mutex
{
std::unique_lock<std::mutex> watch_set_lock(update_mutex_);
for (const LocalRepo &repo : watch_set_)
if (isContainsPrefix(path, repo.worktree)) {
*repo_id = repo.id;
worktree = repo.worktree;
break;
}
}
if (worktree.isEmpty() || repo_id->isEmpty())
return false;
*path_in_repo = QDir(worktree).relativeFilePath(path);
if (!path_in_repo->startsWith("/"))
*path_in_repo = "/" + *path_in_repo;
if (path.endsWith("/"))
*path_in_repo += "/";
// we have a empty path_in_repo representing the root of the directory,
// and we are okay!
if (path_in_repo->startsWith("."))
return false;
*account = seafApplet->accountManager()->getAccountByRepo(*repo_id);
if (!account->isValid())
return false;
return true;
}
void FinderSyncHost::doShowFileHistory(const QString &path)
{
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
QUrl url = "/repo/file_revisions/" + repo_id + "/";
url = ::includeQueryParams(url, {{"p", path_in_repo}});
AutoLoginService::instance()->startAutoLogin(url.toString());
}
<commit_msg>Fixed generating shared link from finder menu<commit_after>#include "finder-sync/finder-sync-host.h"
#include <vector>
#include <mutex>
#include <memory>
#include <QDir>
#include <QFileInfo>
#include "account.h"
#include "account-mgr.h"
#include "auto-login-service.h"
#include "settings-mgr.h"
#include "seafile-applet.h"
#include "rpc/local-repo.h"
#include "rpc/rpc-client.h"
#include "filebrowser/file-browser-requests.h"
#include "filebrowser/sharedlink-dialog.h"
#include "filebrowser/seafilelink-dialog.h"
#include "utils/utils.h"
enum PathStatus {
SYNC_STATUS_NONE = 0,
SYNC_STATUS_SYNCING,
SYNC_STATUS_ERROR,
SYNC_STATUS_IGNORED,
SYNC_STATUS_SYNCED,
SYNC_STATUS_READONLY,
SYNC_STATUS_PAUSED,
SYNC_STATUS_LOCKED,
SYNC_STATUS_LOCKED_BY_ME,
MAX_SYNC_STATUS,
};
namespace {
struct QtLaterDeleter {
public:
void operator()(QObject *ptr) {
ptr->deleteLater();
}
};
} // anonymous namespace
static const char *const kPathStatus[] = {
"none", "syncing", "error", "ignored", "synced", "readonly", "paused", "locked", "locked_by_me", NULL,
};
static inline PathStatus getPathStatusFromString(const QString &status) {
for (int p = SYNC_STATUS_NONE; p < MAX_SYNC_STATUS; ++p)
if (kPathStatus[p] == status)
return static_cast<PathStatus>(p);
return SYNC_STATUS_NONE;
}
inline static bool isContainsPrefix(const QString &path,
const QString &prefix) {
if (prefix.size() > path.size())
return false;
if (!path.startsWith(prefix))
return false;
if (prefix.size() < path.size() && path[prefix.size()] != '/')
return false;
return true;
}
static std::mutex update_mutex_;
static std::vector<LocalRepo> watch_set_;
static std::unique_ptr<GetSharedLinkRequest, QtLaterDeleter> get_shared_link_req_;
static std::unique_ptr<LockFileRequest, QtLaterDeleter> lock_file_req_;
FinderSyncHost::FinderSyncHost() : rpc_client_(new SeafileRpcClient) {
rpc_client_->connectDaemon();
}
FinderSyncHost::~FinderSyncHost() {
get_shared_link_req_.reset();
lock_file_req_.reset();
}
utils::BufferArray FinderSyncHost::getWatchSet(size_t header_size,
int max_size) {
updateWatchSet(); // lock is inside
std::unique_lock<std::mutex> lock(update_mutex_);
std::vector<QByteArray> array;
size_t byte_count = header_size;
unsigned count = (max_size >= 0 && watch_set_.size() > (unsigned)max_size)
? max_size
: watch_set_.size();
for (unsigned i = 0; i < count; ++i) {
array.emplace_back(watch_set_[i].worktree.toUtf8());
byte_count += 36 + array.back().size() + 3;
}
// rount byte_count to longword-size
size_t round_end = byte_count & 3;
if (round_end)
byte_count += 4 - round_end;
utils::BufferArray retval;
retval.resize(byte_count);
// zeroize rounds
switch (round_end) {
case 1:
retval[byte_count - 3] = '\0';
case 2:
retval[byte_count - 2] = '\0';
case 3:
retval[byte_count - 1] = '\0';
default:
break;
}
assert(retval.size() == byte_count);
char *pos = retval.data() + header_size;
for (unsigned i = 0; i != count; ++i) {
// copy repo_id
memcpy(pos, watch_set_[i].id.toUtf8().data(), 36);
pos += 36;
// copy worktree
memcpy(pos, array[i].data(), array[i].size() + 1);
pos += array[i].size() + 1;
// copy status
*pos++ = watch_set_[i].sync_state;
*pos++ = '\0';
}
return retval;
}
void FinderSyncHost::updateWatchSet() {
std::unique_lock<std::mutex> lock(update_mutex_);
// update watch_set_
if (rpc_client_->listLocalRepos(&watch_set_)) {
qWarning("[FinderSync] update watch set failed");
watch_set_.clear();
return;
}
for (LocalRepo &repo : watch_set_)
rpc_client_->getSyncStatus(repo);
lock.unlock();
}
uint32_t FinderSyncHost::getFileStatus(const char *repo_id, const char *path) {
std::unique_lock<std::mutex> lock(update_mutex_);
QString repo = QString::fromUtf8(repo_id, 36);
QString path_in_repo = path;
QString status;
bool isDirectory = path_in_repo.endsWith('/');
if (isDirectory)
path_in_repo.resize(path_in_repo.size() - 1);
if (rpc_client_->getRepoFileStatus(
repo,
path_in_repo,
isDirectory, &status) != 0) {
return PathStatus::SYNC_STATUS_NONE;
}
return getPathStatusFromString(status);
}
void FinderSyncHost::doShareLink(const QString &path) {
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
get_shared_link_req_.reset(new GetSharedLinkRequest(
account, repo_id, QString("/").append(path_in_repo),
QFileInfo(path).isFile()));
connect(get_shared_link_req_.get(), SIGNAL(success(const QString &, const QString&)), this,
SLOT(onShareLinkGenerated(const QString &)));
get_shared_link_req_->send();
}
void FinderSyncHost::doInternalLink(const QString &path)
{
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
SeafileLinkDialog(repo_id, account, path_in_repo).exec();
}
void FinderSyncHost::doLockFile(const QString &path, bool lock)
{
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
lock_file_req_.reset(new LockFileRequest(account, repo_id, path_in_repo, lock));
connect(lock_file_req_.get(), SIGNAL(success()),
this, SLOT(onLockFileSuccess()));
lock_file_req_->send();
}
void FinderSyncHost::onShareLinkGenerated(const QString &link)
{
SharedLinkDialog *dialog = new SharedLinkDialog(link, NULL);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
dialog->raise();
dialog->activateWindow();
}
void FinderSyncHost::onLockFileSuccess()
{
LockFileRequest* req = qobject_cast<LockFileRequest*>(sender());
if (!req)
return;
rpc_client_->markFileLockState(req->repoId(), req->path(), req->lock());
}
bool FinderSyncHost::lookUpFileInformation(const QString &path, QString *repo_id, Account *account, QString *path_in_repo)
{
QString worktree;
// work in a mutex
{
std::unique_lock<std::mutex> watch_set_lock(update_mutex_);
for (const LocalRepo &repo : watch_set_)
if (isContainsPrefix(path, repo.worktree)) {
*repo_id = repo.id;
worktree = repo.worktree;
break;
}
}
if (worktree.isEmpty() || repo_id->isEmpty())
return false;
*path_in_repo = QDir(worktree).relativeFilePath(path);
if (!path_in_repo->startsWith("/"))
*path_in_repo = "/" + *path_in_repo;
if (path.endsWith("/"))
*path_in_repo += "/";
// we have a empty path_in_repo representing the root of the directory,
// and we are okay!
if (path_in_repo->startsWith("."))
return false;
*account = seafApplet->accountManager()->getAccountByRepo(*repo_id);
if (!account->isValid())
return false;
return true;
}
void FinderSyncHost::doShowFileHistory(const QString &path)
{
QString repo_id;
Account account;
QString path_in_repo;
if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) {
qWarning("[FinderSync] invalid path %s", path.toUtf8().data());
return;
}
QUrl url = "/repo/file_revisions/" + repo_id + "/";
url = ::includeQueryParams(url, {{"p", path_in_repo}});
AutoLoginService::instance()->startAutoLogin(url.toString());
}
<|endoftext|> |
<commit_before>/*
* ssfpbands_main.cpp
*
* Created by Tobias Wood on 14/03/2014.
* Copyright (c) 2014 Tobias Wood.
*
* 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/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Eigen/Dense"
#include "Nifti/Nifti.h"
#include "QUIT/QUIT.h"
using namespace std;
using namespace Eigen;
using namespace QUIT;
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: ssfpbands [options] input \n\
\n\
Input must be a single complex image with 0, 90, 180, 360 phase-cycles in order\n\
along the 4th dimension.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print more information.\n\
--out, -o path : Specify an output filename (default image base).\n\
--mask, -m file : Mask input with specified file.\n\
--flip, -F : Data order is phase, then flip-angle (default opposite).\n\
--phases, -p N : Number of phase-cycling patterns used (default is 4).\n\
--threads, -T N : Use N threads (default=hardware limit).\n\
--save, -sR : Save the robustly regularised GS (default)\n\
M : Save the magnitude regularised GS\n\
G : Save the unregularised GS\n\
C : Save the CS\n"
};
enum class Save { RR, MR, GS, CS };
static Save mode = Save::RR;
static bool verbose = false;
static size_t phase_dim = 4, flip_dim = 3, nPhases = 4;
static string prefix;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"flip", required_argument, 0, 'F'},
{"phases", required_argument, 0, 'p'},
{"threads", required_argument, 0, 'T'},
{"save", required_argument, 0, 's'},
{0, 0, 0, 0}
};
// From Knuth, surprised this isn't in STL
unsigned long long choose(unsigned long long n, unsigned long long k) {
if (k > n)
return 0;
unsigned long long r = 1;
for (unsigned long long d = 1; d <= k; ++d) {
r *= n--;
r /= d;
}
return r;
}
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Nifti::File maskFile;
MultiArray<int8_t, 3> maskData;
ThreadPool threads;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, "hvo:m:Fs:p:T:", long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'm':
cout << "Reading mask file " << optarg << endl;
maskFile.open(optarg, Nifti::Mode::Read);
maskData.resize(maskFile.matrix());
maskFile.readVolumes(maskData.begin(), maskData.end(), 0, 1);
break;
case 'o':
prefix = optarg;
cout << "Output prefix will be: " << prefix << endl;
break;
case 'F':
phase_dim = 3; flip_dim = 4; break;
case 'p':
nPhases = atoi(optarg);
if ((nPhases % 2) != 0) {
cerr << "Number of phase-cycling patterns must be divisible by 2." << endl;
return EXIT_FAILURE;
}
if (nPhases < 4) {
cerr << "Must have a minimum of 4 phase-cycling patterns." << endl;
return EXIT_FAILURE;
}
break;
case 's':
switch(*optarg) {
case 'R': mode = Save::RR; break;
case 'M': mode = Save::MR; break;
case 'G': mode = Save::GS; break;
case 'C': mode = Save::CS; break;
default:
cerr << "Unknown desired save image: " << *optarg << endl;
return EXIT_FAILURE;
}
break;
case 'T':
threads.resize(atoi(optarg));
break;
case 'h':
case '?': // getopt will print an error message
return EXIT_FAILURE;
}
}
if (verbose) cout << version << endl << credit_me << endl;
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
if (verbose) cout << "Opening input file: " << argv[optind] << endl;
string fname(argv[optind++]);
Nifti::File inputFile(fname);
Nifti::Header inHdr = inputFile.header();
if (maskFile && !maskFile.header().matchesSpace(inHdr)) {
cerr << "Mask does not match input file." << endl;
return EXIT_FAILURE;
}
const auto d = inputFile.matrix();
size_t nFlip = inputFile.dim(4) / nPhases;
if (nFlip < 1) {
cerr << "The specified number of phase-cycling patterns is inconsistent with the number of volumes in the input file." << endl;
return EXIT_FAILURE;
}
size_t nLines = nPhases / 2;
size_t nCrossings = choose(nLines, 2);
if (verbose) cout << "Reading data..." << endl;
MultiArray<complex<float>, 4> input(inputFile.dims().head(4));
inputFile.readVolumes(input.begin(), input.end());
if (prefix == "") {
prefix = inputFile.basePath() + "_";
}
inputFile.close();
if (verbose) cout << "Prepping data..." << endl;
typedef typename MultiArray<complex<float>, 5>::Index idx_t;
idx_t reshape_dims; reshape_dims << d, 0, 0;
reshape_dims[phase_dim] = nPhases;
reshape_dims[flip_dim] = nFlip;
MultiArray<complex<float>, 5> reshaped = input.reshape<5>(reshape_dims);
idx_t split_start = idx_t::Zero();
reshape_dims[phase_dim] = 2;
MultiArray<complex<float>, 5> aData = reshaped.slice<5>(split_start, reshape_dims);
split_start[phase_dim] = 2;
MultiArray<complex<float>, 5> bData = reshaped.slice<5>(split_start, reshape_dims);
// For results
MultiArray<complex<float>, 4> output(d, nFlip);
//**************************************************************************
// Do the fitting
//**************************************************************************
clock_t startClock = clock();
for (size_t vol = nFlip; vol-- > 0;) { // Reverse iterate over volumes
if (verbose) cout << "Processing volume " << vol << "..." << endl;
for (size_t vk = 0; vk < d[2]; vk++) {
function<void (const size_t, const size_t)> processVox = [&] (const size_t vi, const size_t vj) {
MatrixXf sols(2, nCrossings); sols.setZero();
if (!maskFile || (maskData[{vi,vj,vk}])) {
MultiArray<complex<float>, 5>::Index idx;
idx << vi,vj,vk,0,0;
idx[flip_dim] = vol;
size_t si = 0;
for (size_t li = 0; li < nLines; li++) {
idx_t idx_i; idx_i << vi,vj,vk,0,0;
idx_i[flip_dim] = vol;
idx_i[phase_dim] = li;
for (size_t lj = li + 1; lj < nLines; lj++) {
idx_t idx_j = idx_i;
idx_j[phase_dim] = lj;
Vector2f a_i{aData[idx_i].real(), aData[idx_i].imag()};
Vector2f a_j{aData[idx_j].real(), aData[idx_j].imag()};
Vector2f b_i{bData[idx_i].real(), bData[idx_i].imag()};
Vector2f b_j{bData[idx_j].real(), bData[idx_j].imag()};
Vector2f d_i = (b_i - a_i);
Vector2f d_j = (b_j - a_j);
Vector2f n_i{d_i[1], -d_i[0]};
Vector2f n_j{d_j[1], -d_j[0]};
float mu = (a_j - a_i).dot(n_j) / d_i.dot(n_j);
float nu = (a_i - a_j).dot(n_i) / d_j.dot(n_i);
float xi = 1.0 - pow(d_i.dot(d_j) / (d_i.norm() * d_j.norm()),2.0);
Vector2f cs = (a_i + a_j + b_i + b_j) / 4.0;
Vector2f gs = a_i + mu * d_i;
Vector2f rs = cs;
if (vol < (nFlip - 1)) { // Use the phase of the last flip-angle for regularisation
float phase = arg(output[{vi,vj,vk,nFlip-1}]);
Vector2f d_p{cos(phase),sin(phase)};
float lm_i = (a_i).dot(n_i) / d_p.dot(n_i);
float lm_j = (a_j).dot(n_j) / d_p.dot(n_j);
Vector2f p_i = lm_i * d_p;
Vector2f p_j = lm_j * d_p;
rs = (p_i + p_j) / 2.0;
}
bool rob_reg = true;
// Do the logic this way round so NaN does not propagate
if ((mu > -xi) && (mu < 1 + xi) && (nu > -xi) && (nu < 1 + xi))
rob_reg = false;
float gs_norm = gs.norm();
bool mag_reg = true;
if ((gs_norm < a_i.norm()) &&
(gs_norm < a_j.norm()) &&
(gs_norm < b_i.norm()) &&
(gs_norm < b_j.norm())) {
mag_reg = false;
}
switch (mode) {
case Save::RR: sols.col(si++) = rob_reg ? rs : gs; break;
case Save::MR: sols.col(si++) = mag_reg ? cs : gs; break;
case Save::GS: sols.col(si++) = gs; break;
case Save::CS: sols.col(si++) = cs; break;
}
}
}
}
Vector2f mean_sol = sols.rowwise().mean();
output[{vi,vj,vk,vol}] = {mean_sol[0], mean_sol[1]};
};
threads.for_loop2(processVox, d[0], d[1]);
}
}
printElapsedClock(startClock, d.prod());
inHdr.setDim(4, nFlip);
inHdr.setDatatype(Nifti::DataType::COMPLEX64);
string outname = prefix;
switch (mode) {
case Save::RR: outname.append("reg" + OutExt()); break;
case Save::MR: outname.append("magreg" + OutExt()); break;
case Save::GS: outname.append("gs" + OutExt()); break;
case Save::CS: outname.append("cs" + OutExt()); break;
}
if (verbose) cout << "Output filename: " << outname << endl;
Nifti::File outFile(inHdr, outname);
outFile.writeVolumes(output.begin(), output.end());
outFile.close();
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<commit_msg>Fixed regularisation triggers.<commit_after>/*
* ssfpbands_main.cpp
*
* Created by Tobias Wood on 14/03/2014.
* Copyright (c) 2014 Tobias Wood.
*
* 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/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Eigen/Dense"
#include "Nifti/Nifti.h"
#include "QUIT/QUIT.h"
using namespace std;
using namespace Eigen;
using namespace QUIT;
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: ssfpbands [options] input \n\
\n\
Input must be a single complex image with 0, 90, 180, 360 phase-cycles in order\n\
along the 4th dimension.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print more information.\n\
--out, -o path : Specify an output filename (default image base).\n\
--mask, -m file : Mask input with specified file.\n\
--flip, -F : Data order is phase, then flip-angle (default opposite).\n\
--phases, -p N : Number of phase-cycling patterns used (default is 4).\n\
--threads, -T N : Use N threads (default=hardware limit).\n\
--save, -sR : Save the robustly regularised GS (default)\n\
M : Save the magnitude regularised GS\n\
G : Save the unregularised GS\n\
C : Save the CS\n"
};
enum class Save { RR, MR, GS, CS };
static Save mode = Save::RR;
static bool verbose = false;
static size_t phase_dim = 4, flip_dim = 3, nPhases = 4;
static string prefix;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"flip", required_argument, 0, 'F'},
{"phases", required_argument, 0, 'p'},
{"threads", required_argument, 0, 'T'},
{"save", required_argument, 0, 's'},
{0, 0, 0, 0}
};
// From Knuth, surprised this isn't in STL
unsigned long long choose(unsigned long long n, unsigned long long k) {
if (k > n)
return 0;
unsigned long long r = 1;
for (unsigned long long d = 1; d <= k; ++d) {
r *= n--;
r /= d;
}
return r;
}
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Nifti::File maskFile;
MultiArray<int8_t, 3> maskData;
ThreadPool threads;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, "hvo:m:Fs:p:T:", long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'm':
cout << "Reading mask file " << optarg << endl;
maskFile.open(optarg, Nifti::Mode::Read);
maskData.resize(maskFile.matrix());
maskFile.readVolumes(maskData.begin(), maskData.end(), 0, 1);
break;
case 'o':
prefix = optarg;
cout << "Output prefix will be: " << prefix << endl;
break;
case 'F':
phase_dim = 3; flip_dim = 4; break;
case 'p':
nPhases = atoi(optarg);
if ((nPhases % 2) != 0) {
cerr << "Number of phase-cycling patterns must be divisible by 2." << endl;
return EXIT_FAILURE;
}
if (nPhases < 4) {
cerr << "Must have a minimum of 4 phase-cycling patterns." << endl;
return EXIT_FAILURE;
}
break;
case 's':
switch(*optarg) {
case 'R': mode = Save::RR; break;
case 'M': mode = Save::MR; break;
case 'G': mode = Save::GS; break;
case 'C': mode = Save::CS; break;
default:
cerr << "Unknown desired save image: " << *optarg << endl;
return EXIT_FAILURE;
}
break;
case 'T':
threads.resize(atoi(optarg));
break;
case 'h':
case '?': // getopt will print an error message
return EXIT_FAILURE;
}
}
if (verbose) cout << version << endl << credit_me << endl;
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
if (verbose) cout << "Opening input file: " << argv[optind] << endl;
string fname(argv[optind++]);
Nifti::File inputFile(fname);
Nifti::Header inHdr = inputFile.header();
if (maskFile && !maskFile.header().matchesSpace(inHdr)) {
cerr << "Mask does not match input file." << endl;
return EXIT_FAILURE;
}
const auto d = inputFile.matrix();
size_t nFlip = inputFile.dim(4) / nPhases;
if (nFlip < 1) {
cerr << "The specified number of phase-cycling patterns is inconsistent with the number of volumes in the input file." << endl;
return EXIT_FAILURE;
}
size_t nLines = nPhases / 2;
size_t nCrossings = choose(nLines, 2);
if (verbose) cout << "Reading data..." << endl;
MultiArray<complex<float>, 4> input(inputFile.dims().head(4));
inputFile.readVolumes(input.begin(), input.end());
if (prefix == "") {
prefix = inputFile.basePath() + "_";
}
inputFile.close();
if (verbose) cout << "Prepping data..." << endl;
typedef typename MultiArray<complex<float>, 5>::Index idx_t;
idx_t reshape_dims; reshape_dims << d, 0, 0;
reshape_dims[phase_dim] = nPhases;
reshape_dims[flip_dim] = nFlip;
MultiArray<complex<float>, 5> reshaped = input.reshape<5>(reshape_dims);
idx_t split_start = idx_t::Zero();
reshape_dims[phase_dim] = 2;
MultiArray<complex<float>, 5> aData = reshaped.slice<5>(split_start, reshape_dims);
split_start[phase_dim] = 2;
MultiArray<complex<float>, 5> bData = reshaped.slice<5>(split_start, reshape_dims);
// For results
MultiArray<complex<float>, 4> output(d, nFlip);
//**************************************************************************
// Do the fitting
//**************************************************************************
clock_t startClock = clock();
for (size_t vol = nFlip; vol-- > 0;) { // Reverse iterate over volumes
if (verbose) cout << "Processing volume " << vol << "..." << endl;
for (size_t vk = 0; vk < d[2]; vk++) {
function<void (const size_t, const size_t)> processVox = [&] (const size_t vi, const size_t vj) {
MatrixXf sols(2, nCrossings); sols.setZero();
if (!maskFile || (maskData[{vi,vj,vk}])) {
MultiArray<complex<float>, 5>::Index idx;
idx << vi,vj,vk,0,0;
idx[flip_dim] = vol;
size_t si = 0;
for (size_t li = 0; li < nLines; li++) {
idx_t idx_i; idx_i << vi,vj,vk,0,0;
idx_i[flip_dim] = vol;
idx_i[phase_dim] = li;
for (size_t lj = li + 1; lj < nLines; lj++) {
idx_t idx_j = idx_i;
idx_j[phase_dim] = lj;
Vector2f a_i{aData[idx_i].real(), aData[idx_i].imag()};
Vector2f a_j{aData[idx_j].real(), aData[idx_j].imag()};
Vector2f b_i{bData[idx_i].real(), bData[idx_i].imag()};
Vector2f b_j{bData[idx_j].real(), bData[idx_j].imag()};
Vector2f d_i = (b_i - a_i);
Vector2f d_j = (b_j - a_j);
Vector2f n_i{d_i[1], -d_i[0]};
Vector2f n_j{d_j[1], -d_j[0]};
float mu = (a_j - a_i).dot(n_j) / d_i.dot(n_j);
float nu = (a_i - a_j).dot(n_i) / d_j.dot(n_i);
float xi = 1.0 - pow(d_i.dot(d_j) / (d_i.norm() * d_j.norm()),2.0);
Vector2f cs = (a_i + a_j + b_i + b_j) / 4.0;
Vector2f gs = a_i + mu * d_i;
Vector2f rs = cs;
if (vol < (nFlip - 1)) { // Use the phase of the last flip-angle for regularisation
float phase = arg(output[{vi,vj,vk,nFlip-1}]);
Vector2f d_p{cos(phase),sin(phase)};
float lm_i = (a_i).dot(n_i) / d_p.dot(n_i);
float lm_j = (a_j).dot(n_j) / d_p.dot(n_j);
Vector2f p_i = lm_i * d_p;
Vector2f p_j = lm_j * d_p;
rs = (p_i + p_j) / 2.0;
}
bool line_reg = true;
// Do the logic this way round so NaN does not propagate
if ((mu > -xi) && (mu < 1 + xi) && (nu > -xi) && (nu < 1 + xi))
line_reg = false;
float norm = gs.norm();
if (mode == Save::RR)
norm = rs.norm();
bool mag_reg = true;
if ((norm < a_i.norm()) ||
(norm < a_j.norm()) ||
(norm < b_i.norm()) ||
(norm < b_j.norm())) {
mag_reg = false;
}
switch (mode) {
case Save::RR:
if (line_reg) {
sols.col(si++) = mag_reg ? cs : rs; break;
} else {
sols.col(si++) = gs;
}
break;
case Save::MR: sols.col(si++) = mag_reg ? cs : gs; break;
case Save::GS: sols.col(si++) = gs; break;
case Save::CS: sols.col(si++) = cs; break;
}
}
}
}
Vector2f mean_sol = sols.rowwise().mean();
output[{vi,vj,vk,vol}] = {mean_sol[0], mean_sol[1]};
};
threads.for_loop2(processVox, d[0], d[1]);
}
}
printElapsedClock(startClock, d.prod());
inHdr.setDim(4, nFlip);
inHdr.setDatatype(Nifti::DataType::COMPLEX64);
string outname = prefix;
switch (mode) {
case Save::RR: outname.append("reg" + OutExt()); break;
case Save::MR: outname.append("magreg" + OutExt()); break;
case Save::GS: outname.append("gs" + OutExt()); break;
case Save::CS: outname.append("cs" + OutExt()); break;
}
if (verbose) cout << "Output filename: " << outname << endl;
Nifti::File outFile(inHdr, outname);
outFile.writeVolumes(output.begin(), output.end());
outFile.close();
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <fcntl.h>
#include <errno.h>
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_.get()) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_.get() == NULL);
is_persistent_ = is_persistent;
event_.reset(e);
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return event_.release();
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
if (event_.get() == NULL) {
return true;
}
// event_del() is a no-op of the event isn't active.
return (event_del(event_.get()) == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = read(socket, &buf, 1);
DCHECK(nread == 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
// |should_delete_event| is true if we're modifying an event that's currently
// active in |controller|.
// If we're modifying an existing event and there's an error then we need to
// tell libevent to clean it up via event_delete() before returning.
bool should_delete_event = true;
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
should_delete_event = false;
// Ownership is transferred to the controller.
evt.reset(new event);
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification,
delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Transfer ownership of e to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
bool old_in_run = in_run_;
in_run_ = true;
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_base_loopexit(event_base_, &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
in_run_ = old_in_run;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = write(wakeup_pipe_in_, &buf, 1);
DCHECK(nwrite == 1);
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<commit_msg>Followup for one missed review comment (sorting includes).<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_.get()) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_.get() == NULL);
is_persistent_ = is_persistent;
event_.reset(e);
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return event_.release();
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
if (event_.get() == NULL) {
return true;
}
// event_del() is a no-op of the event isn't active.
return (event_del(event_.get()) == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = read(socket, &buf, 1);
DCHECK(nread == 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
// |should_delete_event| is true if we're modifying an event that's currently
// active in |controller|.
// If we're modifying an existing event and there's an error then we need to
// tell libevent to clean it up via event_delete() before returning.
bool should_delete_event = true;
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
should_delete_event = false;
// Ownership is transferred to the controller.
evt.reset(new event);
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification,
delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Transfer ownership of e to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
bool old_in_run = in_run_;
in_run_ = true;
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_base_loopexit(event_base_, &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
in_run_ = old_in_run;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = write(wakeup_pipe_in_, &buf, 1);
DCHECK(nwrite == 1);
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<|endoftext|> |
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <fcntl.h>
#include <errno.h>
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_.get()) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_.get() == NULL);
is_persistent_ = is_persistent;
event_.reset(e);
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return event_.release();
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
if (event_.get() == NULL) {
return true;
}
// event_del() is a no-op of the event isn't active.
return (event_del(event_.get()) == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = read(socket, &buf, 1);
DCHECK(nread == 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
// |should_delete_event| is true if we're modifying an event that's currently
// active in |controller|.
// If we're modifying an existing event and there's an error then we need to
// tell libevent to clean it up via event_delete() before returning.
bool should_delete_event = true;
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
should_delete_event = false;
// Ownership is transferred to the controller.
evt.reset(new event);
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification,
delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Transfer ownership of e to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
bool old_in_run = in_run_;
in_run_ = true;
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_base_loopexit(event_base_, &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
in_run_ = old_in_run;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = write(wakeup_pipe_in_, &buf, 1);
DCHECK(nwrite == 1);
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<commit_msg>Followup for one missed review comment (sorting includes).<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_.get()) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_.get() == NULL);
is_persistent_ = is_persistent;
event_.reset(e);
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return event_.release();
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
if (event_.get() == NULL) {
return true;
}
// event_del() is a no-op of the event isn't active.
return (event_del(event_.get()) == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = read(socket, &buf, 1);
DCHECK(nread == 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
// |should_delete_event| is true if we're modifying an event that's currently
// active in |controller|.
// If we're modifying an existing event and there's an error then we need to
// tell libevent to clean it up via event_delete() before returning.
bool should_delete_event = true;
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
should_delete_event = false;
// Ownership is transferred to the controller.
evt.reset(new event);
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification,
delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Transfer ownership of e to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
bool old_in_run = in_run_;
in_run_ = true;
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_base_loopexit(event_base_, &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
in_run_ = old_in_run;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = write(wakeup_pipe_in_, &buf, 1);
DCHECK(nwrite == 1);
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/path_service.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/file_path.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/platform_test.h"
namespace {
// Returns true if PathService::Get returns true and sets the path parameter
// to non-empty for the given PathService::DirType enumeration value.
bool ReturnsValidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(dir_type, &path);
return result && !path.value().empty() && file_util::PathExists(path);
}
#if defined(OS_WIN)
// Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.
bool ReturnsInvalidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);
return !result && path.empty();
}
#endif
} // namespace
// On the Mac this winds up using some autoreleased objects, so we need to
// be a PlatformTest.
typedef PlatformTest PathServiceTest;
// Test that all PathService::Get calls return a value and a true result
// in the development environment. (This test was created because a few
// later changes to Get broke the semantics of the function and yielded the
// correct value while returning false.)
TEST_F(PathServiceTest, Get) {
for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#if defined(OS_WIN)
for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {
if (key == base::DIR_LOCAL_APP_DATA_LOW &&
base::win::GetVersion() < base::win::VERSION_VISTA) {
// DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to
// fail.
EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
} else {
EXPECT_TRUE(ReturnsValidPath(key)) << key;
}
}
#elif defined(OS_MACOSX)
for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#endif
}
<commit_msg>If chromium has not been started yet, the cache path will not 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 "base/path_service.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/file_path.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/platform_test.h"
namespace {
// Returns true if PathService::Get returns true and sets the path parameter
// to non-empty for the given PathService::DirType enumeration value.
bool ReturnsValidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(dir_type, &path);
#if defined(OS_POSIX)
// If chromium has never been started on this account, the cache path will not
// exist.
if (dir_type == base::DIR_USER_CACHE)
return result && !path.value().empty();
#endif
return result && !path.value().empty() && file_util::PathExists(path);
}
#if defined(OS_WIN)
// Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.
bool ReturnsInvalidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);
return !result && path.empty();
}
#endif
} // namespace
// On the Mac this winds up using some autoreleased objects, so we need to
// be a PlatformTest.
typedef PlatformTest PathServiceTest;
// Test that all PathService::Get calls return a value and a true result
// in the development environment. (This test was created because a few
// later changes to Get broke the semantics of the function and yielded the
// correct value while returning false.)
TEST_F(PathServiceTest, Get) {
for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#if defined(OS_WIN)
for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {
if (key == base::DIR_LOCAL_APP_DATA_LOW &&
base::win::GetVersion() < base::win::VERSION_VISTA) {
// DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to
// fail.
EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
} else {
EXPECT_TRUE(ReturnsValidPath(key)) << key;
}
}
#elif defined(OS_MACOSX)
for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#endif
}
<|endoftext|> |
<commit_before><commit_msg>coverity#1213486 Uncaught exception<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: flbytes.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-06-27 21:49:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _FLBYTES_HXX
#include <flbytes.hxx>
#endif
#ifndef _SVSTDARR_ULONGS_DECL
#define _SVSTDARR_ULONGS
#include <svtools/svstdarr.hxx>
#undef _SVSTDARR_ULONGS
#endif
namespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes;
// unnamed namespaces don't work well yet
//============================================================================
namespace unnamed_svtools_flbytes {
inline ULONG MyMin( long a, long b )
{
return Max( long( Min( a , b ) ), 0L );
}
}
//============================================================================
//
// SvFillLockBytes
//
//============================================================================
TYPEINIT1(SvFillLockBytes, SvLockBytes);
//============================================================================
SvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes )
: xLockBytes( pLockBytes ),
nFilledSize( 0 ),
bTerminated( FALSE )
{
}
//============================================================================
ErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount,
ULONG *pRead ) const
{
if( bTerminated )
return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
else
{
ULONG nWanted = nPos + nCount;
if( IsSynchronMode() )
{
while( nWanted > nFilledSize && !bTerminated )
Application::Yield();
return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
}
else
{
ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead );
return ( !nCount || nRead == nCount || nErr ) ?
nErr : ERRCODE_IO_PENDING;
}
}
}
//============================================================================
ErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer,
ULONG nCount, ULONG *pWritten )
{
if( bTerminated )
return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
else
{
ULONG nWanted = nPos + nCount;
if( IsSynchronMode() )
{
while( nWanted > nFilledSize && !bTerminated )
Application::Yield();
return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
}
else
{
ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten );
return ( !nCount || nRead == nCount || nErr ) ?
nErr : ERRCODE_IO_PENDING;
}
}
}
//============================================================================
ErrCode SvFillLockBytes::Flush() const
{
return xLockBytes->Flush( );
}
//============================================================================
ErrCode SvFillLockBytes::SetSize( ULONG nSize )
{
return xLockBytes->SetSize( nSize );
}
//============================================================================
ErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType)
{
return xLockBytes->LockRegion( nPos, nCount, eType );
}
//============================================================================
ErrCode SvFillLockBytes::UnlockRegion(
ULONG nPos, ULONG nCount, LockType eType)
{
return xLockBytes->UnlockRegion( nPos, nCount, eType );
}
//============================================================================
ErrCode SvFillLockBytes::Stat(
SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
return xLockBytes->Stat( pStat, eFlag );
}
//============================================================================
ErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten )
{
ErrCode nRet = xLockBytes->WriteAt(
nFilledSize, pBuffer, nCount, pWritten );
nFilledSize += *pWritten;
return nRet;
}
//============================================================================
void SvFillLockBytes::Terminate()
{
bTerminated = TRUE;
}
//============================================================================
SV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* )
//============================================================================
//
// SvSyncLockBytes
//
//============================================================================
TYPEINIT1(SvSyncLockBytes, SvOpenLockBytes);
//============================================================================
// virtual
ErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,
ULONG * pRead) const
{
for (ULONG nReadTotal = 0;;)
{
ULONG nReadCount = 0;
ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount,
&nReadCount);
nReadTotal += nReadCount;
if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
{
if (pRead)
*pRead = nReadTotal;
return nError;
}
nPos += nReadCount;
pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount;
nCount -= nReadCount;
Application::Yield();
}
}
//============================================================================
// virtual
ErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer,
ULONG nCount, ULONG * pWritten)
{
for (ULONG nWrittenTotal = 0;;)
{
ULONG nWrittenCount = 0;
ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount,
&nWrittenCount);
nWrittenTotal += nWrittenCount;
if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
{
if (pWritten)
*pWritten = nWrittenTotal;
return nError;
}
nPos += nWrittenCount;
pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount;
nCount -= nWrittenCount;
Application::Yield();
}
}
//============================================================================
//
// SvCompositeLockBytes
//
//============================================================================
struct SvCompositeLockBytes_Impl
{
SvLockBytesMemberList aLockBytes;
SvULongs aPositions;
SvULongs aOffsets;
BOOL bPending;
ULONG RelativeOffset( ULONG nPos ) const;
ErrCode ReadWrite_Impl(
ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
BOOL bRead );
SvCompositeLockBytes_Impl() : bPending( FALSE ){}
};
//============================================================================
ULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const
{
const SvULongs& rPositions = aPositions;
const SvULongs& rOffsets = aOffsets;
USHORT nMinPos = 0;
USHORT nListCount = rPositions.Count();
// Erster Lockbytes, der bearbeitet werden muss
while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
nMinPos ++;
ULONG nSectionStart = rPositions[ nMinPos ];
if( nSectionStart > nPos )
return ULONG_MAX;
return rOffsets[ nMinPos ] + nPos - nSectionStart;
}
//============================================================================
ErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl(
ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
BOOL bRead )
{
ErrCode nErr = ERRCODE_NONE;
SvULongs& rPositions = aPositions;
SvULongs& rOffsets = aOffsets;
SvLockBytesMemberList& rLockBytes = aLockBytes;
ULONG nBytes = nCount;
USHORT nListCount = rPositions.Count();
USHORT nMinPos = 0;
// Erster Lockbytes, der bearbeitet werden muss
while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
nMinPos ++;
ULONG nSectionStart = rPositions[ nMinPos ];
if( nSectionStart > nPos )
{
// Es wird aus fuehrendem Leerbereich gearbeitet
*pProcessed = 0;
return ERRCODE_IO_CANTREAD;
}
ULONG nDone;
while( nMinPos < nListCount )
{
ULONG nToProcess;
ULONG nSectionStop;
if( nMinPos + 1 < nListCount )
{
nSectionStop = rPositions[ nMinPos + 1 ];
nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes );
}
else
{
nToProcess = nBytes;
nSectionStop = 0;
}
ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ];
SvLockBytes* pLB = rLockBytes.GetObject( nMinPos );
if( bRead )
nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone );
else
nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone );
nBytes -= nDone;
if( nErr || nDone < nToProcess || !nBytes )
{
*pProcessed = nCount - nBytes;
// Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und
// bPending gesetzt ist, Pending zurueck
if( !nDone && nMinPos == nListCount - 1 )
return bPending ? ERRCODE_IO_PENDING : nErr;
else return nErr;
}
pBuffer = static_cast< sal_Char * >(pBuffer) + nDone;
nPos += nDone;
nSectionStart = nSectionStop;
nMinPos++;
}
return nErr;
}
//============================================================================
TYPEINIT1(SvCompositeLockBytes, SvLockBytes);
//============================================================================
SvCompositeLockBytes::SvCompositeLockBytes()
: pImpl( new SvCompositeLockBytes_Impl )
{
}
//============================================================================
SvCompositeLockBytes::~SvCompositeLockBytes()
{
delete pImpl;
}
//============================================================================
void SvCompositeLockBytes::SetIsPending( BOOL bSet )
{
pImpl->bPending = bSet;
}
//============================================================================
ULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const
{
return pImpl->RelativeOffset( nPos );
}
//============================================================================
ErrCode SvCompositeLockBytes::ReadAt(
ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const
{
return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE );
}
//============================================================================
ErrCode SvCompositeLockBytes::WriteAt(
ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten )
{
return pImpl->ReadWrite_Impl(
nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE );
}
//============================================================================
ErrCode SvCompositeLockBytes::Flush() const
{
SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes;
ErrCode nErr = ERRCODE_NONE;
for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; )
nErr = rLockBytes.GetObject( nCount )->Flush();
return nErr;
}
//============================================================================
ErrCode SvCompositeLockBytes::SetSize( ULONG )
{
DBG_ERROR( "not implemented" );
return ERRCODE_IO_NOTSUPPORTED;
}
//============================================================================
ErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType )
{
DBG_ERROR( "not implemented" );
return ERRCODE_IO_NOTSUPPORTED;
}
//============================================================================
ErrCode SvCompositeLockBytes::UnlockRegion(
ULONG, ULONG, LockType )
{
DBG_ERROR( "not implemented" );
return ERRCODE_IO_NOTSUPPORTED;
}
//============================================================================
ErrCode SvCompositeLockBytes::Stat(
SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
USHORT nMax = pImpl->aPositions.Count() - 1;
SvLockBytesStat aStat;
ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag );
pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize;
return nErr;
}
//============================================================================
void SvCompositeLockBytes::Append(
SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset )
{
USHORT nCount = pImpl->aOffsets.Count();
pImpl->aLockBytes.Insert( pLockBytes, nCount );
pImpl->aPositions.Insert( nPos, nCount );
pImpl->aOffsets.Insert( nOffset, nCount );
}
//============================================================================
SvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const
{
return pImpl->aLockBytes.Count() ?
pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.246); FILE MERGED 2008/04/01 15:45:18 thb 1.5.246.3: #i85898# Stripping all external header guards 2008/04/01 12:43:48 thb 1.5.246.2: #i85898# Stripping all external header guards 2008/03/31 13:02:16 rt 1.5.246.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: flbytes.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <vcl/svapp.hxx>
#include <flbytes.hxx>
#ifndef _SVSTDARR_ULONGS_DECL
#define _SVSTDARR_ULONGS
#include <svtools/svstdarr.hxx>
#undef _SVSTDARR_ULONGS
#endif
namespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes;
// unnamed namespaces don't work well yet
//============================================================================
namespace unnamed_svtools_flbytes {
inline ULONG MyMin( long a, long b )
{
return Max( long( Min( a , b ) ), 0L );
}
}
//============================================================================
//
// SvFillLockBytes
//
//============================================================================
TYPEINIT1(SvFillLockBytes, SvLockBytes);
//============================================================================
SvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes )
: xLockBytes( pLockBytes ),
nFilledSize( 0 ),
bTerminated( FALSE )
{
}
//============================================================================
ErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount,
ULONG *pRead ) const
{
if( bTerminated )
return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
else
{
ULONG nWanted = nPos + nCount;
if( IsSynchronMode() )
{
while( nWanted > nFilledSize && !bTerminated )
Application::Yield();
return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
}
else
{
ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead );
return ( !nCount || nRead == nCount || nErr ) ?
nErr : ERRCODE_IO_PENDING;
}
}
}
//============================================================================
ErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer,
ULONG nCount, ULONG *pWritten )
{
if( bTerminated )
return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
else
{
ULONG nWanted = nPos + nCount;
if( IsSynchronMode() )
{
while( nWanted > nFilledSize && !bTerminated )
Application::Yield();
return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
}
else
{
ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten );
return ( !nCount || nRead == nCount || nErr ) ?
nErr : ERRCODE_IO_PENDING;
}
}
}
//============================================================================
ErrCode SvFillLockBytes::Flush() const
{
return xLockBytes->Flush( );
}
//============================================================================
ErrCode SvFillLockBytes::SetSize( ULONG nSize )
{
return xLockBytes->SetSize( nSize );
}
//============================================================================
ErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType)
{
return xLockBytes->LockRegion( nPos, nCount, eType );
}
//============================================================================
ErrCode SvFillLockBytes::UnlockRegion(
ULONG nPos, ULONG nCount, LockType eType)
{
return xLockBytes->UnlockRegion( nPos, nCount, eType );
}
//============================================================================
ErrCode SvFillLockBytes::Stat(
SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
return xLockBytes->Stat( pStat, eFlag );
}
//============================================================================
ErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten )
{
ErrCode nRet = xLockBytes->WriteAt(
nFilledSize, pBuffer, nCount, pWritten );
nFilledSize += *pWritten;
return nRet;
}
//============================================================================
void SvFillLockBytes::Terminate()
{
bTerminated = TRUE;
}
//============================================================================
SV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* )
//============================================================================
//
// SvSyncLockBytes
//
//============================================================================
TYPEINIT1(SvSyncLockBytes, SvOpenLockBytes);
//============================================================================
// virtual
ErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,
ULONG * pRead) const
{
for (ULONG nReadTotal = 0;;)
{
ULONG nReadCount = 0;
ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount,
&nReadCount);
nReadTotal += nReadCount;
if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
{
if (pRead)
*pRead = nReadTotal;
return nError;
}
nPos += nReadCount;
pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount;
nCount -= nReadCount;
Application::Yield();
}
}
//============================================================================
// virtual
ErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer,
ULONG nCount, ULONG * pWritten)
{
for (ULONG nWrittenTotal = 0;;)
{
ULONG nWrittenCount = 0;
ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount,
&nWrittenCount);
nWrittenTotal += nWrittenCount;
if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
{
if (pWritten)
*pWritten = nWrittenTotal;
return nError;
}
nPos += nWrittenCount;
pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount;
nCount -= nWrittenCount;
Application::Yield();
}
}
//============================================================================
//
// SvCompositeLockBytes
//
//============================================================================
struct SvCompositeLockBytes_Impl
{
SvLockBytesMemberList aLockBytes;
SvULongs aPositions;
SvULongs aOffsets;
BOOL bPending;
ULONG RelativeOffset( ULONG nPos ) const;
ErrCode ReadWrite_Impl(
ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
BOOL bRead );
SvCompositeLockBytes_Impl() : bPending( FALSE ){}
};
//============================================================================
ULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const
{
const SvULongs& rPositions = aPositions;
const SvULongs& rOffsets = aOffsets;
USHORT nMinPos = 0;
USHORT nListCount = rPositions.Count();
// Erster Lockbytes, der bearbeitet werden muss
while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
nMinPos ++;
ULONG nSectionStart = rPositions[ nMinPos ];
if( nSectionStart > nPos )
return ULONG_MAX;
return rOffsets[ nMinPos ] + nPos - nSectionStart;
}
//============================================================================
ErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl(
ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
BOOL bRead )
{
ErrCode nErr = ERRCODE_NONE;
SvULongs& rPositions = aPositions;
SvULongs& rOffsets = aOffsets;
SvLockBytesMemberList& rLockBytes = aLockBytes;
ULONG nBytes = nCount;
USHORT nListCount = rPositions.Count();
USHORT nMinPos = 0;
// Erster Lockbytes, der bearbeitet werden muss
while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
nMinPos ++;
ULONG nSectionStart = rPositions[ nMinPos ];
if( nSectionStart > nPos )
{
// Es wird aus fuehrendem Leerbereich gearbeitet
*pProcessed = 0;
return ERRCODE_IO_CANTREAD;
}
ULONG nDone;
while( nMinPos < nListCount )
{
ULONG nToProcess;
ULONG nSectionStop;
if( nMinPos + 1 < nListCount )
{
nSectionStop = rPositions[ nMinPos + 1 ];
nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes );
}
else
{
nToProcess = nBytes;
nSectionStop = 0;
}
ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ];
SvLockBytes* pLB = rLockBytes.GetObject( nMinPos );
if( bRead )
nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone );
else
nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone );
nBytes -= nDone;
if( nErr || nDone < nToProcess || !nBytes )
{
*pProcessed = nCount - nBytes;
// Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und
// bPending gesetzt ist, Pending zurueck
if( !nDone && nMinPos == nListCount - 1 )
return bPending ? ERRCODE_IO_PENDING : nErr;
else return nErr;
}
pBuffer = static_cast< sal_Char * >(pBuffer) + nDone;
nPos += nDone;
nSectionStart = nSectionStop;
nMinPos++;
}
return nErr;
}
//============================================================================
TYPEINIT1(SvCompositeLockBytes, SvLockBytes);
//============================================================================
SvCompositeLockBytes::SvCompositeLockBytes()
: pImpl( new SvCompositeLockBytes_Impl )
{
}
//============================================================================
SvCompositeLockBytes::~SvCompositeLockBytes()
{
delete pImpl;
}
//============================================================================
void SvCompositeLockBytes::SetIsPending( BOOL bSet )
{
pImpl->bPending = bSet;
}
//============================================================================
ULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const
{
return pImpl->RelativeOffset( nPos );
}
//============================================================================
ErrCode SvCompositeLockBytes::ReadAt(
ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const
{
return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE );
}
//============================================================================
ErrCode SvCompositeLockBytes::WriteAt(
ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten )
{
return pImpl->ReadWrite_Impl(
nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE );
}
//============================================================================
ErrCode SvCompositeLockBytes::Flush() const
{
SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes;
ErrCode nErr = ERRCODE_NONE;
for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; )
nErr = rLockBytes.GetObject( nCount )->Flush();
return nErr;
}
//============================================================================
ErrCode SvCompositeLockBytes::SetSize( ULONG )
{
DBG_ERROR( "not implemented" );
return ERRCODE_IO_NOTSUPPORTED;
}
//============================================================================
ErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType )
{
DBG_ERROR( "not implemented" );
return ERRCODE_IO_NOTSUPPORTED;
}
//============================================================================
ErrCode SvCompositeLockBytes::UnlockRegion(
ULONG, ULONG, LockType )
{
DBG_ERROR( "not implemented" );
return ERRCODE_IO_NOTSUPPORTED;
}
//============================================================================
ErrCode SvCompositeLockBytes::Stat(
SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
USHORT nMax = pImpl->aPositions.Count() - 1;
SvLockBytesStat aStat;
ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag );
pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize;
return nErr;
}
//============================================================================
void SvCompositeLockBytes::Append(
SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset )
{
USHORT nCount = pImpl->aOffsets.Count();
pImpl->aLockBytes.Insert( pLockBytes, nCount );
pImpl->aPositions.Insert( nPos, nCount );
pImpl->aOffsets.Insert( nOffset, nCount );
}
//============================================================================
SvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const
{
return pImpl->aLockBytes.Count() ?
pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0;
}
<|endoftext|> |
<commit_before>#include "QGCRadioChannelDisplay.h"
#include <QPainter>
QGCRadioChannelDisplay::QGCRadioChannelDisplay(QWidget *parent) : QWidget(parent)
{
m_showMinMax = false;
m_min = 0;
m_max = 1;
m_value = 1500;
m_orientation = Qt::Vertical;
m_name = "Yaw";
}
void QGCRadioChannelDisplay::setName(QString name)
{
m_name = name;
update();
}
void QGCRadioChannelDisplay::setOrientation(Qt::Orientation orient)
{
m_orientation = orient;
update();
}
void QGCRadioChannelDisplay::paintEvent(QPaintEvent *event)
{
//Values range from 0-3000.
//1500 is the middle, static servo value.
QPainter painter(this);
int currval = m_value;
if (currval > m_max)
{
currval = m_max;
}
if (currval < m_min)
{
currval = m_min;
}
if (m_orientation == Qt::Vertical)
{
painter.drawRect(0,0,width()-1,(height()-1) - (painter.fontMetrics().height() * 2));
painter.setBrush(QBrush(QColor::fromRgb(50,255,50),Qt::SolidPattern));
painter.setPen(QColor::fromRgb(50,255,50));
//m_value - m_min / m_max - m_min
//if (!m_showMinMax)
//{
// int newval = (height()-2-(painter.fontMetrics().height() * 2)) * ((float)(currval - m_min) / ((m_max-m_min)+1));
// int newvaly = (height()-2-(painter.fontMetrics().height() * 2)) - newval;
// painter.drawRect(1,newvaly,width()-3,((height()-2) - newvaly - (painter.fontMetrics().height() * 2)));
//}
//else
//{
int newval = (height()-2-(painter.fontMetrics().height() * 2)) * ((float)((currval - 800.0) / 1401));
int newvaly = (height()-2-(painter.fontMetrics().height() * 2)) - newval;
painter.drawRect(1,newvaly,width()-3,((height()-2) - newvaly - (painter.fontMetrics().height() * 2)));
//}
QString valstr = QString::number(m_value);
painter.setPen(QColor::fromRgb(255,255,255));
painter.drawText((width()/2.0) - (painter.fontMetrics().width(m_name)/2.0),((height()-3) - (painter.fontMetrics().height()*1)),m_name);
painter.drawText((width()/2.0) - (painter.fontMetrics().width(valstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),valstr);
if (m_showMinMax)
{
painter.setBrush(Qt::NoBrush);
painter.setPen(QColor::fromRgb(255,0,0));
int maxyval = (height()-3 - (painter.fontMetrics().height() * 2)) - (((height()-3-(painter.fontMetrics().height() * 2)) * ((float)(m_max - 800) / 1400.0)));
int minyval = (height()-3 - (painter.fontMetrics().height() * 2)) - (((height()-3-(painter.fontMetrics().height() * 2)) * ((float)(m_min - 800) / 1400.0)));
painter.drawRect(2,maxyval,width()-3,minyval - maxyval);
QString minstr = QString::number(m_min);
painter.drawText((width() / 2.0) - (painter.fontMetrics().width("min")/2.0),minyval,"min");
painter.drawText((width() / 2.0) - (painter.fontMetrics().width(minstr)/2.0),minyval + painter.fontMetrics().height(),minstr);
QString maxstr = QString::number(m_max);
painter.drawText((width() / 2.0) - (painter.fontMetrics().width("max")/2.0),maxyval,"max");
painter.drawText((width() / 2.0) - (painter.fontMetrics().width(maxstr)/2.0),maxyval + painter.fontMetrics().height(),maxstr);
//painter.drawRect(width() * ,2,((width()-1) * ((float)m_max / 3000.0)) - (width() * ((float)m_min / 3000.0)),(height()-5) - (painter.fontMetrics().height() * 2));
}
}
else
{
painter.drawRect(0,0,width()-1,(height()-1) - (painter.fontMetrics().height() * 2));
painter.setBrush(QBrush(QColor::fromRgb(50,255,50),Qt::SolidPattern));
painter.setPen(QColor::fromRgb(50,255,50));
//if (!m_showMinMax)
//{
// painter.drawRect(1,1,(width()-3) * ((float)(currval-m_min) / (m_max-m_min)),(height()-3) - (painter.fontMetrics().height() * 2));
//}
//else
//{
painter.drawRect(1,1,(width()-3) * ((float)(currval-800.0) / 1400.0),(height()-3) - (painter.fontMetrics().height() * 2));
//}
painter.setPen(QColor::fromRgb(255,255,255));
QString valstr = QString::number(m_value);
painter.drawText((width()/2.0) - (painter.fontMetrics().width(m_name)/2.0),((height()-3) - (painter.fontMetrics().height()*1)),m_name);
painter.drawText((width()/2.0) - (painter.fontMetrics().width(valstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),valstr);
if (m_showMinMax)
{
painter.setBrush(Qt::NoBrush);
painter.setPen(QColor::fromRgb(255,0,0));
painter.drawRect(width() * ((float)(m_min - 800.0) / 1400.0),2,((width()-1) * ((float)(m_max-800.0) / 1400.0)) - (width() * ((float)(m_min-800.0) / 1400.0)),(height()-5) - (painter.fontMetrics().height() * 2));
QString minstr = QString::number(m_min);
painter.drawText((width() * ((float)(m_min-800.0) / 1400.0)) - (painter.fontMetrics().width("min")/2.0),((height()-3) - (painter.fontMetrics().height()*1)),"min");
painter.drawText((width() * ((float)(m_min-800.0) / 1400.0)) - (painter.fontMetrics().width(minstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),minstr);
QString maxstr = QString::number(m_max);
painter.drawText((width() * ((float)(m_max-800.0) / 1400.0)) - (painter.fontMetrics().width("max")/2.0),((height()-3) - (painter.fontMetrics().height()*1)),"max");
painter.drawText((width() * ((float)(m_max-800.0) / 1400.0)) - (painter.fontMetrics().width(maxstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),maxstr);
}
}
}
void QGCRadioChannelDisplay::setValue(int value)
{
if (value < 0)
{
m_value = 0;
}
else if (value > 3000)
{
m_value = 3000;
}
else
{
m_value = value;
}
update();
}
void QGCRadioChannelDisplay::showMinMax()
{
m_showMinMax = true;
update();
}
void QGCRadioChannelDisplay::hideMinMax()
{
m_showMinMax = false;
update();
}
void QGCRadioChannelDisplay::setMin(int value)
{
m_min = value;
if (m_min == m_max)
{
m_min--;
}
update();
}
void QGCRadioChannelDisplay::setMax(int value)
{
m_max = value;
if (m_min == m_max)
{
m_max++;
}
update();
}
<commit_msg>Changed RadioChannel bars to use proper Palette colors, so text is always visible<commit_after>#include "QGCRadioChannelDisplay.h"
#include <QPainter>
QGCRadioChannelDisplay::QGCRadioChannelDisplay(QWidget *parent) : QWidget(parent)
{
m_showMinMax = false;
m_min = 0;
m_max = 1;
m_value = 1500;
m_orientation = Qt::Vertical;
m_name = "Yaw";
}
void QGCRadioChannelDisplay::setName(QString name)
{
m_name = name;
update();
}
void QGCRadioChannelDisplay::setOrientation(Qt::Orientation orient)
{
m_orientation = orient;
update();
}
void QGCRadioChannelDisplay::paintEvent(QPaintEvent *event)
{
//Values range from 0-3000.
//1500 is the middle, static servo value.
QPainter painter(this);
int currval = m_value;
if (currval > m_max)
{
currval = m_max;
}
if (currval < m_min)
{
currval = m_min;
}
if (m_orientation == Qt::Vertical)
{
painter.drawRect(0,0,width()-1,(height()-1) - (painter.fontMetrics().height() * 2));
painter.setBrush(QBrush(QColor::fromRgb(50,255,50),Qt::SolidPattern));
//m_value - m_min / m_max - m_min
//if (!m_showMinMax)
//{
// int newval = (height()-2-(painter.fontMetrics().height() * 2)) * ((float)(currval - m_min) / ((m_max-m_min)+1));
// int newvaly = (height()-2-(painter.fontMetrics().height() * 2)) - newval;
// painter.drawRect(1,newvaly,width()-3,((height()-2) - newvaly - (painter.fontMetrics().height() * 2)));
//}
//else
//{
int newval = (height()-2-(painter.fontMetrics().height() * 2)) * ((float)((currval - 800.0) / 1401));
int newvaly = (height()-2-(painter.fontMetrics().height() * 2)) - newval;
painter.drawRect(1,newvaly,width()-3,((height()-2) - newvaly - (painter.fontMetrics().height() * 2)));
//}
QString valstr = QString::number(m_value);
painter.setBrush(this->palette().windowText());
painter.drawText((width()/2.0) - (painter.fontMetrics().width(m_name)/2.0),((height()-3) - (painter.fontMetrics().height()*1)),m_name);
painter.drawText((width()/2.0) - (painter.fontMetrics().width(valstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),valstr);
if (m_showMinMax)
{
painter.setBrush(Qt::NoBrush);
painter.setPen(QColor::fromRgb(255,0,0));
int maxyval = (height()-3 - (painter.fontMetrics().height() * 2)) - (((height()-3-(painter.fontMetrics().height() * 2)) * ((float)(m_max - 800) / 1400.0)));
int minyval = (height()-3 - (painter.fontMetrics().height() * 2)) - (((height()-3-(painter.fontMetrics().height() * 2)) * ((float)(m_min - 800) / 1400.0)));
painter.drawRect(2,maxyval,width()-3,minyval - maxyval);
QString minstr = QString::number(m_min);
painter.drawText((width() / 2.0) - (painter.fontMetrics().width("min")/2.0),minyval,"min");
painter.drawText((width() / 2.0) - (painter.fontMetrics().width(minstr)/2.0),minyval + painter.fontMetrics().height(),minstr);
QString maxstr = QString::number(m_max);
painter.drawText((width() / 2.0) - (painter.fontMetrics().width("max")/2.0),maxyval,"max");
painter.drawText((width() / 2.0) - (painter.fontMetrics().width(maxstr)/2.0),maxyval + painter.fontMetrics().height(),maxstr);
//painter.drawRect(width() * ,2,((width()-1) * ((float)m_max / 3000.0)) - (width() * ((float)m_min / 3000.0)),(height()-5) - (painter.fontMetrics().height() * 2));
}
}
else
{
painter.drawRect(0,0,width()-1,(height()-1) - (painter.fontMetrics().height() * 2));
painter.setBrush(QBrush(QColor::fromRgb(50,255,50),Qt::SolidPattern));
//painter.setPen(QColor::fromRgb(50,255,50));
//if (!m_showMinMax)
//{
// painter.drawRect(1,1,(width()-3) * ((float)(currval-m_min) / (m_max-m_min)),(height()-3) - (painter.fontMetrics().height() * 2));
//}
//else
//{
painter.drawRect(1,1,(width()-3) * ((float)(currval-800.0) / 1400.0),(height()-3) - (painter.fontMetrics().height() * 2));
//}
painter.setBrush(this->palette().windowText());
QString valstr = QString::number(m_value);
painter.drawText((width()/2.0) - (painter.fontMetrics().width(m_name)/2.0),((height()-3) - (painter.fontMetrics().height()*1)),m_name);
painter.drawText((width()/2.0) - (painter.fontMetrics().width(valstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),valstr);
if (m_showMinMax)
{
painter.setBrush(Qt::NoBrush);
painter.setPen(QColor::fromRgb(255,0,0));
painter.drawRect(width() * ((float)(m_min - 800.0) / 1400.0),2,((width()-1) * ((float)(m_max-800.0) / 1400.0)) - (width() * ((float)(m_min-800.0) / 1400.0)),(height()-5) - (painter.fontMetrics().height() * 2));
QString minstr = QString::number(m_min);
painter.drawText((width() * ((float)(m_min-800.0) / 1400.0)) - (painter.fontMetrics().width("min")/2.0),((height()-3) - (painter.fontMetrics().height()*1)),"min");
painter.drawText((width() * ((float)(m_min-800.0) / 1400.0)) - (painter.fontMetrics().width(minstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),minstr);
QString maxstr = QString::number(m_max);
painter.drawText((width() * ((float)(m_max-800.0) / 1400.0)) - (painter.fontMetrics().width("max")/2.0),((height()-3) - (painter.fontMetrics().height()*1)),"max");
painter.drawText((width() * ((float)(m_max-800.0) / 1400.0)) - (painter.fontMetrics().width(maxstr)/2.0),((height()-3) - (painter.fontMetrics().height() * 0)),maxstr);
}
}
}
void QGCRadioChannelDisplay::setValue(int value)
{
if (value < 0)
{
m_value = 0;
}
else if (value > 3000)
{
m_value = 3000;
}
else
{
m_value = value;
}
update();
}
void QGCRadioChannelDisplay::showMinMax()
{
m_showMinMax = true;
update();
}
void QGCRadioChannelDisplay::hideMinMax()
{
m_showMinMax = false;
update();
}
void QGCRadioChannelDisplay::setMin(int value)
{
m_min = value;
if (m_min == m_max)
{
m_min--;
}
update();
}
void QGCRadioChannelDisplay::setMax(int value)
{
m_max = value;
if (m_min == m_max)
{
m_max++;
}
update();
}
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <dariadb.h>
#include <storage/fs.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
#include <thread>
#include <atomic>
#include <cassert>
class BenchCallback :public dariadb::storage::Cursor::Callback {
public:
void call(dariadb::storage::Chunk_Ptr &) {
count++;
}
size_t count;
};
const std::string storagePath = "benchStorage/";
std::atomic_long append_count{ 0 }, read_all_times{ 0 };
size_t thread_count = 5;
size_t iteration_count = 1000000;
const size_t chunks_count = 1024;
const size_t chunks_size = 1024;
bool stop_info = false;
bool stop_read_all{ false };
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
{
dariadb::Time t = 0;
dariadb::Meas first;
first.id = 1;
first.time = t;
dariadb::storage::Chunk_Ptr ch = std::make_shared<dariadb::storage::Chunk>(chunks_size, first);
for (int i = 0;; i++, t++) {
first.flag = dariadb::Flag(i);
first.time = t;
first.value = dariadb::Value(i);
if (!ch->append(first)) {
break;
}
}
if (dariadb::utils::fs::path_exists(storagePath)) {
dariadb::utils::fs::rm(storagePath);
}
dariadb::storage::PageManager::start(storagePath, dariadb::storage::STORAGE_MODE::SINGLE, chunks_count, chunks_size);
auto start = clock();
for (size_t i = 0; i < chunks_count; ++i) {
auto res = dariadb::storage::PageManager::instance()->append_chunk(ch);
ch->maxTime += dariadb::Time(chunks_size);
ch->minTime += dariadb::Time(chunks_size);
assert(res);
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "insert : " << elapsed << std::endl;
dariadb::storage::PageManager::stop();
if (dariadb::utils::fs::path_exists(storagePath)) {
dariadb::utils::fs::rm(storagePath);
}
}
}
<commit_msg>page read benchmark;<commit_after>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <dariadb.h>
#include <storage/fs.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
#include <thread>
#include <atomic>
#include <cassert>
class BenchCallback :public dariadb::storage::Cursor::Callback {
public:
void call(dariadb::storage::Chunk_Ptr &) {
count++;
}
size_t count;
};
const std::string storagePath = "benchStorage/";
const size_t chunks_count = 1024;
const size_t chunks_size = 1024;
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
{
dariadb::Time t = 0;
dariadb::Meas first;
first.id = 1;
first.time = t;
dariadb::storage::Chunk_Ptr ch = std::make_shared<dariadb::storage::Chunk>(chunks_size, first);
for (int i = 0;; i++, t++) {
first.flag = dariadb::Flag(i);
first.time = t;
first.value = dariadb::Value(i);
if (!ch->append(first)) {
break;
}
}
if (dariadb::utils::fs::path_exists(storagePath)) {
dariadb::utils::fs::rm(storagePath);
}
dariadb::storage::PageManager::start(storagePath, dariadb::storage::STORAGE_MODE::SINGLE, chunks_count, chunks_size);
auto start = clock();
for (size_t i = 0; i < chunks_count; ++i) {
dariadb::storage::PageManager::instance()->append_chunk(ch);
ch->maxTime += dariadb::Time(chunks_size);
ch->minTime += dariadb::Time(chunks_size);
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "insert : " << elapsed << std::endl;
BenchCallback*clbk = new BenchCallback;
start = clock();
auto cursor = dariadb::storage::PageManager::instance()->get_chunks(dariadb::IdArray{}, 0, ch->maxTime, 0);
cursor->readAll(clbk);
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "readAll : " << elapsed << std::endl;
cursor = nullptr;
delete clbk;
dariadb::storage::PageManager::stop();
if (dariadb::utils::fs::path_exists(storagePath)) {
dariadb::utils::fs::rm(storagePath);
}
ch = nullptr;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 Damien Tardy-Panis
*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
**/
#include "Ahistaa.h"
#include <QDebug>
Ahistaa::Ahistaa(QObject *parent) :
Comic(parent)
{
m_info.id = QString("ahistaa");
m_info.name = QString("Ahistaa");
m_info.color = QColor(177, 177, 177);
m_info.authors = QStringList("Kris K");
m_info.homepage = QUrl("http://ahistaa.sarjakuvablogit.com/");
m_info.country = QLocale::Finland;
m_info.language = QLocale::Finnish;
m_info.startDate = QDate::fromString("2014-11-05", Qt::ISODate);
m_info.endDate = QDate::currentDate();
m_info.stripSourceUrl = QUrl("http://ahistaa.sarjakuvablogit.com/feed/");
}
QUrl Ahistaa::extractStripImageUrl(QByteArray data)
{
return regexExtractStripImageUrl(data, "<img[^>]*src=\"([^\"]*)\"");
}
<commit_msg>fix Ahistaa new location<commit_after>/**
* Copyright (c) 2015 Damien Tardy-Panis
*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
**/
#include "Ahistaa.h"
#include <QDebug>
Ahistaa::Ahistaa(QObject *parent) :
Comic(parent)
{
m_info.id = QString("ahistaa");
m_info.name = QString("Ahistaa");
m_info.color = QColor(177, 177, 177);
m_info.authors = QStringList("Kris K");
m_info.homepage = QUrl("http://ahistaa.tumblr.com/");
m_info.country = QLocale::Finland;
m_info.language = QLocale::Finnish;
m_info.startDate = QDate::fromString("2014-11-05", Qt::ISODate);
m_info.endDate = QDate::currentDate();
m_info.stripSourceUrl = QUrl("http://ahistaa.tumblr.com/rss");
}
QUrl Ahistaa::extractStripImageUrl(QByteArray data)
{
return regexExtractStripImageUrl(data, "<img[^&]*src=\"([^\"]*media.tumblr.com/[^\"]*)\"");
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.2 2000/02/06 07:47:48 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:08:31 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:44:37 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(XMLDOCUMENTHANDLER_HPP)
#define XMLDOCUMENTHANDLER_HPP
#include <util/XML4CDefs.hpp>
#include <util/RefVectorOf.hpp>
#include <framework/XMLAttr.hpp>
class XMLElementDecl;
class XMLEntityDecl;
/**
*
* This abstract class provides the interface for the scanner to return
* XML document information up to the parser as it scans through the
* document. The interface is very similar to org.sax.DocumentHandler, but
* has some extra methods required to get all the data out.
*
* Some of the methods are designated as 'advanced' callbacks. They are
* enabled only if the 'setAdvancedCallbacks' flag has been set on the
* scanner. This scheme is used to avoid overhead when these more advanced
* events are not needed, such as in a SAX parser.</p>
*/
class XMLPARSER_EXPORT XMLDocumentHandler
{
public:
// -----------------------------------------------------------------------
// Constructors are hidden, just the virtual destructor is exposed
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
virtual ~XMLDocumentHandler()
{
}
//@}
/** @name The document handler interface */
//@{
/**
* Receive notification of character data.
*
* <p>The scanner will call this method to report each chunk of
* character data. The scanner may return all contiguous character
* data in a single chunk, or they may split it into several
* chunks; however, all of the characters in any single event
* will come from the same external entity, so that the Locator
* provides useful information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The content (characters) between markup from the XML
* document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #ignorableWhitespace
* @see Locator
*/
virtual void docCharacters
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/**
* Receive notification of comments in the XML content being parsed.
*
* @param comment The text of the comment.
*/
virtual void docComment
(
const XMLCh* const comment
) = 0;
/**
* Receive notification of PI's parsed in the XML content.
*
* @param target The name of the PI.
* @param data The body of the PI.
*/
virtual void docPI
(
const XMLCh* const target
, const XMLCh* const data
) = 0;
/**
* Receive notification after the scanner has parsed the end of the
* document.
*/
virtual void endDocument() = 0;
/**
* This method is called when scanner encounters the end of element tag.
* There will be a corresponding startElement() event for every
* endElement() event, but not necessarily the other way around. For
* empty tags, there is only a startElement() call.
*
* @param elementName The name of the element whose end tag was just
* parsed.
* @param isRoot Indicates if this is the root element.
*/
virtual void endElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const bool isRoot
) = 0;
/**
* This method is called when scanner encounters the end of an entity
* reference.
*
* @param entityName The name of the entity reference just scanned.
*/
virtual void endEntityReference
(
const XMLEntityDecl& entDecl
) = 0;
/**
* Receive notification of ignorable whitespace in element content.
*
* <p>Validating Parsers must use this method to report each chunk
* of ignorable whitespace (see the W3C XML 1.0 recommendation,
* section 2.10): non-validating parsers may also use this method
* if they are capable of parsing and using content models.</p>
*
* <p>The scanner may return all contiguous whitespace in a single
* chunk, or it may split it into several chunks; however, all of
* the characters in any single event will come from the same
* external entity, so that the Locator provides useful
* information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The whitespace characters from the XML document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #characters
*/
virtual void ignorableWhitespace
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/**
* This method is used to give the registered document handler a
* chance to reset itself. Its called by the scanner at the start of
* every parse.
*/
virtual void resetDocument() = 0;
/**
* This method is the first callback called the scanner at the
* start of every parse.
*/
virtual void startDocument() = 0;
virtual void startElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const XMLCh* const prefixName
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount
, const bool isEmpty
, const bool isRoot
) = 0;
/**
* Receive notification when the scanner hits an entity reference.
* This is currently useful only to DOM parser configurations as SAX
* does not provide any api to return this information.
*
* @param entityName The name of the entity that was referenced.
*/
virtual void startEntityReference(const XMLEntityDecl& entDecl) = 0;
/**
* Receive notification when the scanner hits the XML declaration
* clause in the XML file. Currently neither DOM nor SAX provide
* API's to return back this information. This is an advanced
* callback.
*
* @param versionStr The value of the <code>version</code> attribute
* of the XML decl.
* @param encodingStr The value of the <code>encoding</code> attribute
* of the XML decl.
* @param standaloneStr The value of the <code>standalone</code>
* attribute of the XML decl.
* @param autoEncodingStr The encoding string auto-detected by the
* scanner. In absence of any 'encoding' attribute in the
* XML decl, the XML standard specifies how a parser can
* auto-detect. If there is no <code>encodingStr</code>
* this is what will be used to try to decode the file.
*/
virtual void XMLDecl
(
const XMLCh* const versionStr
, const XMLCh* const encodingStr
, const XMLCh* const standaloneStr
, const XMLCh* const autoEncodingStr
) = 0;
//@}
protected :
// -----------------------------------------------------------------------
// Hidden Constructors
// -----------------------------------------------------------------------
XMLDocumentHandler()
{
}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLDocumentHandler(const XMLDocumentHandler&);
void operator=(const XMLDocumentHandler&);
};
#endif
<commit_msg>Added docs for startElement<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.3 2000/02/09 19:47:27 abagchi
* Added docs for startElement
*
* Revision 1.2 2000/02/06 07:47:48 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:08:31 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:44:37 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(XMLDOCUMENTHANDLER_HPP)
#define XMLDOCUMENTHANDLER_HPP
#include <util/XML4CDefs.hpp>
#include <util/RefVectorOf.hpp>
#include <framework/XMLAttr.hpp>
class XMLElementDecl;
class XMLEntityDecl;
/**
*
* This abstract class provides the interface for the scanner to return
* XML document information up to the parser as it scans through the
* document. The interface is very similar to org.sax.DocumentHandler, but
* has some extra methods required to get all the data out.
*
* Some of the methods are designated as 'advanced' callbacks. They are
* enabled only if the 'setAdvancedCallbacks' flag has been set on the
* scanner. This scheme is used to avoid overhead when these more advanced
* events are not needed, such as in a SAX parser.</p>
*/
class XMLPARSER_EXPORT XMLDocumentHandler
{
public:
// -----------------------------------------------------------------------
// Constructors are hidden, just the virtual destructor is exposed
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
virtual ~XMLDocumentHandler()
{
}
//@}
/** @name The document handler interface */
//@{
/**
* Receive notification of character data.
*
* <p>The scanner will call this method to report each chunk of
* character data. The scanner may return all contiguous character
* data in a single chunk, or they may split it into several
* chunks; however, all of the characters in any single event
* will come from the same external entity, so that the Locator
* provides useful information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The content (characters) between markup from the XML
* document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #ignorableWhitespace
* @see Locator
*/
virtual void docCharacters
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/**
* Receive notification of comments in the XML content being parsed.
*
* @param comment The text of the comment.
*/
virtual void docComment
(
const XMLCh* const comment
) = 0;
/**
* Receive notification of PI's parsed in the XML content.
*
* @param target The name of the PI.
* @param data The body of the PI.
*/
virtual void docPI
(
const XMLCh* const target
, const XMLCh* const data
) = 0;
/**
* Receive notification after the scanner has parsed the end of the
* document.
*/
virtual void endDocument() = 0;
/**
* This method is called when scanner encounters the end of element tag.
* There will be a corresponding startElement() event for every
* endElement() event, but not necessarily the other way around. For
* empty tags, there is only a startElement() call.
*
* @param elementDecl The name of the element whose end tag was just
* parsed.
* @param uriId The ID of the URI in the URI pool (only valid if
* name spaces is enabled)
* @param isRoot Indicates if this is the root element.
*/
virtual void endElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const bool isRoot
) = 0;
/**
* This method is called when scanner encounters the end of an entity
* reference.
*
* @param entityName The name of the entity reference just scanned.
*/
virtual void endEntityReference
(
const XMLEntityDecl& entDecl
) = 0;
/**
* Receive notification of ignorable whitespace in element content.
*
* <p>Validating Parsers must use this method to report each chunk
* of ignorable whitespace (see the W3C XML 1.0 recommendation,
* section 2.10): non-validating parsers may also use this method
* if they are capable of parsing and using content models.</p>
*
* <p>The scanner may return all contiguous whitespace in a single
* chunk, or it may split it into several chunks; however, all of
* the characters in any single event will come from the same
* external entity, so that the Locator provides useful
* information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The whitespace characters from the XML document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #characters
*/
virtual void ignorableWhitespace
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/**
* This method is used to give the registered document handler a
* chance to reset itself. Its called by the scanner at the start of
* every parse.
*/
virtual void resetDocument() = 0;
/**
* This method is the first callback called the scanner at the
* start of every parse.
*/
virtual void startDocument() = 0;
/**
* This method is called when scanner encounters the start of an element tag.
* All elements must always have a startElement() tag. Empty tags will
* only have the startElement() tag and no endElement() tag.
*
* @param elementDecl The name of the element whose start tag was just
* parsed.
* @param uriId The ID of the URI in the URI pool (only valid if
* name spaces is enabled)
* @param prefixName The string representing the prefix name
* @param attrList List of attributes in the element
* @param attrCount Count of the attributes in the element
* @param isEmpty Indicates if the element is empty
* @param isRoot Indicates if this is the root element.
*
*/
virtual void startElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const XMLCh* const prefixName
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount
, const bool isEmpty
, const bool isRoot
) = 0;
/**
* Receive notification when the scanner hits an entity reference.
* This is currently useful only to DOM parser configurations as SAX
* does not provide any api to return this information.
*
* @param entityName The name of the entity that was referenced.
*/
virtual void startEntityReference(const XMLEntityDecl& entDecl) = 0;
/**
* Receive notification when the scanner hits the XML declaration
* clause in the XML file. Currently neither DOM nor SAX provide
* API's to return back this information. This is an advanced
* callback.
*
* @param versionStr The value of the <code>version</code> attribute
* of the XML decl.
* @param encodingStr The value of the <code>encoding</code> attribute
* of the XML decl.
* @param standaloneStr The value of the <code>standalone</code>
* attribute of the XML decl.
* @param autoEncodingStr The encoding string auto-detected by the
* scanner. In absence of any 'encoding' attribute in the
* XML decl, the XML standard specifies how a parser can
* auto-detect. If there is no <code>encodingStr</code>
* this is what will be used to try to decode the file.
*/
virtual void XMLDecl
(
const XMLCh* const versionStr
, const XMLCh* const encodingStr
, const XMLCh* const standaloneStr
, const XMLCh* const autoEncodingStr
) = 0;
//@}
protected :
// -----------------------------------------------------------------------
// Hidden Constructors
// -----------------------------------------------------------------------
XMLDocumentHandler()
{
}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLDocumentHandler(const XMLDocumentHandler&);
void operator=(const XMLDocumentHandler&);
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2013 Plenluno All rights reserved.
#include "./gtest_net_common.h"
namespace libj {
namespace node {
TEST(GTestNetTcp, TestMemoryLeak) {
net::Socket::Ptr socket = net::createConnection(8080);
ASSERT_TRUE(!!socket);
}
static const UInt NUM_CONNS = 7;
TEST(GTestNetTcp, TestTcp) {
Int port = 10000;
net::Server::Ptr server = net::createServer();
server->on(
net::Server::EVENT_CONNECTION,
JsFunction::Ptr(new GTestNetServerOnConnection(server, NUM_CONNS)));
server->listen(port);
for (Size i = 0; i < NUM_CONNS; i++) {
net::Socket::Ptr socket = net::createConnection(port);
GTestOnData::Ptr onData(new GTestOnData());
JsFunction::Ptr onEnd(new GTestOnEnd(onData));
JsFunction::Ptr onClose(new GTestOnClose());
JsFunction::Ptr onConnect(new GTestNetSocketOnConnect(socket));
socket->on(net::Socket::EVENT_DATA, onData);
socket->on(net::Socket::EVENT_END, onEnd);
socket->on(net::Socket::EVENT_CLOSE, onClose);
socket->on(net::Socket::EVENT_CONNECT, onConnect);
}
node::run();
ASSERT_EQ(NUM_CONNS, GTestOnClose::count());
JsArray::CPtr messages = GTestOnEnd::messages();
Size numMsgs = messages->length();
ASSERT_EQ(NUM_CONNS, numMsgs);
for (Size i = 0; i < numMsgs; i++) {
console::printf(console::LEVEL_INFO, ".");
String::CPtr msg = messages->getCPtr<Buffer>(i)->toString();
ASSERT_TRUE(msg->equals(str("abc")));
}
console::printf(console::LEVEL_INFO, "\n");
clearGTestCommon();
}
} // namespace node
} // namespace libj
<commit_msg>change a port number<commit_after>// Copyright (c) 2012-2013 Plenluno All rights reserved.
#include "./gtest_net_common.h"
namespace libj {
namespace node {
TEST(GTestNetTcp, TestMemoryLeak) {
net::Socket::Ptr socket = net::createConnection(10000);
ASSERT_TRUE(!!socket);
}
static const UInt NUM_CONNS = 7;
TEST(GTestNetTcp, TestTcp) {
Int port = 10000;
net::Server::Ptr server = net::createServer();
server->on(
net::Server::EVENT_CONNECTION,
JsFunction::Ptr(new GTestNetServerOnConnection(server, NUM_CONNS)));
server->listen(port);
for (Size i = 0; i < NUM_CONNS; i++) {
net::Socket::Ptr socket = net::createConnection(port);
GTestOnData::Ptr onData(new GTestOnData());
JsFunction::Ptr onEnd(new GTestOnEnd(onData));
JsFunction::Ptr onClose(new GTestOnClose());
JsFunction::Ptr onConnect(new GTestNetSocketOnConnect(socket));
socket->on(net::Socket::EVENT_DATA, onData);
socket->on(net::Socket::EVENT_END, onEnd);
socket->on(net::Socket::EVENT_CLOSE, onClose);
socket->on(net::Socket::EVENT_CONNECT, onConnect);
}
node::run();
ASSERT_EQ(NUM_CONNS, GTestOnClose::count());
JsArray::CPtr messages = GTestOnEnd::messages();
Size numMsgs = messages->length();
ASSERT_EQ(NUM_CONNS, numMsgs);
for (Size i = 0; i < numMsgs; i++) {
console::printf(console::LEVEL_INFO, ".");
String::CPtr msg = messages->getCPtr<Buffer>(i)->toString();
ASSERT_TRUE(msg->equals(str("abc")));
}
console::printf(console::LEVEL_INFO, "\n");
clearGTestCommon();
}
} // namespace node
} // namespace libj
<|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 <tools/debug.hxx>
#include <vcl/ctrl.hxx>
#include "assclass.hxx"
Assistent::Assistent(int nNoOfPages)
: mnPages(nNoOfPages), mnCurrentPage(1)
{
if(mnPages > MAX_PAGES)
mnPages = MAX_PAGES;
mpPageStatus.reset(new bool[mnPages]);
for(int i=0; i < mnPages; ++i)
mpPageStatus[i] = true;
}
bool Assistent::InsertControl(int nDestPage,Control* pUsedControl)
{
DBG_ASSERT( (nDestPage > 0) && (nDestPage <= mnPages), "Seite nicht vorhanden!");
if((nDestPage>0)&&(nDestPage<=mnPages))
{
maPages[nDestPage-1].push_back(pUsedControl);
pUsedControl->Hide();
pUsedControl->Disable();
return true;
}
return false;
}
bool Assistent::NextPage()
{
if(mnCurrentPage<mnPages)
{
int nPage = mnCurrentPage+1;
while(nPage <= mnPages && !mpPageStatus[nPage-1])
nPage++;
if(nPage <= mnPages)
return GotoPage(nPage);
}
return false;
}
bool Assistent::PreviousPage()
{
if(mnCurrentPage>1)
{
int nPage = mnCurrentPage-1;
while(nPage >= 0 && !mpPageStatus[nPage-1])
nPage--;
if(nPage >= 0)
return GotoPage(nPage);
}
return false;
}
bool Assistent::GotoPage(const int nPageToGo)
{
DBG_ASSERT( (nPageToGo > 0) && (nPageToGo <= mnPages), "Seite nicht vorhanden!");
if((nPageToGo>0)&&(nPageToGo<=mnPages)&&mpPageStatus[nPageToGo-1])
{
int nIndex=mnCurrentPage-1;
std::vector<Control*>::iterator iter = maPages[nIndex].begin();
std::vector<Control*>::iterator iterEnd = maPages[nIndex].end();
for(; iter != iterEnd; ++iter)
{
(*iter)->Disable();
(*iter)->Hide();
}
mnCurrentPage=nPageToGo;
nIndex=mnCurrentPage-1;
iter = maPages[nIndex].begin();
iterEnd = maPages[nIndex].end();
for(; iter != iterEnd; ++iter)
{
(*iter)->Enable();
(*iter)->Show();
}
return true;
}
return false;
}
bool Assistent::IsLastPage() const
{
if(mnCurrentPage == mnPages)
return true;
int nPage = mnCurrentPage+1;
while(nPage <= mnPages && !mpPageStatus[nPage-1])
nPage++;
return nPage > mnPages;
}
bool Assistent::IsFirstPage() const
{
if(mnCurrentPage == 1)
return true;
int nPage = mnCurrentPage-1;
while(nPage > 0 && !mpPageStatus[nPage-1])
nPage--;
return nPage == 0;
}
int Assistent::GetCurrentPage() const
{
return mnCurrentPage;
}
bool Assistent::IsEnabled( int nPage ) const
{
DBG_ASSERT( (nPage>0) && (nPage <= mnPages), "Seite nicht vorhanden!" );
return (nPage>0) && (nPage <= mnPages && mpPageStatus[nPage-1]);
}
void Assistent::EnablePage( int nPage )
{
DBG_ASSERT( (nPage>0) && (nPage <= mnPages), "Seite nicht vorhanden!" );
if((nPage>0) && (nPage < mnPages && !mpPageStatus[nPage-1]))
{
mpPageStatus[nPage-1] = true;
}
}
void Assistent::DisablePage( int nPage )
{
DBG_ASSERT( (nPage>0) && (nPage <= mnPages), "Seite nicht vorhanden!" );
if((nPage>0) && (nPage <= mnPages && mpPageStatus[nPage-1]))
{
mpPageStatus[nPage-1] = false;
if(mnCurrentPage == nPage)
GotoPage(1);
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>sd/source/ui/dlg/assclass.cxx debug message translation<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 <tools/debug.hxx>
#include <vcl/ctrl.hxx>
#include "assclass.hxx"
Assistent::Assistent(int nNoOfPages)
: mnPages(nNoOfPages), mnCurrentPage(1)
{
if(mnPages > MAX_PAGES)
mnPages = MAX_PAGES;
mpPageStatus.reset(new bool[mnPages]);
for(int i=0; i < mnPages; ++i)
mpPageStatus[i] = true;
}
bool Assistent::InsertControl(int nDestPage,Control* pUsedControl)
{
DBG_ASSERT( (nDestPage > 0) && (nDestPage <= mnPages), "Page not aviable!");
if((nDestPage>0)&&(nDestPage<=mnPages))
{
maPages[nDestPage-1].push_back(pUsedControl);
pUsedControl->Hide();
pUsedControl->Disable();
return true;
}
return false;
}
bool Assistent::NextPage()
{
if(mnCurrentPage<mnPages)
{
int nPage = mnCurrentPage+1;
while(nPage <= mnPages && !mpPageStatus[nPage-1])
nPage++;
if(nPage <= mnPages)
return GotoPage(nPage);
}
return false;
}
bool Assistent::PreviousPage()
{
if(mnCurrentPage>1)
{
int nPage = mnCurrentPage-1;
while(nPage >= 0 && !mpPageStatus[nPage-1])
nPage--;
if(nPage >= 0)
return GotoPage(nPage);
}
return false;
}
bool Assistent::GotoPage(const int nPageToGo)
{
DBG_ASSERT( (nPageToGo > 0) && (nPageToGo <= mnPages), "Page not aviable!");
if((nPageToGo>0)&&(nPageToGo<=mnPages)&&mpPageStatus[nPageToGo-1])
{
int nIndex=mnCurrentPage-1;
std::vector<Control*>::iterator iter = maPages[nIndex].begin();
std::vector<Control*>::iterator iterEnd = maPages[nIndex].end();
for(; iter != iterEnd; ++iter)
{
(*iter)->Disable();
(*iter)->Hide();
}
mnCurrentPage=nPageToGo;
nIndex=mnCurrentPage-1;
iter = maPages[nIndex].begin();
iterEnd = maPages[nIndex].end();
for(; iter != iterEnd; ++iter)
{
(*iter)->Enable();
(*iter)->Show();
}
return true;
}
return false;
}
bool Assistent::IsLastPage() const
{
if(mnCurrentPage == mnPages)
return true;
int nPage = mnCurrentPage+1;
while(nPage <= mnPages && !mpPageStatus[nPage-1])
nPage++;
return nPage > mnPages;
}
bool Assistent::IsFirstPage() const
{
if(mnCurrentPage == 1)
return true;
int nPage = mnCurrentPage-1;
while(nPage > 0 && !mpPageStatus[nPage-1])
nPage--;
return nPage == 0;
}
int Assistent::GetCurrentPage() const
{
return mnCurrentPage;
}
bool Assistent::IsEnabled( int nPage ) const
{
DBG_ASSERT( (nPage>0) && (nPage <= mnPages), "Page not aviable!" );
return (nPage>0) && (nPage <= mnPages && mpPageStatus[nPage-1]);
}
void Assistent::EnablePage( int nPage )
{
DBG_ASSERT( (nPage>0) && (nPage <= mnPages), "Page not aviable!" );
if((nPage>0) && (nPage < mnPages && !mpPageStatus[nPage-1]))
{
mpPageStatus[nPage-1] = true;
}
}
void Assistent::DisablePage( int nPage )
{
DBG_ASSERT( (nPage>0) && (nPage <= mnPages), "Page not aviable!" );
if((nPage>0) && (nPage <= mnPages && mpPageStatus[nPage-1]))
{
mpPageStatus[nPage-1] = false;
if(mnCurrentPage == nPage)
GotoPage(1);
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xtabdash.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 13:58:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ---------------------------------------------------------------
#ifndef SVX_LIGHT
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _SVX_XPROPERTYTABLE_HXX
#include "XPropertyTable.hxx"
#endif
#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#include "xmlxtexp.hxx"
#include "xmlxtimp.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <tools/urlobj.hxx>
#include <vcl/virdev.hxx>
#include <vcl/window.hxx>
#include <svtools/itemset.hxx>
#include <sfx2/docfile.hxx>
#include "dialogs.hrc"
#include "dialmgr.hxx"
#include "xtable.hxx"
#include "xpool.hxx"
#include "xoutx.hxx"
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <xlineit0.hxx>
#endif
#ifndef _SVX_XLNCLIT_HXX //autogen
#include <xlnclit.hxx>
#endif
#ifndef _SVX_XLNWTIT_HXX //autogen
#include <xlnwtit.hxx>
#endif
#ifndef _SVX_XLNDSIT_HXX //autogen
#include <xlndsit.hxx>
#endif
using namespace com::sun::star;
using namespace rtl;
#define GLOBALOVERFLOW
sal_Unicode const pszExtDash[] = {'s','o','d'};
char const aChckDash[] = { 0x04, 0x00, 'S','O','D','L'}; // < 5.2
char const aChckDash0[] = { 0x04, 0x00, 'S','O','D','0'}; // = 5.2
char const aChckXML[] = { '<', '?', 'x', 'm', 'l' }; // = 6.0
// -----------------
// class XDashTable
// -----------------
/*************************************************************************
|*
|* XDashTable::XDashTable()
|*
*************************************************************************/
XDashTable::XDashTable( const String& rPath,
XOutdevItemPool* pInPool,
USHORT nInitSize, USHORT nReSize ) :
XPropertyTable( rPath, pInPool, nInitSize, nReSize)
{
pBmpTable = new Table( nInitSize, nReSize );
}
/************************************************************************/
XDashTable::~XDashTable()
{
}
/************************************************************************/
XDashEntry* XDashTable::Replace(long nIndex, XDashEntry* pEntry )
{
return (XDashEntry*) XPropertyTable::Replace(nIndex, pEntry);
}
/************************************************************************/
XDashEntry* XDashTable::Remove(long nIndex)
{
return (XDashEntry*) XPropertyTable::Remove(nIndex, 0);
}
/************************************************************************/
XDashEntry* XDashTable::GetDash(long nIndex) const
{
return (XDashEntry*) XPropertyTable::Get(nIndex, 0);
}
/************************************************************************/
BOOL XDashTable::Load()
{
return( FALSE );
}
/************************************************************************/
BOOL XDashTable::Save()
{
return( FALSE );
}
/************************************************************************/
BOOL XDashTable::Create()
{
return( FALSE );
}
/************************************************************************/
BOOL XDashTable::CreateBitmapsForUI()
{
return( FALSE );
}
/************************************************************************/
Bitmap* XDashTable::CreateBitmapForUI( long /*nIndex*/, BOOL /*bDelete*/)
{
return( NULL );
}
// ----------------
// class XDashList
// ----------------
/*************************************************************************
|*
|* XDashList::XDashList()
|*
*************************************************************************/
XDashList::XDashList( const String& rPath,
XOutdevItemPool* pInPool,
USHORT nInitSize, USHORT nReSize ) :
XPropertyList ( rPath, pInPool, nInitSize, nReSize),
pVD ( NULL ),
pXOut ( NULL ),
pXFSet ( NULL ),
pXLSet ( NULL )
{
pBmpList = new List( nInitSize, nReSize );
}
/************************************************************************/
XDashList::~XDashList()
{
if( pVD ) delete pVD;
if( pXOut ) delete pXOut;
if( pXFSet ) delete pXFSet;
if( pXLSet ) delete pXLSet;
}
/************************************************************************/
XDashEntry* XDashList::Replace(XDashEntry* pEntry, long nIndex )
{
return (XDashEntry*) XPropertyList::Replace(pEntry, nIndex);
}
/************************************************************************/
XDashEntry* XDashList::Remove(long nIndex)
{
return (XDashEntry*) XPropertyList::Remove(nIndex, 0);
}
/************************************************************************/
XDashEntry* XDashList::GetDash(long nIndex) const
{
return (XDashEntry*) XPropertyList::Get(nIndex, 0);
}
/************************************************************************/
BOOL XDashList::Load()
{
if( bListDirty )
{
bListDirty = FALSE;
INetURLObject aURL( aPath );
if( INET_PROT_NOT_VALID == aURL.GetProtocol() )
{
DBG_ASSERT( !aPath.Len(), "invalid URL" );
return FALSE;
}
aURL.Append( aName );
if( !aURL.getExtension().getLength() )
aURL.setExtension( rtl::OUString( pszExtDash, 3 ) );
uno::Reference< container::XNameContainer > xTable( SvxUnoXDashTable_createInstance( this ), uno::UNO_QUERY );
return SvxXMLXTableImport::load( aURL.GetMainURL( INetURLObject::NO_DECODE ), xTable );
}
return( FALSE );
}
/************************************************************************/
BOOL XDashList::Save()
{
INetURLObject aURL( aPath );
if( INET_PROT_NOT_VALID == aURL.GetProtocol() )
{
DBG_ASSERT( !aPath.Len(), "invalid URL" );
return FALSE;
}
aURL.Append( aName );
if( !aURL.getExtension().getLength() )
aURL.setExtension( rtl::OUString( pszExtDash, 3 ) );
uno::Reference< container::XNameContainer > xTable( SvxUnoXDashTable_createInstance( this ), uno::UNO_QUERY );
return SvxXMLXTableExportComponent::save( aURL.GetMainURL( INetURLObject::NO_DECODE ), xTable );
}
/************************************************************************/
BOOL XDashList::Create()
{
XubString aStr( SVX_RES( RID_SVXSTR_LINESTYLE ) );
xub_StrLen nLen;
aStr.AppendAscii(" 1");
nLen = aStr.Len() - 1;
Insert(new XDashEntry(XDash(XDASH_RECT,1, 50,1, 50, 50),aStr));
aStr.SetChar(nLen, sal_Unicode('2'));
Insert(new XDashEntry(XDash(XDASH_RECT,1,500,1,500,500),aStr));
aStr.SetChar(nLen, sal_Unicode('3'));
Insert(new XDashEntry(XDash(XDASH_RECT,2, 50,3,250,120),aStr));
return( TRUE );
}
/************************************************************************/
BOOL XDashList::CreateBitmapsForUI()
{
for( long i = 0; i < Count(); i++)
{
Bitmap* pBmp = CreateBitmapForUI( i, FALSE );
DBG_ASSERT( pBmp, "XDashList: Bitmap(UI) konnte nicht erzeugt werden!" );
if( pBmp )
pBmpList->Insert( pBmp, i );
}
// Loeschen, da JOE den Pool vorm Dtor entfernt!
if( pVD ) { delete pVD; pVD = NULL; }
if( pXOut ) { delete pXOut; pXOut = NULL; }
if( pXFSet ){ delete pXFSet; pXFSet = NULL; }
if( pXLSet ){ delete pXLSet; pXLSet = NULL; }
return( TRUE );
}
/************************************************************************/
Bitmap* XDashList::CreateBitmapForUI( long nIndex, BOOL bDelete )
{
Point aZero;
if( !pVD ) // und pXOut und pXFSet und pXLSet
{
pVD = new VirtualDevice;
DBG_ASSERT( pVD, "XDashList: Konnte kein VirtualDevice erzeugen!" );
pVD->SetMapMode( MAP_100TH_MM );
pVD->SetOutputSize( pVD->PixelToLogic( Size( BITMAP_WIDTH * 2, BITMAP_HEIGHT ) ) );
const StyleSettings& rStyles = Application::GetSettings().GetStyleSettings();
pVD->SetFillColor( rStyles.GetFieldColor() );
pVD->SetLineColor( rStyles.GetFieldColor() );
pXOut = new XOutputDevice( pVD );
DBG_ASSERT( pVD, "XDashList: Konnte kein XOutDevice erzeugen!" );
pXFSet = new XFillAttrSetItem( pXPool );
DBG_ASSERT( pVD, "XDashList: Konnte kein XFillAttrSetItem erzeugen!" );
pXLSet = new XLineAttrSetItem( pXPool );
DBG_ASSERT( pVD, "XDashList: Konnte kein XLineAttrSetItem erzeugen!" );
pXLSet->GetItemSet().Put( XLineStyleItem( XLINE_DASH ) );
pXLSet->GetItemSet().Put( XLineColorItem( String(), RGB_Color( rStyles.GetFieldTextColor().GetColor() ) ) );
pXLSet->GetItemSet().Put( XLineWidthItem( 30 ) );
}
Size aVDSize = pVD->GetOutputSize();
pVD->DrawRect( Rectangle( aZero, aVDSize ) );
pXLSet->GetItemSet().Put( XLineDashItem( String(), GetDash( nIndex )->GetDash() ) );
//-/ pXOut->SetLineAttr( *pXLSet );
pXOut->SetLineAttr( pXLSet->GetItemSet() );
pXOut->DrawLine( Point( 0, aVDSize.Height() / 2 ),
Point( aVDSize.Width(), aVDSize.Height() / 2 ) );
Bitmap* pBitmap = new Bitmap( pVD->GetBitmap( aZero, aVDSize ) );
// Loeschen, da JOE den Pool vorm Dtor entfernt!
if( bDelete )
{
if( pVD ) { delete pVD; pVD = NULL; }
if( pXOut ) { delete pXOut; pXOut = NULL; }
if( pXFSet ){ delete pXFSet; pXFSet = NULL; }
if( pXLSet ){ delete pXLSet; pXLSet = NULL; }
}
return( pBitmap );
}
// eof
<commit_msg>INTEGRATION: CWS vgbugs07 (1.18.254); FILE MERGED 2007/06/04 13:27:42 vg 1.18.254.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xtabdash.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: hr $ $Date: 2007-06-27 19:35:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ---------------------------------------------------------------
#ifndef SVX_LIGHT
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _SVX_XPROPERTYTABLE_HXX
#include "XPropertyTable.hxx"
#endif
#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#include "xmlxtexp.hxx"
#include "xmlxtimp.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <tools/urlobj.hxx>
#include <vcl/virdev.hxx>
#include <vcl/window.hxx>
#include <svtools/itemset.hxx>
#include <sfx2/docfile.hxx>
#include <svx/dialogs.hrc>
#include <svx/dialmgr.hxx>
#include <svx/xtable.hxx>
#include <svx/xpool.hxx>
#include <svx/xoutx.hxx>
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _SVX_XLNCLIT_HXX //autogen
#include <svx/xlnclit.hxx>
#endif
#ifndef _SVX_XLNWTIT_HXX //autogen
#include <svx/xlnwtit.hxx>
#endif
#ifndef _SVX_XLNDSIT_HXX //autogen
#include <svx/xlndsit.hxx>
#endif
using namespace com::sun::star;
using namespace rtl;
#define GLOBALOVERFLOW
sal_Unicode const pszExtDash[] = {'s','o','d'};
char const aChckDash[] = { 0x04, 0x00, 'S','O','D','L'}; // < 5.2
char const aChckDash0[] = { 0x04, 0x00, 'S','O','D','0'}; // = 5.2
char const aChckXML[] = { '<', '?', 'x', 'm', 'l' }; // = 6.0
// -----------------
// class XDashTable
// -----------------
/*************************************************************************
|*
|* XDashTable::XDashTable()
|*
*************************************************************************/
XDashTable::XDashTable( const String& rPath,
XOutdevItemPool* pInPool,
USHORT nInitSize, USHORT nReSize ) :
XPropertyTable( rPath, pInPool, nInitSize, nReSize)
{
pBmpTable = new Table( nInitSize, nReSize );
}
/************************************************************************/
XDashTable::~XDashTable()
{
}
/************************************************************************/
XDashEntry* XDashTable::Replace(long nIndex, XDashEntry* pEntry )
{
return (XDashEntry*) XPropertyTable::Replace(nIndex, pEntry);
}
/************************************************************************/
XDashEntry* XDashTable::Remove(long nIndex)
{
return (XDashEntry*) XPropertyTable::Remove(nIndex, 0);
}
/************************************************************************/
XDashEntry* XDashTable::GetDash(long nIndex) const
{
return (XDashEntry*) XPropertyTable::Get(nIndex, 0);
}
/************************************************************************/
BOOL XDashTable::Load()
{
return( FALSE );
}
/************************************************************************/
BOOL XDashTable::Save()
{
return( FALSE );
}
/************************************************************************/
BOOL XDashTable::Create()
{
return( FALSE );
}
/************************************************************************/
BOOL XDashTable::CreateBitmapsForUI()
{
return( FALSE );
}
/************************************************************************/
Bitmap* XDashTable::CreateBitmapForUI( long /*nIndex*/, BOOL /*bDelete*/)
{
return( NULL );
}
// ----------------
// class XDashList
// ----------------
/*************************************************************************
|*
|* XDashList::XDashList()
|*
*************************************************************************/
XDashList::XDashList( const String& rPath,
XOutdevItemPool* pInPool,
USHORT nInitSize, USHORT nReSize ) :
XPropertyList ( rPath, pInPool, nInitSize, nReSize),
pVD ( NULL ),
pXOut ( NULL ),
pXFSet ( NULL ),
pXLSet ( NULL )
{
pBmpList = new List( nInitSize, nReSize );
}
/************************************************************************/
XDashList::~XDashList()
{
if( pVD ) delete pVD;
if( pXOut ) delete pXOut;
if( pXFSet ) delete pXFSet;
if( pXLSet ) delete pXLSet;
}
/************************************************************************/
XDashEntry* XDashList::Replace(XDashEntry* pEntry, long nIndex )
{
return (XDashEntry*) XPropertyList::Replace(pEntry, nIndex);
}
/************************************************************************/
XDashEntry* XDashList::Remove(long nIndex)
{
return (XDashEntry*) XPropertyList::Remove(nIndex, 0);
}
/************************************************************************/
XDashEntry* XDashList::GetDash(long nIndex) const
{
return (XDashEntry*) XPropertyList::Get(nIndex, 0);
}
/************************************************************************/
BOOL XDashList::Load()
{
if( bListDirty )
{
bListDirty = FALSE;
INetURLObject aURL( aPath );
if( INET_PROT_NOT_VALID == aURL.GetProtocol() )
{
DBG_ASSERT( !aPath.Len(), "invalid URL" );
return FALSE;
}
aURL.Append( aName );
if( !aURL.getExtension().getLength() )
aURL.setExtension( rtl::OUString( pszExtDash, 3 ) );
uno::Reference< container::XNameContainer > xTable( SvxUnoXDashTable_createInstance( this ), uno::UNO_QUERY );
return SvxXMLXTableImport::load( aURL.GetMainURL( INetURLObject::NO_DECODE ), xTable );
}
return( FALSE );
}
/************************************************************************/
BOOL XDashList::Save()
{
INetURLObject aURL( aPath );
if( INET_PROT_NOT_VALID == aURL.GetProtocol() )
{
DBG_ASSERT( !aPath.Len(), "invalid URL" );
return FALSE;
}
aURL.Append( aName );
if( !aURL.getExtension().getLength() )
aURL.setExtension( rtl::OUString( pszExtDash, 3 ) );
uno::Reference< container::XNameContainer > xTable( SvxUnoXDashTable_createInstance( this ), uno::UNO_QUERY );
return SvxXMLXTableExportComponent::save( aURL.GetMainURL( INetURLObject::NO_DECODE ), xTable );
}
/************************************************************************/
BOOL XDashList::Create()
{
XubString aStr( SVX_RES( RID_SVXSTR_LINESTYLE ) );
xub_StrLen nLen;
aStr.AppendAscii(" 1");
nLen = aStr.Len() - 1;
Insert(new XDashEntry(XDash(XDASH_RECT,1, 50,1, 50, 50),aStr));
aStr.SetChar(nLen, sal_Unicode('2'));
Insert(new XDashEntry(XDash(XDASH_RECT,1,500,1,500,500),aStr));
aStr.SetChar(nLen, sal_Unicode('3'));
Insert(new XDashEntry(XDash(XDASH_RECT,2, 50,3,250,120),aStr));
return( TRUE );
}
/************************************************************************/
BOOL XDashList::CreateBitmapsForUI()
{
for( long i = 0; i < Count(); i++)
{
Bitmap* pBmp = CreateBitmapForUI( i, FALSE );
DBG_ASSERT( pBmp, "XDashList: Bitmap(UI) konnte nicht erzeugt werden!" );
if( pBmp )
pBmpList->Insert( pBmp, i );
}
// Loeschen, da JOE den Pool vorm Dtor entfernt!
if( pVD ) { delete pVD; pVD = NULL; }
if( pXOut ) { delete pXOut; pXOut = NULL; }
if( pXFSet ){ delete pXFSet; pXFSet = NULL; }
if( pXLSet ){ delete pXLSet; pXLSet = NULL; }
return( TRUE );
}
/************************************************************************/
Bitmap* XDashList::CreateBitmapForUI( long nIndex, BOOL bDelete )
{
Point aZero;
if( !pVD ) // und pXOut und pXFSet und pXLSet
{
pVD = new VirtualDevice;
DBG_ASSERT( pVD, "XDashList: Konnte kein VirtualDevice erzeugen!" );
pVD->SetMapMode( MAP_100TH_MM );
pVD->SetOutputSize( pVD->PixelToLogic( Size( BITMAP_WIDTH * 2, BITMAP_HEIGHT ) ) );
const StyleSettings& rStyles = Application::GetSettings().GetStyleSettings();
pVD->SetFillColor( rStyles.GetFieldColor() );
pVD->SetLineColor( rStyles.GetFieldColor() );
pXOut = new XOutputDevice( pVD );
DBG_ASSERT( pVD, "XDashList: Konnte kein XOutDevice erzeugen!" );
pXFSet = new XFillAttrSetItem( pXPool );
DBG_ASSERT( pVD, "XDashList: Konnte kein XFillAttrSetItem erzeugen!" );
pXLSet = new XLineAttrSetItem( pXPool );
DBG_ASSERT( pVD, "XDashList: Konnte kein XLineAttrSetItem erzeugen!" );
pXLSet->GetItemSet().Put( XLineStyleItem( XLINE_DASH ) );
pXLSet->GetItemSet().Put( XLineColorItem( String(), RGB_Color( rStyles.GetFieldTextColor().GetColor() ) ) );
pXLSet->GetItemSet().Put( XLineWidthItem( 30 ) );
}
Size aVDSize = pVD->GetOutputSize();
pVD->DrawRect( Rectangle( aZero, aVDSize ) );
pXLSet->GetItemSet().Put( XLineDashItem( String(), GetDash( nIndex )->GetDash() ) );
//-/ pXOut->SetLineAttr( *pXLSet );
pXOut->SetLineAttr( pXLSet->GetItemSet() );
pXOut->DrawLine( Point( 0, aVDSize.Height() / 2 ),
Point( aVDSize.Width(), aVDSize.Height() / 2 ) );
Bitmap* pBitmap = new Bitmap( pVD->GetBitmap( aZero, aVDSize ) );
// Loeschen, da JOE den Pool vorm Dtor entfernt!
if( bDelete )
{
if( pVD ) { delete pVD; pVD = NULL; }
if( pXOut ) { delete pXOut; pXOut = NULL; }
if( pXFSet ){ delete pXFSet; pXFSet = NULL; }
if( pXLSet ){ delete pXLSet; pXLSet = NULL; }
}
return( pBitmap );
}
// eof
<|endoftext|> |
<commit_before>#/*************************************************************************
*
* $RCSfile: gluectrl.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ka $ $Date: 2002-04-18 15:45:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#include <svx/dialogs.hrc>
#ifndef _SVDGLUE_HXX //autogen
#include <svx/svdglue.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#include "strings.hrc"
#include "gluectrl.hxx"
#include "sdresid.hxx"
#include "app.hrc"
// z.Z. werden von Joe nur die u.a. Moeglichkeiten unterstuetzt
#define ESCDIR_COUNT 5
static UINT16 aEscDirArray[] =
{
SDRESC_SMART,
SDRESC_LEFT,
SDRESC_RIGHT,
SDRESC_TOP,
SDRESC_BOTTOM,
// SDRESC_LO,
// SDRESC_LU,
// SDRESC_RO,
// SDRESC_RU,
// SDRESC_HORZ,
// SDRESC_VERT,
// SDRESC_ALL
};
SFX_IMPL_TOOLBOX_CONTROL( SdTbxCtlGlueEscDir, SfxUInt16Item )
/*************************************************************************
|*
|* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Listbox
|*
\************************************************************************/
GlueEscDirLB::GlueEscDirLB( Window* pParent ) :
ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) )
{
String aStr; aStr += sal_Unicode('X');
Size aXSize( GetTextWidth( aStr ), GetTextHeight() );
//SetPosPixel( Point( aSize.Width(), 0 ) );
SetSizePixel( Size( aXSize.Width() * 12, aXSize.Height() * 10 ) );
Fill();
//SelectEntryPos( 0 );
Show();
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
GlueEscDirLB::~GlueEscDirLB()
{
}
/*************************************************************************
|*
|* Ermittelt die Austrittsrichtung und verschickt den entspr. Slot
|*
\************************************************************************/
void GlueEscDirLB::Select()
{
UINT16 nPos = GetSelectEntryPos();
SfxUInt16Item aItem( SID_GLUE_ESCDIR, aEscDirArray[ nPos ] );
SfxViewFrame::Current()->GetDispatcher()->Execute( SID_GLUE_ESCDIR, SFX_CALLMODE_ASYNCHRON |
SFX_CALLMODE_RECORD, &aItem, (void*) NULL, 0L );
}
/*************************************************************************
|*
|* Fuellen der Listbox mit Strings
|*
\************************************************************************/
void GlueEscDirLB::Fill()
{
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_SMART ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LEFT ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RIGHT ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_TOP ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_BOTTOM ) ) );
/*
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LO ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LU ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RO ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RU ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_HORZ ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_VERT ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_ALL ) ) );
*/
}
/*************************************************************************
|*
|* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Toolbox-Control
|*
\************************************************************************/
SdTbxCtlGlueEscDir::SdTbxCtlGlueEscDir( USHORT nId, ToolBox& rTbx,
SfxBindings& rBindings ) :
SfxToolBoxControl( nId, rTbx, rBindings )
{
}
/*************************************************************************
|*
|* Stellt Status in der Listbox des Controllers dar
|*
\************************************************************************/
void SdTbxCtlGlueEscDir::StateChanged( USHORT nSId,
SfxItemState eState, const SfxPoolItem* pState )
{
if( eState == SFX_ITEM_AVAILABLE )
{
GlueEscDirLB* pGlueEscDirLB = (GlueEscDirLB*) ( GetToolBox().
GetItemWindow( SID_GLUE_ESCDIR ) );
if( pGlueEscDirLB )
{
if( pState )
{
pGlueEscDirLB->Enable();
if ( IsInvalidItem( pState ) )
{
pGlueEscDirLB->SetNoSelection();
}
else
{
UINT16 nEscDir = ( (const SfxUInt16Item*) pState )->GetValue();
pGlueEscDirLB->SelectEntryPos( GetEscDirPos( nEscDir ) );
}
}
else
{
pGlueEscDirLB->Disable();
pGlueEscDirLB->SetNoSelection();
}
}
}
SfxToolBoxControl::StateChanged( nSId, eState, pState );
}
/*************************************************************************
|*
|* No Comment
|*
\************************************************************************/
Window* SdTbxCtlGlueEscDir::CreateItemWindow( Window *pParent )
{
if( GetId() == SID_GLUE_ESCDIR )
{
return( new GlueEscDirLB( pParent ) );
}
return( NULL );
}
/*************************************************************************
|*
|* Liefert Position im Array fuer EscDir zurueck (Mapping fuer Listbox)
|*
\************************************************************************/
UINT16 SdTbxCtlGlueEscDir::GetEscDirPos( UINT16 nEscDir )
{
for( UINT16 i = 0; i < ESCDIR_COUNT; i++ )
{
if( aEscDirArray[ i ] == nEscDir )
return( i );
}
return( 99 );
}
<commit_msg>INTEGRATION: CWS docking1 (1.4.378); FILE MERGED 2004/04/25 05:44:01 cd 1.4.378.1: #i26252# Transition of toolbar controllers<commit_after>#/*************************************************************************
*
* $RCSfile: gluectrl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-07-06 12:25:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#include <svx/dialogs.hrc>
#ifndef _SVDGLUE_HXX //autogen
#include <svx/svdglue.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#include "strings.hrc"
#include "gluectrl.hxx"
#include "sdresid.hxx"
#include "app.hrc"
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
// z.Z. werden von Joe nur die u.a. Moeglichkeiten unterstuetzt
#define ESCDIR_COUNT 5
static UINT16 aEscDirArray[] =
{
SDRESC_SMART,
SDRESC_LEFT,
SDRESC_RIGHT,
SDRESC_TOP,
SDRESC_BOTTOM,
// SDRESC_LO,
// SDRESC_LU,
// SDRESC_RO,
// SDRESC_RU,
// SDRESC_HORZ,
// SDRESC_VERT,
// SDRESC_ALL
};
SFX_IMPL_TOOLBOX_CONTROL( SdTbxCtlGlueEscDir, SfxUInt16Item )
/*************************************************************************
|*
|* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Listbox
|*
\************************************************************************/
GlueEscDirLB::GlueEscDirLB( Window* pParent, const Reference< XFrame >& rFrame ) :
ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ),
m_xFrame( rFrame )
{
String aStr; aStr += sal_Unicode('X');
Size aXSize( GetTextWidth( aStr ), GetTextHeight() );
//SetPosPixel( Point( aSize.Width(), 0 ) );
SetSizePixel( Size( aXSize.Width() * 12, aXSize.Height() * 10 ) );
Fill();
//SelectEntryPos( 0 );
Show();
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
GlueEscDirLB::~GlueEscDirLB()
{
}
/*************************************************************************
|*
|* Ermittelt die Austrittsrichtung und verschickt den entspr. Slot
|*
\************************************************************************/
void GlueEscDirLB::Select()
{
UINT16 nPos = GetSelectEntryPos();
SfxUInt16Item aItem( SID_GLUE_ESCDIR, aEscDirArray[ nPos ] );
if ( m_xFrame.is() )
{
Any a;
Sequence< PropertyValue > aArgs( 1 );
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GlueEscapeDirection" ));
aItem.QueryValue( a );
aArgs[0].Value = a;
SfxToolBoxControl::Dispatch( Reference< XDispatchProvider >( m_xFrame->getController(), UNO_QUERY ),
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GlueEscapeDirection" )),
aArgs );
}
/*
SfxViewFrame::Current()->GetDispatcher()->Execute( SID_GLUE_ESCDIR, SFX_CALLMODE_ASYNCHRON |
SFX_CALLMODE_RECORD, &aItem, (void*) NULL, 0L );
*/
}
/*************************************************************************
|*
|* Fuellen der Listbox mit Strings
|*
\************************************************************************/
void GlueEscDirLB::Fill()
{
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_SMART ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LEFT ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RIGHT ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_TOP ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_BOTTOM ) ) );
/*
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LO ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LU ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RO ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RU ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_HORZ ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_VERT ) ) );
InsertEntry( String( SdResId( STR_GLUE_ESCDIR_ALL ) ) );
*/
}
/*************************************************************************
|*
|* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Toolbox-Control
|*
\************************************************************************/
SdTbxCtlGlueEscDir::SdTbxCtlGlueEscDir(
USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx )
{
}
/*************************************************************************
|*
|* Stellt Status in der Listbox des Controllers dar
|*
\************************************************************************/
void SdTbxCtlGlueEscDir::StateChanged( USHORT nSId,
SfxItemState eState, const SfxPoolItem* pState )
{
if( eState == SFX_ITEM_AVAILABLE )
{
GlueEscDirLB* pGlueEscDirLB = (GlueEscDirLB*) ( GetToolBox().
GetItemWindow( GetId() ) );
if( pGlueEscDirLB )
{
if( pState )
{
pGlueEscDirLB->Enable();
if ( IsInvalidItem( pState ) )
{
pGlueEscDirLB->SetNoSelection();
}
else
{
UINT16 nEscDir = ( (const SfxUInt16Item*) pState )->GetValue();
pGlueEscDirLB->SelectEntryPos( GetEscDirPos( nEscDir ) );
}
}
else
{
pGlueEscDirLB->Disable();
pGlueEscDirLB->SetNoSelection();
}
}
}
SfxToolBoxControl::StateChanged( nSId, eState, pState );
}
/*************************************************************************
|*
|* No Comment
|*
\************************************************************************/
Window* SdTbxCtlGlueEscDir::CreateItemWindow( Window *pParent )
{
if( GetSlotId() == SID_GLUE_ESCDIR )
{
return( new GlueEscDirLB( pParent, m_xFrame ) );
}
return( NULL );
}
/*************************************************************************
|*
|* Liefert Position im Array fuer EscDir zurueck (Mapping fuer Listbox)
|*
\************************************************************************/
UINT16 SdTbxCtlGlueEscDir::GetEscDirPos( UINT16 nEscDir )
{
for( UINT16 i = 0; i < ESCDIR_COUNT; i++ )
{
if( aEscDirArray[ i ] == nEscDir )
return( i );
}
return( 99 );
}
<|endoftext|> |
<commit_before>//=============================================================================
// ■ main.cpp
//-----------------------------------------------------------------------------
// VMGS的主程序。
//=============================================================================
#include "VMGS.hpp"
namespace VM76 {
Shaders* shader_textured = NULL;
Shaders* gui = NULL;
Shaders* shader_basic = NULL;
Res::Texture* tile_texture = NULL;
TextRenderer* trex = NULL; // 2333 T-Rex
Cube* block_pointer;
Tiles* clist[16];
Map* map;
glm::mat4 gui_2d_projection;
int hand_id = 1;
Axis* axe;
Object* obj = new Object();
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
#define PRESS(n) key == n && action == GLFW_PRESS
if (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -1.0));
if (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 1.0));
if (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 1.0, 0.0));
if (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -1.0, 0.0));
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_1)) hand_id = 1;
if (PRESS(GLFW_KEY_2)) hand_id = 2;
if (PRESS(GLFW_KEY_3)) hand_id = 3;
if (PRESS(GLFW_KEY_4)) hand_id = 4;
if (PRESS(GLFW_KEY_5)) hand_id = 5;
if (PRESS(GLFW_KEY_6)) hand_id = 6;
if (PRESS(GLFW_KEY_7)) hand_id = 7;
if (PRESS(GLFW_KEY_8)) hand_id = 8;
if (PRESS(GLFW_KEY_9)) hand_id = 9;
if (PRESS(GLFW_KEY_SPACE)) {
map->place_block(obj->pos, hand_id);
}
static Audio::Channel_Vorbis* loop = NULL;
static Audio::Channel_Triangle* triangle = NULL;
static Audio::Channel_Sine* sine = NULL;
if (PRESS(GLFW_KEY_SEMICOLON)) {
Audio::play_sound("../Media/soft-ping.ogg", false);
}
if (PRESS(GLFW_KEY_APOSTROPHE)) {
if (loop) {
Audio::stop(loop);
loop = NULL;
} else {
loop = Audio::play_sound("../Media/loop-test.ogg", true, .1f);
}
}
if (PRESS(GLFW_KEY_LEFT_BRACKET)) {
if (triangle) {
Audio::stop(triangle);
triangle = NULL;
} else {
triangle = new Audio::Channel_Triangle(440);
Audio::play_channel(triangle);
}
}
if (PRESS(GLFW_KEY_RIGHT_BRACKET)) {
if (sine) {
Audio::stop(sine);
sine = NULL;
} else {
sine = new Audio::Channel_Sine(440);
Audio::play_channel(sine);
}
}
#undef PRESS
}
void loop() {
do {
::main_draw_start();
update_control();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shader_textured->use();
// Setup uniforms
shader_textured->set_float("brightness", VMDE->state.brightness);
shader_textured->set_texture("colortex0", tile_texture, 0);
// Textured blocks rendering
shader_textured->ProjectionView(projection, view);
map->render();
// Setup uniforms
// Non textured rendering
shader_basic->use();
shader_basic->set_float("opaque", 0.5);
shader_textured->ProjectionView(projection, view);
block_pointer->mat[0] = obj->transform();
block_pointer->update_instance(1);
block_pointer->render();
axe->render();
// GUI rendering
gui->use();
gui->set_texture("atlastex", tile_texture, 0);
gui->ProjectionView(gui_2d_projection, glm::mat4(1.0));
glDisable(GL_DEPTH_TEST);
if (hand_id > 0)
clist[hand_id - 1]->render();
char frame_count[64];
sprintf(frame_count, "FPS: %d Hand ID: %d Pointer ID: %d",
VMDE->fps,
hand_id,
0//map->tiles[map->calcTileIndex(obj->pos)].tid
);
trex->instanceRenderText(
frame_count, gui_2d_projection,
glm::mat4(1.0),
glm::translate(glm::mat4(1.0), glm::vec3(0.01,0.94,0.0)),
0.025, 0.05, true
);
glEnable(GL_DEPTH_TEST);
::main_draw_end();
} while (!VMDE->done);
}
void start_game() {
::init_engine(860, 540, "VM / 76");
init_control();
tile_texture = new Res::Texture("../Media/terrain.png");
shader_textured = Shaders::CreateFromFile("../Media/shaders/gbuffers_textured.vsh", "../Media/shaders/gbuffers_textured.fsh");
shader_basic = Shaders::CreateFromFile("../Media/shaders/gbuffers_basic.vsh", "../Media/shaders/gbuffers_basic.fsh");
gui = Shaders::CreateFromFile("../Media/shaders/gui.vsh", "../Media/shaders/gui.fsh");
float aspectRatio = float(VMDE->width) / float(VMDE->height);
gui_2d_projection = glm::ortho(0.0, 1.0 * aspectRatio, 0.0, 1.0, -1.0, 1.0);
projection = glm::perspective(1.3f, float(VMDE->width) / float(VMDE->height), 0.1f, 1000.0f);
view = glm::lookAt(glm::vec3(0.0, 2.6, 0.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
// GL settings initialize
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glDepthRange(0.0f, 1.0f);
glClearDepth(1.0f);
glDepthMask(GL_TRUE);
block_pointer = new Cube(1);
// Set up hand block indicator's matrix
glm::mat4 block_display = glm::translate(glm::mat4(1.0), glm::vec3(0.02, 0.06, 0.2));
block_display = glm::scale(block_display, glm::vec3(0.1f));
block_display = glm::rotate(block_display, Util::PIf / 4.0f, glm::vec3(1.0, 0.0, 0.0));
block_display = glm::rotate(block_display, Util::PIf / 4.0f, glm::vec3(0.0, 1.0, 0.0));
TiledMap::init_cinstances(clist);
for (int i = 0; i < 16; i++) {
clist[i]->mat[0] = new glm::mat4[1]; clist[i]->mat[0][0] = block_display;
clist[i]->mat[1] = new glm::mat4[1]; clist[i]->mat[1][0] = block_display;
clist[i]->mat[2] = new glm::mat4[1]; clist[i]->mat[2][0] = block_display;
clist[i]->mat[3] = new glm::mat4[1]; clist[i]->mat[3][0] = block_display;
clist[i]->mat[4] = new glm::mat4[1]; clist[i]->mat[4][0] = block_display;
clist[i]->mat[5] = new glm::mat4[1]; clist[i]->mat[5][0] = block_display;
clist[i]->update_instance(1,1,1,1,1,1);
}
axe = new Axis();
trex = new TextRenderer();
map = new Map(6,6,6,64); // Maximum capability of the card
block_pointer->obj->data.mat_c = 1;
glfwSetKeyCallback(window, key_callback);
loop();
terminate();
}
void terminate() {
log("starting to terminate");
terminate_engine();
VMDE_Dispose(tile_texture);
VMDE_Dispose(block_pointer);
for (int i = 0; i < 16; i++) VMDE_Dispose(clist[i]);
VMDE_Dispose(map);
VMDE_Dispose(trex);
VMDE_Dispose(gui);
VMDE_Dispose(shader_textured);
VMDE_Dispose(shader_basic);
log("terminated successfully");
}
}
int main() {
log("Hello! This is VM76. Nice to meet you!");
VM76::start_game();
}
<commit_msg>把默认的改回32blocks为一chunk(经过测试500blocks全部加载fps为48,可喜可贺<commit_after>//=============================================================================
// ■ main.cpp
//-----------------------------------------------------------------------------
// VMGS的主程序。
//=============================================================================
#include "VMGS.hpp"
namespace VM76 {
Shaders* shader_textured = NULL;
Shaders* gui = NULL;
Shaders* shader_basic = NULL;
Res::Texture* tile_texture = NULL;
TextRenderer* trex = NULL; // 2333 T-Rex
Cube* block_pointer;
Tiles* clist[16];
Map* map;
glm::mat4 gui_2d_projection;
int hand_id = 1;
Axis* axe;
Object* obj = new Object();
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
#define PRESS(n) key == n && action == GLFW_PRESS
if (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -1.0));
if (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 1.0));
if (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 1.0, 0.0));
if (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -1.0, 0.0));
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_1)) hand_id = 1;
if (PRESS(GLFW_KEY_2)) hand_id = 2;
if (PRESS(GLFW_KEY_3)) hand_id = 3;
if (PRESS(GLFW_KEY_4)) hand_id = 4;
if (PRESS(GLFW_KEY_5)) hand_id = 5;
if (PRESS(GLFW_KEY_6)) hand_id = 6;
if (PRESS(GLFW_KEY_7)) hand_id = 7;
if (PRESS(GLFW_KEY_8)) hand_id = 8;
if (PRESS(GLFW_KEY_9)) hand_id = 9;
if (PRESS(GLFW_KEY_SPACE)) {
map->place_block(obj->pos, hand_id);
}
static Audio::Channel_Vorbis* loop = NULL;
static Audio::Channel_Triangle* triangle = NULL;
static Audio::Channel_Sine* sine = NULL;
if (PRESS(GLFW_KEY_SEMICOLON)) {
Audio::play_sound("../Media/soft-ping.ogg", false);
}
if (PRESS(GLFW_KEY_APOSTROPHE)) {
if (loop) {
Audio::stop(loop);
loop = NULL;
} else {
loop = Audio::play_sound("../Media/loop-test.ogg", true, .1f);
}
}
if (PRESS(GLFW_KEY_LEFT_BRACKET)) {
if (triangle) {
Audio::stop(triangle);
triangle = NULL;
} else {
triangle = new Audio::Channel_Triangle(440);
Audio::play_channel(triangle);
}
}
if (PRESS(GLFW_KEY_RIGHT_BRACKET)) {
if (sine) {
Audio::stop(sine);
sine = NULL;
} else {
sine = new Audio::Channel_Sine(440);
Audio::play_channel(sine);
}
}
#undef PRESS
}
void loop() {
do {
::main_draw_start();
update_control();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shader_textured->use();
// Setup uniforms
shader_textured->set_float("brightness", VMDE->state.brightness);
shader_textured->set_texture("colortex0", tile_texture, 0);
// Textured blocks rendering
shader_textured->ProjectionView(projection, view);
map->render();
// Setup uniforms
// Non textured rendering
shader_basic->use();
shader_basic->set_float("opaque", 0.5);
shader_textured->ProjectionView(projection, view);
block_pointer->mat[0] = obj->transform();
block_pointer->update_instance(1);
block_pointer->render();
axe->render();
// GUI rendering
gui->use();
gui->set_texture("atlastex", tile_texture, 0);
gui->ProjectionView(gui_2d_projection, glm::mat4(1.0));
glDisable(GL_DEPTH_TEST);
if (hand_id > 0)
clist[hand_id - 1]->render();
char frame_count[64];
sprintf(frame_count, "FPS: %d Hand ID: %d Pointer ID: %d",
VMDE->fps,
hand_id,
0//map->tiles[map->calcTileIndex(obj->pos)].tid
);
trex->instanceRenderText(
frame_count, gui_2d_projection,
glm::mat4(1.0),
glm::translate(glm::mat4(1.0), glm::vec3(0.01,0.94,0.0)),
0.025, 0.05, true
);
glEnable(GL_DEPTH_TEST);
::main_draw_end();
} while (!VMDE->done);
}
void start_game() {
::init_engine(860, 540, "VM / 76");
init_control();
tile_texture = new Res::Texture("../Media/terrain.png");
shader_textured = Shaders::CreateFromFile("../Media/shaders/gbuffers_textured.vsh", "../Media/shaders/gbuffers_textured.fsh");
shader_basic = Shaders::CreateFromFile("../Media/shaders/gbuffers_basic.vsh", "../Media/shaders/gbuffers_basic.fsh");
gui = Shaders::CreateFromFile("../Media/shaders/gui.vsh", "../Media/shaders/gui.fsh");
float aspectRatio = float(VMDE->width) / float(VMDE->height);
gui_2d_projection = glm::ortho(0.0, 1.0 * aspectRatio, 0.0, 1.0, -1.0, 1.0);
projection = glm::perspective(1.3f, float(VMDE->width) / float(VMDE->height), 0.1f, 1000.0f);
view = glm::lookAt(glm::vec3(0.0, 2.6, 0.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
// GL settings initialize
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glDepthRange(0.0f, 1.0f);
glClearDepth(1.0f);
glDepthMask(GL_TRUE);
block_pointer = new Cube(1);
// Set up hand block indicator's matrix
glm::mat4 block_display = glm::translate(glm::mat4(1.0), glm::vec3(0.02, 0.06, 0.2));
block_display = glm::scale(block_display, glm::vec3(0.1f));
block_display = glm::rotate(block_display, Util::PIf / 4.0f, glm::vec3(1.0, 0.0, 0.0));
block_display = glm::rotate(block_display, Util::PIf / 4.0f, glm::vec3(0.0, 1.0, 0.0));
TiledMap::init_cinstances(clist);
for (int i = 0; i < 16; i++) {
clist[i]->mat[0] = new glm::mat4[1]; clist[i]->mat[0][0] = block_display;
clist[i]->mat[1] = new glm::mat4[1]; clist[i]->mat[1][0] = block_display;
clist[i]->mat[2] = new glm::mat4[1]; clist[i]->mat[2][0] = block_display;
clist[i]->mat[3] = new glm::mat4[1]; clist[i]->mat[3][0] = block_display;
clist[i]->mat[4] = new glm::mat4[1]; clist[i]->mat[4][0] = block_display;
clist[i]->mat[5] = new glm::mat4[1]; clist[i]->mat[5][0] = block_display;
clist[i]->update_instance(1,1,1,1,1,1);
}
axe = new Axis();
trex = new TextRenderer();
map = new Map(6,6,6,32); // Maximum capability of the card
block_pointer->obj->data.mat_c = 1;
glfwSetKeyCallback(window, key_callback);
loop();
terminate();
}
void terminate() {
log("starting to terminate");
terminate_engine();
VMDE_Dispose(tile_texture);
VMDE_Dispose(block_pointer);
for (int i = 0; i < 16; i++) VMDE_Dispose(clist[i]);
VMDE_Dispose(map);
VMDE_Dispose(trex);
VMDE_Dispose(gui);
VMDE_Dispose(shader_textured);
VMDE_Dispose(shader_basic);
log("terminated successfully");
}
}
int main() {
log("Hello! This is VM76. Nice to meet you!");
VM76::start_game();
}
<|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 "fusumry.hxx"
#include <editeng/eeitem.hxx>
#include <svx/svdotext.hxx>
#include <svx/svdundo.hxx>
#include <sfx2/printer.hxx>
#include <editeng/outlobj.hxx>
#include "strings.hrc"
#include "pres.hxx"
#include "View.hxx"
#include "sdpage.hxx"
#include "Outliner.hxx"
#include "drawview.hxx"
#include "drawdoc.hxx"
#include "ViewShell.hxx"
#include "DrawDocShell.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#include "DrawViewShell.hxx"
namespace sd {
TYPEINIT1( FuSummaryPage, FuPoor );
FuSummaryPage::FuSummaryPage (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
rtl::Reference<FuPoor> FuSummaryPage::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
rtl::Reference<FuPoor> xFunc( new FuSummaryPage( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuSummaryPage::DoExecute( SfxRequest& )
{
::sd::Outliner* pOutl = NULL;
SdPage* pSummaryPage = NULL;
sal_uInt16 i = 0;
sal_uInt16 nFirstPage = SDRPAGE_NOTFOUND;
sal_uInt16 nSelectedPages = 0;
sal_uInt16 nCount = mpDoc->GetSdPageCount(PK_STANDARD);
while (i < nCount && nSelectedPages <= 1)
{
/* How many pages are selected?
exactly one: pool everything from this page
otherwise: only pool the selected pages */
SdPage* pActualPage = mpDoc->GetSdPage(i, PK_STANDARD);
if (pActualPage->IsSelected())
{
if (nFirstPage == SDRPAGE_NOTFOUND)
{
nFirstPage = i;
}
nSelectedPages++;
}
i++;
}
bool bBegUndo = false;
SfxStyleSheet* pStyle = NULL;
for (i = nFirstPage; i < nCount; i++)
{
SdPage* pActualPage = mpDoc->GetSdPage(i, PK_STANDARD);
if (nSelectedPages <= 1 || pActualPage->IsSelected())
{
SdPage* pActualNotesPage = mpDoc->GetSdPage(i, PK_NOTES);
SdrTextObj* pTextObj = (SdrTextObj*) pActualPage->GetPresObj(PRESOBJ_TITLE);
if (pTextObj && !pTextObj->IsEmptyPresObj())
{
if (!pSummaryPage)
{
// insert "table of content"-page and create outliner
const bool bUndo = mpView->IsUndoEnabled();
if( bUndo )
{
mpView->BegUndo(SD_RESSTR(STR_UNDO_SUMMARY_PAGE));
bBegUndo = true;
}
SetOfByte aVisibleLayers = pActualPage->TRG_GetMasterPageVisibleLayers();
// page with title & structuring!
pSummaryPage = (SdPage*) mpDoc->AllocPage(false);
pSummaryPage->SetSize(pActualPage->GetSize() );
pSummaryPage->SetBorder(pActualPage->GetLftBorder(),
pActualPage->GetUppBorder(),
pActualPage->GetRgtBorder(),
pActualPage->GetLwrBorder() );
// insert page at the back
mpDoc->InsertPage(pSummaryPage, nCount * 2 + 1);
if( bUndo )
mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoNewPage(*pSummaryPage));
// use MasterPage of the current page
pSummaryPage->TRG_SetMasterPage(pActualPage->TRG_GetMasterPage());
pSummaryPage->SetLayoutName(pActualPage->GetLayoutName());
pSummaryPage->SetAutoLayout(AUTOLAYOUT_ENUM, sal_True);
pSummaryPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
pSummaryPage->setHeaderFooterSettings(pActualPage->getHeaderFooterSettings());
// notes-page
SdPage* pNotesPage = (SdPage*) mpDoc->AllocPage(false);
pNotesPage->SetSize(pActualNotesPage->GetSize());
pNotesPage->SetBorder(pActualNotesPage->GetLftBorder(),
pActualNotesPage->GetUppBorder(),
pActualNotesPage->GetRgtBorder(),
pActualNotesPage->GetLwrBorder() );
pNotesPage->SetPageKind(PK_NOTES);
// insert page at the back
mpDoc->InsertPage(pNotesPage, nCount * 2 + 2);
if( bUndo )
mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoNewPage(*pNotesPage));
// use MasterPage of the current page
pNotesPage->TRG_SetMasterPage(pActualNotesPage->TRG_GetMasterPage());
pNotesPage->SetLayoutName(pActualNotesPage->GetLayoutName());
pNotesPage->SetAutoLayout(pActualNotesPage->GetAutoLayout(), sal_True);
pNotesPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
pNotesPage->setHeaderFooterSettings(pActualNotesPage->getHeaderFooterSettings());
pOutl = new ::sd::Outliner( mpDoc, OUTLINERMODE_OUTLINEOBJECT );
pOutl->SetUpdateMode(false);
pOutl->EnableUndo(false);
if (mpDocSh)
pOutl->SetRefDevice(SD_MOD()->GetRefDevice( *mpDocSh ));
pOutl->SetDefTab( mpDoc->GetDefaultTabulator() );
pOutl->SetStyleSheetPool((SfxStyleSheetPool*) mpDoc->GetStyleSheetPool());
pStyle = pSummaryPage->GetStyleSheetForPresObj( PRESOBJ_OUTLINE );
pOutl->SetStyleSheet( 0, pStyle );
}
// add text
OutlinerParaObject* pParaObj = pTextObj->GetOutlinerParaObject();
// #118876#, check if the OutlinerParaObject is created successfully
if( pParaObj )
{
pParaObj->SetOutlinerMode( OUTLINERMODE_OUTLINEOBJECT );
pOutl->AddText(*pParaObj);
}
}
}
}
if (pSummaryPage)
{
SdrTextObj* pTextObj = (SdrTextObj*) pSummaryPage->GetPresObj(PRESOBJ_OUTLINE);
// remove hard break- and character attributes
SfxItemSet aEmptyEEAttr(mpDoc->GetPool(), EE_ITEMS_START, EE_ITEMS_END);
sal_Int32 nParaCount = pOutl->GetParagraphCount();
for (sal_Int32 nPara = 0; nPara < nParaCount; nPara++)
{
pOutl->SetStyleSheet( nPara, pStyle );
pOutl->QuickRemoveCharAttribs(nPara);
pOutl->SetParaAttribs(nPara, aEmptyEEAttr);
pOutl->SetDepth(pOutl->GetParagraph(nPara), 0);
}
pTextObj->SetOutlinerParaObject( pOutl->CreateParaObject() );
pTextObj->SetEmptyPresObj(false);
// remove hard attributes (Flag to sal_True)
SfxItemSet aAttr(mpDoc->GetPool());
aAttr.Put(XLineStyleItem(XLINE_NONE));
aAttr.Put(XFillStyleItem(XFILL_NONE));
pTextObj->SetMergedItemSet(aAttr);
if( bBegUndo )
mpView->EndUndo();
delete pOutl;
DrawViewShell* pDrawViewShell= dynamic_cast< DrawViewShell* >( mpViewShell );
if(pDrawViewShell)
{
pDrawViewShell->SwitchPage( (pSummaryPage->GetPageNum() - 1) / 2);
}
}
}
} // end of namespace sd
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#736147 Dereference null return value<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 "fusumry.hxx"
#include <editeng/eeitem.hxx>
#include <svx/svdotext.hxx>
#include <svx/svdundo.hxx>
#include <sfx2/printer.hxx>
#include <editeng/outlobj.hxx>
#include "strings.hrc"
#include "pres.hxx"
#include "View.hxx"
#include "sdpage.hxx"
#include "Outliner.hxx"
#include "drawview.hxx"
#include "drawdoc.hxx"
#include "ViewShell.hxx"
#include "DrawDocShell.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#include "DrawViewShell.hxx"
namespace sd {
TYPEINIT1( FuSummaryPage, FuPoor );
FuSummaryPage::FuSummaryPage (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
rtl::Reference<FuPoor> FuSummaryPage::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
rtl::Reference<FuPoor> xFunc( new FuSummaryPage( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuSummaryPage::DoExecute( SfxRequest& )
{
::sd::Outliner* pOutl = NULL;
SdPage* pSummaryPage = NULL;
sal_uInt16 i = 0;
sal_uInt16 nFirstPage = SDRPAGE_NOTFOUND;
sal_uInt16 nSelectedPages = 0;
sal_uInt16 nCount = mpDoc->GetSdPageCount(PK_STANDARD);
while (i < nCount && nSelectedPages <= 1)
{
/* How many pages are selected?
exactly one: pool everything from this page
otherwise: only pool the selected pages */
SdPage* pActualPage = mpDoc->GetSdPage(i, PK_STANDARD);
if (pActualPage->IsSelected())
{
if (nFirstPage == SDRPAGE_NOTFOUND)
{
nFirstPage = i;
}
nSelectedPages++;
}
i++;
}
bool bBegUndo = false;
SfxStyleSheet* pStyle = NULL;
for (i = nFirstPage; i < nCount; i++)
{
SdPage* pActualPage = mpDoc->GetSdPage(i, PK_STANDARD);
if (nSelectedPages <= 1 || pActualPage->IsSelected())
{
SdPage* pActualNotesPage = mpDoc->GetSdPage(i, PK_NOTES);
SdrTextObj* pTextObj = (SdrTextObj*) pActualPage->GetPresObj(PRESOBJ_TITLE);
if (pTextObj && !pTextObj->IsEmptyPresObj())
{
if (!pSummaryPage)
{
// insert "table of content"-page and create outliner
const bool bUndo = mpView->IsUndoEnabled();
if( bUndo )
{
mpView->BegUndo(SD_RESSTR(STR_UNDO_SUMMARY_PAGE));
bBegUndo = true;
}
SetOfByte aVisibleLayers = pActualPage->TRG_GetMasterPageVisibleLayers();
// page with title & structuring!
pSummaryPage = (SdPage*) mpDoc->AllocPage(false);
pSummaryPage->SetSize(pActualPage->GetSize() );
pSummaryPage->SetBorder(pActualPage->GetLftBorder(),
pActualPage->GetUppBorder(),
pActualPage->GetRgtBorder(),
pActualPage->GetLwrBorder() );
// insert page at the back
mpDoc->InsertPage(pSummaryPage, nCount * 2 + 1);
if( bUndo )
mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoNewPage(*pSummaryPage));
// use MasterPage of the current page
pSummaryPage->TRG_SetMasterPage(pActualPage->TRG_GetMasterPage());
pSummaryPage->SetLayoutName(pActualPage->GetLayoutName());
pSummaryPage->SetAutoLayout(AUTOLAYOUT_ENUM, sal_True);
pSummaryPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
pSummaryPage->setHeaderFooterSettings(pActualPage->getHeaderFooterSettings());
// notes-page
SdPage* pNotesPage = (SdPage*) mpDoc->AllocPage(false);
pNotesPage->SetSize(pActualNotesPage->GetSize());
pNotesPage->SetBorder(pActualNotesPage->GetLftBorder(),
pActualNotesPage->GetUppBorder(),
pActualNotesPage->GetRgtBorder(),
pActualNotesPage->GetLwrBorder() );
pNotesPage->SetPageKind(PK_NOTES);
// insert page at the back
mpDoc->InsertPage(pNotesPage, nCount * 2 + 2);
if( bUndo )
mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoNewPage(*pNotesPage));
// use MasterPage of the current page
pNotesPage->TRG_SetMasterPage(pActualNotesPage->TRG_GetMasterPage());
pNotesPage->SetLayoutName(pActualNotesPage->GetLayoutName());
pNotesPage->SetAutoLayout(pActualNotesPage->GetAutoLayout(), sal_True);
pNotesPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);
pNotesPage->setHeaderFooterSettings(pActualNotesPage->getHeaderFooterSettings());
pOutl = new ::sd::Outliner( mpDoc, OUTLINERMODE_OUTLINEOBJECT );
pOutl->SetUpdateMode(false);
pOutl->EnableUndo(false);
if (mpDocSh)
pOutl->SetRefDevice(SD_MOD()->GetRefDevice( *mpDocSh ));
pOutl->SetDefTab( mpDoc->GetDefaultTabulator() );
pOutl->SetStyleSheetPool((SfxStyleSheetPool*) mpDoc->GetStyleSheetPool());
pStyle = pSummaryPage->GetStyleSheetForPresObj( PRESOBJ_OUTLINE );
pOutl->SetStyleSheet( 0, pStyle );
}
// add text
OutlinerParaObject* pParaObj = pTextObj->GetOutlinerParaObject();
// #118876#, check if the OutlinerParaObject is created successfully
if( pParaObj )
{
pParaObj->SetOutlinerMode( OUTLINERMODE_OUTLINEOBJECT );
pOutl->AddText(*pParaObj);
}
}
}
}
if (!pSummaryPage)
return;
SdrTextObj* pTextObj = (SdrTextObj*) pSummaryPage->GetPresObj(PRESOBJ_OUTLINE);
if (!pTextObj)
return;
// remove hard break- and character attributes
SfxItemSet aEmptyEEAttr(mpDoc->GetPool(), EE_ITEMS_START, EE_ITEMS_END);
sal_Int32 nParaCount = pOutl->GetParagraphCount();
for (sal_Int32 nPara = 0; nPara < nParaCount; nPara++)
{
pOutl->SetStyleSheet( nPara, pStyle );
pOutl->QuickRemoveCharAttribs(nPara);
pOutl->SetParaAttribs(nPara, aEmptyEEAttr);
pOutl->SetDepth(pOutl->GetParagraph(nPara), 0);
}
pTextObj->SetOutlinerParaObject( pOutl->CreateParaObject() );
pTextObj->SetEmptyPresObj(false);
// remove hard attributes (Flag to sal_True)
SfxItemSet aAttr(mpDoc->GetPool());
aAttr.Put(XLineStyleItem(XLINE_NONE));
aAttr.Put(XFillStyleItem(XFILL_NONE));
pTextObj->SetMergedItemSet(aAttr);
if( bBegUndo )
mpView->EndUndo();
delete pOutl;
DrawViewShell* pDrawViewShell= dynamic_cast< DrawViewShell* >( mpViewShell );
if(pDrawViewShell)
{
pDrawViewShell->SwitchPage( (pSummaryPage->GetPageNum() - 1) / 2);
}
}
} // end of namespace sd
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// VTK Viewer
// Written 2012-2013 Hal Canary <http://cs.unc.edu/~hal>
// Copyright 2012-2013 University of North Carolina at Chapel Hill.
//
// 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
//
// LICENSE.md in this repository or
// 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 "VTKViewer.h"
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPLYReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkRenderWindow.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkColorTransferFunction.h>
#include <vtkPolyDataNormals.h>
#include <vtkPointData.h>
#include <vtkOBJReader.h>
#include <vtkSTLReader.h>
#include <vtkVersion.h>
#if VTK_MAJOR_VERSION <= 5
#define setInputData(x,y) ((x)->SetInput(y))
#else
#define setInputData(x,y) ((x)->SetInputData(y))
#endif
#include <vtkCamera.h>
#include <iostream>
using std::cout;
VTKViewer::VTKViewer() :
renderer(vtkSmartPointer < vtkRenderer >::New())
{
vtkSmartPointer < vtkRenderWindow > renderWindow =
vtkSmartPointer < vtkRenderWindow >::New();
renderWindow->StereoCapableWindowOn();
renderWindow->SetStereoTypeToRedBlue();
renderWindow->AddRenderer(renderer);
renderer->ResetCamera();
this->resize(480, 480);
this->setMinimumSize(480, 360);
this->SetRenderWindow(renderWindow);
connect(&(this->timer), SIGNAL(timeout()), this, SLOT(rotate()));
this->timer.start(66);
}
void VTKViewer::add(vtkPolyData * polyData)
{
double range[2];
polyData->GetScalarRange(range);
vtkSmartPointer< vtkColorTransferFunction > colorMap
= vtkSmartPointer< vtkColorTransferFunction >::New();
colorMap->SetColorSpaceToLab();
colorMap->AddRGBPoint(range[0], 0.865, 0.865, 0.865);
colorMap->AddRGBPoint(range[1], 0.706, 0.016, 0.150);
colorMap->Build();
vtkSmartPointer < vtkPolyDataMapper > mapper =
vtkSmartPointer < vtkPolyDataMapper >::New();
mapper->SetLookupTable(colorMap);
if (polyData->GetPointData()->GetNormals() == NULL)
{
vtkSmartPointer< vtkPolyDataNormals > polyDataNormals
= vtkSmartPointer< vtkPolyDataNormals >::New();
setInputData(polyDataNormals, polyData);
polyDataNormals->SetFeatureAngle(90.0);
mapper->SetInputConnection(polyDataNormals->GetOutputPort());
}
else
{
setInputData(mapper, polyData);
}
vtkSmartPointer < vtkActor > actor =
vtkSmartPointer < vtkActor >::New();
actor->GetProperty()->SetPointSize(3);
actor->SetMapper(mapper);
this->renderer->AddActor(actor);
}
void VTKViewer::add(const char * file_name)
{
// TODO: add logic for other file formats.
vtkSmartPointer < vtkPolyData > polyData =
vtkSmartPointer< vtkPolyData >::New();
QString filename = QString::fromUtf8(file_name);
if (filename.endsWith(".vtp") || filename.endsWith(".VTP"))
{
vtkSmartPointer< vtkXMLPolyDataReader > reader =
vtkSmartPointer< vtkXMLPolyDataReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".vtk") || filename.endsWith(".VTK"))
{
vtkSmartPointer< vtkPolyDataReader > reader =
vtkSmartPointer< vtkPolyDataReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".ply") || filename.endsWith(".PLY"))
{
vtkSmartPointer< vtkPLYReader > reader =
vtkSmartPointer< vtkPLYReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".obj") || filename.endsWith(".OBJ"))
{
vtkSmartPointer< vtkOBJReader > reader =
vtkSmartPointer< vtkOBJReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".stl") || filename.endsWith(".STL"))
{
vtkSmartPointer< vtkSTLReader > reader =
vtkSmartPointer< vtkSTLReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else
{
std::cerr << file_name
<< ": BAD FILE NAME. Should end in VTK, VTP, PLY, OBJ, or STL.\n";
exit(1);
return;
}
this->add(polyData);
}
void VTKViewer::toggle()
{
if (this->timer.isActive())
this->timer.stop();
else
this->timer.start(33);
}
void VTKViewer::rotate()
{
vtkCamera * camera = this->renderer->GetActiveCamera();
assert(camera != NULL);
camera->Azimuth(1);
this->renderer->GetRenderWindow()->Render();
}
void VTKViewer::stereo()
{
vtkRenderWindow * rw = this->renderer->GetRenderWindow();
assert(rw != NULL);
rw->SetStereoRender(! rw->GetStereoRender());
rw->Render();
}
void VTKViewer::changeStereoType()
{
vtkRenderWindow * rw = this->renderer->GetRenderWindow();
assert(rw != NULL);
int type = rw->GetStereoType();
type = (type % 9) + 1;
rw->SetStereoType(type);
switch(type)
{
case 1: cout << "VTK_STEREO_CRYSTAL_EYES\n"; break;
case 2: cout << "VTK_STEREO_RED_BLUE\n"; break;
case 3: cout << "VTK_STEREO_INTERLACED\n"; break;
case 4: cout << "VTK_STEREO_LEFT\n"; break;
case 5: cout << "VTK_STEREO_RIGHT\n"; break;
case 6: cout << "VTK_STEREO_DRESDEN\n"; break;
case 7: cout << "VTK_STEREO_ANAGLYPH\n"; break;
case 8: cout << "VTK_STEREO_CHECKERBOARD\n"; break;
case 9: cout << "VTK_STEREO_SPLITVIEWPORT_HORIZONTAL\n"; break;
}
rw->Render();
}
<commit_msg>Read .PDB (Protein Data Bank) files.<commit_after>// VTK Viewer
// Written 2012-2013 Hal Canary <http://cs.unc.edu/~hal>
// Copyright 2012-2013 University of North Carolina at Chapel Hill.
//
// 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
//
// LICENSE.md in this repository or
// 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 "VTKViewer.h"
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPLYReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkRenderWindow.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkColorTransferFunction.h>
#include <vtkPolyDataNormals.h>
#include <vtkPointData.h>
#include <vtkOBJReader.h>
#include <vtkPDBReader.h>
#include <vtkSphereSource.h>
#include <vtkGlyph3D.h>
#include <vtkTubeFilter.h>
#include <vtkAppendPolyData.h>
#include <vtkSTLReader.h>
#include <vtkVersion.h>
#if VTK_MAJOR_VERSION <= 5
#define setInputData(x,y) ((x)->SetInput(y))
#else
#define setInputData(x,y) ((x)->SetInputData(y))
#endif
#include <vtkCamera.h>
#include <iostream>
using std::cout;
static void ReadPDB(const char * file_name, vtkPolyData * polyData)
{
vtkSmartPointer<vtkPDBReader> pdb =
vtkSmartPointer<vtkPDBReader>::New();
pdb->SetFileName(file_name);
pdb->SetHBScale(1.0);
pdb->SetBScale(1.0);
pdb->Update();
vtkSmartPointer<vtkSphereSource> sphere =
vtkSmartPointer<vtkSphereSource>::New();
sphere->SetCenter(0, 0, 0);
sphere->SetRadius(1);
vtkSmartPointer<vtkGlyph3D> glyph =
vtkSmartPointer<vtkGlyph3D>::New();
glyph->SetInputConnection(pdb->GetOutputPort());
glyph->SetSourceConnection(sphere->GetOutputPort());
glyph->SetOrient(1);
glyph->SetColorMode(1);
glyph->SetScaleMode(2);
glyph->SetScaleFactor(.25);
glyph->Update();
vtkSmartPointer<vtkTubeFilter> tube =
vtkSmartPointer<vtkTubeFilter>::New();
tube->SetInputConnection(pdb->GetOutputPort());
tube->SetNumberOfSides(6);
tube->CappingOff();
tube->SetRadius(0.2);
tube->SetVaryRadius(0);
tube->SetRadiusFactor(10);
tube->Update();
vtkSmartPointer< vtkAppendPolyData > appendFilter =
vtkSmartPointer< vtkAppendPolyData >::New();
appendFilter->AddInputConnection(glyph->GetOutputPort());
appendFilter->AddInputConnection(tube->GetOutputPort());
appendFilter->Update();
polyData->ShallowCopy(appendFilter->GetOutput());
return;
}
VTKViewer::VTKViewer() :
renderer(vtkSmartPointer < vtkRenderer >::New())
{
vtkSmartPointer < vtkRenderWindow > renderWindow =
vtkSmartPointer < vtkRenderWindow >::New();
renderWindow->StereoCapableWindowOn();
renderWindow->SetStereoTypeToRedBlue();
renderWindow->AddRenderer(renderer);
renderer->ResetCamera();
this->resize(480, 480);
this->setMinimumSize(480, 360);
this->SetRenderWindow(renderWindow);
connect(&(this->timer), SIGNAL(timeout()), this, SLOT(rotate()));
this->timer.start(66);
}
void VTKViewer::add(vtkPolyData * polyData)
{
double range[2];
polyData->GetScalarRange(range);
vtkSmartPointer< vtkColorTransferFunction > colorMap
= vtkSmartPointer< vtkColorTransferFunction >::New();
colorMap->SetColorSpaceToLab();
colorMap->AddRGBPoint(range[0], 0.865, 0.865, 0.865);
colorMap->AddRGBPoint(range[1], 0.706, 0.016, 0.150);
colorMap->Build();
vtkSmartPointer < vtkPolyDataMapper > mapper =
vtkSmartPointer < vtkPolyDataMapper >::New();
mapper->SetLookupTable(colorMap);
if (polyData->GetPointData()->GetNormals() == NULL)
{
vtkSmartPointer< vtkPolyDataNormals > polyDataNormals
= vtkSmartPointer< vtkPolyDataNormals >::New();
setInputData(polyDataNormals, polyData);
polyDataNormals->SetFeatureAngle(90.0);
mapper->SetInputConnection(polyDataNormals->GetOutputPort());
}
else
{
setInputData(mapper, polyData);
}
vtkSmartPointer < vtkActor > actor =
vtkSmartPointer < vtkActor >::New();
actor->GetProperty()->SetPointSize(3);
actor->SetMapper(mapper);
this->renderer->AddActor(actor);
}
void VTKViewer::add(const char * file_name)
{
// TODO: add logic for other file formats.
vtkSmartPointer < vtkPolyData > polyData =
vtkSmartPointer< vtkPolyData >::New();
QString filename = QString::fromUtf8(file_name);
if (filename.endsWith(".vtp") || filename.endsWith(".VTP"))
{
vtkSmartPointer< vtkXMLPolyDataReader > reader =
vtkSmartPointer< vtkXMLPolyDataReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".vtk") || filename.endsWith(".VTK"))
{
vtkSmartPointer< vtkPolyDataReader > reader =
vtkSmartPointer< vtkPolyDataReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".ply") || filename.endsWith(".PLY"))
{
vtkSmartPointer< vtkPLYReader > reader =
vtkSmartPointer< vtkPLYReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".obj") || filename.endsWith(".OBJ"))
{
vtkSmartPointer< vtkOBJReader > reader =
vtkSmartPointer< vtkOBJReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".stl") || filename.endsWith(".STL"))
{
vtkSmartPointer< vtkSTLReader > reader =
vtkSmartPointer< vtkSTLReader >::New();
reader->SetFileName(file_name);
reader->Update();
polyData->ShallowCopy(reader->GetOutput());
}
else if (filename.endsWith(".pdb") || filename.endsWith(".PDB"))
{
ReadPDB(file_name, polyData);
}
else
{
std::cerr << file_name
<< ": BAD FILE NAME. Should end in VTK, VTP, PLY, OBJ, STL, or PDB.\n";
exit(1);
return;
}
this->add(polyData);
}
void VTKViewer::toggle()
{
if (this->timer.isActive())
this->timer.stop();
else
this->timer.start(33);
}
void VTKViewer::rotate()
{
vtkCamera * camera = this->renderer->GetActiveCamera();
assert(camera != NULL);
camera->Azimuth(1);
this->renderer->GetRenderWindow()->Render();
}
void VTKViewer::stereo()
{
vtkRenderWindow * rw = this->renderer->GetRenderWindow();
assert(rw != NULL);
rw->SetStereoRender(! rw->GetStereoRender());
rw->Render();
}
void VTKViewer::changeStereoType()
{
vtkRenderWindow * rw = this->renderer->GetRenderWindow();
assert(rw != NULL);
int type = rw->GetStereoType();
type = (type % 9) + 1;
rw->SetStereoType(type);
switch(type)
{
case 1: cout << "VTK_STEREO_CRYSTAL_EYES\n"; break;
case 2: cout << "VTK_STEREO_RED_BLUE\n"; break;
case 3: cout << "VTK_STEREO_INTERLACED\n"; break;
case 4: cout << "VTK_STEREO_LEFT\n"; break;
case 5: cout << "VTK_STEREO_RIGHT\n"; break;
case 6: cout << "VTK_STEREO_DRESDEN\n"; break;
case 7: cout << "VTK_STEREO_ANAGLYPH\n"; break;
case 8: cout << "VTK_STEREO_CHECKERBOARD\n"; break;
case 9: cout << "VTK_STEREO_SPLITVIEWPORT_HORIZONTAL\n"; break;
}
rw->Render();
}
<|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/chromeos/clock_menu_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/i18n/time_format.h"
#include "base/string_util.h"
#include "base/time.h"
#include "grit/generated_resources.h"
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton()
: MenuButton(NULL, std::wstring(), this, false),
clock_menu_(this) {
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
UpdateText();
}
void ClockMenuButton::SetNextTimer() {
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateText);
}
void ClockMenuButton::UpdateText() {
base::Time::Exploded now;
base::Time::Now().LocalExplode(&now);
int hour = now.hour % 12;
if (hour == 0)
hour = 12;
std::wstring hour_str = IntToWString(hour);
std::wstring min_str = IntToWString(now.minute);
// Append a "0" before the minute if it's only a single digit.
if (now.minute < 10)
min_str = IntToWString(0) + min_str;
int msg = now.hour < 12 ? IDS_STATUSBAR_CLOCK_SHORT_TIME_AM :
IDS_STATUSBAR_CLOCK_SHORT_TIME_PM;
std::wstring time_string = l10n_util::GetStringF(msg, hour_str, min_str);
SetText(time_string);
SchedulePaint();
SetNextTimer();
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::Menu2Model implementation:
int ClockMenuButton::GetItemCount() const {
return 1;
}
views::Menu2Model::ItemType ClockMenuButton::GetTypeAt(int index) const {
return views::Menu2Model::TYPE_COMMAND;
}
string16 ClockMenuButton::GetLabelAt(int index) const {
return WideToUTF16(base::TimeFormatFriendlyDate(base::Time::Now()));
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt,
gfx::NativeView hwnd) {
clock_menu_.Rebuild();
clock_menu_.UpdateStates();
clock_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
<commit_msg>Really fix the changed include to fix the ChromeOS build this time.<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/chromeos/clock_menu_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/i18n/time_formatting.h"
#include "base/string_util.h"
#include "base/time.h"
#include "grit/generated_resources.h"
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton()
: MenuButton(NULL, std::wstring(), this, false),
clock_menu_(this) {
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
UpdateText();
}
void ClockMenuButton::SetNextTimer() {
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateText);
}
void ClockMenuButton::UpdateText() {
base::Time::Exploded now;
base::Time::Now().LocalExplode(&now);
int hour = now.hour % 12;
if (hour == 0)
hour = 12;
std::wstring hour_str = IntToWString(hour);
std::wstring min_str = IntToWString(now.minute);
// Append a "0" before the minute if it's only a single digit.
if (now.minute < 10)
min_str = IntToWString(0) + min_str;
int msg = now.hour < 12 ? IDS_STATUSBAR_CLOCK_SHORT_TIME_AM :
IDS_STATUSBAR_CLOCK_SHORT_TIME_PM;
std::wstring time_string = l10n_util::GetStringF(msg, hour_str, min_str);
SetText(time_string);
SchedulePaint();
SetNextTimer();
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::Menu2Model implementation:
int ClockMenuButton::GetItemCount() const {
return 1;
}
views::Menu2Model::ItemType ClockMenuButton::GetTypeAt(int index) const {
return views::Menu2Model::TYPE_COMMAND;
}
string16 ClockMenuButton::GetLabelAt(int index) const {
return WideToUTF16(base::TimeFormatFriendlyDate(base::Time::Now()));
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt,
gfx::NativeView hwnd) {
clock_menu_.Rebuild();
clock_menu_.UpdateStates();
clock_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unoaprms.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:48:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SD_UNOAPRMS_HXX
#define _SD_UNOAPRMS_HXX
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_
#include <com/sun/star/presentation/AnimationEffect.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_
#include <com/sun/star/presentation/AnimationSpeed.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _SD_SDUNDO_HXX
#include "sdundo.hxx"
#endif
#ifndef _SD_ANMDEF_HXX
#include "anmdef.hxx"
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdopath.hxx>
#endif
#ifndef _SV_COLOR_HXX //autogen
#include <vcl/color.hxx>
#endif
class SdDrawDocument;
class SdrObject;
class SdAnimationPrmsUndoAction : public SdUndoAction
{
SdrObject* pObject;
BOOL bOldActive;
BOOL bNewActive;
BOOL bOldDimPrevious;
BOOL bNewDimPrevious;
BOOL bOldDimHide;
BOOL bNewDimHide;
BOOL bOldSoundOn;
BOOL bNewSoundOn;
BOOL bOldSecondSoundOn;
BOOL bNewSecondSoundOn;
BOOL bOldPlayFull;
BOOL bNewPlayFull;
BOOL bOldSecondPlayFull;
BOOL bNewSecondPlayFull;
::com::sun::star::presentation::AnimationEffect eOldEffect;
::com::sun::star::presentation::AnimationEffect eNewEffect;
::com::sun::star::presentation::AnimationEffect eOldTextEffect;
::com::sun::star::presentation::AnimationEffect eNewTextEffect;
::com::sun::star::presentation::AnimationSpeed eOldSpeed;
::com::sun::star::presentation::AnimationSpeed eNewSpeed;
::com::sun::star::presentation::AnimationEffect eOldSecondEffect;
::com::sun::star::presentation::AnimationEffect eNewSecondEffect;
::com::sun::star::presentation::AnimationSpeed eOldSecondSpeed;
::com::sun::star::presentation::AnimationSpeed eNewSecondSpeed;
Color aOldDimColor;
Color aNewDimColor;
Color aOldBlueScreen;
Color aNewBlueScreen;
String aOldSoundFile;
String aNewSoundFile;
SdrPathObj* pOldPathObj;
SdrPathObj* pNewPathObj;
::com::sun::star::presentation::ClickAction eOldClickAction;
::com::sun::star::presentation::ClickAction eNewClickAction;
String aOldBookmark;
String aNewBookmark;
BOOL bOldInvisibleInPres;
BOOL bNewInvisibleInPres;
USHORT nOldVerb;
USHORT nNewVerb;
ULONG nOldPresOrder;
ULONG nNewPresOrder;
BOOL bInfoCreated;
public:
TYPEINFO();
SdAnimationPrmsUndoAction(SdDrawDocument* pTheDoc, SdrObject* pObj,
BOOL bCreated):
SdUndoAction (pTheDoc),
pObject (pObj),
bInfoCreated (bCreated)
{}
SdAnimationPrmsUndoAction( SdDrawDocument* pTheDoc, SdrObject* pObj );
void SetActive(BOOL bTheOldActive, BOOL bTheNewActive)
{ bOldActive = bTheOldActive; bNewActive = bTheNewActive; }
void SetEffect(::com::sun::star::presentation::AnimationEffect eTheOldEffect, ::com::sun::star::presentation::AnimationEffect eTheNewEffect)
{ eOldEffect = eTheOldEffect; eNewEffect = eTheNewEffect; }
void SetTextEffect(::com::sun::star::presentation::AnimationEffect eTheOldEffect, ::com::sun::star::presentation::AnimationEffect eTheNewEffect)
{ eOldTextEffect = eTheOldEffect; eNewTextEffect = eTheNewEffect; }
void SetSpeed(::com::sun::star::presentation::AnimationSpeed eTheOldSpeed, ::com::sun::star::presentation::AnimationSpeed eTheNewSpeed)
{ eOldSpeed = eTheOldSpeed; eNewSpeed = eTheNewSpeed; }
void SetDim(BOOL bTheOldDim, BOOL bTheNewDim)
{ bOldDimPrevious = bTheOldDim; bNewDimPrevious = bTheNewDim; }
void SetDimColor(Color aTheOldDimColor, Color aTheNewDimColor)
{ aOldDimColor = aTheOldDimColor; aNewDimColor = aTheNewDimColor; }
void SetDimHide(BOOL bTheOldDimHide, BOOL bTheNewDimHide)
{ bOldDimHide = bTheOldDimHide; bNewDimHide = bTheNewDimHide; }
void SetSoundOn(BOOL bTheOldSoundOn, BOOL bTheNewSoundOn)
{ bOldSoundOn = bTheOldSoundOn; bNewSoundOn = bTheNewSoundOn; }
void SetSound(String aTheOldSound, String aTheNewSound)
{ aOldSoundFile = aTheOldSound; aNewSoundFile = aTheNewSound; }
void SetBlueScreen(Color aTheOldBlueScreen, Color aTheNewBlueScreen)
{ aOldBlueScreen = aTheOldBlueScreen; aNewBlueScreen = aTheNewBlueScreen; }
void SetPlayFull(BOOL bTheOldPlayFull, BOOL bTheNewPlayFull)
{ bOldPlayFull = bTheOldPlayFull; bNewPlayFull = bTheNewPlayFull; }
void SetPathObj(SdrPathObj* pTheOldPath, SdrPathObj* pTheNewPath)
{ pOldPathObj = pTheOldPath; pNewPathObj = pTheNewPath; }
void SetClickAction(::com::sun::star::presentation::ClickAction eTheOldAction, ::com::sun::star::presentation::ClickAction eTheNewAction)
{ eOldClickAction = eTheOldAction; eNewClickAction = eTheNewAction; }
void SetBookmark(String aTheOldBookmark, String aTheNewBookmark)
{ aOldBookmark = aTheOldBookmark; aNewBookmark = aTheNewBookmark; }
void SetInvisibleInPres(BOOL bTheOldInvisibleInPres, BOOL bTheNewInvisibleInPres)
{ bOldInvisibleInPres = bTheOldInvisibleInPres; bNewInvisibleInPres = bTheNewInvisibleInPres; }
void SetVerb(USHORT nTheOldVerb, USHORT nTheNewVerb)
{ nOldVerb = nTheOldVerb; nNewVerb = nTheNewVerb; }
void SetSecondEffect(::com::sun::star::presentation::AnimationEffect eTheOldEffect, ::com::sun::star::presentation::AnimationEffect eTheNewEffect)
{ eOldSecondEffect = eTheOldEffect; eNewSecondEffect = eTheNewEffect; }
void SetSecondSpeed(::com::sun::star::presentation::AnimationSpeed eTheOldSpeed, ::com::sun::star::presentation::AnimationSpeed eTheNewSpeed)
{ eOldSecondSpeed = eTheOldSpeed; eNewSecondSpeed = eTheNewSpeed; }
void SetSecondSoundOn(BOOL bTheOldSoundOn, BOOL bTheNewSoundOn)
{ bOldSecondSoundOn = bTheOldSoundOn; bNewSecondSoundOn = bTheNewSoundOn; }
void SetSecondPlayFull(BOOL bTheOldPlayFull, BOOL bTheNewPlayFull)
{ bOldSecondPlayFull = bTheOldPlayFull; bNewSecondPlayFull = bTheNewPlayFull; }
void SetPresOrder(ULONG nTheOldPresOrder, ULONG nTheNewPresOrder)
{ nOldPresOrder = nTheOldPresOrder; nNewPresOrder = nTheNewPresOrder; }
virtual ~SdAnimationPrmsUndoAction();
virtual void Undo();
virtual void Redo();
virtual void Repeat();
};
#endif // _SD_UNOAPRMS_HXX
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.1.1.1.336); FILE MERGED 2003/12/11 09:17:30 mt 1.1.1.1.336.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/*************************************************************************
*
* $RCSfile: unoaprms.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2004-01-06 18:47:31 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SD_UNOAPRMS_HXX
#define _SD_UNOAPRMS_HXX
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_
#include <com/sun/star/presentation/AnimationEffect.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_
#include <com/sun/star/presentation/AnimationSpeed.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _SD_SDUNDO_HXX
#include "sdundo.hxx"
#endif
#ifndef _SD_ANMDEF_HXX
#include "anmdef.hxx"
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdopath.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
class SdDrawDocument;
class SdrObject;
class SdAnimationPrmsUndoAction : public SdUndoAction
{
SdrObject* pObject;
BOOL bOldActive;
BOOL bNewActive;
BOOL bOldDimPrevious;
BOOL bNewDimPrevious;
BOOL bOldDimHide;
BOOL bNewDimHide;
BOOL bOldSoundOn;
BOOL bNewSoundOn;
BOOL bOldSecondSoundOn;
BOOL bNewSecondSoundOn;
BOOL bOldPlayFull;
BOOL bNewPlayFull;
BOOL bOldSecondPlayFull;
BOOL bNewSecondPlayFull;
::com::sun::star::presentation::AnimationEffect eOldEffect;
::com::sun::star::presentation::AnimationEffect eNewEffect;
::com::sun::star::presentation::AnimationEffect eOldTextEffect;
::com::sun::star::presentation::AnimationEffect eNewTextEffect;
::com::sun::star::presentation::AnimationSpeed eOldSpeed;
::com::sun::star::presentation::AnimationSpeed eNewSpeed;
::com::sun::star::presentation::AnimationEffect eOldSecondEffect;
::com::sun::star::presentation::AnimationEffect eNewSecondEffect;
::com::sun::star::presentation::AnimationSpeed eOldSecondSpeed;
::com::sun::star::presentation::AnimationSpeed eNewSecondSpeed;
Color aOldDimColor;
Color aNewDimColor;
Color aOldBlueScreen;
Color aNewBlueScreen;
String aOldSoundFile;
String aNewSoundFile;
SdrPathObj* pOldPathObj;
SdrPathObj* pNewPathObj;
::com::sun::star::presentation::ClickAction eOldClickAction;
::com::sun::star::presentation::ClickAction eNewClickAction;
String aOldBookmark;
String aNewBookmark;
BOOL bOldInvisibleInPres;
BOOL bNewInvisibleInPres;
USHORT nOldVerb;
USHORT nNewVerb;
ULONG nOldPresOrder;
ULONG nNewPresOrder;
BOOL bInfoCreated;
public:
TYPEINFO();
SdAnimationPrmsUndoAction(SdDrawDocument* pTheDoc, SdrObject* pObj,
BOOL bCreated):
SdUndoAction (pTheDoc),
pObject (pObj),
bInfoCreated (bCreated)
{}
SdAnimationPrmsUndoAction( SdDrawDocument* pTheDoc, SdrObject* pObj );
void SetActive(BOOL bTheOldActive, BOOL bTheNewActive)
{ bOldActive = bTheOldActive; bNewActive = bTheNewActive; }
void SetEffect(::com::sun::star::presentation::AnimationEffect eTheOldEffect, ::com::sun::star::presentation::AnimationEffect eTheNewEffect)
{ eOldEffect = eTheOldEffect; eNewEffect = eTheNewEffect; }
void SetTextEffect(::com::sun::star::presentation::AnimationEffect eTheOldEffect, ::com::sun::star::presentation::AnimationEffect eTheNewEffect)
{ eOldTextEffect = eTheOldEffect; eNewTextEffect = eTheNewEffect; }
void SetSpeed(::com::sun::star::presentation::AnimationSpeed eTheOldSpeed, ::com::sun::star::presentation::AnimationSpeed eTheNewSpeed)
{ eOldSpeed = eTheOldSpeed; eNewSpeed = eTheNewSpeed; }
void SetDim(BOOL bTheOldDim, BOOL bTheNewDim)
{ bOldDimPrevious = bTheOldDim; bNewDimPrevious = bTheNewDim; }
void SetDimColor(Color aTheOldDimColor, Color aTheNewDimColor)
{ aOldDimColor = aTheOldDimColor; aNewDimColor = aTheNewDimColor; }
void SetDimHide(BOOL bTheOldDimHide, BOOL bTheNewDimHide)
{ bOldDimHide = bTheOldDimHide; bNewDimHide = bTheNewDimHide; }
void SetSoundOn(BOOL bTheOldSoundOn, BOOL bTheNewSoundOn)
{ bOldSoundOn = bTheOldSoundOn; bNewSoundOn = bTheNewSoundOn; }
void SetSound(String aTheOldSound, String aTheNewSound)
{ aOldSoundFile = aTheOldSound; aNewSoundFile = aTheNewSound; }
void SetBlueScreen(Color aTheOldBlueScreen, Color aTheNewBlueScreen)
{ aOldBlueScreen = aTheOldBlueScreen; aNewBlueScreen = aTheNewBlueScreen; }
void SetPlayFull(BOOL bTheOldPlayFull, BOOL bTheNewPlayFull)
{ bOldPlayFull = bTheOldPlayFull; bNewPlayFull = bTheNewPlayFull; }
void SetPathObj(SdrPathObj* pTheOldPath, SdrPathObj* pTheNewPath)
{ pOldPathObj = pTheOldPath; pNewPathObj = pTheNewPath; }
void SetClickAction(::com::sun::star::presentation::ClickAction eTheOldAction, ::com::sun::star::presentation::ClickAction eTheNewAction)
{ eOldClickAction = eTheOldAction; eNewClickAction = eTheNewAction; }
void SetBookmark(String aTheOldBookmark, String aTheNewBookmark)
{ aOldBookmark = aTheOldBookmark; aNewBookmark = aTheNewBookmark; }
void SetInvisibleInPres(BOOL bTheOldInvisibleInPres, BOOL bTheNewInvisibleInPres)
{ bOldInvisibleInPres = bTheOldInvisibleInPres; bNewInvisibleInPres = bTheNewInvisibleInPres; }
void SetVerb(USHORT nTheOldVerb, USHORT nTheNewVerb)
{ nOldVerb = nTheOldVerb; nNewVerb = nTheNewVerb; }
void SetSecondEffect(::com::sun::star::presentation::AnimationEffect eTheOldEffect, ::com::sun::star::presentation::AnimationEffect eTheNewEffect)
{ eOldSecondEffect = eTheOldEffect; eNewSecondEffect = eTheNewEffect; }
void SetSecondSpeed(::com::sun::star::presentation::AnimationSpeed eTheOldSpeed, ::com::sun::star::presentation::AnimationSpeed eTheNewSpeed)
{ eOldSecondSpeed = eTheOldSpeed; eNewSecondSpeed = eTheNewSpeed; }
void SetSecondSoundOn(BOOL bTheOldSoundOn, BOOL bTheNewSoundOn)
{ bOldSecondSoundOn = bTheOldSoundOn; bNewSecondSoundOn = bTheNewSoundOn; }
void SetSecondPlayFull(BOOL bTheOldPlayFull, BOOL bTheNewPlayFull)
{ bOldSecondPlayFull = bTheOldPlayFull; bNewSecondPlayFull = bTheNewPlayFull; }
void SetPresOrder(ULONG nTheOldPresOrder, ULONG nTheNewPresOrder)
{ nOldPresOrder = nTheOldPresOrder; nNewPresOrder = nTheNewPresOrder; }
virtual ~SdAnimationPrmsUndoAction();
virtual void Undo();
virtual void Redo();
virtual void Repeat();
};
#endif // _SD_UNOAPRMS_HXX
<|endoftext|> |
<commit_before>#include "clientmodel.h"
#include "main.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QTimer>
ClientModel::ClientModel(QObject *parent) :
QObject(parent), optionsModel(0), addressTableModel(0)
{
/* Until we build signal notifications into the bitcoin core,
simply update everything using a timer.
*/
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(MODEL_UPDATE_DELAY);
optionsModel = new OptionsModel(this);
addressTableModel = new AddressTableModel(this);
}
qint64 ClientModel::getBalance()
{
return GetBalance();
}
QString ClientModel::getAddress()
{
std::vector<unsigned char> vchPubKey;
if (CWalletDB("r").ReadDefaultKey(vchPubKey))
{
return QString::fromStdString(PubKeyToAddress(vchPubKey));
} else {
return QString();
}
}
int ClientModel::getNumConnections()
{
return vNodes.size();
}
int ClientModel::getNumBlocks()
{
return nBestHeight;
}
int ClientModel::getNumTransactions()
{
int numTransactions = 0;
CRITICAL_BLOCK(cs_mapWallet)
{
numTransactions = mapWallet.size();
}
return numTransactions;
}
void ClientModel::update()
{
emit balanceChanged(getBalance());
emit addressChanged(getAddress());
emit numConnectionsChanged(getNumConnections());
emit numBlocksChanged(getNumBlocks());
emit numTransactionsChanged(getNumTransactions());
}
void ClientModel::setAddress(const QString &defaultAddress)
{
uint160 hash160;
std::string strAddress = defaultAddress.toStdString();
if (!AddressToHash160(strAddress, hash160))
return;
if (!mapPubKeys.count(hash160))
return;
CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);
}
ClientModel::StatusCode ClientModel::sendCoins(const QString &payTo, qint64 payAmount)
{
uint160 hash160 = 0;
bool valid = false;
if(!AddressToHash160(payTo.toUtf8().constData(), hash160))
{
return InvalidAddress;
}
if(payAmount <= 0)
{
return InvalidAmount;
}
if(payAmount > getBalance())
{
return AmountExceedsBalance;
}
if((payAmount + nTransactionFee) > getBalance())
{
return AmountWithFeeExceedsBalance;
}
CRITICAL_BLOCK(cs_main)
{
// Send to bitcoin address
CWalletTx wtx;
CScript scriptPubKey;
scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;
std::string strError = SendMoney(scriptPubKey, payAmount, wtx, true);
if (strError == "")
return OK;
else if (strError == "ABORTED")
return Aborted;
else
{
emit error(tr("Sending..."), QString::fromStdString(strError));
return MiscError;
}
}
// Add addresses that we've sent to to the address book
std::string strAddress = payTo.toStdString();
CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(strAddress))
SetAddressBookName(strAddress, "");
return OK;
}
OptionsModel *ClientModel::getOptionsModel()
{
return optionsModel;
}
AddressTableModel *ClientModel::getAddressTableModel()
{
return addressTableModel;
}
<commit_msg>comment update<commit_after>#include "clientmodel.h"
#include "main.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QTimer>
ClientModel::ClientModel(QObject *parent) :
QObject(parent), optionsModel(0), addressTableModel(0)
{
/* Until signal notifications is built into the bitcoin core,
simply update everything after polling using a timer.
*/
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(MODEL_UPDATE_DELAY);
optionsModel = new OptionsModel(this);
addressTableModel = new AddressTableModel(this);
}
qint64 ClientModel::getBalance()
{
return GetBalance();
}
QString ClientModel::getAddress()
{
std::vector<unsigned char> vchPubKey;
if (CWalletDB("r").ReadDefaultKey(vchPubKey))
{
return QString::fromStdString(PubKeyToAddress(vchPubKey));
} else {
return QString();
}
}
int ClientModel::getNumConnections()
{
return vNodes.size();
}
int ClientModel::getNumBlocks()
{
return nBestHeight;
}
int ClientModel::getNumTransactions()
{
int numTransactions = 0;
CRITICAL_BLOCK(cs_mapWallet)
{
numTransactions = mapWallet.size();
}
return numTransactions;
}
void ClientModel::update()
{
/* Plainly emit all signals for now. To be precise this should check
wether the values actually changed first.
*/
emit balanceChanged(getBalance());
emit addressChanged(getAddress());
emit numConnectionsChanged(getNumConnections());
emit numBlocksChanged(getNumBlocks());
emit numTransactionsChanged(getNumTransactions());
}
void ClientModel::setAddress(const QString &defaultAddress)
{
uint160 hash160;
std::string strAddress = defaultAddress.toStdString();
if (!AddressToHash160(strAddress, hash160))
return;
if (!mapPubKeys.count(hash160))
return;
CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);
}
ClientModel::StatusCode ClientModel::sendCoins(const QString &payTo, qint64 payAmount)
{
uint160 hash160 = 0;
bool valid = false;
if(!AddressToHash160(payTo.toUtf8().constData(), hash160))
{
return InvalidAddress;
}
if(payAmount <= 0)
{
return InvalidAmount;
}
if(payAmount > getBalance())
{
return AmountExceedsBalance;
}
if((payAmount + nTransactionFee) > getBalance())
{
return AmountWithFeeExceedsBalance;
}
CRITICAL_BLOCK(cs_main)
{
// Send to bitcoin address
CWalletTx wtx;
CScript scriptPubKey;
scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;
std::string strError = SendMoney(scriptPubKey, payAmount, wtx, true);
if (strError == "")
return OK;
else if (strError == "ABORTED")
return Aborted;
else
{
emit error(tr("Sending..."), QString::fromStdString(strError));
return MiscError;
}
}
// Add addresses that we've sent to to the address book
std::string strAddress = payTo.toStdString();
CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(strAddress))
SetAddressBookName(strAddress, "");
return OK;
}
OptionsModel *ClientModel::getOptionsModel()
{
return optionsModel;
}
AddressTableModel *ClientModel::getAddressTableModel()
{
return addressTableModel;
}
<|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/dom_ui/dom_ui_theme_source.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/theme_provider.h"
#include "base/gfx/png_encoder.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/theme_resources_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(OS_WIN)
#include "chrome/browser/views/bookmark_bar_view.h"
#elif defined(OS_LINUX)
#include "chrome/browser/gtk/bookmark_bar_gtk.h"
#endif
// Path for the New Tab CSS. When we get more than a few of these, we should
// use a resource map rather than hard-coded strings.
static const char* kNewTabCSSPath = "css/newtab.css";
static const char* kNewIncognitoTabCSSPath = "css/newincognitotab.css";
static string16 SkColorToRGBAString(SkColor color) {
return WideToUTF16(l10n_util::GetStringF(IDS_RGBA_CSS_FORMAT_STRING,
IntToWString(SkColorGetR(color)),
IntToWString(SkColorGetG(color)),
IntToWString(SkColorGetB(color)),
DoubleToWString(SkColorGetA(color) / 255.0)));
}
static std::string StripQueryParams(const std::string& path) {
GURL path_url = GURL(std::string(chrome::kChromeUIScheme) + "://" +
std::string(chrome::kChromeUIThemePath) + "/" + path);
return path_url.path().substr(1); // path() always includes a leading '/'.
}
////////////////////////////////////////////////////////////////////////////////
// DOMUIThemeSource, public:
DOMUIThemeSource::DOMUIThemeSource(Profile* profile)
: DataSource(chrome::kChromeUIThemePath, MessageLoop::current()),
profile_(profile) {
InitNewTabCSS();
InitNewIncognitoTabCSS();
}
void DOMUIThemeSource::StartDataRequest(const std::string& path,
int request_id) {
// Our path may include cachebuster arguments, so trim them off.
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath) {
SendNewTabCSS(request_id, new_tab_css_);
return;
} else if (uncached_path == kNewIncognitoTabCSSPath) {
SendNewTabCSS(request_id, new_incognito_tab_css_);
return;
} else {
int resource_id = ThemeResourcesUtil::GetId(uncached_path);
if (resource_id != -1) {
SendThemeBitmap(request_id, resource_id);
return;
}
}
// We don't have any data to send back.
SendResponse(request_id, NULL);
}
std::string DOMUIThemeSource::GetMimeType(const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
return "text/css";
}
return "image/png";
}
void DOMUIThemeSource::SendResponse(int request_id, RefCountedBytes* data) {
ChromeURLDataManager::DataSource::SendResponse(request_id, data);
}
MessageLoop* DOMUIThemeSource::MessageLoopForRequestPath(
const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
// All of the operations that need to be on the UI thread for these
// requests are performed in InitNewTabCSS and InitNewIncognitoTabCSS,
// called by the constructor. It is safe to call StartDataRequest for
// these resources from any thread, so return NULL.
return NULL;
}
// Superclass
return DataSource::MessageLoopForRequestPath(path);
}
////////////////////////////////////////////////////////////////////////////////
// DOMUIThemeSource, private:
void DOMUIThemeSource::InitNewTabCSS() {
ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
// Get our theme colors
SkColor color_background =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_BACKGROUND);
SkColor color_text = tp->GetColor(BrowserThemeProvider::COLOR_NTP_TEXT);
SkColor color_link = tp->GetColor(BrowserThemeProvider::COLOR_NTP_LINK);
SkColor color_link_underline =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_LINK_UNDERLINE);
SkColor color_section =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION);
SkColor color_section_text =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_TEXT);
SkColor color_section_link =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_LINK);
SkColor color_section_link_underline =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_LINK_UNDERLINE);
SkColor color_header =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_HEADER);
// Generate a lighter color for the header gradients.
color_utils::HSL header_lighter;
color_utils::SkColorToHSL(color_header, &header_lighter);
header_lighter.l += (1 - header_lighter.l) * 0.33;
SkColor color_header_gradient_light =
color_utils::HSLToSkColor(header_lighter, SkColorGetA(color_header));
// Generate section border color from the header color. See
// BookmarkBarView::Paint for how we do this for the bookmark bar
// borders.
SkColor color_section_border =
SkColorSetARGB(80,
SkColorGetR(color_header),
SkColorGetG(color_header),
SkColorGetB(color_header));
// Generate the replacements.
std::vector<string16> subst;
// A second list of replacements, each of which must be in $$x format,
// where x is a digit from 1-9.
std::vector<string16> subst2;
// Cache-buster for background.
subst.push_back(WideToUTF16(
profile_->GetPrefs()->GetString(prefs::kCurrentThemeID))); // $1
// Colors.
subst.push_back(SkColorToRGBAString(color_background)); // $2
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(false))); // $3
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(true))); // $4
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundTilingCSS())); // $5
subst.push_back(SkColorToRGBAString(color_header)); // $6
subst.push_back(SkColorToRGBAString(color_header_gradient_light)); // $7
subst.push_back(SkColorToRGBAString(color_text)); // $8
subst.push_back(SkColorToRGBAString(color_link)); // $9
subst2.push_back(SkColorToRGBAString(color_section)); // $$1
subst2.push_back(SkColorToRGBAString(color_section_border)); // $$2
subst2.push_back(SkColorToRGBAString(color_section_text)); // $$3
subst2.push_back(SkColorToRGBAString(color_section_link)); // $$4
subst2.push_back(
UTF8ToUTF16(tp->HasCustomImage(IDR_THEME_NTP_ATTRIBUTION) ?
"block" : "none")); // $$5
subst2.push_back(SkColorToRGBAString(color_link_underline)); // $$6
subst2.push_back(SkColorToRGBAString(color_section_link_underline)); // $$7
if (profile_->GetPrefs()->GetInteger(prefs::kNTPThemePromoRemaining) > 0)
subst2.push_back(UTF8ToUTF16("block")); // $$8
else
subst2.push_back(UTF8ToUTF16("none")); // $$8
// Get our template.
static const base::StringPiece new_tab_theme_css(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_NEW_TAB_THEME_CSS));
// Create the string from our template and the replacements.
string16 format_string = ASCIIToUTF16(new_tab_theme_css.as_string());
const std::string css_string = UTF16ToASCII(ReplaceStringPlaceholders(
format_string, subst, NULL));
new_tab_css_ = UTF16ToASCII(ReplaceStringPlaceholders(
ASCIIToUTF16(css_string), subst2, NULL));
}
void DOMUIThemeSource::InitNewIncognitoTabCSS() {
ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
// Get our theme colors
SkColor color_background =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_BACKGROUND);
// Generate the replacements.
std::vector<string16> subst;
// Cache-buster for background.
subst.push_back(WideToUTF16(
profile_->GetPrefs()->GetString(prefs::kCurrentThemeID))); // $1
// Colors.
subst.push_back(SkColorToRGBAString(color_background)); // $2
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(false))); // $3
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(true))); // $4
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundTilingCSS())); // $5
// Get our template.
static const base::StringPiece new_tab_theme_css(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_NEW_INCOGNITO_TAB_THEME_CSS));
// Create the string from our template and the replacements.
string16 format_string = ASCIIToUTF16(new_tab_theme_css.as_string());
new_incognito_tab_css_ = UTF16ToASCII(ReplaceStringPlaceholders(
format_string, subst, NULL));
}
void DOMUIThemeSource::SendNewTabCSS(int request_id,
const std::string& css_string) {
// Convert to a format appropriate for sending.
scoped_refptr<RefCountedBytes> css_bytes(new RefCountedBytes);
css_bytes->data.resize(css_string.size());
std::copy(css_string.begin(), css_string.end(), css_bytes->data.begin());
// Send.
SendResponse(request_id, css_bytes);
}
void DOMUIThemeSource::SendThemeBitmap(int request_id, int resource_id) {
ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
std::vector<unsigned char> png_bytes;
if (tp->GetRawData(resource_id, &png_bytes)) {
scoped_refptr<RefCountedBytes> image_data =
new RefCountedBytes(png_bytes);
SendResponse(request_id, image_data);
} else {
SendResponse(request_id, NULL);
}
}
std::string DOMUIThemeSource::GetNewTabBackgroundCSS(bool bar_attached) {
int alignment;
profile_->GetThemeProvider()->GetDisplayProperty(
BrowserThemeProvider::NTP_BACKGROUND_ALIGNMENT, &alignment);
// TODO(glen): This is a quick workaround to hide the notused.png image when
// no image is provided - we don't have time right now to figure out why
// this is painting as white.
// http://crbug.com/17593
if (!profile_->GetThemeProvider()->HasCustomImage(IDR_THEME_NTP_BACKGROUND)) {
return "-64px";
}
if (bar_attached)
return BrowserThemeProvider::AlignmentToString(alignment);
// The bar is detached, so we must offset the background by the bar size
// if it's a top-aligned bar.
#if defined(OS_WIN)
int offset = BookmarkBarView::kNewtabBarHeight;
#elif defined(OS_LINUX)
int offset = BookmarkBarGtk::kBookmarkBarNTPHeight;
#else
int offset = 0;
#endif
if (alignment & BrowserThemeProvider::ALIGN_TOP) {
if (alignment & BrowserThemeProvider::ALIGN_LEFT)
return "0% " + IntToString(-offset) + "px";
else if (alignment & BrowserThemeProvider::ALIGN_RIGHT)
return "100% " + IntToString(-offset) + "px";
return "center " + IntToString(-offset) + "px";
}
return BrowserThemeProvider::AlignmentToString(alignment);
}
std::string DOMUIThemeSource::GetNewTabBackgroundTilingCSS() {
int repeat_mode;
profile_->GetThemeProvider()->GetDisplayProperty(
BrowserThemeProvider::NTP_BACKGROUND_TILING, &repeat_mode);
return BrowserThemeProvider::TilingToString(repeat_mode);
}
<commit_msg>Fix linux views build.<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/dom_ui/dom_ui_theme_source.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/theme_provider.h"
#include "base/gfx/png_encoder.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/theme_resources_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
#include "chrome/browser/views/bookmark_bar_view.h"
#elif defined(OS_LINUX)
#include "chrome/browser/gtk/bookmark_bar_gtk.h"
#endif
// Path for the New Tab CSS. When we get more than a few of these, we should
// use a resource map rather than hard-coded strings.
static const char* kNewTabCSSPath = "css/newtab.css";
static const char* kNewIncognitoTabCSSPath = "css/newincognitotab.css";
static string16 SkColorToRGBAString(SkColor color) {
return WideToUTF16(l10n_util::GetStringF(IDS_RGBA_CSS_FORMAT_STRING,
IntToWString(SkColorGetR(color)),
IntToWString(SkColorGetG(color)),
IntToWString(SkColorGetB(color)),
DoubleToWString(SkColorGetA(color) / 255.0)));
}
static std::string StripQueryParams(const std::string& path) {
GURL path_url = GURL(std::string(chrome::kChromeUIScheme) + "://" +
std::string(chrome::kChromeUIThemePath) + "/" + path);
return path_url.path().substr(1); // path() always includes a leading '/'.
}
////////////////////////////////////////////////////////////////////////////////
// DOMUIThemeSource, public:
DOMUIThemeSource::DOMUIThemeSource(Profile* profile)
: DataSource(chrome::kChromeUIThemePath, MessageLoop::current()),
profile_(profile) {
InitNewTabCSS();
InitNewIncognitoTabCSS();
}
void DOMUIThemeSource::StartDataRequest(const std::string& path,
int request_id) {
// Our path may include cachebuster arguments, so trim them off.
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath) {
SendNewTabCSS(request_id, new_tab_css_);
return;
} else if (uncached_path == kNewIncognitoTabCSSPath) {
SendNewTabCSS(request_id, new_incognito_tab_css_);
return;
} else {
int resource_id = ThemeResourcesUtil::GetId(uncached_path);
if (resource_id != -1) {
SendThemeBitmap(request_id, resource_id);
return;
}
}
// We don't have any data to send back.
SendResponse(request_id, NULL);
}
std::string DOMUIThemeSource::GetMimeType(const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
return "text/css";
}
return "image/png";
}
void DOMUIThemeSource::SendResponse(int request_id, RefCountedBytes* data) {
ChromeURLDataManager::DataSource::SendResponse(request_id, data);
}
MessageLoop* DOMUIThemeSource::MessageLoopForRequestPath(
const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
// All of the operations that need to be on the UI thread for these
// requests are performed in InitNewTabCSS and InitNewIncognitoTabCSS,
// called by the constructor. It is safe to call StartDataRequest for
// these resources from any thread, so return NULL.
return NULL;
}
// Superclass
return DataSource::MessageLoopForRequestPath(path);
}
////////////////////////////////////////////////////////////////////////////////
// DOMUIThemeSource, private:
void DOMUIThemeSource::InitNewTabCSS() {
ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
// Get our theme colors
SkColor color_background =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_BACKGROUND);
SkColor color_text = tp->GetColor(BrowserThemeProvider::COLOR_NTP_TEXT);
SkColor color_link = tp->GetColor(BrowserThemeProvider::COLOR_NTP_LINK);
SkColor color_link_underline =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_LINK_UNDERLINE);
SkColor color_section =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION);
SkColor color_section_text =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_TEXT);
SkColor color_section_link =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_LINK);
SkColor color_section_link_underline =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_LINK_UNDERLINE);
SkColor color_header =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_HEADER);
// Generate a lighter color for the header gradients.
color_utils::HSL header_lighter;
color_utils::SkColorToHSL(color_header, &header_lighter);
header_lighter.l += (1 - header_lighter.l) * 0.33;
SkColor color_header_gradient_light =
color_utils::HSLToSkColor(header_lighter, SkColorGetA(color_header));
// Generate section border color from the header color. See
// BookmarkBarView::Paint for how we do this for the bookmark bar
// borders.
SkColor color_section_border =
SkColorSetARGB(80,
SkColorGetR(color_header),
SkColorGetG(color_header),
SkColorGetB(color_header));
// Generate the replacements.
std::vector<string16> subst;
// A second list of replacements, each of which must be in $$x format,
// where x is a digit from 1-9.
std::vector<string16> subst2;
// Cache-buster for background.
subst.push_back(WideToUTF16(
profile_->GetPrefs()->GetString(prefs::kCurrentThemeID))); // $1
// Colors.
subst.push_back(SkColorToRGBAString(color_background)); // $2
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(false))); // $3
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(true))); // $4
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundTilingCSS())); // $5
subst.push_back(SkColorToRGBAString(color_header)); // $6
subst.push_back(SkColorToRGBAString(color_header_gradient_light)); // $7
subst.push_back(SkColorToRGBAString(color_text)); // $8
subst.push_back(SkColorToRGBAString(color_link)); // $9
subst2.push_back(SkColorToRGBAString(color_section)); // $$1
subst2.push_back(SkColorToRGBAString(color_section_border)); // $$2
subst2.push_back(SkColorToRGBAString(color_section_text)); // $$3
subst2.push_back(SkColorToRGBAString(color_section_link)); // $$4
subst2.push_back(
UTF8ToUTF16(tp->HasCustomImage(IDR_THEME_NTP_ATTRIBUTION) ?
"block" : "none")); // $$5
subst2.push_back(SkColorToRGBAString(color_link_underline)); // $$6
subst2.push_back(SkColorToRGBAString(color_section_link_underline)); // $$7
if (profile_->GetPrefs()->GetInteger(prefs::kNTPThemePromoRemaining) > 0)
subst2.push_back(UTF8ToUTF16("block")); // $$8
else
subst2.push_back(UTF8ToUTF16("none")); // $$8
// Get our template.
static const base::StringPiece new_tab_theme_css(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_NEW_TAB_THEME_CSS));
// Create the string from our template and the replacements.
string16 format_string = ASCIIToUTF16(new_tab_theme_css.as_string());
const std::string css_string = UTF16ToASCII(ReplaceStringPlaceholders(
format_string, subst, NULL));
new_tab_css_ = UTF16ToASCII(ReplaceStringPlaceholders(
ASCIIToUTF16(css_string), subst2, NULL));
}
void DOMUIThemeSource::InitNewIncognitoTabCSS() {
ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
// Get our theme colors
SkColor color_background =
tp->GetColor(BrowserThemeProvider::COLOR_NTP_BACKGROUND);
// Generate the replacements.
std::vector<string16> subst;
// Cache-buster for background.
subst.push_back(WideToUTF16(
profile_->GetPrefs()->GetString(prefs::kCurrentThemeID))); // $1
// Colors.
subst.push_back(SkColorToRGBAString(color_background)); // $2
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(false))); // $3
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundCSS(true))); // $4
subst.push_back(UTF8ToUTF16(GetNewTabBackgroundTilingCSS())); // $5
// Get our template.
static const base::StringPiece new_tab_theme_css(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_NEW_INCOGNITO_TAB_THEME_CSS));
// Create the string from our template and the replacements.
string16 format_string = ASCIIToUTF16(new_tab_theme_css.as_string());
new_incognito_tab_css_ = UTF16ToASCII(ReplaceStringPlaceholders(
format_string, subst, NULL));
}
void DOMUIThemeSource::SendNewTabCSS(int request_id,
const std::string& css_string) {
// Convert to a format appropriate for sending.
scoped_refptr<RefCountedBytes> css_bytes(new RefCountedBytes);
css_bytes->data.resize(css_string.size());
std::copy(css_string.begin(), css_string.end(), css_bytes->data.begin());
// Send.
SendResponse(request_id, css_bytes);
}
void DOMUIThemeSource::SendThemeBitmap(int request_id, int resource_id) {
ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
std::vector<unsigned char> png_bytes;
if (tp->GetRawData(resource_id, &png_bytes)) {
scoped_refptr<RefCountedBytes> image_data =
new RefCountedBytes(png_bytes);
SendResponse(request_id, image_data);
} else {
SendResponse(request_id, NULL);
}
}
std::string DOMUIThemeSource::GetNewTabBackgroundCSS(bool bar_attached) {
int alignment;
profile_->GetThemeProvider()->GetDisplayProperty(
BrowserThemeProvider::NTP_BACKGROUND_ALIGNMENT, &alignment);
// TODO(glen): This is a quick workaround to hide the notused.png image when
// no image is provided - we don't have time right now to figure out why
// this is painting as white.
// http://crbug.com/17593
if (!profile_->GetThemeProvider()->HasCustomImage(IDR_THEME_NTP_BACKGROUND)) {
return "-64px";
}
if (bar_attached)
return BrowserThemeProvider::AlignmentToString(alignment);
// The bar is detached, so we must offset the background by the bar size
// if it's a top-aligned bar.
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
int offset = BookmarkBarView::kNewtabBarHeight;
#elif defined(OS_LINUX)
int offset = BookmarkBarGtk::kBookmarkBarNTPHeight;
#else
int offset = 0;
#endif
if (alignment & BrowserThemeProvider::ALIGN_TOP) {
if (alignment & BrowserThemeProvider::ALIGN_LEFT)
return "0% " + IntToString(-offset) + "px";
else if (alignment & BrowserThemeProvider::ALIGN_RIGHT)
return "100% " + IntToString(-offset) + "px";
return "center " + IntToString(-offset) + "px";
}
return BrowserThemeProvider::AlignmentToString(alignment);
}
std::string DOMUIThemeSource::GetNewTabBackgroundTilingCSS() {
int repeat_mode;
profile_->GetThemeProvider()->GetDisplayProperty(
BrowserThemeProvider::NTP_BACKGROUND_TILING, &repeat_mode);
return BrowserThemeProvider::TilingToString(repeat_mode);
}
<|endoftext|> |
<commit_before>void Fragment(Int_t nev=0, Int_t debug=0)
{
gROOT->Reset();
gStyle->SetPalette(1);
gStyle->SetCanvasColor(33);
gStyle->SetFrameFillColor(38);
Float_t b;
Int_t nspectp, nspectn, nspectpfree, nspectnfree;
Int_t zz[100], nn[100], nalpha, ztot, ntot;
void spectator(Float_t, Int_t*, Int_t*);
TH2F *hsp = new TH2F("hsp","Spectator protons vs b",100,0.,20.,100,0.,150.);
hsp -> SetXTitle("b (fm)");
hsp -> SetYTitle("Num. of spectator protons");
TH2F *hsn = new TH2F("hsn","Spectator neutrons vs b",100,0.,20.,100,0.,150.);
hsn -> SetXTitle("b (fm)");
hsn -> SetYTitle("Num. of spectator neutrons");
TH2F *hFragp = new TH2F("hFragp","Free spectator protons vs b",100,0.,20.,100,0.,150.);
hFragp -> SetXTitle("b (fm)");
hFragp -> SetYTitle("Num. of free spectator protons");
TH2F *hFragn = new TH2F("hFragn","Free spectator neutrons vs b",100,0.,20.,100,0.,150.);
hFragn -> SetXTitle("b (fm)");
hFragn -> SetYTitle("Num. of free spectator neutrons");
TF1 *funb = new TF1("funb","x",0,15);
for(Int_t ievent=0; ievent<nev; ievent++){
if(ievent%1000==0){printf("Processing event %d\n",ievent);}
b= Float_t(funb->GetRandom());
spectator(b, &nspectp, &nspectn);
hsp -> Fill(b,nspectp);
hsn -> Fill(b,nspectn);
AliZDCFragment *gallio = new AliZDCFragment(b);
for(Int_t j=0; j<=99; j++){
zz[j] =0;
nn[j] =0;
}
//
// Generation of fragments
gallio->GenerateIMF(zz, nalpha);
Int_t NFrag = gallio->GetFragmentNum();
//
// Attach neutrons
ztot=0;
ntot=0;
gallio->AttachNeutrons(zz, nn, ztot, ntot);
nspectpfree = nspectp-ztot-2*nalpha;
nspectnfree = nspectn-ntot-2*nalpha;
hFragp -> Fill(b,nspectpfree);
hFragn -> Fill(b,nspectnfree);
//
// Print
if(debug == 1){
printf("\n b = %f\n",b);
printf("\n #spect p = %d, #spect n = %d\n",nspectp,nspectn);
printf("\n #spect p free = %d, #spect n free = %d\n",nspectpfree,nspectnfree);
printf("\n #fragments = %f\n",NFrag);
for(Int_t i=0; i<NFrag; i++){
printf("\n ZZ[%d] = %d, NN[%d] = %d\n",i,zz[i],i,nn[i]);
}
printf("\n NAlpha = %d, Ztot = %d, Ntot = %d\n\n",nalpha,ztot,ntot);
}
delete gallio;
} //Event loop
TCanvas *c1 = new TCanvas("c1","Fragmentation",0,10,580,700);
c1->cd();
c1->SetFillColor(29);
c1->Divide(2,2);
c1->cd(1);
hsp -> Draw("box");
c1->cd(2);
hsn -> Draw("box");
c1->cd(3);
hFragp -> Draw("box");
c1->cd(4);
hFragn -> Draw("box");
}
void spectator(Float_t b, Int_t* NSpectp, Int_t* NSpectn)
{
Float_t SppvsB[6] = {3.633,-1.518,1.360,-.4899e-1,-.2398e-2,.1066e-3};
Float_t SpnvsB[6] = {5.639,-1.685,1.803,-.3129e-1,-.6618e-2,.2352e-3};
Float_t Sigmap[4] = {.5668,-.2200e-1,.3657e-3,-.2201e-5};
Float_t Sigman[4] = {.4185,-.9798e-2,.1052e-3,-.4238e-6};
Float_t rnsp = SppvsB[0]+SppvsB[1]*b+SppvsB[2]*(b*b)+SppvsB[3]*(b*b*b)+
SppvsB[4]*(b*b*b*b)+SppvsB[5]*(b*b*b*b*b);
Float_t rnsn = SpnvsB[0]+SpnvsB[1]*b+SpnvsB[2]*(b*b)+SpnvsB[3]*(b*b*b)+
SpnvsB[4]*(b*b*b*b)+SpnvsB[5]*(b*b*b*b*b);
Float_t snsp = Sigmap[0]+Sigmap[1]*rnsp+Sigmap[2]*(rnsp*rnsp)+Sigmap[3]*
(rnsp*rnsp*rnsp);
Float_t snsn = Sigman[0]+Sigman[1]*rnsn+Sigman[2]*(rnsn*rnsn)+Sigman[3]*
(rnsn*rnsn*rnsn);
snsp = snsp*rnsp;
snsn = snsn*rnsn;
Float_t xgaup = gRandom->Gaus(0.0,1.0);
snsp = snsp*xgaup;
Float_t xgaun = gRandom->Gaus(0.0,1.0);
snsn = snsn*xgaun;
rnsp=rnsp+snsp;
rnsn=rnsn+snsn;
*NSpectp = Int_t(rnsp);
*NSpectn = Int_t(rnsn);
}
<commit_msg>Updated macro<commit_after>void Fragment(Int_t nev=0, Int_t debug=0)
{
gROOT->Reset();
Float_t b;
Int_t nspectp, nspectn, nspectpfree, nspectnfree;
Int_t zz[100], nn[100], nalpha, ztot, ntot;
void spectator(Float_t, Int_t*, Int_t*);
TH2F *hsp = new TH2F("hsp","Spectator protons vs b",100,0.,20.,100,0.,150.);
hsp -> SetXTitle("b (fm)");
hsp -> SetYTitle("Num. of spectator protons");
TH2F *hsn = new TH2F("hsn","Spectator neutrons vs b",100,0.,20.,100,0.,150.);
hsn -> SetXTitle("b (fm)");
hsn -> SetYTitle("Num. of spectator neutrons");
TH2F *hFragp = new TH2F("hFragp","Free spectator protons vs b",100,0.,20.,100,0.,150.);
hFragp -> SetXTitle("b (fm)");
hFragp -> SetYTitle("Num. of free spectator protons");
TH2F *hFragn = new TH2F("hFragn","Free spectator neutrons vs b",100,0.,20.,100,0.,150.);
hFragn -> SetXTitle("b (fm)");
hFragn -> SetYTitle("Num. of free spectator neutrons");
TF1 *funb = new TF1("funb","x",0,15);
for(Int_t ievent=0; ievent<nev; ievent++){
if(ievent%1000==0){printf("Processing event %d\n",ievent);}
b= Float_t(funb->GetRandom());
spectator(b, &nspectp, &nspectn);
hsp -> Fill(b,nspectp);
hsn -> Fill(b,nspectn);
AliZDCFragment *gallio = new AliZDCFragment(b);
for(Int_t j=0; j<=99; j++){
zz[j] =0;
nn[j] =0;
}
//
// Generation of fragments
gallio->GenerateIMF();
Int_t NFrag = gallio->GetFragmentNum();
//
// Attach neutrons
ztot=0;
ntot=0;
gallio->AttachNeutrons();
nspectpfree = nspectp-ztot-2*nalpha;
nspectnfree = nspectn-ntot-2*nalpha;
hFragp -> Fill(b,nspectpfree);
hFragn -> Fill(b,nspectnfree);
//
// Print
if(debug == 1){
printf("\n b = %f\n",b);
printf("\n #spect p = %d, #spect n = %d\n",nspectp,nspectn);
printf("\n #spect p free = %d, #spect n free = %d\n",nspectpfree,nspectnfree);
printf("\n #fragments = %f\n",NFrag);
for(Int_t i=0; i<NFrag; i++){
printf("\n ZZ[%d] = %d, NN[%d] = %d\n",i,zz[i],i,nn[i]);
}
printf("\n NAlpha = %d, Ztot = %d, Ntot = %d\n\n",nalpha,ztot,ntot);
}
delete gallio;
} //Event loop
TCanvas *c1 = new TCanvas("c1","Fragmentation",0,10,580,700);
c1->cd();
c1->SetFillColor(29);
c1->Divide(2,2);
c1->cd(1);
hsp -> Draw("box");
c1->cd(2);
hsn -> Draw("box");
c1->cd(3);
hFragp -> Draw("box");
c1->cd(4);
hFragn -> Draw("box");
}
void spectator(Float_t b, Int_t* NSpectp, Int_t* NSpectn)
{
Float_t SppvsB[6] = {3.633,-1.518,1.360,-.4899e-1,-.2398e-2,.1066e-3};
Float_t SpnvsB[6] = {5.639,-1.685,1.803,-.3129e-1,-.6618e-2,.2352e-3};
Float_t Sigmap[4] = {.5668,-.2200e-1,.3657e-3,-.2201e-5};
Float_t Sigman[4] = {.4185,-.9798e-2,.1052e-3,-.4238e-6};
Float_t rnsp = SppvsB[0]+SppvsB[1]*b+SppvsB[2]*(b*b)+SppvsB[3]*(b*b*b)+
SppvsB[4]*(b*b*b*b)+SppvsB[5]*(b*b*b*b*b);
Float_t rnsn = SpnvsB[0]+SpnvsB[1]*b+SpnvsB[2]*(b*b)+SpnvsB[3]*(b*b*b)+
SpnvsB[4]*(b*b*b*b)+SpnvsB[5]*(b*b*b*b*b);
Float_t snsp = Sigmap[0]+Sigmap[1]*rnsp+Sigmap[2]*(rnsp*rnsp)+Sigmap[3]*
(rnsp*rnsp*rnsp);
Float_t snsn = Sigman[0]+Sigman[1]*rnsn+Sigman[2]*(rnsn*rnsn)+Sigman[3]*
(rnsn*rnsn*rnsn);
snsp = snsp*rnsp;
snsn = snsn*rnsn;
Float_t xgaup = gRandom->Gaus(0.0,1.0);
snsp = snsp*xgaup;
Float_t xgaun = gRandom->Gaus(0.0,1.0);
snsn = snsn*xgaun;
rnsp=rnsp+snsp;
rnsn=rnsn+snsn;
*NSpectp = Int_t(rnsp);
*NSpectn = Int_t(rnsn);
}
<|endoftext|> |
<commit_before>//
// PyQtGuiObject.cpp
// MusicPlayer
//
// Created by Albert Zeyer on 18.01.14.
// Copyright (c) 2014 Albert Zeyer. All rights reserved.
//
#include "PyQtGuiObject.hpp"
#include "PythonHelpers.h"
#include "PyThreading.hpp"
#include "QtBaseWidget.hpp"
#include "QtApp.hpp"
static Vec imp_get_pos(GuiObject* obj) {
Vec ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
QPoint pos = widget->pos();
ret.x = pos.x();
ret.y = pos.y();
}
});
return ret;
}
static Vec imp_get_size(GuiObject* obj) {
Vec ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
QSize size = widget->frameSize();
ret.x = size.width();
ret.y = size.height();
}
});
return ret;
}
static Vec imp_get_innnerSize(GuiObject* obj) {
Vec ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
QSize size = widget->size();
ret.x = size.width();
ret.y = size.height();
}
});
return ret;
}
static Autoresize imp_get_autoresize(GuiObject* obj) {
Autoresize ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
// TODO ...
// Not sure. I think Qt doesn't do autoresizing.
}
});
return ret;
}
static void imp_set_pos(GuiObject* obj, const Vec& v) {
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget)
widget->move(v.x, v.y);
});
}
static void imp_set_size(GuiObject* obj, const Vec& v) {
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget)
widget->resize(v.x, v.y);
});
}
static void imp_set_autoresize(GuiObject* obj, const Autoresize& r) {
// TODO ...
}
static void imp_addChild(GuiObject* obj, GuiObject* child) {
{
PyScopedGIL gil;
if(!PyType_IsSubtype(Py_TYPE(child), &QtGuiObject_Type)) {
PyErr_Format(PyExc_ValueError, "QtGuiObject.addChild: we expect a QtGuiObject");
return;
}
}
execInMainThread_sync([&]() {
QtBaseWidget* childWidget = ((PyQtGuiObject*) child)->widget;
((PyQtGuiObject*) obj)->addChild(childWidget);
});
}
static void imp_meth_updateContent(GuiObject* obj) {
((PyQtGuiObject*) obj)->updateContent();
}
// Called *with* the Python GIL.
static void imp_meth_childIter(GuiObject* obj, boost::function<void(GuiObject* child, bool& stop)> callback) {
// We can only access the widget from the main thread, thus this becomes a bit
// more complicated.
PyScopedGIUnlock unlock;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
PyScopedGIL gil;
// Warning: The callback might be called from another (the main) thread
// here. Not sure if that is a problem. I guess (hope) not.
widget->childIter(callback);
});
}
QtBaseWidget* PyQtGuiObject::getParentWidget() {
assert(QApplication::instance()->thread() == QThread::currentThread());
PyScopedGIL gil;
if(parent && !PyType_IsSubtype(Py_TYPE(parent), &QtGuiObject_Type)) {
return ((PyQtGuiObject*) parent)->widget;
}
return NULL;
}
void PyQtGuiObject::addChild(QtBaseWidget* child) {
// Must not have the Python GIL.
execInMainThread_sync([&]() {
if(!widget) return;
child->setParent(widget);
});
}
void PyQtGuiObject::updateContent() {
// Must not have the Python GIL.
execInMainThread_sync([&]() {
if(!widget) return;
widget->updateContent();
});
}
int PyQtGuiObject::init(PyObject* args, PyObject* kwds) {
PyTypeObject* const selfType = &QtGuiObject_Type;
PyObject* base = (PyObject*) selfType->tp_base;
if(base == (PyObject*) &PyBaseObject_Type) base = NULL;
// We didn't set _gui.GuiObject as the base yet, so set it.
if(base == NULL) {
// We need to grab it dynamically because we don't directly link
// the GuiObject_Type in here.
base = modAttrChain("_gui", "GuiObject");
if(!base || PyErr_Occurred()) {
if(PyErr_Occurred())
PyErr_Print();
Py_FatalError("Cannot get _gui.GuiObject");
}
if(!PyType_Check(base))
Py_FatalError("_gui.GuiObject is not a type.");
// Call the base->tp_init first because GuiObject_Type
// also dynamically inits its base on the first tp_init.
// We must have the selfType->base->tp_base correct in order to
// build up a correct selfType->tp_mro.
((PyTypeObject*) base)->tp_init((PyObject*) this, args, kwds);
// Now reinit selfType.
uninitTypeObject(selfType);
selfType->tp_base = (PyTypeObject*) base; // overtake ref
// Just to be sure that we correctly inited the GC stuff.
// Just inherit from our base right now.
assert(PyType_IS_GC(selfType));
assert(selfType->tp_traverse == NULL);
assert(selfType->tp_clear == NULL);
selfType->tp_traverse = ((PyTypeObject*) base)->tp_traverse;
selfType->tp_clear = ((PyTypeObject*) base)->tp_clear;
if(PyType_Ready(selfType) < 0)
Py_FatalError("Can't initialize CocoaGuiObject type");
}
else
((PyTypeObject*) base)->tp_init((PyObject*) this, args, kwds);
get_pos = imp_get_pos;
get_size = imp_get_size;
get_innerSize = imp_get_innnerSize;
get_autoresize = imp_get_autoresize;
set_pos = imp_set_pos;
set_size = imp_set_size;
set_autoresize = imp_set_autoresize;
meth_addChild = imp_addChild;
meth_updateContent = imp_meth_updateContent;
meth_childIter = imp_meth_childIter;
return 0;
}
PyObject* PyQtGuiObject::getattr(const char* key) {
// fallthrough for now
return Py_TYPE(this)->tp_base->tp_getattr((PyObject*) this, (char*) key);
}
int PyQtGuiObject::setattr(const char* key, PyObject* value) {
// fallthrough for now
return Py_TYPE(this)->tp_base->tp_setattr((PyObject*) this, (char*) key, value);
}
<commit_msg>small fix<commit_after>//
// PyQtGuiObject.cpp
// MusicPlayer
//
// Created by Albert Zeyer on 18.01.14.
// Copyright (c) 2014 Albert Zeyer. All rights reserved.
//
#include "PyQtGuiObject.hpp"
#include "PythonHelpers.h"
#include "PyThreading.hpp"
#include "QtBaseWidget.hpp"
#include "QtApp.hpp"
static Vec imp_get_pos(GuiObject* obj) {
Vec ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
QPoint pos = widget->pos();
ret.x = pos.x();
ret.y = pos.y();
}
});
return ret;
}
static Vec imp_get_size(GuiObject* obj) {
Vec ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
QSize size = widget->frameSize();
ret.x = size.width();
ret.y = size.height();
}
});
return ret;
}
static Vec imp_get_innnerSize(GuiObject* obj) {
Vec ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
QSize size = widget->size();
ret.x = size.width();
ret.y = size.height();
}
});
return ret;
}
static Autoresize imp_get_autoresize(GuiObject* obj) {
Autoresize ret;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget) {
// TODO ...
// Not sure. I think Qt doesn't do autoresizing.
}
});
return ret;
}
static void imp_set_pos(GuiObject* obj, const Vec& v) {
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget)
widget->move(v.x, v.y);
});
}
static void imp_set_size(GuiObject* obj, const Vec& v) {
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
if(widget)
widget->resize(v.x, v.y);
});
}
static void imp_set_autoresize(GuiObject* obj, const Autoresize& r) {
// TODO ...
}
static void imp_addChild(GuiObject* obj, GuiObject* child) {
{
PyScopedGIL gil;
if(!PyType_IsSubtype(Py_TYPE(child), &QtGuiObject_Type)) {
PyErr_Format(PyExc_ValueError, "QtGuiObject.addChild: we expect a QtGuiObject");
return;
}
}
execInMainThread_sync([&]() {
QtBaseWidget* childWidget = ((PyQtGuiObject*) child)->widget;
((PyQtGuiObject*) obj)->addChild(childWidget);
});
}
static void imp_meth_updateContent(GuiObject* obj) {
((PyQtGuiObject*) obj)->updateContent();
}
// Called *with* the Python GIL.
static void imp_meth_childIter(GuiObject* obj, boost::function<void(GuiObject* child, bool& stop)> callback) {
// We can only access the widget from the main thread, thus this becomes a bit
// more complicated.
PyScopedGIUnlock unlock;
execInMainThread_sync([&]() {
QtBaseWidget* widget = ((PyQtGuiObject*) obj)->widget;
PyScopedGIL gil;
// Warning: The callback might be called from another (the main) thread
// here. Not sure if that is a problem. I guess (hope) not.
widget->childIter(callback);
});
}
QtBaseWidget* PyQtGuiObject::getParentWidget() {
assert(QApplication::instance()->thread() == QThread::currentThread());
PyScopedGIL gil;
if(parent && !PyType_IsSubtype(Py_TYPE(parent), &QtGuiObject_Type)) {
return ((PyQtGuiObject*) parent)->widget;
}
return NULL;
}
void PyQtGuiObject::addChild(QtBaseWidget* child) {
// Must not have the Python GIL.
execInMainThread_sync([&]() {
if(!widget) return;
child->setParent(widget);
});
}
void PyQtGuiObject::updateContent() {
// Must not have the Python GIL.
execInMainThread_sync([&]() {
if(!widget) return;
widget->updateContent();
});
}
int PyQtGuiObject::init(PyObject* args, PyObject* kwds) {
PyTypeObject* const selfType = &QtGuiObject_Type;
PyObject* base = (PyObject*) selfType->tp_base;
if(base == (PyObject*) &PyBaseObject_Type) base = NULL;
// We didn't set _gui.GuiObject as the base yet, so set it.
if(base == NULL) {
// We need to grab it dynamically because we don't directly link
// the GuiObject_Type in here.
base = modAttrChain("_gui", "GuiObject");
if(!base || PyErr_Occurred()) {
if(PyErr_Occurred())
PyErr_Print();
Py_FatalError("Cannot get _gui.GuiObject");
}
if(!PyType_Check(base))
Py_FatalError("_gui.GuiObject is not a type.");
// Call the base->tp_init first because GuiObject_Type
// also dynamically inits its base on the first tp_init.
// We must have the selfType->base->tp_base correct in order to
// build up a correct selfType->tp_mro.
((PyTypeObject*) base)->tp_init((PyObject*) this, args, kwds);
// Now reinit selfType.
uninitTypeObject(selfType);
selfType->tp_base = (PyTypeObject*) base; // overtake ref
// Just to be sure that we correctly inited the GC stuff.
// Just inherit from our base right now.
assert(PyType_IS_GC(selfType));
assert(selfType->tp_traverse == NULL);
assert(selfType->tp_clear == NULL);
selfType->tp_traverse = ((PyTypeObject*) base)->tp_traverse;
selfType->tp_clear = ((PyTypeObject*) base)->tp_clear;
if(PyType_Ready(selfType) < 0)
Py_FatalError("Can't initialize QtGuiObject type");
}
else
((PyTypeObject*) base)->tp_init((PyObject*) this, args, kwds);
get_pos = imp_get_pos;
get_size = imp_get_size;
get_innerSize = imp_get_innnerSize;
get_autoresize = imp_get_autoresize;
set_pos = imp_set_pos;
set_size = imp_set_size;
set_autoresize = imp_set_autoresize;
meth_addChild = imp_addChild;
meth_updateContent = imp_meth_updateContent;
meth_childIter = imp_meth_childIter;
return 0;
}
PyObject* PyQtGuiObject::getattr(const char* key) {
// fallthrough for now
return Py_TYPE(this)->tp_base->tp_getattr((PyObject*) this, (char*) key);
}
int PyQtGuiObject::setattr(const char* key, PyObject* value) {
// fallthrough for now
return Py_TYPE(this)->tp_base->tp_setattr((PyObject*) this, (char*) key, value);
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/Interpreter/Value.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
void* /*clang::ASTContext**/ C,
const void* value) {
clang::Expr* Exp = (clang::Expr*)E;
clang::ASTContext* Context = (clang::ASTContext*)C;
cling::ValuePrinterInfo VPI(Exp, Context);
cling::printValuePublic(llvm::outs(), value, value, VPI);
cling::flushOStream(llvm::outs());
}
static void StreamChar(llvm::raw_ostream& o, const char v) {
o << '"' << v << "\"\n";
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...\n";
else o << "\"\n";
}
static void StreamRef(llvm::raw_ostream& o, const void* v) {
o <<"&" << v << "\n";
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << v << "\n";
}
static void StreamObj(llvm::raw_ostream& o, const void* v,
const cling::ValuePrinterInfo& VPI) {
const clang::Type* Ty = VPI.getExpr()->getType().getTypePtr();
if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl())
if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) {
cling::Value* V = (cling::Value*)v;
if (V->isValid()) {
o << "boxes [";
const clang::ASTContext& C = *VPI.getASTContext();
o <<
"(" <<
V->type.getAsString(C.getPrintingPolicy()) <<
") ";
clang::QualType valType = V->type.getDesugaredType(C);
if (valType->isPointerType())
o << V->value.PointerVal;
else if (valType->isFloatingType())
o << V->value.DoubleVal;
else if (valType->isIntegerType())
o << V->value.IntVal.getSExtValue();
else if (valType->isBooleanType())
o << V->value.IntVal.getBoolValue();
o << "]\n";
return;
} else
o << "<<<invalid>>> ";
}
// TODO: Print the object members.
o << "@" << v << "\n";
}
static void StreamValue(llvm::raw_ostream& o, const void* const p,
const cling::ValuePrinterInfo& VPI) {
clang::QualType Ty = VPI.getExpr()->getType();
const clang::ASTContext& C = *VPI.getASTContext();
Ty = Ty.getDesugaredType(C);
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(const bool*)p) o << "true\n";
else o << "false\n"; break;
case clang::BuiltinType::Char_U:
case clang::BuiltinType::UChar:
case clang::BuiltinType::Char_S:
case clang::BuiltinType::SChar: StreamChar(o, *(const char*)p); break;
case clang::BuiltinType::Short: o << *(const short*)p << "\n"; break;
case clang::BuiltinType::UShort:
o << *(const unsigned short*)p << "\n";
break;
case clang::BuiltinType::Int: o << *(const int*)p << "\n"; break;
case clang::BuiltinType::UInt:
o << *(const unsigned int*)p << "\n";
break;
case clang::BuiltinType::Long: o << *(const long*)p << "\n"; break;
case clang::BuiltinType::ULong:
o << *(const unsigned long*)p << "\n";
break;
case clang::BuiltinType::LongLong:
o << *(const long long*)p << "\n";
break;
case clang::BuiltinType::ULongLong:
o << *(const unsigned long long*)p << "\n";
break;
case clang::BuiltinType::Float: o << *(const float*)p << "\n"; break;
case clang::BuiltinType::Double: o << *(const double*)p << "\n"; break;
default:
StreamObj(o, p, VPI);
}
}
else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) {
StreamObj(o, p, VPI);
o <<"c_str: ";
StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str()));
}
else if (Ty->isEnumeralType()) {
StreamObj(o, p, VPI);
clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
uint64_t value = *(const uint64_t*)p;
bool IsFirst = true;
llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
E = ED->enumerator_end(); I != E; ++I) {
if (I->getInitVal() == ValAsAPSInt) {
if (!IsFirst) {
o << " ? ";
}
o << "(" << I->getQualifiedNameAsString() << ")";
IsFirst = false;
}
}
o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10) << "\n";
}
else if (Ty->isReferenceType())
StreamRef(o, p);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)p);
else
StreamPtr(o, p);
}
else
StreamObj(o, p, VPI);
}
namespace cling {
void printValuePublicDefault(llvm::raw_ostream& o, const void* const p,
const ValuePrinterInfo& VPI) {
const clang::Expr* E = VPI.getExpr();
o << "(";
o << E->getType().getAsString();
if (E->isRValue()) // show the user that the var cannot be changed
o << " const";
o << ") ";
StreamValue(o, p, VPI);
}
void flushOStream(llvm::raw_ostream& o) {
o.flush();
}
} // end namespace cling
<commit_msg>One more const-correctness fix<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/Interpreter/Value.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
void* /*clang::ASTContext**/ C,
const void* value) {
clang::Expr* Exp = (clang::Expr*)E;
clang::ASTContext* Context = (clang::ASTContext*)C;
cling::ValuePrinterInfo VPI(Exp, Context);
cling::printValuePublic(llvm::outs(), value, value, VPI);
cling::flushOStream(llvm::outs());
}
static void StreamChar(llvm::raw_ostream& o, const char v) {
o << '"' << v << "\"\n";
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...\n";
else o << "\"\n";
}
static void StreamRef(llvm::raw_ostream& o, const void* v) {
o <<"&" << v << "\n";
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << v << "\n";
}
static void StreamObj(llvm::raw_ostream& o, const void* v,
const cling::ValuePrinterInfo& VPI) {
const clang::Type* Ty = VPI.getExpr()->getType().getTypePtr();
if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl())
if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) {
const cling::Value* V = (const cling::Value*)v;
if (V->isValid()) {
o << "boxes [";
const clang::ASTContext& C = *VPI.getASTContext();
o <<
"(" <<
V->type.getAsString(C.getPrintingPolicy()) <<
") ";
clang::QualType valType = V->type.getDesugaredType(C);
if (valType->isPointerType())
o << V->value.PointerVal;
else if (valType->isFloatingType())
o << V->value.DoubleVal;
else if (valType->isIntegerType())
o << V->value.IntVal.getSExtValue();
else if (valType->isBooleanType())
o << V->value.IntVal.getBoolValue();
o << "]\n";
return;
} else
o << "<<<invalid>>> ";
}
// TODO: Print the object members.
o << "@" << v << "\n";
}
static void StreamValue(llvm::raw_ostream& o, const void* const p,
const cling::ValuePrinterInfo& VPI) {
clang::QualType Ty = VPI.getExpr()->getType();
const clang::ASTContext& C = *VPI.getASTContext();
Ty = Ty.getDesugaredType(C);
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(const bool*)p) o << "true\n";
else o << "false\n"; break;
case clang::BuiltinType::Char_U:
case clang::BuiltinType::UChar:
case clang::BuiltinType::Char_S:
case clang::BuiltinType::SChar: StreamChar(o, *(const char*)p); break;
case clang::BuiltinType::Short: o << *(const short*)p << "\n"; break;
case clang::BuiltinType::UShort:
o << *(const unsigned short*)p << "\n";
break;
case clang::BuiltinType::Int: o << *(const int*)p << "\n"; break;
case clang::BuiltinType::UInt:
o << *(const unsigned int*)p << "\n";
break;
case clang::BuiltinType::Long: o << *(const long*)p << "\n"; break;
case clang::BuiltinType::ULong:
o << *(const unsigned long*)p << "\n";
break;
case clang::BuiltinType::LongLong:
o << *(const long long*)p << "\n";
break;
case clang::BuiltinType::ULongLong:
o << *(const unsigned long long*)p << "\n";
break;
case clang::BuiltinType::Float: o << *(const float*)p << "\n"; break;
case clang::BuiltinType::Double: o << *(const double*)p << "\n"; break;
default:
StreamObj(o, p, VPI);
}
}
else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) {
StreamObj(o, p, VPI);
o <<"c_str: ";
StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str()));
}
else if (Ty->isEnumeralType()) {
StreamObj(o, p, VPI);
clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
uint64_t value = *(const uint64_t*)p;
bool IsFirst = true;
llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
E = ED->enumerator_end(); I != E; ++I) {
if (I->getInitVal() == ValAsAPSInt) {
if (!IsFirst) {
o << " ? ";
}
o << "(" << I->getQualifiedNameAsString() << ")";
IsFirst = false;
}
}
o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10) << "\n";
}
else if (Ty->isReferenceType())
StreamRef(o, p);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)p);
else
StreamPtr(o, p);
}
else
StreamObj(o, p, VPI);
}
namespace cling {
void printValuePublicDefault(llvm::raw_ostream& o, const void* const p,
const ValuePrinterInfo& VPI) {
const clang::Expr* E = VPI.getExpr();
o << "(";
o << E->getType().getAsString();
if (E->isRValue()) // show the user that the var cannot be changed
o << " const";
o << ") ";
StreamValue(o, p, VPI);
}
void flushOStream(llvm::raw_ostream& o) {
o.flush();
}
} // end namespace cling
<|endoftext|> |
<commit_before>//===-- ThreadElfCore.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/DataExtractor.h"
#include "lldb/Core/Log.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Unwind.h"
#include "ThreadElfCore.h"
#include "ProcessElfCore.h"
#include "Plugins/Process/Utility/RegisterContextLinux_arm.h"
#include "Plugins/Process/Utility/RegisterContextLinux_arm64.h"
#include "Plugins/Process/Utility/RegisterContextLinux_s390x.h"
#include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
#include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_arm.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_arm64.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_i386.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h"
#include "RegisterContextPOSIXCore_arm.h"
#include "RegisterContextPOSIXCore_arm64.h"
#include "RegisterContextPOSIXCore_mips64.h"
#include "RegisterContextPOSIXCore_powerpc.h"
#include "RegisterContextPOSIXCore_s390x.h"
#include "RegisterContextPOSIXCore_x86_64.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// Construct a Thread object with given data
//----------------------------------------------------------------------
ThreadElfCore::ThreadElfCore (Process &process, const ThreadData &td) :
Thread(process, td.tid),
m_thread_name(td.name),
m_thread_reg_ctx_sp (),
m_signo(td.signo),
m_gpregset_data(td.gpregset),
m_fpregset_data(td.fpregset),
m_vregset_data(td.vregset)
{
}
ThreadElfCore::~ThreadElfCore ()
{
DestroyThread();
}
void
ThreadElfCore::RefreshStateAfterStop()
{
GetRegisterContext()->InvalidateIfNeeded (false);
}
void
ThreadElfCore::ClearStackFrames ()
{
Unwind *unwinder = GetUnwinder ();
if (unwinder)
unwinder->Clear();
Thread::ClearStackFrames();
}
RegisterContextSP
ThreadElfCore::GetRegisterContext ()
{
if (m_reg_context_sp.get() == NULL) {
m_reg_context_sp = CreateRegisterContextForFrame (NULL);
}
return m_reg_context_sp;
}
RegisterContextSP
ThreadElfCore::CreateRegisterContextForFrame (StackFrame *frame)
{
RegisterContextSP reg_ctx_sp;
uint32_t concrete_frame_idx = 0;
Log *log (GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
if (frame)
concrete_frame_idx = frame->GetConcreteFrameIndex ();
if (concrete_frame_idx == 0)
{
if (m_thread_reg_ctx_sp)
return m_thread_reg_ctx_sp;
ProcessElfCore *process = static_cast<ProcessElfCore *>(GetProcess().get());
ArchSpec arch = process->GetArchitecture();
RegisterInfoInterface *reg_interface = NULL;
switch (arch.GetTriple().getOS())
{
case llvm::Triple::FreeBSD:
{
switch (arch.GetMachine())
{
case llvm::Triple::aarch64:
reg_interface = new RegisterContextFreeBSD_arm64(arch);
break;
case llvm::Triple::arm:
reg_interface = new RegisterContextFreeBSD_arm(arch);
break;
case llvm::Triple::ppc:
reg_interface = new RegisterContextFreeBSD_powerpc32(arch);
break;
case llvm::Triple::ppc64:
reg_interface = new RegisterContextFreeBSD_powerpc64(arch);
break;
case llvm::Triple::mips64:
reg_interface = new RegisterContextFreeBSD_mips64(arch);
break;
case llvm::Triple::x86:
reg_interface = new RegisterContextFreeBSD_i386(arch);
break;
case llvm::Triple::x86_64:
reg_interface = new RegisterContextFreeBSD_x86_64(arch);
break;
default:
break;
}
break;
}
case llvm::Triple::Linux:
{
switch (arch.GetMachine())
{
case llvm::Triple::arm:
reg_interface = new RegisterContextLinux_arm(arch);
break;
case llvm::Triple::aarch64:
reg_interface = new RegisterContextLinux_arm64(arch);
break;
case llvm::Triple::systemz:
reg_interface = new RegisterContextLinux_s390x(arch);
break;
case llvm::Triple::x86:
reg_interface = new RegisterContextLinux_i386(arch);
break;
case llvm::Triple::x86_64:
reg_interface = new RegisterContextLinux_x86_64(arch);
break;
default:
break;
}
break;
}
default:
break;
}
if (!reg_interface) {
if (log)
log->Printf ("elf-core::%s:: Architecture(%d) or OS(%d) not supported",
__FUNCTION__, arch.GetMachine(), arch.GetTriple().getOS());
assert (false && "Architecture or OS not supported");
}
switch (arch.GetMachine())
{
case llvm::Triple::aarch64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_arm64 (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::arm:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_arm (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::mips64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_mips64 (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::ppc:
case llvm::Triple::ppc64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_powerpc (*this, reg_interface, m_gpregset_data, m_fpregset_data, m_vregset_data));
break;
case llvm::Triple::systemz:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_s390x (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::x86:
case llvm::Triple::x86_64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_x86_64 (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
default:
break;
}
reg_ctx_sp = m_thread_reg_ctx_sp;
}
else if (m_unwinder_ap.get())
{
reg_ctx_sp = m_unwinder_ap->CreateRegisterContextForFrame (frame);
}
return reg_ctx_sp;
}
bool
ThreadElfCore::CalculateStopInfo ()
{
ProcessSP process_sp (GetProcess());
if (process_sp)
{
SetStopInfo(StopInfo::CreateStopReasonWithSignal (*this, m_signo));
return true;
}
return false;
}
//----------------------------------------------------------------
// Parse PRSTATUS from NOTE entry
//----------------------------------------------------------------
ELFLinuxPrStatus::ELFLinuxPrStatus()
{
memset(this, 0, sizeof(ELFLinuxPrStatus));
}
Error
ELFLinuxPrStatus::Parse(DataExtractor &data, ArchSpec &arch)
{
Error error;
ByteOrder byteorder = data.GetByteOrder();
if (GetSize(arch) > data.GetByteSize())
{
error.SetErrorStringWithFormat("NT_PRSTATUS size should be %lu, but the remaining bytes are: %lu",
GetSize(arch), data.GetByteSize());
return error;
}
switch(arch.GetCore())
{
case ArchSpec::eCore_s390x_generic:
case ArchSpec::eCore_x86_64_x86_64:
data.ExtractBytes(0, sizeof(ELFLinuxPrStatus), byteorder, this);
break;
case ArchSpec::eCore_x86_32_i386:
case ArchSpec::eCore_x86_32_i486:
{
// Parsing from a 32 bit ELF core file, and populating/reusing the structure
// properly, because the struct is for the 64 bit version
offset_t offset = 0;
si_signo = data.GetU32(&offset);
si_code = data.GetU32(&offset);
si_errno = data.GetU32(&offset);
pr_cursig = data.GetU16(&offset);
offset += 2; // pad
pr_sigpend = data.GetU32(&offset);
pr_sighold = data.GetU32(&offset);
pr_pid = data.GetU32(&offset);
pr_ppid = data.GetU32(&offset);
pr_pgrp = data.GetU32(&offset);
pr_sid = data.GetU32(&offset);
pr_utime.tv_sec = data.GetU32(&offset);
pr_utime.tv_usec = data.GetU32(&offset);
pr_stime.tv_sec = data.GetU32(&offset);
pr_stime.tv_usec = data.GetU32(&offset);
pr_cutime.tv_sec = data.GetU32(&offset);
pr_cutime.tv_usec = data.GetU32(&offset);
pr_cstime.tv_sec = data.GetU32(&offset);
pr_cstime.tv_usec = data.GetU32(&offset);
break;
}
default:
error.SetErrorStringWithFormat("ELFLinuxPrStatus::%s Unknown architecture", __FUNCTION__);
break;
}
return error;
}
//----------------------------------------------------------------
// Parse PRPSINFO from NOTE entry
//----------------------------------------------------------------
ELFLinuxPrPsInfo::ELFLinuxPrPsInfo()
{
memset(this, 0, sizeof(ELFLinuxPrPsInfo));
}
Error
ELFLinuxPrPsInfo::Parse(DataExtractor &data, ArchSpec &arch)
{
Error error;
ByteOrder byteorder = data.GetByteOrder();
if (GetSize(arch) > data.GetByteSize())
{
error.SetErrorStringWithFormat("NT_PRPSINFO size should be %lu, but the remaining bytes are: %lu",
GetSize(arch), data.GetByteSize());
return error;
}
switch(arch.GetCore())
{
case ArchSpec::eCore_s390x_generic:
case ArchSpec::eCore_x86_64_x86_64:
data.ExtractBytes(0, sizeof(ELFLinuxPrPsInfo), byteorder, this);
break;
case ArchSpec::eCore_x86_32_i386:
case ArchSpec::eCore_x86_32_i486:
{
// Parsing from a 32 bit ELF core file, and populating/reusing the structure
// properly, because the struct is for the 64 bit version
size_t size = 0;
offset_t offset = 0;
pr_state = data.GetU8(&offset);
pr_sname = data.GetU8(&offset);
pr_zomb = data.GetU8(&offset);
pr_nice = data.GetU8(&offset);
pr_flag = data.GetU32(&offset);
pr_uid = data.GetU16(&offset);
pr_gid = data.GetU16(&offset);
pr_pid = data.GetU32(&offset);
pr_ppid = data.GetU32(&offset);
pr_pgrp = data.GetU32(&offset);
pr_sid = data.GetU32(&offset);
size = 16;
data.ExtractBytes(offset, size, byteorder, pr_fname);
offset += size;
size = 80;
data.ExtractBytes(offset, size, byteorder, pr_psargs);
offset += size;
break;
}
default:
error.SetErrorStringWithFormat("ELFLinuxPrPsInfo::%s Unknown architecture", __FUNCTION__);
break;
}
return error;
}
<commit_msg>Fix printf warnings.<commit_after>//===-- ThreadElfCore.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/DataExtractor.h"
#include "lldb/Core/Log.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Unwind.h"
#include "ThreadElfCore.h"
#include "ProcessElfCore.h"
#include "Plugins/Process/Utility/RegisterContextLinux_arm.h"
#include "Plugins/Process/Utility/RegisterContextLinux_arm64.h"
#include "Plugins/Process/Utility/RegisterContextLinux_s390x.h"
#include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
#include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_arm.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_arm64.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_i386.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h"
#include "Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h"
#include "RegisterContextPOSIXCore_arm.h"
#include "RegisterContextPOSIXCore_arm64.h"
#include "RegisterContextPOSIXCore_mips64.h"
#include "RegisterContextPOSIXCore_powerpc.h"
#include "RegisterContextPOSIXCore_s390x.h"
#include "RegisterContextPOSIXCore_x86_64.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// Construct a Thread object with given data
//----------------------------------------------------------------------
ThreadElfCore::ThreadElfCore (Process &process, const ThreadData &td) :
Thread(process, td.tid),
m_thread_name(td.name),
m_thread_reg_ctx_sp (),
m_signo(td.signo),
m_gpregset_data(td.gpregset),
m_fpregset_data(td.fpregset),
m_vregset_data(td.vregset)
{
}
ThreadElfCore::~ThreadElfCore ()
{
DestroyThread();
}
void
ThreadElfCore::RefreshStateAfterStop()
{
GetRegisterContext()->InvalidateIfNeeded (false);
}
void
ThreadElfCore::ClearStackFrames ()
{
Unwind *unwinder = GetUnwinder ();
if (unwinder)
unwinder->Clear();
Thread::ClearStackFrames();
}
RegisterContextSP
ThreadElfCore::GetRegisterContext ()
{
if (m_reg_context_sp.get() == NULL) {
m_reg_context_sp = CreateRegisterContextForFrame (NULL);
}
return m_reg_context_sp;
}
RegisterContextSP
ThreadElfCore::CreateRegisterContextForFrame (StackFrame *frame)
{
RegisterContextSP reg_ctx_sp;
uint32_t concrete_frame_idx = 0;
Log *log (GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
if (frame)
concrete_frame_idx = frame->GetConcreteFrameIndex ();
if (concrete_frame_idx == 0)
{
if (m_thread_reg_ctx_sp)
return m_thread_reg_ctx_sp;
ProcessElfCore *process = static_cast<ProcessElfCore *>(GetProcess().get());
ArchSpec arch = process->GetArchitecture();
RegisterInfoInterface *reg_interface = NULL;
switch (arch.GetTriple().getOS())
{
case llvm::Triple::FreeBSD:
{
switch (arch.GetMachine())
{
case llvm::Triple::aarch64:
reg_interface = new RegisterContextFreeBSD_arm64(arch);
break;
case llvm::Triple::arm:
reg_interface = new RegisterContextFreeBSD_arm(arch);
break;
case llvm::Triple::ppc:
reg_interface = new RegisterContextFreeBSD_powerpc32(arch);
break;
case llvm::Triple::ppc64:
reg_interface = new RegisterContextFreeBSD_powerpc64(arch);
break;
case llvm::Triple::mips64:
reg_interface = new RegisterContextFreeBSD_mips64(arch);
break;
case llvm::Triple::x86:
reg_interface = new RegisterContextFreeBSD_i386(arch);
break;
case llvm::Triple::x86_64:
reg_interface = new RegisterContextFreeBSD_x86_64(arch);
break;
default:
break;
}
break;
}
case llvm::Triple::Linux:
{
switch (arch.GetMachine())
{
case llvm::Triple::arm:
reg_interface = new RegisterContextLinux_arm(arch);
break;
case llvm::Triple::aarch64:
reg_interface = new RegisterContextLinux_arm64(arch);
break;
case llvm::Triple::systemz:
reg_interface = new RegisterContextLinux_s390x(arch);
break;
case llvm::Triple::x86:
reg_interface = new RegisterContextLinux_i386(arch);
break;
case llvm::Triple::x86_64:
reg_interface = new RegisterContextLinux_x86_64(arch);
break;
default:
break;
}
break;
}
default:
break;
}
if (!reg_interface) {
if (log)
log->Printf ("elf-core::%s:: Architecture(%d) or OS(%d) not supported",
__FUNCTION__, arch.GetMachine(), arch.GetTriple().getOS());
assert (false && "Architecture or OS not supported");
}
switch (arch.GetMachine())
{
case llvm::Triple::aarch64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_arm64 (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::arm:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_arm (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::mips64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_mips64 (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::ppc:
case llvm::Triple::ppc64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_powerpc (*this, reg_interface, m_gpregset_data, m_fpregset_data, m_vregset_data));
break;
case llvm::Triple::systemz:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_s390x (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
case llvm::Triple::x86:
case llvm::Triple::x86_64:
m_thread_reg_ctx_sp.reset(new RegisterContextCorePOSIX_x86_64 (*this, reg_interface, m_gpregset_data, m_fpregset_data));
break;
default:
break;
}
reg_ctx_sp = m_thread_reg_ctx_sp;
}
else if (m_unwinder_ap.get())
{
reg_ctx_sp = m_unwinder_ap->CreateRegisterContextForFrame (frame);
}
return reg_ctx_sp;
}
bool
ThreadElfCore::CalculateStopInfo ()
{
ProcessSP process_sp (GetProcess());
if (process_sp)
{
SetStopInfo(StopInfo::CreateStopReasonWithSignal (*this, m_signo));
return true;
}
return false;
}
//----------------------------------------------------------------
// Parse PRSTATUS from NOTE entry
//----------------------------------------------------------------
ELFLinuxPrStatus::ELFLinuxPrStatus()
{
memset(this, 0, sizeof(ELFLinuxPrStatus));
}
Error
ELFLinuxPrStatus::Parse(DataExtractor &data, ArchSpec &arch)
{
Error error;
ByteOrder byteorder = data.GetByteOrder();
if (GetSize(arch) > data.GetByteSize())
{
error.SetErrorStringWithFormat("NT_PRSTATUS size should be %lu, but the remaining bytes are: %" PRIu64,
GetSize(arch), data.GetByteSize());
return error;
}
switch(arch.GetCore())
{
case ArchSpec::eCore_s390x_generic:
case ArchSpec::eCore_x86_64_x86_64:
data.ExtractBytes(0, sizeof(ELFLinuxPrStatus), byteorder, this);
break;
case ArchSpec::eCore_x86_32_i386:
case ArchSpec::eCore_x86_32_i486:
{
// Parsing from a 32 bit ELF core file, and populating/reusing the structure
// properly, because the struct is for the 64 bit version
offset_t offset = 0;
si_signo = data.GetU32(&offset);
si_code = data.GetU32(&offset);
si_errno = data.GetU32(&offset);
pr_cursig = data.GetU16(&offset);
offset += 2; // pad
pr_sigpend = data.GetU32(&offset);
pr_sighold = data.GetU32(&offset);
pr_pid = data.GetU32(&offset);
pr_ppid = data.GetU32(&offset);
pr_pgrp = data.GetU32(&offset);
pr_sid = data.GetU32(&offset);
pr_utime.tv_sec = data.GetU32(&offset);
pr_utime.tv_usec = data.GetU32(&offset);
pr_stime.tv_sec = data.GetU32(&offset);
pr_stime.tv_usec = data.GetU32(&offset);
pr_cutime.tv_sec = data.GetU32(&offset);
pr_cutime.tv_usec = data.GetU32(&offset);
pr_cstime.tv_sec = data.GetU32(&offset);
pr_cstime.tv_usec = data.GetU32(&offset);
break;
}
default:
error.SetErrorStringWithFormat("ELFLinuxPrStatus::%s Unknown architecture", __FUNCTION__);
break;
}
return error;
}
//----------------------------------------------------------------
// Parse PRPSINFO from NOTE entry
//----------------------------------------------------------------
ELFLinuxPrPsInfo::ELFLinuxPrPsInfo()
{
memset(this, 0, sizeof(ELFLinuxPrPsInfo));
}
Error
ELFLinuxPrPsInfo::Parse(DataExtractor &data, ArchSpec &arch)
{
Error error;
ByteOrder byteorder = data.GetByteOrder();
if (GetSize(arch) > data.GetByteSize())
{
error.SetErrorStringWithFormat("NT_PRPSINFO size should be %lu, but the remaining bytes are: %" PRIu64,
GetSize(arch), data.GetByteSize());
return error;
}
switch(arch.GetCore())
{
case ArchSpec::eCore_s390x_generic:
case ArchSpec::eCore_x86_64_x86_64:
data.ExtractBytes(0, sizeof(ELFLinuxPrPsInfo), byteorder, this);
break;
case ArchSpec::eCore_x86_32_i386:
case ArchSpec::eCore_x86_32_i486:
{
// Parsing from a 32 bit ELF core file, and populating/reusing the structure
// properly, because the struct is for the 64 bit version
size_t size = 0;
offset_t offset = 0;
pr_state = data.GetU8(&offset);
pr_sname = data.GetU8(&offset);
pr_zomb = data.GetU8(&offset);
pr_nice = data.GetU8(&offset);
pr_flag = data.GetU32(&offset);
pr_uid = data.GetU16(&offset);
pr_gid = data.GetU16(&offset);
pr_pid = data.GetU32(&offset);
pr_ppid = data.GetU32(&offset);
pr_pgrp = data.GetU32(&offset);
pr_sid = data.GetU32(&offset);
size = 16;
data.ExtractBytes(offset, size, byteorder, pr_fname);
offset += size;
size = 80;
data.ExtractBytes(offset, size, byteorder, pr_psargs);
offset += size;
break;
}
default:
error.SetErrorStringWithFormat("ELFLinuxPrPsInfo::%s Unknown architecture", __FUNCTION__);
break;
}
return error;
}
<|endoftext|> |
<commit_before>#pragma once
#include "external/glad/glad.h"
#include <GLFW/glfw3.h>
#include <string>
#include <vector>
//! \brief Namespace containing a few helpers for the EDA221 labs.
namespace eda221
{
//! \brief Formalise mapping between an OpenGL VAO attribute binding,
//! and the meaning of that attribute.
enum class shader_bindings : unsigned int{
vertices = 0u, //!< = 0, value of the binding point for vertices
normals, //!< = 1, value of the binding point for normals
texcoords, //!< = 2, value of the binding point for texcoords
tangents, //!< = 3, value of the binding point for tangents
binormals //!< = 4, value of the binding point for binormals
};
//! \brief Contains the data for a mesh in OpenGL.
struct mesh_data {
GLuint vao; //!< OpenGL name of the Vertex Array Object
GLuint bo; //!< OpenGL name of the Buffer Object
GLuint ibo; //!< OpenGL name of the Buffer Object for indices
size_t indices_nb; //!< number of indices stored in ibo
};
//! \brief Load objects found in an object/scene file, using assimp.
//!
//! @param [in] filename of the object/scene file to load, relative to
//! the `res/scenes` folder
//! @return a vector of filled in `mesh_data` structures, one per
//! object found in the input file
std::vector<mesh_data> loadObjects(std::string const& filename);
//! \brief Load a PNG image into an OpenGL 2D-texture.
//!
//! @param [in] filename of the PNG image, relative to the `textures`
//! folder within the `resources` folder.
//! @param [in] generate_mipmap whether or not to generate a mipmap hierarchy
//! @return the name of the OpenGL 2D-texture
GLuint loadTexture2D(std::string const& filename,
bool generate_mipmap = true);
//! \brief Load six PNG images into an OpenGL cubemap-texture.
//!
//! @param [in] posx path to the texture on the left of the cubemap
//! @param [in] negx path to the texture on the right of the cubemap
//! @param [in] posy path to the texture on the top of the cubemap
//! @param [in] negy path to the texture on the bottom of the cubemap
//! @param [in] negz path to the texture on the front of the cubemap
//! @param [in] posz path to the texture on the back of the cubemap
//! @param [in] generate_mipmap whether or not to generate a mipmap hierarchy
//! @return the name of the OpenGL cubemap-texture
//!
//! All paths are relative to the `res/cubemaps` folder.
GLuint loadTextureCubeMap(std::string const& posx, std::string const& negx,
std::string const& posy, std::string const& negy,
std::string const& negz, std::string const& posz,
bool generate_mipmap = false);
//! \brief Create an OpenGL program consisting of a vertex and a
//! fragment shader.
//!
//! @param [in] vert_shader_source_path of the vertex shader source
//! code, relative to the `shaders/EDA221` folder
//! @param [in] frag_shader_source_path of the fragment shader source
//! code, relative to the `shaders/EDA221` folder
//! @return the name of the OpenGL shader program
GLuint createProgram(std::string const& vert_shader_source_path,
std::string const& frag_shader_source_path);
}
<commit_msg>EDA221/helpers: mesh_data now stores texture bindings<commit_after>#pragma once
#include "external/glad/glad.h"
#include <GLFW/glfw3.h>
#include <string>
#include <vector>
#include <unordered_map>
//! \brief Namespace containing a few helpers for the EDA221 labs.
namespace eda221
{
//! \brief Formalise mapping between an OpenGL VAO attribute binding,
//! and the meaning of that attribute.
enum class shader_bindings : unsigned int{
vertices = 0u, //!< = 0, value of the binding point for vertices
normals, //!< = 1, value of the binding point for normals
texcoords, //!< = 2, value of the binding point for texcoords
tangents, //!< = 3, value of the binding point for tangents
binormals //!< = 4, value of the binding point for binormals
};
//! \brief Association of a sampler name used in GLSL to a
//! corresponding texture ID.
using texture_bindings = std::unordered_map<std::string, GLuint>;
//! \brief Contains the data for a mesh in OpenGL.
struct mesh_data {
GLuint vao; //!< OpenGL name of the Vertex Array Object
GLuint bo; //!< OpenGL name of the Buffer Object
GLuint ibo; //!< OpenGL name of the Buffer Object for indices
size_t indices_nb; //!< number of indices stored in ibo
texture_bindings bindings; //!< texture bindings for this mesh
};
//! \brief Load objects found in an object/scene file, using assimp.
//!
//! @param [in] filename of the object/scene file to load, relative to
//! the `res/scenes` folder
//! @return a vector of filled in `mesh_data` structures, one per
//! object found in the input file
std::vector<mesh_data> loadObjects(std::string const& filename);
//! \brief Load a PNG image into an OpenGL 2D-texture.
//!
//! @param [in] filename of the PNG image, relative to the `textures`
//! folder within the `resources` folder.
//! @param [in] generate_mipmap whether or not to generate a mipmap hierarchy
//! @return the name of the OpenGL 2D-texture
GLuint loadTexture2D(std::string const& filename,
bool generate_mipmap = true);
//! \brief Load six PNG images into an OpenGL cubemap-texture.
//!
//! @param [in] posx path to the texture on the left of the cubemap
//! @param [in] negx path to the texture on the right of the cubemap
//! @param [in] posy path to the texture on the top of the cubemap
//! @param [in] negy path to the texture on the bottom of the cubemap
//! @param [in] negz path to the texture on the front of the cubemap
//! @param [in] posz path to the texture on the back of the cubemap
//! @param [in] generate_mipmap whether or not to generate a mipmap hierarchy
//! @return the name of the OpenGL cubemap-texture
//!
//! All paths are relative to the `res/cubemaps` folder.
GLuint loadTextureCubeMap(std::string const& posx, std::string const& negx,
std::string const& posy, std::string const& negy,
std::string const& negz, std::string const& posz,
bool generate_mipmap = false);
//! \brief Create an OpenGL program consisting of a vertex and a
//! fragment shader.
//!
//! @param [in] vert_shader_source_path of the vertex shader source
//! code, relative to the `shaders/EDA221` folder
//! @param [in] frag_shader_source_path of the fragment shader source
//! code, relative to the `shaders/EDA221` folder
//! @return the name of the OpenGL shader program
GLuint createProgram(std::string const& vert_shader_source_path,
std::string const& frag_shader_source_path);
}
<|endoftext|> |
<commit_before>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// OCClient.cpp : Defines the entry point for the console application.
//
#include <string>
#include <cstdlib>
#include <pthread.h>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"
using namespace OC;
const int SUCCESS_RESPONSE = 0;
std::shared_ptr<OCResource> curResource;
std::mutex resourceLock;
int observe_count()
{
static int oc = 0;
return ++oc;
}
static void printUsage()
{
std::cout << "Usage roomclient <0|1>" << std::endl;
std::cout<<"connectivityType: Default" << std::endl;
std::cout << "connectivityType 0: IP" << std::endl;
}
// Forward declaration
void putRoomRepresentation(std::shared_ptr<OCResource> resource);
void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
void printRoomRepresentation(const OCRepresentation& rep)
{
std::cout << "\tResource URI: " << rep.getUri() << std::endl;
if(rep.hasAttribute("name"))
{
std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
}
std::vector<OCRepresentation> children = rep.getChildren();
for(auto oit = children.begin(); oit != children.end(); ++oit)
{
std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
if(oit->getUri().find("light") != std::string::npos)
{
if(oit->hasAttribute("state") && oit->hasAttribute("color"))
{
std::cout << "\t\tstate:" << oit->getValue<bool>("state") << std::endl;
std::cout << "\t\tcolor:" << oit->getValue<int>("color") << std::endl;
}
}
else if(oit->getUri().find("fan") != std::string::npos)
{
if(oit->hasAttribute("state") && oit->hasAttribute("speed"))
{
std::cout << "\t\tstate:" << oit->getValue<bool>("state") << std::endl;
std::cout << "\t\tspeed:" << oit->getValue<int>("speed") << std::endl;
}
}
}
}
// callback handler on GET request
void onGet(const HeaderOptions& /*headerOptions*/,
const OCRepresentation& rep, const int eCode)
{
if(eCode == SUCCESS_RESPONSE)
{
std::cout << "GET request was successful" << std::endl;
printRoomRepresentation(rep);
putRoomRepresentation(curResource);
}
else
{
std::cout << "onGET Response error: " << eCode << std::endl;
std::exit(-1);
}
}
void onGet1(const HeaderOptions& /*headerOptions*/,
const OCRepresentation& rep, const int eCode)
{
if(eCode == SUCCESS_RESPONSE)
{
std::cout << "GET request was successful" << std::endl;
printRoomRepresentation(rep);
}
else
{
std::cout << "onGET Response error: " << eCode << std::endl;
std::exit(-1);
}
}
// Local function to get representation of room resource
void getRoomRepresentation(std::shared_ptr<OCResource> resource,
std::string interface, GetCallback getCallback)
{
if(resource)
{
std::cout << "Getting room representation on: "<< interface << std::endl;
resource->get("core.room", interface, QueryParamsMap(), getCallback);
}
}
// Local function to put a different state for this resource
void putRoomRepresentation(std::shared_ptr<OCResource> resource)
{
if(resource)
{
OCRepresentation rep;
std::cout << "Putting room representation on: " << BATCH_INTERFACE << std::endl;
bool state = true;
int speed = 10;
rep.setValue("state", state);
rep.setValue("speed", speed);
// Invoke resource's pit API with attribute map, query map and the callback parameter
resource->put("core.room", BATCH_INTERFACE, rep, QueryParamsMap(), &onPut);
}
}
// callback handler on PUT request
void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
if(eCode == SUCCESS_RESPONSE)
{
std::cout << "PUT request was successful" << std::endl;
printRoomRepresentation(rep);
getRoomRepresentation(curResource, DEFAULT_INTERFACE, onGet1);
}
else
{
std::cout << "onPut Response error: " << eCode << std::endl;
std::exit(-1);
}
}
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
std::lock_guard<std::mutex> lock(resourceLock);
if(curResource)
{
std::cout << "Found another resource, ignoring"<<std::endl;
return;
}
std::string resourceURI;
std::string hostAddress;
std::string platformDiscoveryURI = "/oic/p";
std::string deviceDiscoveryURI = "/oic/d";
try
{
// Do some operations with resource object.
if(resource)
{
std::cout<<"DISCOVERED Resource:"<<std::endl;
// Get the resource URI
resourceURI = resource->uri();
std::cout << "\tURI of the resource: " << resourceURI << std::endl;
// Get the resource host address
hostAddress = resource->host();
std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
// Get the resource types
std::cout << "\tList of resource types: " << std::endl;
for(auto &resourceTypes : resource->getResourceTypes())
{
std::cout << "\t\t" << resourceTypes << std::endl;
}
// Get the resource interfaces
std::cout << "\tList of resource interfaces: " << std::endl;
for(auto &resourceInterfaces : resource->getResourceInterfaces())
{
std::cout << "\t\t" << resourceInterfaces << std::endl;
}
OCStackResult ret;
std::cout << "Querying for platform information... " << std::endl;
ret = OCPlatform::getPlatformInfo("", platformDiscoveryURI, CT_ADAPTER_IP, NULL);
if (ret == OC_STACK_OK)
{
std::cout << "Get platform information is done." << std::endl;
}
else
{
std::cout << "Get platform information failed." << std::endl;
}
std::cout << "Querying for device information... " << std::endl;
ret = OCPlatform::getDeviceInfo(resource->host(), deviceDiscoveryURI,
resource->connectivityType(), NULL);
if (ret == OC_STACK_OK)
{
std::cout << "Getting device information is done." << std::endl;
}
else
{
std::cout << "Getting device information failed." << std::endl;
}
if(resourceURI == "/a/room")
{
curResource = resource;
// Call a local function which will internally invoke get API on the resource pointer
getRoomRepresentation(resource, BATCH_INTERFACE, onGet);
}
}
else
{
// Resource is invalid
std::cout << "Resource is invalid" << std::endl;
}
}
catch(std::exception& e)
{
std::cerr << "Exception caught in Found Resource: "<< e.what() <<std::endl;
}
}
int main(int argc, char* argv[]) {
std::ostringstream requestURI;
OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
try
{
std::size_t inputValLen;
int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
if(optionSelected == 0)
{
std::cout << "Using IP."<< std::endl;
connectivityType = CT_ADAPTER_IP;
}
else
{
std::cout << "Invalid connectivity type selected. Using default IP"<< std::endl;
}
}
else
{
std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
catch(std::exception&)
{
std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
}
else
{
std::cout << "Default input argument. Using IP as Default connectivity type" << std::endl;
printUsage();
}
// Create PlatformConfig object
PlatformConfig cfg {
OC::ServiceType::InProc,
OC::ModeType::Client,
"0.0.0.0",
0,
OC::QualityOfService::LowQos
};
OCPlatform::Configure(cfg);
try
{
// Find all resources
requestURI << OC_RSRVD_WELL_KNOWN_URI;
OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
// A condition variable will free the mutex it is given, then do a non-
// intensive block until 'notify' is called on it. In this case, since we
// don't ever call cv.notify, this should be a non-processor intensive version
// of while(true);
std::mutex blocker;
std::condition_variable cv;
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
}catch(OCException& e)
{
oclog() << "Exception in main: "<< e.what();
}
return 0;
}
<commit_msg>fix process onPut message of roomclient app<commit_after>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// OCClient.cpp : Defines the entry point for the console application.
//
#include <string>
#include <cstdlib>
#include <pthread.h>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"
using namespace OC;
std::shared_ptr<OCResource> curResource;
std::mutex resourceLock;
int observe_count()
{
static int oc = 0;
return ++oc;
}
static void printUsage()
{
std::cout << "Usage roomclient <0|1>" << std::endl;
std::cout<<"connectivityType: Default" << std::endl;
std::cout << "connectivityType 0: IP" << std::endl;
}
// Forward declaration
void putRoomRepresentation(std::shared_ptr<OCResource> resource);
void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
void printRoomRepresentation(const OCRepresentation& rep)
{
std::cout << "\tResource URI: " << rep.getUri() << std::endl;
if(rep.hasAttribute("name"))
{
std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
}
std::vector<OCRepresentation> children = rep.getChildren();
for(auto oit = children.begin(); oit != children.end(); ++oit)
{
std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
if(oit->getUri().find("light") != std::string::npos)
{
if(oit->hasAttribute("state") && oit->hasAttribute("color"))
{
std::cout << "\t\tstate:" << oit->getValue<bool>("state") << std::endl;
std::cout << "\t\tcolor:" << oit->getValue<int>("color") << std::endl;
}
}
else if(oit->getUri().find("fan") != std::string::npos)
{
if(oit->hasAttribute("state") && oit->hasAttribute("speed"))
{
std::cout << "\t\tstate:" << oit->getValue<bool>("state") << std::endl;
std::cout << "\t\tspeed:" << oit->getValue<int>("speed") << std::endl;
}
}
}
}
// callback handler on GET request
void onGet(const HeaderOptions& /*headerOptions*/,
const OCRepresentation& rep, const int eCode)
{
if (eCode == OC_STACK_OK)
{
std::cout << "GET request was successful" << std::endl;
printRoomRepresentation(rep);
putRoomRepresentation(curResource);
}
else
{
std::cout << "onGET Response error: " << eCode << std::endl;
std::exit(-1);
}
}
void onGet1(const HeaderOptions& /*headerOptions*/,
const OCRepresentation& rep, const int eCode)
{
if (eCode == OC_STACK_OK)
{
std::cout << "GET request was successful" << std::endl;
printRoomRepresentation(rep);
}
else
{
std::cout << "onGET Response error: " << eCode << std::endl;
std::exit(-1);
}
}
// Local function to get representation of room resource
void getRoomRepresentation(std::shared_ptr<OCResource> resource,
std::string interface, GetCallback getCallback)
{
if(resource)
{
std::cout << "Getting room representation on: "<< interface << std::endl;
resource->get("core.room", interface, QueryParamsMap(), getCallback);
}
}
// Local function to put a different state for this resource
void putRoomRepresentation(std::shared_ptr<OCResource> resource)
{
if(resource)
{
OCRepresentation rep;
std::cout << "Putting room representation on: " << BATCH_INTERFACE << std::endl;
bool state = true;
int speed = 10;
rep.setValue("state", state);
rep.setValue("speed", speed);
// Invoke resource's pit API with attribute map, query map and the callback parameter
resource->put("core.room", BATCH_INTERFACE, rep, QueryParamsMap(), &onPut);
}
}
// callback handler on PUT request
void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CHANGED)
{
std::cout << "PUT request was successful" << std::endl;
printRoomRepresentation(rep);
getRoomRepresentation(curResource, DEFAULT_INTERFACE, onGet1);
}
else
{
std::cout << "onPut Response error: " << eCode << std::endl;
std::exit(-1);
}
}
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
std::lock_guard<std::mutex> lock(resourceLock);
if(curResource)
{
std::cout << "Found another resource, ignoring"<<std::endl;
return;
}
std::string resourceURI;
std::string hostAddress;
std::string platformDiscoveryURI = "/oic/p";
std::string deviceDiscoveryURI = "/oic/d";
try
{
// Do some operations with resource object.
if(resource)
{
std::cout<<"DISCOVERED Resource:"<<std::endl;
// Get the resource URI
resourceURI = resource->uri();
std::cout << "\tURI of the resource: " << resourceURI << std::endl;
// Get the resource host address
hostAddress = resource->host();
std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
// Get the resource types
std::cout << "\tList of resource types: " << std::endl;
for(auto &resourceTypes : resource->getResourceTypes())
{
std::cout << "\t\t" << resourceTypes << std::endl;
}
// Get the resource interfaces
std::cout << "\tList of resource interfaces: " << std::endl;
for(auto &resourceInterfaces : resource->getResourceInterfaces())
{
std::cout << "\t\t" << resourceInterfaces << std::endl;
}
OCStackResult ret;
std::cout << "Querying for platform information... " << std::endl;
ret = OCPlatform::getPlatformInfo("", platformDiscoveryURI, CT_ADAPTER_IP, NULL);
if (ret == OC_STACK_OK)
{
std::cout << "Get platform information is done." << std::endl;
}
else
{
std::cout << "Get platform information failed." << std::endl;
}
std::cout << "Querying for device information... " << std::endl;
ret = OCPlatform::getDeviceInfo(resource->host(), deviceDiscoveryURI,
resource->connectivityType(), NULL);
if (ret == OC_STACK_OK)
{
std::cout << "Getting device information is done." << std::endl;
}
else
{
std::cout << "Getting device information failed." << std::endl;
}
if(resourceURI == "/a/room")
{
curResource = resource;
// Call a local function which will internally invoke get API on the resource pointer
getRoomRepresentation(resource, BATCH_INTERFACE, onGet);
}
}
else
{
// Resource is invalid
std::cout << "Resource is invalid" << std::endl;
}
}
catch(std::exception& e)
{
std::cerr << "Exception caught in Found Resource: "<< e.what() <<std::endl;
}
}
int main(int argc, char* argv[]) {
std::ostringstream requestURI;
OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
try
{
std::size_t inputValLen;
int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
if(optionSelected == 0)
{
std::cout << "Using IP."<< std::endl;
connectivityType = CT_ADAPTER_IP;
}
else
{
std::cout << "Invalid connectivity type selected. Using default IP"<< std::endl;
}
}
else
{
std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
catch(std::exception&)
{
std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
}
else
{
std::cout << "Default input argument. Using IP as Default connectivity type" << std::endl;
printUsage();
}
// Create PlatformConfig object
PlatformConfig cfg {
OC::ServiceType::InProc,
OC::ModeType::Client,
"0.0.0.0",
0,
OC::QualityOfService::LowQos
};
OCPlatform::Configure(cfg);
try
{
// Find all resources
requestURI << OC_RSRVD_WELL_KNOWN_URI;
OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
// A condition variable will free the mutex it is given, then do a non-
// intensive block until 'notify' is called on it. In this case, since we
// don't ever call cv.notify, this should be a non-processor intensive version
// of while(true);
std::mutex blocker;
std::condition_variable cv;
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
}catch(OCException& e)
{
oclog() << "Exception in main: "<< e.what();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "UserEventFilter.h"
#include "ItemFilter.h"
#include "PurchaseManager.h"
#include "CartManager.h"
#include "EventManager.h"
#include "RateManager.h"
#include <bundles/recommend/RecommendSchema.h>
#include <glog/logging.h>
namespace
{
using namespace sf1r;
void excludeItems(
const ItemIdSet& excludeItemSet,
std::vector<itemid_t>& inputItems
)
{
if (excludeItemSet.empty())
return;
std::vector<itemid_t> newInputItems;
for (std::vector<itemid_t>::const_iterator it = inputItems.begin();
it != inputItems.end(); ++it)
{
if (excludeItemSet.find(*it) == excludeItemSet.end())
{
newInputItems.push_back(*it);
}
}
newInputItems.swap(inputItems);
}
void excludeItems(
const ItemIdSet& excludeItemSet,
ItemRateMap& itemRateMap
)
{
if (excludeItemSet.empty())
return;
for (ItemRateMap::iterator it = itemRateMap.begin();
it != itemRateMap.end();)
{
if (excludeItemSet.find(it->first) == excludeItemSet.end())
{
++it;
}
else
{
itemRateMap.erase(it++);
}
}
}
}
namespace sf1r
{
UserEventFilter::UserEventFilter(
PurchaseManager& purchaseManager,
CartManager& cartManager,
EventManager& eventManager,
RateManager& rateManager
)
: purchaseManager_(purchaseManager)
, cartManager_(cartManager)
, eventManager_(eventManager)
, rateManager_(rateManager)
{
}
bool UserEventFilter::filter(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemFilter& filter
) const
{
assert(userId);
return (filterRateItem_(userId, filter)
&& filterPurchaseItem_(userId, filter)
&& filterCartItem_(userId, filter)
&& filterPreferenceItem_(userId, inputItemVec, filter));
}
bool UserEventFilter::filterRateItem_(
const std::string& userId,
ItemFilter& filter
) const
{
ItemRateMap itemRateMap;
if (! rateManager_.getItemRateMap(userId, itemRateMap))
{
LOG(ERROR) << "failed to get rates for user id " << userId;
return false;
}
for (ItemRateMap::const_iterator it = itemRateMap.begin();
it != itemRateMap.end(); ++it)
{
filter.insert(it->first);
}
return true;
}
bool UserEventFilter::filterPurchaseItem_(
const std::string& userId,
ItemFilter& filter
) const
{
ItemIdSet purchaseItemSet;
if (! purchaseManager_.getPurchaseItemSet(userId, purchaseItemSet))
{
LOG(ERROR) << "failed to get purchased items for user id " << userId;
return false;
}
filter.insert(purchaseItemSet.begin(), purchaseItemSet.end());
return true;
}
bool UserEventFilter::filterCartItem_(
const std::string& userId,
ItemFilter& filter
) const
{
std::vector<itemid_t> cartItemVec;
if (! cartManager_.getCart(userId, cartItemVec))
{
LOG(ERROR) << "failed to get shopping cart items for user id " << userId;
return false;
}
filter.insert(cartItemVec.begin(), cartItemVec.end());
return true;
}
bool UserEventFilter::filterPreferenceItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemFilter& filter
) const
{
EventManager::EventItemMap eventItemMap;
if (! eventManager_.getEvent(userId, eventItemMap))
{
LOG(ERROR) << "failed to get events for user id " << userId;
return false;
}
for (EventManager::EventItemMap::const_iterator it = eventItemMap.begin();
it != eventItemMap.end(); ++it)
{
filter.insert(it->second.begin(), it->second.end());
}
const ItemIdSet& notRecInputSet = eventItemMap[RecommendSchema::NOT_REC_INPUT_EVENT];
excludeItems(notRecInputSet, inputItemVec);
return true;
}
bool UserEventFilter::addUserEvent(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemRateMap& itemRateMap,
ItemEventMap& itemEventMap,
ItemFilter& filter
) const
{
assert(userId);
inputItemVec.clear();
return (addRateItem_(userId, itemRateMap, itemEventMap)
&& addPurchaseItem_(userId, inputItemVec, itemEventMap)
&& addCartItem_(userId, inputItemVec, itemEventMap)
&& addPreferenceItem_(userId, inputItemVec, itemRateMap, itemEventMap, filter));
}
bool UserEventFilter::addRateItem_(
const std::string& userId,
ItemRateMap& itemRateMap,
ItemEventMap& itemEventMap
) const
{
if (! rateManager_.getItemRateMap(userId, itemRateMap))
{
LOG(ERROR) << "failed to get rates for user id " << userId;
return false;
}
for (ItemRateMap::iterator it = itemRateMap.begin();
it != itemRateMap.end();)
{
ItemEventMap::value_type itemEvent(it->first, RecommendSchema::RATE_EVENT);
if (itemEventMap.insert(itemEvent).second)
{
++it;
}
else
{
itemRateMap.erase(it++);
}
}
return true;
}
bool UserEventFilter::addPurchaseItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemEventMap& itemEventMap
) const
{
ItemIdSet purchaseItemSet;
if (! purchaseManager_.getPurchaseItemSet(userId, purchaseItemSet))
{
LOG(ERROR) << "failed to get purchased items for user id " << userId;
return false;
}
for (ItemIdSet::const_iterator it = purchaseItemSet.begin();
it != purchaseItemSet.end(); ++it)
{
ItemEventMap::value_type itemEvent(*it, RecommendSchema::PURCHASE_EVENT);
if (itemEventMap.insert(itemEvent).second)
{
inputItemVec.push_back(*it);
}
}
return true;
}
bool UserEventFilter::addCartItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemEventMap& itemEventMap
) const
{
std::vector<itemid_t> cartItemVec;
if (! cartManager_.getCart(userId, cartItemVec))
{
LOG(ERROR) << "failed to get shopping cart items for user id " << userId;
return false;
}
for (std::vector<itemid_t>::const_iterator it = cartItemVec.begin();
it != cartItemVec.end(); ++it)
{
ItemEventMap::value_type itemEvent(*it, RecommendSchema::CART_EVENT);
if (itemEventMap.insert(itemEvent).second)
{
inputItemVec.push_back(*it);
}
}
return true;
}
bool UserEventFilter::addPreferenceItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemRateMap& itemRateMap,
ItemEventMap& itemEventMap,
ItemFilter& filter
) const
{
EventManager::EventItemMap eventItemMap;
if (! eventManager_.getEvent(userId, eventItemMap))
{
LOG(ERROR) << "failed to get events for user id " << userId;
return false;
}
for (EventManager::EventItemMap::const_iterator eventIt = eventItemMap.begin();
eventIt != eventItemMap.end(); ++eventIt)
{
if (eventIt->first == RecommendSchema::NOT_REC_RESULT_EVENT
|| eventIt->first == RecommendSchema::NOT_REC_INPUT_EVENT)
{
filter.insert(eventIt->second.begin(), eventIt->second.end());
}
else
{
const std::string& eventName = eventIt->first;
const ItemIdSet& eventItems = eventIt->second;
for (ItemIdSet::const_iterator it = eventItems.begin();
it != eventItems.end(); ++it)
{
ItemEventMap::value_type itemEvent(*it, eventName);
if (itemEventMap.insert(itemEvent).second)
{
inputItemVec.push_back(*it);
}
}
}
}
const ItemIdSet& notRecInputSet = eventItemMap[RecommendSchema::NOT_REC_INPUT_EVENT];
excludeItems(notRecInputSet, inputItemVec);
excludeItems(notRecInputSet, itemRateMap);
return true;
}
} // namespace sf1r
<commit_msg>fix compile error under debug mode.<commit_after>#include "UserEventFilter.h"
#include "ItemFilter.h"
#include "PurchaseManager.h"
#include "CartManager.h"
#include "EventManager.h"
#include "RateManager.h"
#include <bundles/recommend/RecommendSchema.h>
#include <glog/logging.h>
namespace
{
using namespace sf1r;
void excludeItems(
const ItemIdSet& excludeItemSet,
std::vector<itemid_t>& inputItems
)
{
if (excludeItemSet.empty())
return;
std::vector<itemid_t> newInputItems;
for (std::vector<itemid_t>::const_iterator it = inputItems.begin();
it != inputItems.end(); ++it)
{
if (excludeItemSet.find(*it) == excludeItemSet.end())
{
newInputItems.push_back(*it);
}
}
newInputItems.swap(inputItems);
}
void excludeItems(
const ItemIdSet& excludeItemSet,
ItemRateMap& itemRateMap
)
{
if (excludeItemSet.empty())
return;
for (ItemRateMap::iterator it = itemRateMap.begin();
it != itemRateMap.end();)
{
if (excludeItemSet.find(it->first) == excludeItemSet.end())
{
++it;
}
else
{
itemRateMap.erase(it++);
}
}
}
}
namespace sf1r
{
UserEventFilter::UserEventFilter(
PurchaseManager& purchaseManager,
CartManager& cartManager,
EventManager& eventManager,
RateManager& rateManager
)
: purchaseManager_(purchaseManager)
, cartManager_(cartManager)
, eventManager_(eventManager)
, rateManager_(rateManager)
{
}
bool UserEventFilter::filter(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemFilter& filter
) const
{
assert(!userId.empty());
return (filterRateItem_(userId, filter)
&& filterPurchaseItem_(userId, filter)
&& filterCartItem_(userId, filter)
&& filterPreferenceItem_(userId, inputItemVec, filter));
}
bool UserEventFilter::filterRateItem_(
const std::string& userId,
ItemFilter& filter
) const
{
ItemRateMap itemRateMap;
if (! rateManager_.getItemRateMap(userId, itemRateMap))
{
LOG(ERROR) << "failed to get rates for user id " << userId;
return false;
}
for (ItemRateMap::const_iterator it = itemRateMap.begin();
it != itemRateMap.end(); ++it)
{
filter.insert(it->first);
}
return true;
}
bool UserEventFilter::filterPurchaseItem_(
const std::string& userId,
ItemFilter& filter
) const
{
ItemIdSet purchaseItemSet;
if (! purchaseManager_.getPurchaseItemSet(userId, purchaseItemSet))
{
LOG(ERROR) << "failed to get purchased items for user id " << userId;
return false;
}
filter.insert(purchaseItemSet.begin(), purchaseItemSet.end());
return true;
}
bool UserEventFilter::filterCartItem_(
const std::string& userId,
ItemFilter& filter
) const
{
std::vector<itemid_t> cartItemVec;
if (! cartManager_.getCart(userId, cartItemVec))
{
LOG(ERROR) << "failed to get shopping cart items for user id " << userId;
return false;
}
filter.insert(cartItemVec.begin(), cartItemVec.end());
return true;
}
bool UserEventFilter::filterPreferenceItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemFilter& filter
) const
{
EventManager::EventItemMap eventItemMap;
if (! eventManager_.getEvent(userId, eventItemMap))
{
LOG(ERROR) << "failed to get events for user id " << userId;
return false;
}
for (EventManager::EventItemMap::const_iterator it = eventItemMap.begin();
it != eventItemMap.end(); ++it)
{
filter.insert(it->second.begin(), it->second.end());
}
const ItemIdSet& notRecInputSet = eventItemMap[RecommendSchema::NOT_REC_INPUT_EVENT];
excludeItems(notRecInputSet, inputItemVec);
return true;
}
bool UserEventFilter::addUserEvent(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemRateMap& itemRateMap,
ItemEventMap& itemEventMap,
ItemFilter& filter
) const
{
assert(!userId.empty());
inputItemVec.clear();
return (addRateItem_(userId, itemRateMap, itemEventMap)
&& addPurchaseItem_(userId, inputItemVec, itemEventMap)
&& addCartItem_(userId, inputItemVec, itemEventMap)
&& addPreferenceItem_(userId, inputItemVec, itemRateMap, itemEventMap, filter));
}
bool UserEventFilter::addRateItem_(
const std::string& userId,
ItemRateMap& itemRateMap,
ItemEventMap& itemEventMap
) const
{
if (! rateManager_.getItemRateMap(userId, itemRateMap))
{
LOG(ERROR) << "failed to get rates for user id " << userId;
return false;
}
for (ItemRateMap::iterator it = itemRateMap.begin();
it != itemRateMap.end();)
{
ItemEventMap::value_type itemEvent(it->first, RecommendSchema::RATE_EVENT);
if (itemEventMap.insert(itemEvent).second)
{
++it;
}
else
{
itemRateMap.erase(it++);
}
}
return true;
}
bool UserEventFilter::addPurchaseItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemEventMap& itemEventMap
) const
{
ItemIdSet purchaseItemSet;
if (! purchaseManager_.getPurchaseItemSet(userId, purchaseItemSet))
{
LOG(ERROR) << "failed to get purchased items for user id " << userId;
return false;
}
for (ItemIdSet::const_iterator it = purchaseItemSet.begin();
it != purchaseItemSet.end(); ++it)
{
ItemEventMap::value_type itemEvent(*it, RecommendSchema::PURCHASE_EVENT);
if (itemEventMap.insert(itemEvent).second)
{
inputItemVec.push_back(*it);
}
}
return true;
}
bool UserEventFilter::addCartItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemEventMap& itemEventMap
) const
{
std::vector<itemid_t> cartItemVec;
if (! cartManager_.getCart(userId, cartItemVec))
{
LOG(ERROR) << "failed to get shopping cart items for user id " << userId;
return false;
}
for (std::vector<itemid_t>::const_iterator it = cartItemVec.begin();
it != cartItemVec.end(); ++it)
{
ItemEventMap::value_type itemEvent(*it, RecommendSchema::CART_EVENT);
if (itemEventMap.insert(itemEvent).second)
{
inputItemVec.push_back(*it);
}
}
return true;
}
bool UserEventFilter::addPreferenceItem_(
const std::string& userId,
std::vector<itemid_t>& inputItemVec,
ItemRateMap& itemRateMap,
ItemEventMap& itemEventMap,
ItemFilter& filter
) const
{
EventManager::EventItemMap eventItemMap;
if (! eventManager_.getEvent(userId, eventItemMap))
{
LOG(ERROR) << "failed to get events for user id " << userId;
return false;
}
for (EventManager::EventItemMap::const_iterator eventIt = eventItemMap.begin();
eventIt != eventItemMap.end(); ++eventIt)
{
if (eventIt->first == RecommendSchema::NOT_REC_RESULT_EVENT
|| eventIt->first == RecommendSchema::NOT_REC_INPUT_EVENT)
{
filter.insert(eventIt->second.begin(), eventIt->second.end());
}
else
{
const std::string& eventName = eventIt->first;
const ItemIdSet& eventItems = eventIt->second;
for (ItemIdSet::const_iterator it = eventItems.begin();
it != eventItems.end(); ++it)
{
ItemEventMap::value_type itemEvent(*it, eventName);
if (itemEventMap.insert(itemEvent).second)
{
inputItemVec.push_back(*it);
}
}
}
}
const ItemIdSet& notRecInputSet = eventItemMap[RecommendSchema::NOT_REC_INPUT_EVENT];
excludeItems(notRecInputSet, inputItemVec);
excludeItems(notRecInputSet, itemRateMap);
return true;
}
} // namespace sf1r
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: drawdlg.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2007-05-10 16:22:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif
#include <svx/xtable.hxx>
#include "view.hxx"
#include "wrtsh.hxx"
#include "docsh.hxx"
#include "cmdid.h"
#include "drawsh.hxx"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDrawShell::ExecDrawDlg(SfxRequest& rReq)
{
SwWrtShell* pSh = &GetShell();
SdrView* pView = pSh->GetDrawView();
SdrModel* pDoc = pView->GetModel();
Window* pWin = GetView().GetWindow();
BOOL bChanged = pDoc->IsChanged();
pDoc->SetChanged(FALSE);
SfxItemSet aNewAttr( pDoc->GetItemPool() );
pView->GetAttributes( aNewAttr );
GetView().NoRotate();
switch (rReq.GetSlot())
{
case FN_DRAWTEXT_ATTR_DLG:
{
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if ( pFact )
{
SfxAbstractTabDialog *pDlg = pFact->CreateTextTabDialog( NULL, &aNewAttr, RID_SVXDLG_TEXT, pView );
USHORT nResult = pDlg->Execute();
if (nResult == RET_OK)
{
if (pView->AreObjectsMarked())
{
pSh->StartAction();
pView->SetAttributes(*pDlg->GetOutputItemSet());
rReq.Done(*(pDlg->GetOutputItemSet()));
pSh->EndAction();
}
}
delete( pDlg );
}
}
break;
case SID_ATTRIBUTES_AREA:
{
BOOL bHasMarked = pView->AreObjectsMarked();
//CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, &aNewAttr, pDoc, pView );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
&aNewAttr,
pDoc,
RID_SVXDLG_AREA,
pView);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
const SvxColorTableItem* pColorItem = (const SvxColorTableItem*)
GetView().GetDocShell()->GetItem(SID_COLOR_TABLE);
if(pColorItem->GetColorTable() == XColorTable::GetStdColorTable())
pDlg->DontDeleteColorTable();
if (pDlg->Execute() == RET_OK)
{
pSh->StartAction();
if (bHasMarked)
pView->SetAttributes(*pDlg->GetOutputItemSet());
else
pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
pSh->EndAction();
static USHORT __READONLY_DATA aInval[] =
{
SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, 0
};
SfxBindings &rBnd = GetView().GetViewFrame()->GetBindings();
rBnd.Invalidate(aInval);
rBnd.Update(SID_ATTR_FILL_STYLE);
rBnd.Update(SID_ATTR_FILL_COLOR);
}
delete pDlg;
}
break;
case SID_ATTRIBUTES_LINE:
{
BOOL bHasMarked = pView->AreObjectsMarked();
const SdrObject* pObj = NULL;
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
//CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog(NULL, &aNewAttr,
//CHINA001 pDoc, pObj, bHasMarked);
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog( NULL,
&aNewAttr,
pDoc,
RID_SVXDLG_LINE,
pObj,
bHasMarked);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
if (pDlg->Execute() == RET_OK)
{
pSh->StartAction();
if(bHasMarked)
pView->SetAttrToMarked(*pDlg->GetOutputItemSet(), FALSE);
else
pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
pSh->EndAction();
static USHORT __READONLY_DATA aInval[] =
{
SID_ATTR_LINE_STYLE, SID_ATTR_LINE_WIDTH,
SID_ATTR_LINE_COLOR, 0
};
GetView().GetViewFrame()->GetBindings().Invalidate(aInval);
}
delete pDlg;
}
break;
default:
break;
}
if (pDoc->IsChanged())
GetShell().SetModified();
else
if (bChanged)
pDoc->SetChanged(TRUE);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDrawShell::ExecDrawAttrArgs(SfxRequest& rReq)
{
SwWrtShell* pSh = &GetShell();
SdrView* pView = pSh->GetDrawView();
const SfxItemSet* pArgs = rReq.GetArgs();
BOOL bChanged = pView->GetModel()->IsChanged();
pView->GetModel()->SetChanged(FALSE);
GetView().NoRotate();
if (pArgs)
{
if(pView->AreObjectsMarked())
pView->SetAttrToMarked(*rReq.GetArgs(), FALSE);
else
pView->SetDefaultAttr(*rReq.GetArgs(), FALSE);
}
else
{
SfxDispatcher* pDis = pSh->GetView().GetViewFrame()->GetDispatcher();
switch (rReq.GetSlot())
{
case SID_ATTR_FILL_STYLE:
case SID_ATTR_FILL_COLOR:
case SID_ATTR_FILL_GRADIENT:
case SID_ATTR_FILL_HATCH:
case SID_ATTR_FILL_BITMAP:
pDis->Execute(SID_ATTRIBUTES_AREA, FALSE);
break;
case SID_ATTR_LINE_STYLE:
case SID_ATTR_LINE_DASH:
case SID_ATTR_LINE_WIDTH:
case SID_ATTR_LINE_COLOR:
pDis->Execute(SID_ATTRIBUTES_LINE, FALSE);
break;
}
}
if (pView->GetModel()->IsChanged())
GetShell().SetModified();
else
if (bChanged)
pView->GetModel()->SetChanged(TRUE);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDrawShell::GetDrawAttrState(SfxItemSet& rSet)
{
SdrView* pSdrView = GetShell().GetDrawView();
if (pSdrView->AreObjectsMarked())
{
BOOL bDisable = Disable( rSet );
if( !bDisable )
pSdrView->GetAttributes( rSet );
}
else
rSet.Put(pSdrView->GetDefaultAttr());
}
<commit_msg>INTEGRATION: CWS swwarnings (1.11.222); FILE MERGED 2007/05/29 13:59:03 os 1.11.222.3: RESYNC: (1.11-1.13); FILE MERGED 2007/04/13 12:18:12 tl 1.11.222.2: #i69287# binfilter related comments removed 2007/03/26 12:09:17 tl 1.11.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: drawdlg.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:26:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif
#include <svx/xtable.hxx>
#include "view.hxx"
#include "wrtsh.hxx"
#include "docsh.hxx"
#include "cmdid.h"
#include "drawsh.hxx"
#include <svx/svxdlg.hxx>
#include <svx/dialogs.hrc>
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDrawShell::ExecDrawDlg(SfxRequest& rReq)
{
SwWrtShell* pSh = &GetShell();
SdrView* pView = pSh->GetDrawView();
SdrModel* pDoc = pView->GetModel();
BOOL bChanged = pDoc->IsChanged();
pDoc->SetChanged(FALSE);
SfxItemSet aNewAttr( pDoc->GetItemPool() );
pView->GetAttributes( aNewAttr );
GetView().NoRotate();
switch (rReq.GetSlot())
{
case FN_DRAWTEXT_ATTR_DLG:
{
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if ( pFact )
{
SfxAbstractTabDialog *pDlg = pFact->CreateTextTabDialog( NULL, &aNewAttr, RID_SVXDLG_TEXT, pView );
USHORT nResult = pDlg->Execute();
if (nResult == RET_OK)
{
if (pView->AreObjectsMarked())
{
pSh->StartAction();
pView->SetAttributes(*pDlg->GetOutputItemSet());
rReq.Done(*(pDlg->GetOutputItemSet()));
pSh->EndAction();
}
}
delete( pDlg );
}
}
break;
case SID_ATTRIBUTES_AREA:
{
BOOL bHasMarked = pView->AreObjectsMarked();
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");
AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
&aNewAttr,
pDoc,
RID_SVXDLG_AREA,
pView);
DBG_ASSERT(pDlg, "Dialogdiet fail!");
const SvxColorTableItem* pColorItem = (const SvxColorTableItem*)
GetView().GetDocShell()->GetItem(SID_COLOR_TABLE);
if(pColorItem->GetColorTable() == XColorTable::GetStdColorTable())
pDlg->DontDeleteColorTable();
if (pDlg->Execute() == RET_OK)
{
pSh->StartAction();
if (bHasMarked)
pView->SetAttributes(*pDlg->GetOutputItemSet());
else
pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
pSh->EndAction();
static USHORT __READONLY_DATA aInval[] =
{
SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, 0
};
SfxBindings &rBnd = GetView().GetViewFrame()->GetBindings();
rBnd.Invalidate(aInval);
rBnd.Update(SID_ATTR_FILL_STYLE);
rBnd.Update(SID_ATTR_FILL_COLOR);
}
delete pDlg;
}
break;
case SID_ATTRIBUTES_LINE:
{
BOOL bHasMarked = pView->AreObjectsMarked();
const SdrObject* pObj = NULL;
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");
SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog( NULL,
&aNewAttr,
pDoc,
RID_SVXDLG_LINE,
pObj,
bHasMarked);
DBG_ASSERT(pDlg, "Dialogdiet fail!");
if (pDlg->Execute() == RET_OK)
{
pSh->StartAction();
if(bHasMarked)
pView->SetAttrToMarked(*pDlg->GetOutputItemSet(), FALSE);
else
pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
pSh->EndAction();
static USHORT __READONLY_DATA aInval[] =
{
SID_ATTR_LINE_STYLE, SID_ATTR_LINE_WIDTH,
SID_ATTR_LINE_COLOR, 0
};
GetView().GetViewFrame()->GetBindings().Invalidate(aInval);
}
delete pDlg;
}
break;
default:
break;
}
if (pDoc->IsChanged())
GetShell().SetModified();
else
if (bChanged)
pDoc->SetChanged(TRUE);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDrawShell::ExecDrawAttrArgs(SfxRequest& rReq)
{
SwWrtShell* pSh = &GetShell();
SdrView* pView = pSh->GetDrawView();
const SfxItemSet* pArgs = rReq.GetArgs();
BOOL bChanged = pView->GetModel()->IsChanged();
pView->GetModel()->SetChanged(FALSE);
GetView().NoRotate();
if (pArgs)
{
if(pView->AreObjectsMarked())
pView->SetAttrToMarked(*rReq.GetArgs(), FALSE);
else
pView->SetDefaultAttr(*rReq.GetArgs(), FALSE);
}
else
{
SfxDispatcher* pDis = pSh->GetView().GetViewFrame()->GetDispatcher();
switch (rReq.GetSlot())
{
case SID_ATTR_FILL_STYLE:
case SID_ATTR_FILL_COLOR:
case SID_ATTR_FILL_GRADIENT:
case SID_ATTR_FILL_HATCH:
case SID_ATTR_FILL_BITMAP:
pDis->Execute(SID_ATTRIBUTES_AREA, FALSE);
break;
case SID_ATTR_LINE_STYLE:
case SID_ATTR_LINE_DASH:
case SID_ATTR_LINE_WIDTH:
case SID_ATTR_LINE_COLOR:
pDis->Execute(SID_ATTRIBUTES_LINE, FALSE);
break;
}
}
if (pView->GetModel()->IsChanged())
GetShell().SetModified();
else
if (bChanged)
pView->GetModel()->SetChanged(TRUE);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwDrawShell::GetDrawAttrState(SfxItemSet& rSet)
{
SdrView* pSdrView = GetShell().GetDrawView();
if (pSdrView->AreObjectsMarked())
{
BOOL bDisable = Disable( rSet );
if( !bDisable )
pSdrView->GetAttributes( rSet );
}
else
rSet.Put(pSdrView->GetDefaultAttr());
}
<|endoftext|> |
<commit_before><commit_msg>fix fdo#40496: don't reset RES_PARATR_ADJUST & RES_FRAMEDIR attributes.<commit_after><|endoftext|> |
<commit_before>/*
* Vulkan Model loader using ASSIMP
*
* Copyright(C) 2016-2017 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license(MIT) (http://opensource.org/licenses/MIT)
*/
#pragma once
#include <stdlib.h>
#include <string>
#include <fstream>
#include <vector>
#include "vulkan/vulkan.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "VulkanDevice.hpp"
#include "VulkanBuffer.hpp"
#if defined(__ANDROID__)
#include <android/asset_manager.h>
#endif
namespace vks
{
/** @brief Vertex layout components */
typedef enum Component {
VERTEX_COMPONENT_POSITION = 0x0,
VERTEX_COMPONENT_NORMAL = 0x1,
VERTEX_COMPONENT_COLOR = 0x2,
VERTEX_COMPONENT_UV = 0x3,
VERTEX_COMPONENT_TANGENT = 0x4,
VERTEX_COMPONENT_BITANGENT = 0x5,
VERTEX_COMPONENT_DUMMY_FLOAT = 0x6,
VERTEX_COMPONENT_DUMMY_VEC4 = 0x7
} Component;
/** @brief Stores vertex layout components for model loading and Vulkan vertex input and atribute bindings */
struct VertexLayout {
public:
/** @brief Components used to generate vertices from */
std::vector<Component> components;
VertexLayout(std::vector<Component> components)
{
this->components = std::move(components);
}
uint32_t stride()
{
uint32_t res = 0;
for (auto& component : components)
{
switch (component)
{
case VERTEX_COMPONENT_UV:
res += 2 * sizeof(float);
break;
case VERTEX_COMPONENT_DUMMY_FLOAT:
res += sizeof(float);
break;
case VERTEX_COMPONENT_DUMMY_VEC4:
res += 4 * sizeof(float);
break;
default:
// All components except the ones listed above are made up of 3 floats
res += 3 * sizeof(float);
}
}
return res;
}
};
/** @brief Used to parametrize model loading */
struct ModelCreateInfo {
glm::vec3 center;
glm::vec3 scale;
glm::vec2 uvscale;
ModelCreateInfo() {};
ModelCreateInfo(glm::vec3 scale, glm::vec2 uvscale, glm::vec3 center)
{
this->center = center;
this->scale = scale;
this->uvscale = uvscale;
}
ModelCreateInfo(float scale, float uvscale, float center)
{
this->center = glm::vec3(center);
this->scale = glm::vec3(scale);
this->uvscale = glm::vec2(uvscale);
}
};
struct Model {
VkDevice device = nullptr;
vks::Buffer vertices;
vks::Buffer indices;
uint32_t indexCount = 0;
uint32_t vertexCount = 0;
/** @brief Stores vertex and index base and counts for each part of a model */
struct ModelPart {
uint32_t vertexBase;
uint32_t vertexCount;
uint32_t indexBase;
uint32_t indexCount;
};
std::vector<ModelPart> parts;
static const int defaultFlags = aiProcess_FlipWindingOrder | aiProcess_Triangulate | aiProcess_PreTransformVertices | aiProcess_CalcTangentSpace | aiProcess_GenSmoothNormals;
struct Dimension
{
glm::vec3 min = glm::vec3(FLT_MAX);
glm::vec3 max = glm::vec3(-FLT_MAX);
glm::vec3 size;
} dim;
/** @brief Release all Vulkan resources of this model */
void destroy()
{
assert(device);
vkDestroyBuffer(device, vertices.buffer, nullptr);
vkFreeMemory(device, vertices.memory, nullptr);
if (indices.buffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, indices.buffer, nullptr);
vkFreeMemory(device, indices.memory, nullptr);
}
}
/**
* Loads a 3D model from a file into Vulkan buffers
*
* @param device Pointer to the Vulkan device used to generated the vertex and index buffers on
* @param filename File to load (must be a model format supported by ASSIMP)
* @param layout Vertex layout components (position, normals, tangents, etc.)
* @param createInfo MeshCreateInfo structure for load time settings like scale, center, etc.
* @param copyQueue Queue used for the memory staging copy commands (must support transfer)
* @param (Optional) flags ASSIMP model loading flags
*/
bool loadFromFile(const std::string& filename, vks::VertexLayout layout, vks::ModelCreateInfo *createInfo, vks::VulkanDevice *device, VkQueue copyQueue, const int flags = defaultFlags)
{
this->device = device->logicalDevice;
Assimp::Importer Importer;
const aiScene* pScene;
// Load file
#if defined(__ANDROID__)
// Meshes are stored inside the apk on Android (compressed)
// So they need to be loaded via the asset manager
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager, filename.c_str(), AASSET_MODE_STREAMING);
if (!asset) {
LOGE("Could not load mesh from \"%s\"!", filename.c_str());
return false;
}
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
void *meshData = malloc(size);
AAsset_read(asset, meshData, size);
AAsset_close(asset);
pScene = Importer.ReadFileFromMemory(meshData, size, flags);
free(meshData);
#else
pScene = Importer.ReadFile(filename.c_str(), flags);
#endif
if (pScene)
{
parts.clear();
parts.resize(pScene->mNumMeshes);
glm::vec3 scale(1.0f);
glm::vec2 uvscale(1.0f);
glm::vec3 center(0.0f);
if (createInfo)
{
scale = createInfo->scale;
uvscale = createInfo->uvscale;
center = createInfo->center;
}
std::vector<float> vertexBuffer;
std::vector<uint32_t> indexBuffer;
vertexCount = 0;
indexCount = 0;
// Load meshes
for (unsigned int i = 0; i < pScene->mNumMeshes; i++)
{
const aiMesh* paiMesh = pScene->mMeshes[i];
parts[i] = {};
parts[i].vertexBase = vertexCount;
parts[i].indexBase = indexCount;
vertexCount += pScene->mMeshes[i]->mNumVertices;
aiColor3D pColor(0.f, 0.f, 0.f);
pScene->mMaterials[paiMesh->mMaterialIndex]->Get(AI_MATKEY_COLOR_DIFFUSE, pColor);
const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
for (unsigned int j = 0; j < paiMesh->mNumVertices; j++)
{
const aiVector3D* pPos = &(paiMesh->mVertices[j]);
const aiVector3D* pNormal = &(paiMesh->mNormals[j]);
const aiVector3D* pTexCoord = (paiMesh->HasTextureCoords(0)) ? &(paiMesh->mTextureCoords[0][j]) : &Zero3D;
const aiVector3D* pTangent = (paiMesh->HasTangentsAndBitangents()) ? &(paiMesh->mTangents[j]) : &Zero3D;
const aiVector3D* pBiTangent = (paiMesh->HasTangentsAndBitangents()) ? &(paiMesh->mBitangents[j]) : &Zero3D;
for (auto& component : layout.components)
{
switch (component) {
case VERTEX_COMPONENT_POSITION:
vertexBuffer.push_back(pPos->x * scale.x + center.x);
vertexBuffer.push_back(-pPos->y * scale.y + center.y);
vertexBuffer.push_back(pPos->z * scale.z + center.z);
break;
case VERTEX_COMPONENT_NORMAL:
vertexBuffer.push_back(pNormal->x);
vertexBuffer.push_back(-pNormal->y);
vertexBuffer.push_back(pNormal->z);
break;
case VERTEX_COMPONENT_UV:
vertexBuffer.push_back(pTexCoord->x * uvscale.s);
vertexBuffer.push_back(pTexCoord->y * uvscale.t);
break;
case VERTEX_COMPONENT_COLOR:
vertexBuffer.push_back(pColor.r);
vertexBuffer.push_back(pColor.g);
vertexBuffer.push_back(pColor.b);
break;
case VERTEX_COMPONENT_TANGENT:
vertexBuffer.push_back(pTangent->x);
vertexBuffer.push_back(pTangent->y);
vertexBuffer.push_back(pTangent->z);
break;
case VERTEX_COMPONENT_BITANGENT:
vertexBuffer.push_back(pBiTangent->x);
vertexBuffer.push_back(pBiTangent->y);
vertexBuffer.push_back(pBiTangent->z);
break;
// Dummy components for padding
case VERTEX_COMPONENT_DUMMY_FLOAT:
vertexBuffer.push_back(0.0f);
break;
case VERTEX_COMPONENT_DUMMY_VEC4:
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
break;
};
}
dim.max.x = fmax(pPos->x, dim.max.x);
dim.max.y = fmax(pPos->y, dim.max.y);
dim.max.z = fmax(pPos->z, dim.max.z);
dim.min.x = fmin(pPos->x, dim.min.x);
dim.min.y = fmin(pPos->y, dim.min.y);
dim.min.z = fmin(pPos->z, dim.min.z);
}
dim.size = dim.max - dim.min;
parts[i].vertexCount = paiMesh->mNumVertices;
uint32_t indexBase = static_cast<uint32_t>(indexBuffer.size());
for (unsigned int j = 0; j < paiMesh->mNumFaces; j++)
{
const aiFace& Face = paiMesh->mFaces[j];
if (Face.mNumIndices != 3)
continue;
indexBuffer.push_back(indexBase + Face.mIndices[0]);
indexBuffer.push_back(indexBase + Face.mIndices[1]);
indexBuffer.push_back(indexBase + Face.mIndices[2]);
parts[i].indexCount += 3;
indexCount += 3;
}
}
uint32_t vBufferSize = static_cast<uint32_t>(vertexBuffer.size()) * sizeof(float);
uint32_t iBufferSize = static_cast<uint32_t>(indexBuffer.size()) * sizeof(uint32_t);
// Use staging buffer to move vertex and index buffer to device local memory
// Create staging buffers
vks::Buffer vertexStaging, indexStaging;
// Vertex buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
&vertexStaging,
vBufferSize,
vertexBuffer.data()));
// Index buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
&indexStaging,
iBufferSize,
indexBuffer.data()));
// Create device local target buffers
// Vertex buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&vertices,
vBufferSize));
// Index buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&indices,
iBufferSize));
// Copy from staging buffers
VkCommandBuffer copyCmd = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
VkBufferCopy copyRegion{};
copyRegion.size = vertices.size;
vkCmdCopyBuffer(copyCmd, vertexStaging.buffer, vertices.buffer, 1, ©Region);
copyRegion.size = indices.size;
vkCmdCopyBuffer(copyCmd, indexStaging.buffer, indices.buffer, 1, ©Region);
device->flushCommandBuffer(copyCmd, copyQueue);
// Destroy staging resources
vkDestroyBuffer(device->logicalDevice, vertexStaging.buffer, nullptr);
vkFreeMemory(device->logicalDevice, vertexStaging.memory, nullptr);
vkDestroyBuffer(device->logicalDevice, indexStaging.buffer, nullptr);
vkFreeMemory(device->logicalDevice, indexStaging.memory, nullptr);
return true;
}
else
{
printf("Error parsing '%s': '%s'\n", filename.c_str(), Importer.GetErrorString());
#if defined(__ANDROID__)
LOGE("Error parsing '%s': '%s'", filename.c_str(), Importer.GetErrorString());
#endif
return false;
}
};
/**
* Loads a 3D model from a file into Vulkan buffers
*
* @param device Pointer to the Vulkan device used to generated the vertex and index buffers on
* @param filename File to load (must be a model format supported by ASSIMP)
* @param layout Vertex layout components (position, normals, tangents, etc.)
* @param scale Load time scene scale
* @param copyQueue Queue used for the memory staging copy commands (must support transfer)
* @param (Optional) flags ASSIMP model loading flags
*/
bool loadFromFile(const std::string& filename, vks::VertexLayout layout, float scale, vks::VulkanDevice *device, VkQueue copyQueue, const int flags = defaultFlags)
{
vks::ModelCreateInfo modelCreateInfo(scale, 1.0f, 0.0f);
return loadFromFile(filename, layout, &modelCreateInfo, device, copyQueue, flags);
}
};
};<commit_msg> Request memory with VK_MEMORY_PROPERTY_HOST_COHERENT_BIT enabled for model staging buffers.<commit_after>/*
* Vulkan Model loader using ASSIMP
*
* Copyright(C) 2016-2017 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license(MIT) (http://opensource.org/licenses/MIT)
*/
#pragma once
#include <stdlib.h>
#include <string>
#include <fstream>
#include <vector>
#include "vulkan/vulkan.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "VulkanDevice.hpp"
#include "VulkanBuffer.hpp"
#if defined(__ANDROID__)
#include <android/asset_manager.h>
#endif
namespace vks
{
/** @brief Vertex layout components */
typedef enum Component {
VERTEX_COMPONENT_POSITION = 0x0,
VERTEX_COMPONENT_NORMAL = 0x1,
VERTEX_COMPONENT_COLOR = 0x2,
VERTEX_COMPONENT_UV = 0x3,
VERTEX_COMPONENT_TANGENT = 0x4,
VERTEX_COMPONENT_BITANGENT = 0x5,
VERTEX_COMPONENT_DUMMY_FLOAT = 0x6,
VERTEX_COMPONENT_DUMMY_VEC4 = 0x7
} Component;
/** @brief Stores vertex layout components for model loading and Vulkan vertex input and atribute bindings */
struct VertexLayout {
public:
/** @brief Components used to generate vertices from */
std::vector<Component> components;
VertexLayout(std::vector<Component> components)
{
this->components = std::move(components);
}
uint32_t stride()
{
uint32_t res = 0;
for (auto& component : components)
{
switch (component)
{
case VERTEX_COMPONENT_UV:
res += 2 * sizeof(float);
break;
case VERTEX_COMPONENT_DUMMY_FLOAT:
res += sizeof(float);
break;
case VERTEX_COMPONENT_DUMMY_VEC4:
res += 4 * sizeof(float);
break;
default:
// All components except the ones listed above are made up of 3 floats
res += 3 * sizeof(float);
}
}
return res;
}
};
/** @brief Used to parametrize model loading */
struct ModelCreateInfo {
glm::vec3 center;
glm::vec3 scale;
glm::vec2 uvscale;
ModelCreateInfo() {};
ModelCreateInfo(glm::vec3 scale, glm::vec2 uvscale, glm::vec3 center)
{
this->center = center;
this->scale = scale;
this->uvscale = uvscale;
}
ModelCreateInfo(float scale, float uvscale, float center)
{
this->center = glm::vec3(center);
this->scale = glm::vec3(scale);
this->uvscale = glm::vec2(uvscale);
}
};
struct Model {
VkDevice device = nullptr;
vks::Buffer vertices;
vks::Buffer indices;
uint32_t indexCount = 0;
uint32_t vertexCount = 0;
/** @brief Stores vertex and index base and counts for each part of a model */
struct ModelPart {
uint32_t vertexBase;
uint32_t vertexCount;
uint32_t indexBase;
uint32_t indexCount;
};
std::vector<ModelPart> parts;
static const int defaultFlags = aiProcess_FlipWindingOrder | aiProcess_Triangulate | aiProcess_PreTransformVertices | aiProcess_CalcTangentSpace | aiProcess_GenSmoothNormals;
struct Dimension
{
glm::vec3 min = glm::vec3(FLT_MAX);
glm::vec3 max = glm::vec3(-FLT_MAX);
glm::vec3 size;
} dim;
/** @brief Release all Vulkan resources of this model */
void destroy()
{
assert(device);
vkDestroyBuffer(device, vertices.buffer, nullptr);
vkFreeMemory(device, vertices.memory, nullptr);
if (indices.buffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, indices.buffer, nullptr);
vkFreeMemory(device, indices.memory, nullptr);
}
}
/**
* Loads a 3D model from a file into Vulkan buffers
*
* @param device Pointer to the Vulkan device used to generated the vertex and index buffers on
* @param filename File to load (must be a model format supported by ASSIMP)
* @param layout Vertex layout components (position, normals, tangents, etc.)
* @param createInfo MeshCreateInfo structure for load time settings like scale, center, etc.
* @param copyQueue Queue used for the memory staging copy commands (must support transfer)
* @param (Optional) flags ASSIMP model loading flags
*/
bool loadFromFile(const std::string& filename, vks::VertexLayout layout, vks::ModelCreateInfo *createInfo, vks::VulkanDevice *device, VkQueue copyQueue, const int flags = defaultFlags)
{
this->device = device->logicalDevice;
Assimp::Importer Importer;
const aiScene* pScene;
// Load file
#if defined(__ANDROID__)
// Meshes are stored inside the apk on Android (compressed)
// So they need to be loaded via the asset manager
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager, filename.c_str(), AASSET_MODE_STREAMING);
if (!asset) {
LOGE("Could not load mesh from \"%s\"!", filename.c_str());
return false;
}
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
void *meshData = malloc(size);
AAsset_read(asset, meshData, size);
AAsset_close(asset);
pScene = Importer.ReadFileFromMemory(meshData, size, flags);
free(meshData);
#else
pScene = Importer.ReadFile(filename.c_str(), flags);
#endif
if (pScene)
{
parts.clear();
parts.resize(pScene->mNumMeshes);
glm::vec3 scale(1.0f);
glm::vec2 uvscale(1.0f);
glm::vec3 center(0.0f);
if (createInfo)
{
scale = createInfo->scale;
uvscale = createInfo->uvscale;
center = createInfo->center;
}
std::vector<float> vertexBuffer;
std::vector<uint32_t> indexBuffer;
vertexCount = 0;
indexCount = 0;
// Load meshes
for (unsigned int i = 0; i < pScene->mNumMeshes; i++)
{
const aiMesh* paiMesh = pScene->mMeshes[i];
parts[i] = {};
parts[i].vertexBase = vertexCount;
parts[i].indexBase = indexCount;
vertexCount += pScene->mMeshes[i]->mNumVertices;
aiColor3D pColor(0.f, 0.f, 0.f);
pScene->mMaterials[paiMesh->mMaterialIndex]->Get(AI_MATKEY_COLOR_DIFFUSE, pColor);
const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
for (unsigned int j = 0; j < paiMesh->mNumVertices; j++)
{
const aiVector3D* pPos = &(paiMesh->mVertices[j]);
const aiVector3D* pNormal = &(paiMesh->mNormals[j]);
const aiVector3D* pTexCoord = (paiMesh->HasTextureCoords(0)) ? &(paiMesh->mTextureCoords[0][j]) : &Zero3D;
const aiVector3D* pTangent = (paiMesh->HasTangentsAndBitangents()) ? &(paiMesh->mTangents[j]) : &Zero3D;
const aiVector3D* pBiTangent = (paiMesh->HasTangentsAndBitangents()) ? &(paiMesh->mBitangents[j]) : &Zero3D;
for (auto& component : layout.components)
{
switch (component) {
case VERTEX_COMPONENT_POSITION:
vertexBuffer.push_back(pPos->x * scale.x + center.x);
vertexBuffer.push_back(-pPos->y * scale.y + center.y);
vertexBuffer.push_back(pPos->z * scale.z + center.z);
break;
case VERTEX_COMPONENT_NORMAL:
vertexBuffer.push_back(pNormal->x);
vertexBuffer.push_back(-pNormal->y);
vertexBuffer.push_back(pNormal->z);
break;
case VERTEX_COMPONENT_UV:
vertexBuffer.push_back(pTexCoord->x * uvscale.s);
vertexBuffer.push_back(pTexCoord->y * uvscale.t);
break;
case VERTEX_COMPONENT_COLOR:
vertexBuffer.push_back(pColor.r);
vertexBuffer.push_back(pColor.g);
vertexBuffer.push_back(pColor.b);
break;
case VERTEX_COMPONENT_TANGENT:
vertexBuffer.push_back(pTangent->x);
vertexBuffer.push_back(pTangent->y);
vertexBuffer.push_back(pTangent->z);
break;
case VERTEX_COMPONENT_BITANGENT:
vertexBuffer.push_back(pBiTangent->x);
vertexBuffer.push_back(pBiTangent->y);
vertexBuffer.push_back(pBiTangent->z);
break;
// Dummy components for padding
case VERTEX_COMPONENT_DUMMY_FLOAT:
vertexBuffer.push_back(0.0f);
break;
case VERTEX_COMPONENT_DUMMY_VEC4:
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
break;
};
}
dim.max.x = fmax(pPos->x, dim.max.x);
dim.max.y = fmax(pPos->y, dim.max.y);
dim.max.z = fmax(pPos->z, dim.max.z);
dim.min.x = fmin(pPos->x, dim.min.x);
dim.min.y = fmin(pPos->y, dim.min.y);
dim.min.z = fmin(pPos->z, dim.min.z);
}
dim.size = dim.max - dim.min;
parts[i].vertexCount = paiMesh->mNumVertices;
uint32_t indexBase = static_cast<uint32_t>(indexBuffer.size());
for (unsigned int j = 0; j < paiMesh->mNumFaces; j++)
{
const aiFace& Face = paiMesh->mFaces[j];
if (Face.mNumIndices != 3)
continue;
indexBuffer.push_back(indexBase + Face.mIndices[0]);
indexBuffer.push_back(indexBase + Face.mIndices[1]);
indexBuffer.push_back(indexBase + Face.mIndices[2]);
parts[i].indexCount += 3;
indexCount += 3;
}
}
uint32_t vBufferSize = static_cast<uint32_t>(vertexBuffer.size()) * sizeof(float);
uint32_t iBufferSize = static_cast<uint32_t>(indexBuffer.size()) * sizeof(uint32_t);
// Use staging buffer to move vertex and index buffer to device local memory
// Create staging buffers
vks::Buffer vertexStaging, indexStaging;
// Vertex buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&vertexStaging,
vBufferSize,
vertexBuffer.data()));
// Index buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&indexStaging,
iBufferSize,
indexBuffer.data()));
// Create device local target buffers
// Vertex buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&vertices,
vBufferSize));
// Index buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&indices,
iBufferSize));
// Copy from staging buffers
VkCommandBuffer copyCmd = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
VkBufferCopy copyRegion{};
copyRegion.size = vertices.size;
vkCmdCopyBuffer(copyCmd, vertexStaging.buffer, vertices.buffer, 1, ©Region);
copyRegion.size = indices.size;
vkCmdCopyBuffer(copyCmd, indexStaging.buffer, indices.buffer, 1, ©Region);
device->flushCommandBuffer(copyCmd, copyQueue);
// Destroy staging resources
vkDestroyBuffer(device->logicalDevice, vertexStaging.buffer, nullptr);
vkFreeMemory(device->logicalDevice, vertexStaging.memory, nullptr);
vkDestroyBuffer(device->logicalDevice, indexStaging.buffer, nullptr);
vkFreeMemory(device->logicalDevice, indexStaging.memory, nullptr);
return true;
}
else
{
printf("Error parsing '%s': '%s'\n", filename.c_str(), Importer.GetErrorString());
#if defined(__ANDROID__)
LOGE("Error parsing '%s': '%s'", filename.c_str(), Importer.GetErrorString());
#endif
return false;
}
};
/**
* Loads a 3D model from a file into Vulkan buffers
*
* @param device Pointer to the Vulkan device used to generated the vertex and index buffers on
* @param filename File to load (must be a model format supported by ASSIMP)
* @param layout Vertex layout components (position, normals, tangents, etc.)
* @param scale Load time scene scale
* @param copyQueue Queue used for the memory staging copy commands (must support transfer)
* @param (Optional) flags ASSIMP model loading flags
*/
bool loadFromFile(const std::string& filename, vks::VertexLayout layout, float scale, vks::VulkanDevice *device, VkQueue copyQueue, const int flags = defaultFlags)
{
vks::ModelCreateInfo modelCreateInfo(scale, 1.0f, 0.0f);
return loadFromFile(filename, layout, &modelCreateInfo, device, copyQueue, flags);
}
};
};<|endoftext|> |
<commit_before><commit_msg>MessageLoop: use dynamic_annotations.h & RunningOnValgrind instead of valgrind.h & RUNNING_ON_VALGRIND This way we'll be able to delete all tasks on Windows under Dr. Memory TEST=trybots Review URL: http://codereview.chromium.org/6073004<commit_after><|endoftext|> |
<commit_before>/* TimeManager.cpp
*
* Kubo Ryosuke
*/
#include "TimeManager.h"
#include "core/def.h"
#include "logger/Logger.h"
#include <cassert>
#define ENABLE_EASY_LOG 1
namespace sunfish {
void TimeManager::init() {
_depth = 0;
}
void TimeManager::nextDepth() {
_depth++;
assert(_depth < Tree::StackSize);
}
void TimeManager::startDepth() {
_stack[_depth].firstMove = Move::empty();
_stack[_depth].firstValue = -Value::Inf;
}
void TimeManager::addMove(Move move, Value value) {
if (value > _stack[_depth].firstValue) {
_stack[_depth].firstMove = move;
_stack[_depth].firstValue = value;
}
}
bool TimeManager::isEasy(double limit, double elapsed) {
CONSTEXPR int easyDepth = 5;
if (_depth <= easyDepth) {
return false;
}
const auto& easy = _stack[_depth-easyDepth];
const auto& prev = _stack[_depth-1];
const auto& curr = _stack[_depth];
limit = std::min(limit, 3600.0);
if (elapsed < std::max(limit * 0.02, 3.0)) {
return false;
}
double r = elapsed / std::max(limit * 0.25, 3.0);
#if ENABLE_EASY_LOG
{
int easyDiff = curr.firstValue.int32() - easy.firstValue.int32();
int prevDiff = curr.firstValue.int32() - prev.firstValue.int32();
int isSame = curr.firstMove == easy.firstMove ? 1 : 0;
Loggers::message << "time_manager," << r << ',' << easyDiff << ',' << prevDiff << ',' << isSame << ',';
}
#endif
if (curr.firstValue >= easy.firstValue - (256 * r) && curr.firstValue <= easy.firstValue + (512 * r) &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove && curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue - (128 * r) && curr.firstValue <= prev.firstValue + (512 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove &&
curr.firstValue >= easy.firstValue - (128 * r) && curr.firstValue <= easy.firstValue + (512 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
return false;
}
}
<commit_msg>Update TimeManager<commit_after>/* TimeManager.cpp
*
* Kubo Ryosuke
*/
#include "TimeManager.h"
#include "core/def.h"
#include "logger/Logger.h"
#include <cassert>
#define ENABLE_EASY_LOG 1
namespace sunfish {
void TimeManager::init() {
_depth = 0;
}
void TimeManager::nextDepth() {
_depth++;
assert(_depth < Tree::StackSize);
}
void TimeManager::startDepth() {
_stack[_depth].firstMove = Move::empty();
_stack[_depth].firstValue = -Value::Inf;
}
void TimeManager::addMove(Move move, Value value) {
if (value > _stack[_depth].firstValue) {
_stack[_depth].firstMove = move;
_stack[_depth].firstValue = value;
}
}
bool TimeManager::isEasy(double limit, double elapsed) {
CONSTEXPR int easyDepth = 5;
if (_depth <= easyDepth) {
return false;
}
const auto& easy = _stack[_depth-easyDepth];
const auto& prev = _stack[_depth-1];
const auto& curr = _stack[_depth];
limit = std::min(limit, 3600.0);
if (elapsed < std::max(limit * 0.02, 3.0)) {
return false;
}
if (elapsed >= limit * 0.85) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
double r = elapsed / std::max(limit * 0.25, 3.0);
#if ENABLE_EASY_LOG
{
int easyDiff = curr.firstValue.int32() - easy.firstValue.int32();
int prevDiff = curr.firstValue.int32() - prev.firstValue.int32();
int isSame = curr.firstMove == easy.firstMove ? 1 : 0;
Loggers::message << "time_manager," << r << ',' << easyDiff << ',' << prevDiff << ',' << isSame << ',';
}
#endif
if (curr.firstValue >= easy.firstValue - (256 * r) && curr.firstValue <= easy.firstValue + (512 * r) &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove && curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue - (128 * r) && curr.firstValue <= prev.firstValue + (512 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == prev.firstMove &&
curr.firstValue >= prev.firstValue - (64 * r) && curr.firstValue <= prev.firstValue + (256 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
if (curr.firstMove == easy.firstMove &&
curr.firstValue >= easy.firstValue - (128 * r) && curr.firstValue <= easy.firstValue + (512 * r)) {
#if ENABLE_EASY_LOG
Loggers::message << __FILE_LINE__;
#endif
return true;
}
return false;
}
}
<|endoftext|> |
<commit_before><commit_msg>`yli::opengl::get_n_color_channels`: add support for more formats.<commit_after><|endoftext|> |
<commit_before>#include <stdio.h>
//#include <unistd.h>
#include <utility>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <muduo/base/Logging.h>
#include <muduo/base/Thread.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>
#include <bfcp/client/base_client.h>
using namespace muduo;
using namespace muduo::net;
using namespace bfcp;
using namespace bfcp::client;
void controlFunc(EventLoop *loop);
void onClientStateChanged(BaseClient::State state);
void onReceivedResponse(BaseClient::Error error, bfcp_prim prim, void *data);
#define CHECK_CIN_RESULT(res) do {\
if (!(res)) {\
std::cin.clear(); \
std::cin.ignore(); \
break; \
}\
} while (false)
int main(int argc, char* argv[])
{
Logger::setLogLevel(Logger::kTRACE);
LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid();
EventLoop loop;
Thread thread(boost::bind(&controlFunc, &loop));
thread.start();
loop.loop();
thread.join();
}
void printMenu()
{
printf(
"\n--------PARTICIPANT LIST-----------------------------\n"
" ? - Show the menu\n"
" c - Create the Participant\n"
" h - Destroy the Participant\n"
" s - Show the information of the conference\n"
"BFCP Messages:\n"
" f - Hello\n"
" r - FloorRequest\n"
" l - FloorRelease\n"
" o - FloorRequestQuery\n"
" u - UserQuery\n"
" e - FloorQuery\n"
" a - ChairAction\n"
" q - quit\n"
"------------------------------------------------------\n\n");
}
void controlFunc(EventLoop *loop)
{
boost::shared_ptr<BaseClient> client;
printMenu();
char ch;
while (std::cin >> ch)
{
switch (ch)
{
case '?':
printMenu(); break;
case 'c':
{
if (client)
{
printf("Error: A participant already exist\n");
break;
}
printf("Enter the conferenceID of the conference:\n");
uint32_t conferenceID;
CHECK_CIN_RESULT(std::cin >> conferenceID);
printf("Enter the userID of the participant:\n");
uint16_t userID;
CHECK_CIN_RESULT(std::cin >> userID);
InetAddress serverAddr(AF_INET, "127.0.0.1", 7890);
printf("connect to hostport:%s\n", serverAddr.toIpPort().c_str());
client.reset(new BaseClient(loop, serverAddr, conferenceID, userID));
client->setStateChangedCallback(&onClientStateChanged);
client->setResponseReceivedCallback(&onReceivedResponse);
client->connect();
printf("BFCP Participant created.\n");
} break;
case 'h':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
client->forceDisconnect();
// client must destruct in event loop
loop->runInLoop(boost::bind(&boost::shared_ptr<BaseClient>::reset, client));
client = nullptr;
printf("BFCP participant destroyed.\n");
} break;
case 'f':
if (!client)
{
printf("Error: No participant exist\n");
break;
}
client->sendHello();
break;
case 'r':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
FloorRequestParam param;
printf("Request for beneficiary user?: 0=false, 1=true\n");
CHECK_CIN_RESULT(std::cin >> param.hasBeneficiaryID);
if (param.hasBeneficiaryID)
{
printf("Enter the BeneficiaryID of the new request (0 if it's not needed):\n");
CHECK_CIN_RESULT(std::cin >> param.beneficiaryID);
}
printf("Enter the priority for this request (0=lowest --> 4=highest):\n");
int priority = 0;
CHECK_CIN_RESULT(std::cin >> priority);
param.priority = static_cast<bfcp_priority>(priority);
printf("Enter the FloorID:\n");
uint16_t floorID = 0;
CHECK_CIN_RESULT(std::cin >> floorID);
param.floorIDs.push_back(floorID);
printf("Enter the rest floors count:\n");
size_t restCount = 0;
CHECK_CIN_RESULT(std::cin >> restCount);
printf("Enter the rest floorIDs:\n");
for (size_t i = 0; i < restCount; ++i)
{
CHECK_CIN_RESULT(std::cin >> floorID);
param.floorIDs.push_back(floorID);
}
client->sendFloorRequest(param);
printf("Message sent!\n");
} break;
case 'l':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
printf("Enter the FloorRequestID of the request you want to release:\n");
uint16_t floorRequestID;
CHECK_CIN_RESULT(std::cin >> floorRequestID);
client->sendFloorRelease(floorRequestID);
printf("Message send!\n");
} break;
case 'o':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
printf("Enter the FloorRequestID of the request you're interested in:\n");
uint16_t floorRequestID = 0;
CHECK_CIN_RESULT(std::cin >> floorRequestID);
client->sendFloorRequestQuery(floorRequestID);
printf("Message send!\n");
} break;
case 'u':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
UserQueryParam param;
printf("Query the beneficiary user?\n");
CHECK_CIN_RESULT(std::cin >> param.hasBeneficiaryID);
if (param.hasBeneficiaryID)
{
printf("Enter the BeneficiaryID if you want information about a specific user:\n");
CHECK_CIN_RESULT(std::cin >> param.beneficiaryID);
}
client->sendUserQuery(param);
printf("Message send!\n");
} break;
case 'e':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
bfcp_floor_id_list floorIDs;
printf("Enter the floorID count:\n");
size_t floorIDCount = 0;
CHECK_CIN_RESULT(std::cin >> floorIDCount);
printf("Enter the FloorIDs:\n");
uint16_t floorID = 0;
for (size_t i = 0; i < floorIDCount; ++i)
{
CHECK_CIN_RESULT(std::cin >> floorID);
floorIDs.push_back(floorID);
}
client->sendFloorQuery(floorIDs);
printf("Message send!\n");
} break;
case 'a':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
FloorRequestInfoParam param;
printf("Enter the FloorRequestID:\n");
CHECK_CIN_RESULT(std::cin >> param.floorRequestID);
param.valueType |= AttrValueType::kHasOverallRequestStatus;
param.oRS.floorRequestID = param.floorRequestID;
param.oRS.hasRequestStatus = true;
printf("What to do with this request? (2=Accept / 4=Deny / 7=Revoke):\n");
int status;
CHECK_CIN_RESULT(std::cin >> status);
param.oRS.requestStatus.status = static_cast<bfcp_reqstat>(status);
printf("Enter the desired position in queue for this request (0 if you are not interested in that):\n");
CHECK_CIN_RESULT(std::cin >> param.oRS.requestStatus.qpos);
FloorRequestStatusParam floorStatus;
printf("Enter the FloorID:\n");
CHECK_CIN_RESULT(std::cin >> floorStatus.floorID);
param.fRS.push_back(floorStatus);
printf("Enter the rest floors count:\n");
size_t restCount = 0;
CHECK_CIN_RESULT(std::cin >> restCount);
printf("Enter the rest floorIDs:\n");
for (size_t i = 0; i < restCount; ++i)
{
CHECK_CIN_RESULT(std::cin >> floorStatus.floorID);
param.fRS.push_back(floorStatus);
}
client->sendChairAction(param);
printf("Message send!\n");
} break;
case 's':
// TODO:
printf("TODO:\n");
break;
case 'q':
printf("Quit\n");
if (client)
{
client->forceDisconnect();
client.reset();
}
loop->quit();
return;
default:
printf("Invalid menu choice - try again\n");
break;
}
}
}
void onClientStateChanged( BaseClient::State state )
{
}
void onReceivedResponse( BaseClient::Error error, bfcp_prim prim, void *data )
{
}
<commit_msg>update bfcp client for better ui<commit_after>#include <stdio.h>
//#include <unistd.h>
#include <utility>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <muduo/base/Logging.h>
#include <muduo/base/Thread.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>
#include <bfcp/client/base_client.h>
using namespace muduo;
using namespace muduo::net;
using namespace bfcp;
using namespace bfcp::client;
void controlFunc(EventLoop *loop);
void onClientStateChanged(BaseClient::State state);
void onReceivedResponse(BaseClient::Error error, bfcp_prim prim, void *data);
#define CHECK_CIN_RESULT(res) do {\
if (!(res)) {\
std::cin.clear(); \
std::cin.ignore(); \
break; \
}\
} while (false)
int main(int argc, char* argv[])
{
Logger::setLogLevel(Logger::kTRACE);
LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid();
EventLoop loop;
Thread thread(boost::bind(&controlFunc, &loop));
thread.start();
loop.loop();
thread.join();
}
void printMenu()
{
printf(
"\n--------PARTICIPANT LIST-----------------------------\n"
" ? - Show the menu\n"
" c - Create the Participant\n"
" h - Destroy the Participant\n"
" s - Show the information of the conference\n"
"BFCP Messages:\n"
" f - Hello\n"
" r - FloorRequest\n"
" l - FloorRelease\n"
" o - FloorRequestQuery\n"
" u - UserQuery\n"
" e - FloorQuery\n"
" a - ChairAction\n"
" q - quit\n"
"------------------------------------------------------\n\n");
}
void controlFunc(EventLoop *loop)
{
boost::shared_ptr<BaseClient> client;
printMenu();
char ch;
while (std::cin >> ch)
{
switch (ch)
{
case '?':
printMenu(); break;
case 'c':
{
if (client)
{
printf("Error: A participant already exist\n");
break;
}
printf("Enter the conferenceID of the conference:\n");
uint32_t conferenceID;
CHECK_CIN_RESULT(std::cin >> conferenceID);
printf("Enter the userID of the participant:\n");
uint16_t userID;
CHECK_CIN_RESULT(std::cin >> userID);
InetAddress serverAddr(AF_INET, "127.0.0.1", 7890);
printf("connect to hostport:%s\n", serverAddr.toIpPort().c_str());
client.reset(new BaseClient(loop, serverAddr, conferenceID, userID));
client->setStateChangedCallback(&onClientStateChanged);
client->setResponseReceivedCallback(&onReceivedResponse);
client->connect();
printf("BFCP Participant created.\n");
} break;
case 'h':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
client->forceDisconnect();
// client must destruct in event loop
loop->runInLoop(boost::bind(&boost::shared_ptr<BaseClient>::reset, client));
client = nullptr;
printf("BFCP participant destroyed.\n");
} break;
case 'f':
if (!client)
{
printf("Error: No participant exist\n");
break;
}
client->sendHello();
break;
case 'r':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
FloorRequestParam param;
printf("Request for beneficiary user?: 0=false, 1=true\n");
CHECK_CIN_RESULT(std::cin >> param.hasBeneficiaryID);
if (param.hasBeneficiaryID)
{
printf("Enter the BeneficiaryID of the new request:\n");
CHECK_CIN_RESULT(std::cin >> param.beneficiaryID);
}
printf("Enter the priority for this request (0=lowest --> 4=highest):\n");
int priority = 0;
CHECK_CIN_RESULT(std::cin >> priority);
param.priority = static_cast<bfcp_priority>(priority);
printf("Enter the FloorID:\n");
uint16_t floorID = 0;
CHECK_CIN_RESULT(std::cin >> floorID);
param.floorIDs.push_back(floorID);
printf("Enter the rest floors count:\n");
size_t restCount = 0;
CHECK_CIN_RESULT(std::cin >> restCount);
printf("Enter the rest floorIDs:\n");
for (size_t i = 0; i < restCount; ++i)
{
CHECK_CIN_RESULT(std::cin >> floorID);
param.floorIDs.push_back(floorID);
}
client->sendFloorRequest(param);
printf("Message sent!\n");
} break;
case 'l':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
printf("Enter the FloorRequestID of the request you want to release:\n");
uint16_t floorRequestID;
CHECK_CIN_RESULT(std::cin >> floorRequestID);
client->sendFloorRelease(floorRequestID);
printf("Message send!\n");
} break;
case 'o':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
printf("Enter the FloorRequestID of the request you're interested in:\n");
uint16_t floorRequestID = 0;
CHECK_CIN_RESULT(std::cin >> floorRequestID);
client->sendFloorRequestQuery(floorRequestID);
printf("Message send!\n");
} break;
case 'u':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
UserQueryParam param;
printf("Query the beneficiary user?: 0=false, 1=true\n");
CHECK_CIN_RESULT(std::cin >> param.hasBeneficiaryID);
if (param.hasBeneficiaryID)
{
printf("Enter the BeneficiaryID if you want information about a specific user:\n");
CHECK_CIN_RESULT(std::cin >> param.beneficiaryID);
}
client->sendUserQuery(param);
printf("Message send!\n");
} break;
case 'e':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
bfcp_floor_id_list floorIDs;
printf("Enter the floorID count:\n");
size_t floorIDCount = 0;
CHECK_CIN_RESULT(std::cin >> floorIDCount);
printf("Enter the FloorIDs:\n");
uint16_t floorID = 0;
for (size_t i = 0; i < floorIDCount; ++i)
{
CHECK_CIN_RESULT(std::cin >> floorID);
floorIDs.push_back(floorID);
}
client->sendFloorQuery(floorIDs);
printf("Message send!\n");
} break;
case 'a':
{
if (!client)
{
printf("Error: No participant exist\n");
break;
}
FloorRequestInfoParam param;
printf("Enter the FloorRequestID:\n");
CHECK_CIN_RESULT(std::cin >> param.floorRequestID);
param.valueType |= AttrValueType::kHasOverallRequestStatus;
param.oRS.floorRequestID = param.floorRequestID;
param.oRS.hasRequestStatus = true;
printf("What to do with this request? (2=Accept / 4=Deny / 7=Revoke):\n");
int status;
CHECK_CIN_RESULT(std::cin >> status);
param.oRS.requestStatus.status = static_cast<bfcp_reqstat>(status);
printf("Enter the desired position in queue for this request (0 if you are not interested in that):\n");
int pos = 0;
CHECK_CIN_RESULT(std::cin >> pos);
param.oRS.requestStatus.qpos = static_cast<uint8_t>(pos);
FloorRequestStatusParam floorStatus;
printf("Enter the FloorID:\n");
CHECK_CIN_RESULT(std::cin >> floorStatus.floorID);
param.fRS.push_back(floorStatus);
printf("Enter the rest floors count:\n");
size_t restCount = 0;
CHECK_CIN_RESULT(std::cin >> restCount);
printf("Enter the rest floorIDs:\n");
for (size_t i = 0; i < restCount; ++i)
{
CHECK_CIN_RESULT(std::cin >> floorStatus.floorID);
param.fRS.push_back(floorStatus);
}
client->sendChairAction(param);
printf("Message send!\n");
} break;
case 's':
// TODO:
printf("TODO:\n");
break;
case 'q':
printf("Quit\n");
if (client)
{
client->forceDisconnect();
client.reset();
}
loop->quit();
return;
default:
printf("Invalid menu choice - try again\n");
break;
}
}
}
void onClientStateChanged( BaseClient::State state )
{
}
void onReceivedResponse( BaseClient::Error error, bfcp_prim prim, void *data )
{
}
<|endoftext|> |
<commit_before>/*
* opencog/atoms/execution/EvaluationLink.cc
*
* Copyright (C) 2009, 2013, 2014, 2015 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomspace/atom_types.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/atoms/NumberNode.h>
#include <opencog/cython/PythonEval.h>
#include <opencog/guile/SchemeEval.h>
#include "EvaluationLink.h"
#include "ExecutionOutputLink.h"
using namespace opencog;
EvaluationLink::EvaluationLink(const HandleSeq& oset,
TruthValuePtr tv,
AttentionValuePtr av)
: FreeLink(EVALUATION_LINK, oset, tv, av)
{
if ((2 != oset.size()) or
(LIST_LINK != oset[1]->getType()))
{
throw RuntimeException(TRACE_INFO,
"EvaluationLink must have predicate and args!");
}
}
EvaluationLink::EvaluationLink(Handle schema, Handle args,
TruthValuePtr tv,
AttentionValuePtr av)
: FreeLink(EVALUATION_LINK, schema, args, tv, av)
{
if (LIST_LINK != args->getType()) {
throw RuntimeException(TRACE_INFO,
"EvaluationLink must have args in a ListLink!");
}
}
EvaluationLink::EvaluationLink(Link& l)
: FreeLink(l)
{
Type tscope = l.getType();
if (EVALUATION_LINK != tscope) {
throw RuntimeException(TRACE_INFO,
"Expecting an EvaluationLink");
}
}
// Perform a GreaterThan check
static TruthValuePtr greater(AtomSpace* as, LinkPtr ll)
{
if (2 != ll->getArity())
throw RuntimeException(TRACE_INFO,
"GreaterThankLink expects two arguments");
Handle h1(ll->getOutgoingAtom(0));
Handle h2(ll->getOutgoingAtom(1));
if (NUMBER_NODE != h1->getType())
h1 = ExecutionOutputLink::do_execute(as, h1);
if (NUMBER_NODE != h2->getType())
h2 = ExecutionOutputLink::do_execute(as, h2);
NumberNodePtr n1(NumberNodeCast(h1));
NumberNodePtr n2(NumberNodeCast(h2));
if (NULL == n1 or NULL == n2)
throw RuntimeException(TRACE_INFO,
"Expecting c++:greater arguments to be NumberNode's! Got:\n%s\n",
(h1==NULL)? "(invalid handle)" : h1->toShortString().c_str(),
(h2==NULL)? "(invalid handle)" : h2->toShortString().c_str());
if (n1->getValue() > n2->getValue())
return TruthValue::TRUE_TV();
else
return TruthValue::FALSE_TV();
}
static TruthValuePtr equal(AtomSpace* as, LinkPtr ll)
{
const HandleSeq& oset = ll->getOutgoingSet();
if (2 != oset.size())
throw RuntimeException(TRACE_INFO,
"EqualLink expects two arguments");
if (oset[0] == oset[1])
return TruthValue::TRUE_TV();
else
return TruthValue::FALSE_TV();
}
/// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink
///
/// Expects the argument to be an EvaluationLink, which should have the
/// following structure:
///
/// EvaluationLink
/// GroundedPredicateNode "lang: func_name"
/// ListLink
/// SomeAtom
/// OtherAtom
///
/// The "lang:" should be either "scm:" for scheme, or "py:" for python.
/// This method will then invoke "func_name" on the provided ListLink
/// of arguments to the function.
///
TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle execlnk)
{
Type t = execlnk->getType();
if (EVALUATION_LINK == t)
{
LinkPtr l(LinkCast(execlnk));
return do_evaluate(as, l->getOutgoingSet());
}
else if (EQUAL_LINK == t)
{
return equal(as, LinkCast(execlnk));
}
else if (GREATER_THAN_LINK == t)
{
return greater(as, LinkCast(execlnk));
}
else if (NOT_LINK == t)
{
LinkPtr l(LinkCast(execlnk));
TruthValuePtr tv(do_evaluate(as, l->getOutgoingAtom(0)));
return SimpleTruthValue::createTV(
1.0 - tv->getMean(), tv->getCount());
}
throw RuntimeException(TRACE_INFO, "Expecting to get an EvaluationLink!");
}
/// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink
///
/// Expects the sequence to be exactly two atoms long.
/// Expects the first handle of the sequence to be a GroundedPredicateNode
/// Expects the second handle of the sequence to be a ListLink
/// Executes the GroundedPredicateNode, supplying the second handle as argument
///
TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const HandleSeq& sna)
{
if (2 != sna.size())
{
throw RuntimeException(TRACE_INFO,
"Incorrect arity for an EvaluationLink!");
}
return do_evaluate(as, sna[0], sna[1]);
}
/// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink
///
/// Expects "gsn" to be a GroundedPredicateNode
/// Expects "args" to be a ListLink
/// Executes the GroundedPredicateNode, supplying the args as argument
///
TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle gsn, Handle args)
{
if (GROUNDED_PREDICATE_NODE != gsn->getType())
{
throw RuntimeException(TRACE_INFO, "Expecting GroundedPredicateNode!");
}
if (LIST_LINK != args->getType())
{
throw RuntimeException(TRACE_INFO, "Expecting arguments to EvaluationLink!");
}
// Get the schema name.
const std::string& schema = NodeCast(gsn)->getName();
// printf ("Grounded schema name: %s\n", schema.c_str());
// A very special-case C++ comparison.
// This compares two NumberNodes, by their numeric value.
// Hard-coded in C++ for speed. (well, and for convenience ...)
if (0 == schema.compare("c++:greater"))
{
return greater(as, LinkCast(args));
}
// A very special-case C++ comparison.
// This compares a set of atoms, verifying that they are all different.
// Hard-coded in C++ for speed. (well, and for convenience ...)
if (0 == schema.compare("c++:exclusive"))
{
LinkPtr ll(LinkCast(args));
Arity sz = ll->getArity();
for (Arity i=0; i<sz-1; i++) {
Handle h1(ll->getOutgoingAtom(i));
for (Arity j=i+1; j<sz; j++) {
Handle h2(ll->getOutgoingAtom(j));
if (h1 == h2) return TruthValue::FALSE_TV();
}
}
return TruthValue::TRUE_TV();
}
// At this point, we only run scheme and python schemas.
if (0 == schema.compare(0,4,"scm:", 4))
{
#ifdef HAVE_GUILE
// Be friendly, and strip leading white-space, if any.
size_t pos = 4;
while (' ' == schema[pos]) pos++;
SchemeEval* applier = SchemeEval::get_evaluator(as);
return applier->apply_tv(schema.substr(pos), args);
#else
throw RuntimeException(TRACE_INFO,
"Cannot evaluate scheme GroundedPredicateNode!");
#endif /* HAVE_GUILE */
}
if (0 == schema.compare(0, 3,"py:", 3))
{
#ifdef HAVE_CYTHON
// Be friendly, and strip leading white-space, if any.
size_t pos = 3;
while (' ' == schema[pos]) pos++;
PythonEval &applier = PythonEval::instance();
// std::string rc = applier.apply(schema.substr(pos), args);
// if (rc.compare("None") or rc.compare("False")) return false;
return applier.apply_tv(schema.substr(pos), args);
#else
throw RuntimeException(TRACE_INFO,
"Cannot evaluate python GroundedPredicateNode!");
#endif /* HAVE_CYTHON */
}
// Unkown proceedure type.
throw RuntimeException(TRACE_INFO,
"Cannot evaluate unknown GroundedPredicateNode: %s",
schema.c_str());
}
<commit_msg>Another python bugfix<commit_after>/*
* opencog/atoms/execution/EvaluationLink.cc
*
* Copyright (C) 2009, 2013, 2014, 2015 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomspace/atom_types.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/atoms/NumberNode.h>
#include <opencog/cython/PythonEval.h>
#include <opencog/guile/SchemeEval.h>
#include "EvaluationLink.h"
#include "ExecutionOutputLink.h"
using namespace opencog;
EvaluationLink::EvaluationLink(const HandleSeq& oset,
TruthValuePtr tv,
AttentionValuePtr av)
: FreeLink(EVALUATION_LINK, oset, tv, av)
{
if ((2 != oset.size()) or
(LIST_LINK != oset[1]->getType()))
{
throw RuntimeException(TRACE_INFO,
"EvaluationLink must have predicate and args!");
}
}
EvaluationLink::EvaluationLink(Handle schema, Handle args,
TruthValuePtr tv,
AttentionValuePtr av)
: FreeLink(EVALUATION_LINK, schema, args, tv, av)
{
if (LIST_LINK != args->getType()) {
throw RuntimeException(TRACE_INFO,
"EvaluationLink must have args in a ListLink!");
}
}
EvaluationLink::EvaluationLink(Link& l)
: FreeLink(l)
{
Type tscope = l.getType();
if (EVALUATION_LINK != tscope) {
throw RuntimeException(TRACE_INFO,
"Expecting an EvaluationLink");
}
}
// Perform a GreaterThan check
static TruthValuePtr greater(AtomSpace* as, LinkPtr ll)
{
if (2 != ll->getArity())
throw RuntimeException(TRACE_INFO,
"GreaterThankLink expects two arguments");
Handle h1(ll->getOutgoingAtom(0));
Handle h2(ll->getOutgoingAtom(1));
if (NUMBER_NODE != h1->getType())
h1 = ExecutionOutputLink::do_execute(as, h1);
if (NUMBER_NODE != h2->getType())
h2 = ExecutionOutputLink::do_execute(as, h2);
NumberNodePtr n1(NumberNodeCast(h1));
NumberNodePtr n2(NumberNodeCast(h2));
if (NULL == n1 or NULL == n2)
throw RuntimeException(TRACE_INFO,
"Expecting c++:greater arguments to be NumberNode's! Got:\n%s\n",
(h1==NULL)? "(invalid handle)" : h1->toShortString().c_str(),
(h2==NULL)? "(invalid handle)" : h2->toShortString().c_str());
if (n1->getValue() > n2->getValue())
return TruthValue::TRUE_TV();
else
return TruthValue::FALSE_TV();
}
static TruthValuePtr equal(AtomSpace* as, LinkPtr ll)
{
const HandleSeq& oset = ll->getOutgoingSet();
if (2 != oset.size())
throw RuntimeException(TRACE_INFO,
"EqualLink expects two arguments");
if (oset[0] == oset[1])
return TruthValue::TRUE_TV();
else
return TruthValue::FALSE_TV();
}
/// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink
///
/// Expects the argument to be an EvaluationLink, which should have the
/// following structure:
///
/// EvaluationLink
/// GroundedPredicateNode "lang: func_name"
/// ListLink
/// SomeAtom
/// OtherAtom
///
/// The "lang:" should be either "scm:" for scheme, or "py:" for python.
/// This method will then invoke "func_name" on the provided ListLink
/// of arguments to the function.
///
TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle execlnk)
{
Type t = execlnk->getType();
if (EVALUATION_LINK == t)
{
LinkPtr l(LinkCast(execlnk));
return do_evaluate(as, l->getOutgoingSet());
}
else if (EQUAL_LINK == t)
{
return equal(as, LinkCast(execlnk));
}
else if (GREATER_THAN_LINK == t)
{
return greater(as, LinkCast(execlnk));
}
else if (NOT_LINK == t)
{
LinkPtr l(LinkCast(execlnk));
TruthValuePtr tv(do_evaluate(as, l->getOutgoingAtom(0)));
return SimpleTruthValue::createTV(
1.0 - tv->getMean(), tv->getCount());
}
throw RuntimeException(TRACE_INFO, "Expecting to get an EvaluationLink!");
}
/// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink
///
/// Expects the sequence to be exactly two atoms long.
/// Expects the first handle of the sequence to be a GroundedPredicateNode
/// Expects the second handle of the sequence to be a ListLink
/// Executes the GroundedPredicateNode, supplying the second handle as argument
///
TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const HandleSeq& sna)
{
if (2 != sna.size())
{
throw RuntimeException(TRACE_INFO,
"Incorrect arity for an EvaluationLink!");
}
return do_evaluate(as, sna[0], sna[1]);
}
/// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink
///
/// Expects "gsn" to be a GroundedPredicateNode
/// Expects "args" to be a ListLink
/// Executes the GroundedPredicateNode, supplying the args as argument
///
TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, Handle gsn, Handle args)
{
if (GROUNDED_PREDICATE_NODE != gsn->getType())
{
throw RuntimeException(TRACE_INFO, "Expecting GroundedPredicateNode!");
}
if (LIST_LINK != args->getType())
{
throw RuntimeException(TRACE_INFO, "Expecting arguments to EvaluationLink!");
}
// Get the schema name.
const std::string& schema = NodeCast(gsn)->getName();
// printf ("Grounded schema name: %s\n", schema.c_str());
// A very special-case C++ comparison.
// This compares two NumberNodes, by their numeric value.
// Hard-coded in C++ for speed. (well, and for convenience ...)
if (0 == schema.compare("c++:greater"))
{
return greater(as, LinkCast(args));
}
// A very special-case C++ comparison.
// This compares a set of atoms, verifying that they are all different.
// Hard-coded in C++ for speed. (well, and for convenience ...)
if (0 == schema.compare("c++:exclusive"))
{
LinkPtr ll(LinkCast(args));
Arity sz = ll->getArity();
for (Arity i=0; i<sz-1; i++) {
Handle h1(ll->getOutgoingAtom(i));
for (Arity j=i+1; j<sz; j++) {
Handle h2(ll->getOutgoingAtom(j));
if (h1 == h2) return TruthValue::FALSE_TV();
}
}
return TruthValue::TRUE_TV();
}
// At this point, we only run scheme and python schemas.
if (0 == schema.compare(0,4,"scm:", 4))
{
#ifdef HAVE_GUILE
// Be friendly, and strip leading white-space, if any.
size_t pos = 4;
while (' ' == schema[pos]) pos++;
SchemeEval* applier = SchemeEval::get_evaluator(as);
return applier->apply_tv(schema.substr(pos), args);
#else
throw RuntimeException(TRACE_INFO,
"Cannot evaluate scheme GroundedPredicateNode!");
#endif /* HAVE_GUILE */
}
if (0 == schema.compare(0, 3,"py:", 3))
{
#ifdef HAVE_CYTHON
// Be friendly, and strip leading white-space, if any.
size_t pos = 3;
while (' ' == schema[pos]) pos++;
PythonEval &applier = PythonEval::instance(as);
// std::string rc = applier.apply(schema.substr(pos), args);
// if (rc.compare("None") or rc.compare("False")) return false;
return applier.apply_tv(schema.substr(pos), args);
#else
throw RuntimeException(TRACE_INFO,
"Cannot evaluate python GroundedPredicateNode!");
#endif /* HAVE_CYTHON */
}
// Unkown proceedure type.
throw RuntimeException(TRACE_INFO,
"Cannot evaluate unknown GroundedPredicateNode: %s",
schema.c_str());
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/config.h>
#if VSNRAY_HAVE_GLEW
#include <GL/glew.h>
#elif VSNRAY_HAVE_OPENGLES
#include <GLES2/gl2.h>
#endif
#include <visionaray/gl/bvh_outline_renderer.h>
#include <visionaray/gl/handle.h>
#include <visionaray/gl/program.h>
#include <visionaray/gl/shader.h>
namespace visionaray
{
namespace gl
{
//-------------------------------------------------------------------------------------------------
// Private implementation
//
struct bvh_outline_renderer::impl
{
gl::buffer vertex_buffer;
gl::program prog;
gl::shader vert;
gl::shader frag;
GLuint view_loc;
GLuint proj_loc;
GLuint vertex_loc;
};
//-------------------------------------------------------------------------------------------------
// BVH outline renderer OpenGL implementation
//
bvh_outline_renderer::bvh_outline_renderer()
: impl_(new impl)
{
}
bvh_outline_renderer::~bvh_outline_renderer() = default;
void bvh_outline_renderer::frame(mat4 const& view, mat4 const& proj) const
{
// Store OpenGL state
GLint array_buffer_binding = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &array_buffer_binding);
impl_->prog.enable();
glUniformMatrix4fv(impl_->view_loc, 1, GL_FALSE, view.data());
glUniformMatrix4fv(impl_->proj_loc, 1, GL_FALSE, proj.data());
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glVertexAttribPointer(impl_->vertex_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->vertex_loc);
glDrawArrays(GL_LINES, 0, (GLsizei)(num_vertices_));
glDisableVertexAttribArray(impl_->vertex_loc);
impl_->prog.disable();
// Restore OpenGL state
glBindBuffer(GL_ARRAY_BUFFER, array_buffer_binding);
}
void bvh_outline_renderer::destroy()
{
impl_->vertex_buffer.destroy();
if (impl_->prog.check_attached(impl_->vert))
{
impl_->prog.detach_shader(impl_->vert);
}
if (impl_->prog.check_attached(impl_->frag))
{
impl_->prog.detach_shader(impl_->frag);
}
}
bool bvh_outline_renderer::init_gl(float const* data, size_t size)
{
// Store OpenGL state
GLint array_buffer_binding = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &array_buffer_binding);
// Setup shaders
impl_->vert.reset(glCreateShader(GL_VERTEX_SHADER));
impl_->vert.set_source(R"(
attribute vec3 vertex;
uniform mat4 view;
uniform mat4 proj;
void main(void)
{
gl_Position = proj * view * vec4(vertex, 1.0);
}
)");
impl_->vert.compile();
if (!impl_->vert.check_compiled())
{
return false;
}
impl_->frag.reset(glCreateShader(GL_FRAGMENT_SHADER));
impl_->frag.set_source(R"(
void main(void)
{
gl_FragColor = vec4(1.0);
}
)");
impl_->frag.compile();
if (!impl_->frag.check_compiled())
{
return false;
}
impl_->prog.reset(glCreateProgram());
impl_->prog.attach_shader(impl_->vert);
impl_->prog.attach_shader(impl_->frag);
impl_->prog.link();
if (!impl_->prog.check_linked())
{
return false;
}
impl_->vertex_loc = glGetAttribLocation(impl_->prog.get(), "vertex");
impl_->view_loc = glGetUniformLocation(impl_->prog.get(), "view");
impl_->proj_loc = glGetUniformLocation(impl_->prog.get(), "proj");
// Setup vbo
impl_->vertex_buffer.reset(create_buffer());
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
// Restore OpenGL state
glBindBuffer(GL_ARRAY_BUFFER, array_buffer_binding);
return true;
}
} // gl
} // visionaray
<commit_msg>Disable znear/zfar planes for bvh visualization<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/config.h>
#if VSNRAY_HAVE_GLEW
#include <GL/glew.h>
#elif VSNRAY_HAVE_OPENGLES
#include <GLES2/gl2.h>
#endif
#include <visionaray/gl/bvh_outline_renderer.h>
#include <visionaray/gl/handle.h>
#include <visionaray/gl/program.h>
#include <visionaray/gl/shader.h>
namespace visionaray
{
namespace gl
{
//-------------------------------------------------------------------------------------------------
// Private implementation
//
struct bvh_outline_renderer::impl
{
gl::buffer vertex_buffer;
gl::program prog;
gl::shader vert;
gl::shader frag;
GLuint view_loc;
GLuint proj_loc;
GLuint vertex_loc;
};
//-------------------------------------------------------------------------------------------------
// BVH outline renderer OpenGL implementation
//
bvh_outline_renderer::bvh_outline_renderer()
: impl_(new impl)
{
}
bvh_outline_renderer::~bvh_outline_renderer() = default;
void bvh_outline_renderer::frame(mat4 const& view, mat4 const& proj) const
{
// Store OpenGL state
GLint array_buffer_binding = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &array_buffer_binding);
GLboolean depth_clamp_enabled = glIsEnabled(GL_DEPTH_CLAMP);
glEnable(GL_DEPTH_CLAMP);
impl_->prog.enable();
glUniformMatrix4fv(impl_->view_loc, 1, GL_FALSE, view.data());
glUniformMatrix4fv(impl_->proj_loc, 1, GL_FALSE, proj.data());
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glVertexAttribPointer(impl_->vertex_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->vertex_loc);
glDrawArrays(GL_LINES, 0, (GLsizei)(num_vertices_));
glDisableVertexAttribArray(impl_->vertex_loc);
impl_->prog.disable();
// Restore OpenGL state
if (depth_clamp_enabled)
{
glEnable(GL_DEPTH_CLAMP);
}
else
{
glDisable(GL_DEPTH_CLAMP);
}
glBindBuffer(GL_ARRAY_BUFFER, array_buffer_binding);
}
void bvh_outline_renderer::destroy()
{
impl_->vertex_buffer.destroy();
if (impl_->prog.check_attached(impl_->vert))
{
impl_->prog.detach_shader(impl_->vert);
}
if (impl_->prog.check_attached(impl_->frag))
{
impl_->prog.detach_shader(impl_->frag);
}
}
bool bvh_outline_renderer::init_gl(float const* data, size_t size)
{
// Store OpenGL state
GLint array_buffer_binding = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &array_buffer_binding);
// Setup shaders
impl_->vert.reset(glCreateShader(GL_VERTEX_SHADER));
impl_->vert.set_source(R"(
attribute vec3 vertex;
uniform mat4 view;
uniform mat4 proj;
void main(void)
{
gl_Position = proj * view * vec4(vertex, 1.0);
}
)");
impl_->vert.compile();
if (!impl_->vert.check_compiled())
{
return false;
}
impl_->frag.reset(glCreateShader(GL_FRAGMENT_SHADER));
impl_->frag.set_source(R"(
void main(void)
{
gl_FragColor = vec4(1.0);
}
)");
impl_->frag.compile();
if (!impl_->frag.check_compiled())
{
return false;
}
impl_->prog.reset(glCreateProgram());
impl_->prog.attach_shader(impl_->vert);
impl_->prog.attach_shader(impl_->frag);
impl_->prog.link();
if (!impl_->prog.check_linked())
{
return false;
}
impl_->vertex_loc = glGetAttribLocation(impl_->prog.get(), "vertex");
impl_->view_loc = glGetUniformLocation(impl_->prog.get(), "view");
impl_->proj_loc = glGetUniformLocation(impl_->prog.get(), "proj");
// Setup vbo
impl_->vertex_buffer.reset(create_buffer());
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
// Restore OpenGL state
glBindBuffer(GL_ARRAY_BUFFER, array_buffer_binding);
return true;
}
} // gl
} // visionaray
<|endoftext|> |
<commit_before>{
//
// This macro generates a Controlbar menu: To see the output, click begin_html <a href="gif/demos.gif" >here</a> end_html
// To execute an item, click with the left mouse button.
// To see the HELP of a button, click on the right mouse button.
gROOT->Reset();
bar = new TControlBar("vertical", "Demos");
bar->AddButton("Help on Demos",".x demoshelp.C", "Click Here For Help on Running the Demos");
bar->AddButton("browser", "{b = new TBrowser(\"Browser\");}", "Start the ROOT Browser");
bar->AddButton("framework", ".x framework.C", "An Example of Object Oriented User Interface");
bar->AddButton("first", ".x first.C", "An Example of Slide with Root");
bar->AddButton("hsimple", ".x hsimple.C", "An Example Creating Histograms/Ntuples on File");
bar->AddButton("hsum", ".x hsum.C", "Filling Histograms and Some Graphics Options");
bar->AddButton("formula1", ".x formula1.C", "Simple Formula and Functions");
bar->AddButton("surfaces", ".x surfaces.C", "Surface Drawing Options");
bar->AddButton("fillrandom", ".x fillrandom.C","Histograms with Random Numbers from a Function");
bar->AddButton("fit1", ".x fit1.C", "A Simple Fitting Example");
bar->AddButton("multifit", ".x multifit.C", "Fitting in Subranges of Histograms");
bar->AddButton("h1draw", ".x h1draw.C", "Drawing Options for 1D Histograms");
bar->AddButton("graph", ".x graph.C", "Example of a Simple Graph");
bar->AddButton("gerrors", ".x gerrors.C", "Example of a Graph with Error Bars");
bar->AddButton("tornado", ".x tornado.C", "Examples of 3-D PolyMarkers");
bar->AddButton("shapes", ".x shapes.C", "The Geometry Shapes");
bar->AddButton("geometry", ".x geometry.C", "Creation of the NA49 Geometry File");
bar->AddButton("na49view", ".x na49view.C", "Two Views of the NA49 Detector Geometry");
bar->AddButton("file", ".x file.C", "The ROOT File Format");
bar->AddButton("fildir", ".x fildir.C", "The ROOT File, Directories and Keys");
bar->AddButton("tree", ".x tree.C", "The Tree Data Structure");
bar->AddButton("ntuple1", ".x ntuple1.C", "Ntuples and Selections");
bar->AddButton("rootmarks", ".x rootmarks.C", "Prints an Estimated ROOTMARKS for Your Machine");
bar->Show();
gROOT->SaveContext();
}
<commit_msg>Change the way the TBrowser is called.<commit_after>{
//
// This macro generates a Controlbar menu: To see the output, click begin_html <a href="gif/demos.gif" >here</a> end_html
// To execute an item, click with the left mouse button.
// To see the HELP of a button, click on the right mouse button.
gROOT->Reset();
bar = new TControlBar("vertical", "Demos");
bar->AddButton("Help on Demos",".x demoshelp.C", "Click Here For Help on Running the Demos");
bar->AddButton("browser", "new TBrowser;", "Start the ROOT Browser");
bar->AddButton("framework", ".x framework.C", "An Example of Object Oriented User Interface");
bar->AddButton("first", ".x first.C", "An Example of Slide with Root");
bar->AddButton("hsimple", ".x hsimple.C", "An Example Creating Histograms/Ntuples on File");
bar->AddButton("hsum", ".x hsum.C", "Filling Histograms and Some Graphics Options");
bar->AddButton("formula1", ".x formula1.C", "Simple Formula and Functions");
bar->AddButton("surfaces", ".x surfaces.C", "Surface Drawing Options");
bar->AddButton("fillrandom", ".x fillrandom.C","Histograms with Random Numbers from a Function");
bar->AddButton("fit1", ".x fit1.C", "A Simple Fitting Example");
bar->AddButton("multifit", ".x multifit.C", "Fitting in Subranges of Histograms");
bar->AddButton("h1draw", ".x h1draw.C", "Drawing Options for 1D Histograms");
bar->AddButton("graph", ".x graph.C", "Example of a Simple Graph");
bar->AddButton("gerrors", ".x gerrors.C", "Example of a Graph with Error Bars");
bar->AddButton("tornado", ".x tornado.C", "Examples of 3-D PolyMarkers");
bar->AddButton("shapes", ".x shapes.C", "The Geometry Shapes");
bar->AddButton("geometry", ".x geometry.C", "Creation of the NA49 Geometry File");
bar->AddButton("na49view", ".x na49view.C", "Two Views of the NA49 Detector Geometry");
bar->AddButton("file", ".x file.C", "The ROOT File Format");
bar->AddButton("fildir", ".x fildir.C", "The ROOT File, Directories and Keys");
bar->AddButton("tree", ".x tree.C", "The Tree Data Structure");
bar->AddButton("ntuple1", ".x ntuple1.C", "Ntuples and Selections");
bar->AddButton("rootmarks", ".x rootmarks.C", "Prints an Estimated ROOTMARKS for Your Machine");
bar->Show();
gROOT->SaveContext();
}
<|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 <string>
#include "base/basictypes.h"
#include "base/message_loop.h"
#include "jingle/notifier/base/notifier_options.h"
#include "jingle/notifier/listener/mediator_thread_mock.h"
#include "jingle/notifier/listener/mediator_thread_impl.h"
#include "jingle/notifier/listener/talk_mediator_impl.h"
#include "talk/xmpp/xmppengine.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace notifier {
using ::testing::_;
class MockTalkMediatorDelegate : public TalkMediator::Delegate {
public:
MockTalkMediatorDelegate() {}
virtual ~MockTalkMediatorDelegate() {}
MOCK_METHOD1(OnNotificationStateChange,
void(bool notification_changed));
MOCK_METHOD1(OnIncomingNotification,
void(const Notification& data));
MOCK_METHOD0(OnOutgoingNotification, void());
private:
DISALLOW_COPY_AND_ASSIGN(MockTalkMediatorDelegate);
};
class TalkMediatorImplTest : public testing::Test {
protected:
TalkMediatorImplTest() {}
virtual ~TalkMediatorImplTest() {}
TalkMediatorImpl* NewMockedTalkMediator(
MockMediatorThread* mock_mediator_thread) {
return new TalkMediatorImpl(mock_mediator_thread,
NotifierOptions());
}
int last_message_;
private:
// TalkMediatorImpl expects a message loop.
MessageLoop message_loop_;
DISALLOW_COPY_AND_ASSIGN(TalkMediatorImplTest);
};
TEST_F(TalkMediatorImplTest, SetAuthToken) {
scoped_ptr<TalkMediatorImpl> talk1(
NewMockedTalkMediator(new MockMediatorThread()));
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_TRUE(talk1->state_.initialized);
scoped_ptr<TalkMediatorImpl> talk2(
NewMockedTalkMediator(new MockMediatorThread()));
talk2->SetAuthToken("chromium@mail.google.com", "token", "fake_service");
EXPECT_TRUE(talk2->state_.initialized);
scoped_ptr<TalkMediatorImpl> talk3(
NewMockedTalkMediator(new MockMediatorThread()));
talk3->SetAuthToken("chromium@mail.google.com", "token", "fake_service");
EXPECT_TRUE(talk3->state_.initialized);
}
TEST_F(TalkMediatorImplTest, LoginWiring) {
// The TalkMediatorImpl owns the mock.
MockMediatorThread* mock = new MockMediatorThread();
scoped_ptr<TalkMediatorImpl> talk1(NewMockedTalkMediator(mock));
// Login checks states for initialization.
EXPECT_FALSE(talk1->Login());
EXPECT_EQ(0, mock->login_calls);
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_EQ(0, mock->update_settings_calls);
EXPECT_TRUE(talk1->Login());
EXPECT_EQ(1, mock->login_calls);
// We call SetAuthToken again to update the settings after an update.
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_EQ(1, mock->update_settings_calls);
// Successive calls to login will fail. One needs to create a new talk
// mediator object.
EXPECT_FALSE(talk1->Login());
EXPECT_EQ(1, mock->login_calls);
EXPECT_TRUE(talk1->Logout());
EXPECT_EQ(1, mock->logout_calls);
// Successive logout calls do nothing.
EXPECT_FALSE(talk1->Logout());
EXPECT_EQ(1, mock->logout_calls);
}
TEST_F(TalkMediatorImplTest, SendNotification) {
// The TalkMediatorImpl owns the mock.
MockMediatorThread* mock = new MockMediatorThread();
scoped_ptr<TalkMediatorImpl> talk1(NewMockedTalkMediator(mock));
// Failure due to not being logged in.
Notification data;
EXPECT_FALSE(talk1->SendNotification(data));
EXPECT_EQ(0, mock->send_calls);
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_TRUE(talk1->Login());
talk1->OnConnectionStateChange(true);
EXPECT_EQ(1, mock->login_calls);
// Should be subscribed now.
EXPECT_TRUE(talk1->state_.subscribed);
EXPECT_TRUE(talk1->SendNotification(data));
EXPECT_EQ(1, mock->send_calls);
EXPECT_TRUE(talk1->SendNotification(data));
EXPECT_EQ(2, mock->send_calls);
EXPECT_TRUE(talk1->Logout());
EXPECT_EQ(1, mock->logout_calls);
// Failure due to being logged out.
EXPECT_FALSE(talk1->SendNotification(data));
EXPECT_EQ(2, mock->send_calls);
}
TEST_F(TalkMediatorImplTest, MediatorThreadCallbacks) {
// The TalkMediatorImpl owns the mock.
MockMediatorThread* mock = new MockMediatorThread();
scoped_ptr<TalkMediatorImpl> talk1(NewMockedTalkMediator(mock));
MockTalkMediatorDelegate mock_delegate;
EXPECT_CALL(mock_delegate, OnNotificationStateChange(true));
EXPECT_CALL(mock_delegate, OnIncomingNotification(_));
EXPECT_CALL(mock_delegate, OnOutgoingNotification());
talk1->SetDelegate(&mock_delegate);
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_TRUE(talk1->Login());
EXPECT_EQ(1, mock->login_calls);
// The message triggers calls to listen and subscribe.
EXPECT_EQ(1, mock->listen_calls);
EXPECT_EQ(1, mock->subscribe_calls);
EXPECT_TRUE(talk1->state_.subscribed);
// After subscription success is receieved, the talk mediator will allow
// sending of notifications.
Notification outgoing_data;
EXPECT_TRUE(talk1->SendNotification(outgoing_data));
EXPECT_EQ(1, mock->send_calls);
Notification incoming_data;
incoming_data.channel = "service_url";
incoming_data.data = "service_data";
mock->ReceiveNotification(incoming_data);
// Shouldn't trigger a call to the delegate since we disconnect
// it before we logout.
talk1.reset();
}
} // namespace notifier
<commit_msg>[Jingle] Fix jingle_unittests failures<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 <string>
#include "base/basictypes.h"
#include "base/message_loop.h"
#include "jingle/notifier/base/notifier_options.h"
#include "jingle/notifier/listener/mediator_thread_mock.h"
#include "jingle/notifier/listener/mediator_thread_impl.h"
#include "jingle/notifier/listener/talk_mediator_impl.h"
#include "talk/xmpp/xmppengine.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace notifier {
using ::testing::_;
class MockTalkMediatorDelegate : public TalkMediator::Delegate {
public:
MockTalkMediatorDelegate() {}
virtual ~MockTalkMediatorDelegate() {}
MOCK_METHOD1(OnNotificationStateChange,
void(bool notification_changed));
MOCK_METHOD1(OnIncomingNotification,
void(const Notification& data));
MOCK_METHOD0(OnOutgoingNotification, void());
private:
DISALLOW_COPY_AND_ASSIGN(MockTalkMediatorDelegate);
};
class TalkMediatorImplTest : public testing::Test {
protected:
TalkMediatorImplTest() {}
virtual ~TalkMediatorImplTest() {}
TalkMediatorImpl* NewMockedTalkMediator(
MockMediatorThread* mock_mediator_thread) {
return new TalkMediatorImpl(mock_mediator_thread,
NotifierOptions());
}
int last_message_;
private:
// TalkMediatorImpl expects a message loop.
MessageLoop message_loop_;
DISALLOW_COPY_AND_ASSIGN(TalkMediatorImplTest);
};
TEST_F(TalkMediatorImplTest, SetAuthToken) {
scoped_ptr<TalkMediatorImpl> talk1(
NewMockedTalkMediator(new MockMediatorThread()));
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_TRUE(talk1->state_.initialized);
talk1->Logout();
scoped_ptr<TalkMediatorImpl> talk2(
NewMockedTalkMediator(new MockMediatorThread()));
talk2->SetAuthToken("chromium@mail.google.com", "token", "fake_service");
EXPECT_TRUE(talk2->state_.initialized);
talk2->Logout();
scoped_ptr<TalkMediatorImpl> talk3(
NewMockedTalkMediator(new MockMediatorThread()));
talk3->SetAuthToken("chromium@mail.google.com", "token", "fake_service");
EXPECT_TRUE(talk3->state_.initialized);
talk3->Logout();
}
TEST_F(TalkMediatorImplTest, LoginWiring) {
// The TalkMediatorImpl owns the mock.
MockMediatorThread* mock = new MockMediatorThread();
scoped_ptr<TalkMediatorImpl> talk1(NewMockedTalkMediator(mock));
// Login checks states for initialization.
EXPECT_FALSE(talk1->Login());
EXPECT_EQ(0, mock->login_calls);
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_EQ(0, mock->update_settings_calls);
EXPECT_TRUE(talk1->Login());
EXPECT_EQ(1, mock->login_calls);
// We call SetAuthToken again to update the settings after an update.
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_EQ(1, mock->update_settings_calls);
// Successive calls to login will fail. One needs to create a new talk
// mediator object.
EXPECT_FALSE(talk1->Login());
EXPECT_EQ(1, mock->login_calls);
EXPECT_TRUE(talk1->Logout());
EXPECT_EQ(1, mock->logout_calls);
// Successive logout calls do nothing.
EXPECT_FALSE(talk1->Logout());
EXPECT_EQ(1, mock->logout_calls);
}
TEST_F(TalkMediatorImplTest, SendNotification) {
// The TalkMediatorImpl owns the mock.
MockMediatorThread* mock = new MockMediatorThread();
scoped_ptr<TalkMediatorImpl> talk1(NewMockedTalkMediator(mock));
// Failure due to not being logged in.
Notification data;
EXPECT_FALSE(talk1->SendNotification(data));
EXPECT_EQ(0, mock->send_calls);
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_TRUE(talk1->Login());
talk1->OnConnectionStateChange(true);
EXPECT_EQ(1, mock->login_calls);
// Should be subscribed now.
EXPECT_TRUE(talk1->state_.subscribed);
EXPECT_TRUE(talk1->SendNotification(data));
EXPECT_EQ(1, mock->send_calls);
EXPECT_TRUE(talk1->SendNotification(data));
EXPECT_EQ(2, mock->send_calls);
EXPECT_TRUE(talk1->Logout());
EXPECT_EQ(1, mock->logout_calls);
// Failure due to being logged out.
EXPECT_FALSE(talk1->SendNotification(data));
EXPECT_EQ(2, mock->send_calls);
}
TEST_F(TalkMediatorImplTest, MediatorThreadCallbacks) {
// The TalkMediatorImpl owns the mock.
MockMediatorThread* mock = new MockMediatorThread();
scoped_ptr<TalkMediatorImpl> talk1(NewMockedTalkMediator(mock));
MockTalkMediatorDelegate mock_delegate;
EXPECT_CALL(mock_delegate, OnNotificationStateChange(true));
EXPECT_CALL(mock_delegate, OnIncomingNotification(_));
EXPECT_CALL(mock_delegate, OnOutgoingNotification());
talk1->SetDelegate(&mock_delegate);
talk1->SetAuthToken("chromium@gmail.com", "token", "fake_service");
EXPECT_TRUE(talk1->Login());
EXPECT_EQ(1, mock->login_calls);
// The message triggers calls to listen and subscribe.
EXPECT_EQ(1, mock->listen_calls);
EXPECT_EQ(1, mock->subscribe_calls);
EXPECT_TRUE(talk1->state_.subscribed);
// After subscription success is receieved, the talk mediator will allow
// sending of notifications.
Notification outgoing_data;
EXPECT_TRUE(talk1->SendNotification(outgoing_data));
EXPECT_EQ(1, mock->send_calls);
Notification incoming_data;
incoming_data.channel = "service_url";
incoming_data.data = "service_data";
mock->ReceiveNotification(incoming_data);
// Shouldn't trigger a call to the delegate since we disconnect
// it before we logout the mediator thread.
talk1->Logout();
talk1.reset();
}
} // namespace notifier
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.