text stringlengths 54 60.6k |
|---|
<commit_before>/*
SWARM
Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
/*
Blocked bloom filter with precomputed bit patterns
as described in
Putze F, Sanders P, Singler J (2009)
Cache-, Hash- and Space-Efficient Bloom Filters
Journal of Experimental Algorithmics, 14, 4
https://doi.org/10.1145/1498698.1594230
*/
#include "swarm.h"
void bloomflex_patterns_generate(struct bloomflex_s * b);
void bloomflex_patterns_generate(struct bloomflex_s * b)
{
#if 0
printf("Generating %" PRIu64 " patterns with %" PRIu64 " bits set.\n",
b->pattern_count,
b->pattern_k);
#endif
for(auto i = 0U; i < b->pattern_count; i++)
{
uint64_t pattern {0};
for(auto j = 0U; j < b->pattern_k; j++)
{
uint64_t onebit {0};
onebit = 1ULL << (arch_random() & 63);
while ((pattern & onebit) != 0U) {
onebit = 1ULL << (arch_random() & 63);
}
pattern |= onebit;
}
b->patterns[i] = pattern;
}
}
auto bloomflex_init(uint64_t size, unsigned int k) -> struct bloomflex_s *
{
/* Input size is in bytes for full bitmap */
auto * b = static_cast<struct bloomflex_s *>(xmalloc(sizeof(struct bloomflex_s)));
b->size = size >> 3;
b->pattern_shift = 16;
b->pattern_count = 1 << b->pattern_shift;
b->pattern_mask = b->pattern_count - 1;
b->pattern_k = k;
b->patterns = static_cast<uint64_t *>(xmalloc(b->pattern_count * 8));
bloomflex_patterns_generate(b);
b->bitmap = static_cast<uint64_t *>(xmalloc(size));
memset(b->bitmap, UINT8_MAX, size);
return b;
}
void bloomflex_exit(struct bloomflex_s * b)
{
xfree(b->bitmap);
xfree(b->patterns);
xfree(b);
}
<commit_msg>avoid magic numbers<commit_after>/*
SWARM
Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
/*
Blocked bloom filter with precomputed bit patterns
as described in
Putze F, Sanders P, Singler J (2009)
Cache-, Hash- and Space-Efficient Bloom Filters
Journal of Experimental Algorithmics, 14, 4
https://doi.org/10.1145/1498698.1594230
*/
#include "swarm.h"
void bloomflex_patterns_generate(struct bloomflex_s * b);
void bloomflex_patterns_generate(struct bloomflex_s * b)
{
constexpr auto max_range {63U}; // i & max_range = cap values to 63 max
#if 0
printf("Generating %" PRIu64 " patterns with %" PRIu64 " bits set.\n",
b->pattern_count,
b->pattern_k);
#endif
for(auto i = 0U; i < b->pattern_count; i++)
{
uint64_t pattern {0};
for(auto j = 0U; j < b->pattern_k; j++)
{
uint64_t onebit {0};
onebit = 1ULL << (arch_random() & max_range); // 0 <= shift <= 63
while ((pattern & onebit) != 0U) {
onebit = 1ULL << (arch_random() & max_range);
}
pattern |= onebit;
}
b->patterns[i] = pattern;
}
}
auto bloomflex_init(uint64_t size, unsigned int k) -> struct bloomflex_s *
{
/* Input size is in bytes for full bitmap */
constexpr auto multiplier {16U}; // multiply by 65,536
constexpr auto divider {3U}; // divide by 8
auto * b = static_cast<struct bloomflex_s *>(xmalloc(sizeof(struct bloomflex_s)));
b->size = size >> divider;
b->pattern_shift = multiplier;
b->pattern_count = 1 << b->pattern_shift;
b->pattern_mask = b->pattern_count - 1;
b->pattern_k = k;
b->patterns = static_cast<uint64_t *>(xmalloc(b->pattern_count * sizeof(uint64_t)));
bloomflex_patterns_generate(b);
b->bitmap = static_cast<uint64_t *>(xmalloc(size));
memset(b->bitmap, UINT8_MAX, size);
return b;
}
void bloomflex_exit(struct bloomflex_s * b)
{
xfree(b->bitmap);
xfree(b->patterns);
xfree(b);
}
<|endoftext|> |
<commit_before>///
/// @file MainWindow.cpp
///
/// @Copyright (C) 2013 The Imaging Source GmbH; Edgar Thier <edgarthier@gmail.com>
///
#include "MainWindow.h"
#include "ui_mainwindow.h"
#include "../Camera.h"
#include "../utils.h"
#include <memory>
#include <thread>
#include <future>
#include <QThread>
#include <QFileDialog>
#include <QTreeView>
#include <QApplication>
using namespace tis;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tabWidget->setCurrentIndex(0); // assure we always start with overview tab
// assure camera list is sorted after the serial numbers in alphabetical order
ui->cameraList->sortByColumn(0,Qt::AscendingOrder);
ui->cameraList->setSortingEnabled(true);
// disable dropping of leaves as top level items
ui->cameraList->invisibleRootItem()->setFlags( Qt::ItemIsSelectable |
Qt::ItemIsUserCheckable |
Qt::ItemIsEnabled );
// allow passing of camera_list between threads
qRegisterMetaType<camera_list> ("camera_list");
qRegisterMetaType<std::shared_ptr<Camera>> ("std::shared_ptr<Camera>");
// connect thread signal to out update method
connect(&uh, SIGNAL(update(camera_list)), this, SLOT(updateCycle(camera_list)));
connect(&uh, SIGNAL(deprecated(std::shared_ptr<Camera>)), this, SLOT(deprecatedCamera(std::shared_ptr<Camera>)));
uh.start();
// hide progressbar until it is needed
ui->progressFirmwareUpload->setHidden(true);
// disable all tabs except first one
// for (int x = 1; x < ui->tabWidget->count(); ++x)
// {
// ui->tabWidget->setTabEnabled(x, false);
// }
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::displayCamera()
{
// for (int x = 1; x < ui->tabWidget->count(); ++x)
// {
// ui->tabWidget->setTabEnabled(x, true);
// }
QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();
QTreeWidgetItem* item;
if (!selection.empty())
{
item = selection.at(0);
}
else
{
return;
}
auto cam = getCameraFromList(cameras, item->text(coloumn.serial).toStdString());
if (cam == NULL)
{
return;
}
selectedCamera = cam;
blockUpload = false;
// overview tab
ui->displayModelName->setText(QString(cam->getModelName().c_str()));
ui->displaySerialNumber->setText(QString(cam->getSerialNumber().c_str()));
ui->displayVendor->setText(QString(cam->getVendorName().c_str()));
ui->displayCurrentIP->setText(QString(cam->getCurrentIP().c_str()));
ui->displayCurrentNetmask->setText(QString(cam->getCurrentSubnet().c_str()));
ui->displayCurrentGateway->setText(QString(cam->getCurrentGateway().c_str()));
ui->displayMAC->setText(QString(cam->getMAC().c_str()));
// set name tab
ui->editName->setText(QString(cam->getUserDefinedName().c_str()));
// settings tab
ui->editSettingsIP->setText(QString(cam->getPersistentIP().c_str()));
ui->editSettingsNetmask->setText(QString(cam->getPersistentSubnet().c_str()));
ui->editSettingsGateway->setText(QString(cam->getPersistentGateway().c_str()));
if (cam->isDHCPactive())
{
ui->checkBoxDHCP->setChecked(true);
}
else
{
ui->checkBoxDHCP->setChecked(false);
}
if (cam->isStaticIPactive())
{
ui->checkBoxStatic->setChecked(true);
// enable persistent config fields
ui->editSettingsIP->setEnabled(true);
ui->editSettingsNetmask->setEnabled(true);
ui->editSettingsGateway->setEnabled(true);
}
else
{
ui->checkBoxStatic->setChecked(false);
// disable persistent config fields
ui->editSettingsIP->setEnabled(false);
ui->editSettingsNetmask->setEnabled(false);
ui->editSettingsGateway->setEnabled(false);
}
// firmware tab
ui->labelVersion->setText(cam->getFirmwareVersion().c_str());
}
void MainWindow::addNetworkInterfacesToCameraList ()
{
auto interfaces = detectNetworkInterfaces();
for (const auto& interface : interfaces)
{
if ((ui->cameraList->findItems(QString(interface->getInterfaceName().c_str()), Qt::MatchContains).empty()))
{
QTreeWidgetItem* ifa = new QTreeWidgetItem();
ifa->setText(0, QString(interface->getInterfaceName().c_str()));
ifa->setFlags(Qt::ItemIsEnabled);
ifa->setDisabled(false);
ifa->sortChildren(0,Qt::AscendingOrder);
ifa->setExpanded(true);
ui->cameraList->addTopLevelItem(ifa);
}
}
}
void MainWindow::addCameraToCameraList (const std::shared_ptr<Camera> cam)
{
QList<QTreeWidgetItem*> interface = ui->cameraList->findItems(QString(cam->getInterfaceName().c_str()), Qt::MatchContains);
if (!interface.empty())
{
QTreeWidgetItem* new_cam = new QTreeWidgetItem();
QString name = cam->getModelName().c_str();
new_cam->setText(coloumn.model, name);
new_cam->setText(coloumn.serial, QString(cam->getSerialNumber().c_str()));
new_cam->setText(coloumn.name, QString(cam->getUserDefinedName().c_str()));
new_cam->setText(coloumn.ip, QString(cam->getCurrentIP().c_str()));
new_cam->setText(coloumn.netmask, QString(cam->getCurrentSubnet().c_str()));
new_cam->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable
| Qt::ItemIsDropEnabled | Qt::ItemIsEnabled);
new_cam->setDisabled(false);
interface.at(0)->addChild(new_cam);
}
}
void MainWindow::updateCamera (QTreeWidgetItem& item, const std::shared_ptr<Camera> camera)
{
item.setText(coloumn.name, QString(camera->getUserDefinedName().c_str()));
item.setText(coloumn.ip, QString(camera->getCurrentIP().c_str()));
item.setText(coloumn.netmask,QString(camera->getCurrentSubnet().c_str()));
// if nothing is selected we are finished
if (selectedCamera == NULL)
{
return;
}
if (camera->getSerialNumber().compare(selectedCamera->getSerialNumber()) == 0)
{
ui->displayModelName->setText(QString(camera->getModelName().c_str()));
ui->displaySerialNumber->setText(QString(camera->getSerialNumber().c_str()));
ui->displayVendor->setText(QString(camera->getVendorName().c_str()));
ui->displayCurrentIP->setText(QString(camera->getCurrentIP().c_str()));
ui->displayCurrentNetmask->setText(QString(camera->getCurrentSubnet().c_str()));
ui->displayCurrentGateway->setText(QString(camera->getCurrentGateway().c_str()));
ui->displayMAC->setText(QString(camera->getMAC().c_str()));
// firmware tab
ui->labelVersion->setText(camera->getFirmwareVersion().c_str());
}
}
void MainWindow::updateCameraList ()
{
QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();
QString s;
if (!selection.empty())
{
s = selection.at(0)->text(0);
}
addNetworkInterfacesToCameraList();
for (const auto& cam : cameras)
{
QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
QString(cam->getSerialNumber().c_str()),Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
if (list.size() != 1)
{
addCameraToCameraList(cam);
}
else
{
updateCamera(*list.at(0), cam);
}
}
}
void MainWindow::changeToSettings()
{
int index = 1;
for (int x = 0; x < ui->tabWidget->count(); ++x)
{
const QWidget* q = ui->tabWidget->widget(x);
if (q->accessibleName().compare(QString("Settings")) == 0)
{
index = x;
break;
}
}
ui->tabWidget->setCurrentIndex(index);
}
void MainWindow::sendForceIP()
{
std::string forceIP = ui->editForceIP->text().toStdString();
std::string forceGateway = ui->editForceGateway->text().toStdString();
std::string forceNetmask = ui->editForceNetmask->text().toStdString();
std::string errorMessage;
// check if input is valid
if (!isValidIpAddress(forceIP))
{
errorMessage.append("Not a valid IP\n");
}
if (!isValidIpAddress(forceGateway))
{
errorMessage.append("Not a valid netmask\n");
}
if (!isValidIpAddress(forceNetmask))
{
errorMessage.append("Not a valid gateway");
}
if (!errorMessage.empty())
{
QString msg = errorMessage.c_str();
box.showMessage(msg);
return;
}
selectedCamera->forceIP(forceIP, forceNetmask, forceGateway);
}
void MainWindow::saveName()
{
std::string name = ui->editName->text().toStdString();
if (selectedCamera != NULL)
{
selectedCamera->setUserDefinedName(name);
}
ui->editName->setText("");
}
void MainWindow::saveSettings ()
{
if (selectedCamera == NULL)
{
return;
}
// retrieve Settings
bool activateDHCP = ui->checkBoxDHCP->isChecked();
bool activateStatic = ui->checkBoxStatic->isChecked();
std::string ip = ui->editSettingsIP->text().toStdString();
std::string netmask = ui->editSettingsNetmask->text().toStdString();
std::string gateway = ui->editSettingsGateway->text().toStdString();
std::string errorMessage;
// check if input is valid
if (!isValidIpAddress(ip))
{
errorMessage.append("Not a valid IP\n");
}
if (!isValidIpAddress(netmask))
{
errorMessage.append("Not a valid netmask\n");
}
if (!isValidIpAddress(gateway))
{
errorMessage.append("Not a valid gateway");
}
if (!errorMessage.empty())
{
QString msg = errorMessage.c_str();
box.showMessage(msg);
return;
}
if (!selectedCamera->setPersistentIP(ip))
{
QString s = "Error setting Persistent IP.";
box.showMessage(s);
return;
}
if (!selectedCamera->setPersistentSubnet(netmask))
{
QString s = "Error setting Persistent Netmask.";
box.showMessage(s);
return;
}
if (!selectedCamera->setPersistentGateway(gateway))
{
QString s = "Error setting Persistent Gateway.";
box.showMessage(s);
return;
}
if (activateStatic)
{
selectedCamera->setStaticIPstate(true);
}
else
{
selectedCamera->setStaticIPstate(false);
}
if (activateDHCP)
{
selectedCamera->setDHCPstate(true);
}
else
{
selectedCamera->setDHCPstate(false);
}
selectedCamera->resetIP();
}
void MainWindow::allowPersistentConfig (bool allow)
{
if (allow)
{
ui->editSettingsIP->setEnabled(true);
ui->editSettingsNetmask->setEnabled(true);
ui->editSettingsGateway->setEnabled(true);
}
else
{
ui->editSettingsIP->setEnabled(false);
ui->editSettingsNetmask->setEnabled(false);
ui->editSettingsGateway->setEnabled(false);
}
}
void MainWindow::buttonFirmware_clicked ()
{
// show file dialog and fill edit box with selected filepath
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Firmware File"),
QDir::homePath(),
tr("Firmware Files (*.fwpack *.fw)"));
ui->editFirmwarePath->setText(fileName);
}
void MainWindow::uploadFirmware ()
{
if (blockUpload)
{
return;
}
std::string firmware_file = ui->editFirmwarePath->text().toStdString();
if (firmware_file.empty())
{
return;
}
ui->progressFirmwareUpload->setVisible(true);
auto func = [this] (int val)
{
ui->progressFirmwareUpload->setValue(val);
};
if (selectedCamera->uploadFirmware(firmware_file, func))
{
blockUpload = true;
QString s = "Successfully uploaded Firmware. Please reconnect your camera for full funcionality.";
box.showMessage(s);
}
else
{
QString s = "Error while uploading Firmware. Please try again.";
box.showMessage(s);
}
ui->editFirmwarePath->setText("");
ui->progressFirmwareUpload->setVisible(false);
}
void MainWindow::updateCycle (camera_list c)
{
this->cameras = c;
updateCameraList();
}
void MainWindow::deprecatedCamera (std::shared_ptr<Camera> camera)
{
QTreeWidgetItem* item;
QList<QTreeWidgetItem*> l = ui->cameraList->selectedItems();
if (l.size() > 1)
{
// something is wrong; don't make it worse
return;
}
// the lost camera is the selected one, therefore we have to clean up everything
if (l.size() == 1 && camera->getSerialNumber().compare(l.at(0)->text(coloumn.serial).toStdString()) == 0)
{
item = l.at(0);
QString defaultText = "<Select Device>";
QString emptyString = "";
ui->tabWidget->setCurrentIndex(0);
// not working; gui is not updated
// for (int x = 1; x < ui->tabWidget->count(); ++x)
// {
// ui->tabWidget->setTabEnabled(x, false);
// }
ui->displayModelName->setText(defaultText);
ui->displaySerialNumber->setText(defaultText);
ui->displayVendor->setText(defaultText);
ui->displayCurrentIP->setText(defaultText);
ui->displayCurrentNetmask->setText(defaultText);
ui->displayCurrentGateway->setText(defaultText);
ui->displayMAC->setText(defaultText);
// set name tab
ui->editName->setText(emptyString);
// settings tab
ui->editSettingsIP->setText(emptyString);
ui->editSettingsNetmask->setText(emptyString);
ui->editSettingsGateway->setText(emptyString);
ui->checkBoxDHCP->setChecked(false);
ui->checkBoxStatic->setChecked(false);
// enable persistent config fields
ui->editSettingsIP->setEnabled(true);
ui->editSettingsNetmask->setEnabled(true);
ui->editSettingsGateway->setEnabled(true);
// firmware tab
ui->labelVersion->setText(defaultText);
blockUpload = false;
}
else
{
// Not the selected camera
QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
QString(camera->getSerialNumber().c_str()), Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
if (list.size() == 1)
{
item = list.at(0);
}
else
{
return;
}
}
// remove from camera tree
QTreeWidgetItem* par = item->parent();
par->removeChild(item);
}
<commit_msg>Cleanup<commit_after>///
/// @file MainWindow.cpp
///
/// @Copyright (C) 2013 The Imaging Source GmbH; Edgar Thier <edgarthier@gmail.com>
///
#include "MainWindow.h"
#include "ui_mainwindow.h"
#include "../Camera.h"
#include "../utils.h"
#include <memory>
#include <thread>
#include <future>
#include <QThread>
#include <QFileDialog>
#include <QTreeView>
#include <QApplication>
using namespace tis;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tabWidget->setCurrentIndex(0); // assure we always start with overview tab
// assure camera list is sorted after the serial numbers in alphabetical order
ui->cameraList->sortByColumn(0,Qt::AscendingOrder);
ui->cameraList->setSortingEnabled(true);
// disable dropping of leaves as top level items
ui->cameraList->invisibleRootItem()->setFlags( Qt::ItemIsSelectable |
Qt::ItemIsUserCheckable |
Qt::ItemIsEnabled );
// allow passing of camera_list between threads
qRegisterMetaType<camera_list> ("camera_list");
qRegisterMetaType<std::shared_ptr<Camera>> ("std::shared_ptr<Camera>");
// connect thread signal to out update method
connect(&uh, SIGNAL(update(camera_list)), this, SLOT(updateCycle(camera_list)));
connect(&uh, SIGNAL(deprecated(std::shared_ptr<Camera>)), this, SLOT(deprecatedCamera(std::shared_ptr<Camera>)));
uh.start();
// hide progressbar until it is needed
ui->progressFirmwareUpload->setHidden(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::displayCamera()
{
QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();
QTreeWidgetItem* item;
if (!selection.empty())
{
item = selection.at(0);
}
else
{
return;
}
auto cam = getCameraFromList(cameras, item->text(coloumn.serial).toStdString());
if (cam == NULL)
{
return;
}
selectedCamera = cam;
blockUpload = false;
// overview tab
ui->displayModelName->setText(QString(cam->getModelName().c_str()));
ui->displaySerialNumber->setText(QString(cam->getSerialNumber().c_str()));
ui->displayVendor->setText(QString(cam->getVendorName().c_str()));
ui->displayCurrentIP->setText(QString(cam->getCurrentIP().c_str()));
ui->displayCurrentNetmask->setText(QString(cam->getCurrentSubnet().c_str()));
ui->displayCurrentGateway->setText(QString(cam->getCurrentGateway().c_str()));
ui->displayMAC->setText(QString(cam->getMAC().c_str()));
// set name tab
ui->editName->setText(QString(cam->getUserDefinedName().c_str()));
// settings tab
ui->editSettingsIP->setText(QString(cam->getPersistentIP().c_str()));
ui->editSettingsNetmask->setText(QString(cam->getPersistentSubnet().c_str()));
ui->editSettingsGateway->setText(QString(cam->getPersistentGateway().c_str()));
if (cam->isDHCPactive())
{
ui->checkBoxDHCP->setChecked(true);
}
else
{
ui->checkBoxDHCP->setChecked(false);
}
if (cam->isStaticIPactive())
{
ui->checkBoxStatic->setChecked(true);
// enable persistent config fields
ui->editSettingsIP->setEnabled(true);
ui->editSettingsNetmask->setEnabled(true);
ui->editSettingsGateway->setEnabled(true);
}
else
{
ui->checkBoxStatic->setChecked(false);
// disable persistent config fields
ui->editSettingsIP->setEnabled(false);
ui->editSettingsNetmask->setEnabled(false);
ui->editSettingsGateway->setEnabled(false);
}
// firmware tab
ui->labelVersion->setText(cam->getFirmwareVersion().c_str());
}
void MainWindow::addNetworkInterfacesToCameraList ()
{
auto interfaces = detectNetworkInterfaces();
for (const auto& interface : interfaces)
{
if ((ui->cameraList->findItems(QString(interface->getInterfaceName().c_str()), Qt::MatchContains).empty()))
{
QTreeWidgetItem* ifa = new QTreeWidgetItem();
ifa->setText(0, QString(interface->getInterfaceName().c_str()));
ifa->setFlags(Qt::ItemIsEnabled);
ifa->setDisabled(false);
ifa->sortChildren(0,Qt::AscendingOrder);
ifa->setExpanded(true);
ui->cameraList->addTopLevelItem(ifa);
}
}
}
void MainWindow::addCameraToCameraList (const std::shared_ptr<Camera> cam)
{
QList<QTreeWidgetItem*> interface = ui->cameraList->findItems(QString(cam->getInterfaceName().c_str()), Qt::MatchContains);
if (!interface.empty())
{
QTreeWidgetItem* new_cam = new QTreeWidgetItem();
QString name = cam->getModelName().c_str();
new_cam->setText(coloumn.model, name);
new_cam->setText(coloumn.serial, QString(cam->getSerialNumber().c_str()));
new_cam->setText(coloumn.name, QString(cam->getUserDefinedName().c_str()));
new_cam->setText(coloumn.ip, QString(cam->getCurrentIP().c_str()));
new_cam->setText(coloumn.netmask, QString(cam->getCurrentSubnet().c_str()));
new_cam->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable
| Qt::ItemIsDropEnabled | Qt::ItemIsEnabled);
new_cam->setDisabled(false);
interface.at(0)->addChild(new_cam);
}
}
void MainWindow::updateCamera (QTreeWidgetItem& item, const std::shared_ptr<Camera> camera)
{
item.setText(coloumn.name, QString(camera->getUserDefinedName().c_str()));
item.setText(coloumn.ip, QString(camera->getCurrentIP().c_str()));
item.setText(coloumn.netmask,QString(camera->getCurrentSubnet().c_str()));
// if nothing is selected we are finished
if (selectedCamera == NULL)
{
return;
}
if (camera->getSerialNumber().compare(selectedCamera->getSerialNumber()) == 0)
{
ui->displayModelName->setText(QString(camera->getModelName().c_str()));
ui->displaySerialNumber->setText(QString(camera->getSerialNumber().c_str()));
ui->displayVendor->setText(QString(camera->getVendorName().c_str()));
ui->displayCurrentIP->setText(QString(camera->getCurrentIP().c_str()));
ui->displayCurrentNetmask->setText(QString(camera->getCurrentSubnet().c_str()));
ui->displayCurrentGateway->setText(QString(camera->getCurrentGateway().c_str()));
ui->displayMAC->setText(QString(camera->getMAC().c_str()));
// firmware tab
ui->labelVersion->setText(camera->getFirmwareVersion().c_str());
}
}
void MainWindow::updateCameraList ()
{
QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();
QString s;
if (!selection.empty())
{
s = selection.at(0)->text(0);
}
addNetworkInterfacesToCameraList();
for (const auto& cam : cameras)
{
QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
QString(cam->getSerialNumber().c_str()),Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
if (list.size() != 1)
{
addCameraToCameraList(cam);
}
else
{
updateCamera(*list.at(0), cam);
}
}
}
void MainWindow::changeToSettings()
{
int index = 1;
for (int x = 0; x < ui->tabWidget->count(); ++x)
{
const QWidget* q = ui->tabWidget->widget(x);
if (q->accessibleName().compare(QString("Settings")) == 0)
{
index = x;
break;
}
}
ui->tabWidget->setCurrentIndex(index);
}
void MainWindow::sendForceIP()
{
std::string forceIP = ui->editForceIP->text().toStdString();
std::string forceGateway = ui->editForceGateway->text().toStdString();
std::string forceNetmask = ui->editForceNetmask->text().toStdString();
std::string errorMessage;
// check if input is valid
if (!isValidIpAddress(forceIP))
{
errorMessage.append("Not a valid IP\n");
}
if (!isValidIpAddress(forceGateway))
{
errorMessage.append("Not a valid netmask\n");
}
if (!isValidIpAddress(forceNetmask))
{
errorMessage.append("Not a valid gateway");
}
if (!errorMessage.empty())
{
QString msg = errorMessage.c_str();
box.showMessage(msg);
return;
}
selectedCamera->forceIP(forceIP, forceNetmask, forceGateway);
}
void MainWindow::saveName()
{
std::string name = ui->editName->text().toStdString();
if (selectedCamera != NULL)
{
selectedCamera->setUserDefinedName(name);
}
ui->editName->setText("");
}
void MainWindow::saveSettings ()
{
if (selectedCamera == NULL)
{
return;
}
// retrieve Settings
bool activateDHCP = ui->checkBoxDHCP->isChecked();
bool activateStatic = ui->checkBoxStatic->isChecked();
std::string ip = ui->editSettingsIP->text().toStdString();
std::string netmask = ui->editSettingsNetmask->text().toStdString();
std::string gateway = ui->editSettingsGateway->text().toStdString();
std::string errorMessage;
// check if input is valid
if (!isValidIpAddress(ip))
{
errorMessage.append("Not a valid IP\n");
}
if (!isValidIpAddress(netmask))
{
errorMessage.append("Not a valid netmask\n");
}
if (!isValidIpAddress(gateway))
{
errorMessage.append("Not a valid gateway");
}
if (!errorMessage.empty())
{
QString msg = errorMessage.c_str();
box.showMessage(msg);
return;
}
if (!selectedCamera->setPersistentIP(ip))
{
QString s = "Error setting Persistent IP.";
box.showMessage(s);
return;
}
if (!selectedCamera->setPersistentSubnet(netmask))
{
QString s = "Error setting Persistent Netmask.";
box.showMessage(s);
return;
}
if (!selectedCamera->setPersistentGateway(gateway))
{
QString s = "Error setting Persistent Gateway.";
box.showMessage(s);
return;
}
if (activateStatic)
{
selectedCamera->setStaticIPstate(true);
}
else
{
selectedCamera->setStaticIPstate(false);
}
if (activateDHCP)
{
selectedCamera->setDHCPstate(true);
}
else
{
selectedCamera->setDHCPstate(false);
}
selectedCamera->resetIP();
}
void MainWindow::allowPersistentConfig (bool allow)
{
if (allow)
{
ui->editSettingsIP->setEnabled(true);
ui->editSettingsNetmask->setEnabled(true);
ui->editSettingsGateway->setEnabled(true);
}
else
{
ui->editSettingsIP->setEnabled(false);
ui->editSettingsNetmask->setEnabled(false);
ui->editSettingsGateway->setEnabled(false);
}
}
void MainWindow::buttonFirmware_clicked ()
{
// show file dialog and fill edit box with selected filepath
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Firmware File"),
QDir::homePath(),
tr("Firmware Files (*.fwpack *.fw)"));
ui->editFirmwarePath->setText(fileName);
}
void MainWindow::uploadFirmware ()
{
if (blockUpload)
{
return;
}
std::string firmware_file = ui->editFirmwarePath->text().toStdString();
if (firmware_file.empty())
{
return;
}
ui->progressFirmwareUpload->setVisible(true);
auto func = [this] (int val)
{
ui->progressFirmwareUpload->setValue(val);
};
if (selectedCamera->uploadFirmware(firmware_file, func))
{
blockUpload = true;
QString s = "Successfully uploaded Firmware. Please reconnect your camera for full funcionality.";
box.showMessage(s);
}
else
{
QString s = "Error while uploading Firmware. Please try again.";
box.showMessage(s);
}
ui->editFirmwarePath->setText("");
ui->progressFirmwareUpload->setVisible(false);
}
void MainWindow::updateCycle (camera_list c)
{
this->cameras = c;
updateCameraList();
}
void MainWindow::deprecatedCamera (std::shared_ptr<Camera> camera)
{
QTreeWidgetItem* item;
QList<QTreeWidgetItem*> l = ui->cameraList->selectedItems();
if (l.size() > 1)
{
// something is wrong; don't make it worse
return;
}
// the lost camera is the selected one, therefore we have to clean up everything
if (l.size() == 1 && camera->getSerialNumber().compare(l.at(0)->text(coloumn.serial).toStdString()) == 0)
{
item = l.at(0);
QString defaultText = "<Select Device>";
QString emptyString = "";
ui->tabWidget->setCurrentIndex(0);
ui->displayModelName->setText(defaultText);
ui->displaySerialNumber->setText(defaultText);
ui->displayVendor->setText(defaultText);
ui->displayCurrentIP->setText(defaultText);
ui->displayCurrentNetmask->setText(defaultText);
ui->displayCurrentGateway->setText(defaultText);
ui->displayMAC->setText(defaultText);
// set name tab
ui->editName->setText(emptyString);
// settings tab
ui->editSettingsIP->setText(emptyString);
ui->editSettingsNetmask->setText(emptyString);
ui->editSettingsGateway->setText(emptyString);
ui->checkBoxDHCP->setChecked(false);
ui->checkBoxStatic->setChecked(false);
// enable persistent config fields
ui->editSettingsIP->setEnabled(true);
ui->editSettingsNetmask->setEnabled(true);
ui->editSettingsGateway->setEnabled(true);
// firmware tab
ui->labelVersion->setText(defaultText);
blockUpload = false;
}
else
{
// Not the selected camera
QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
QString(camera->getSerialNumber().c_str()), Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
if (list.size() == 1)
{
item = list.at(0);
}
else
{
return;
}
}
// remove from camera tree
QTreeWidgetItem* par = item->parent();
par->removeChild(item);
}
<|endoftext|> |
<commit_before><commit_msg>Planning: faster approach to stop_sign<commit_after><|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2005-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : defines exceptions and validation tools
// ***************************************************************************
#ifndef BOOST_RT_VALIDATION_HPP_062604GER
#define BOOST_RT_VALIDATION_HPP_062604GER
// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>
// Boost.Test
#include <boost/test/utils/class_properties.hpp>
// Boost
#include <boost/shared_ptr.hpp>
// STL
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
#include <stdexcept>
#endif
namespace boost {
namespace BOOST_RT_PARAM_NAMESPACE {
// ************************************************************************** //
// ************** runtime::logic_error ************** //
// ************************************************************************** //
class logic_error
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
: public std::exception
#endif
{
typedef shared_ptr<dstring> dstring_ptr;
public:
// Constructor // !! could we eliminate shared_ptr
explicit logic_error( cstring msg ) : m_msg( new dstring( msg.begin(), msg.size() ) ) {}
~logic_error() BOOST_TEST_NOEXCEPT_OR_THROW_VOID
{}
dstring const& msg() const { return *m_msg; }
virtual char_type const* what() const BOOST_TEST_NOEXCEPT_OR_THROW_VOID
{ return m_msg->c_str(); }
private:
dstring_ptr m_msg;
};
// ************************************************************************** //
// ************** runtime::report_logic_error ************** //
// ************************************************************************** //
inline void
report_logic_error( format_stream& msg )
{
throw BOOST_RT_PARAM_NAMESPACE::logic_error( msg.str() );
}
//____________________________________________________________________________//
#define BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg ) \
boost::BOOST_RT_PARAM_NAMESPACE::report_logic_error( format_stream().ref() << msg )
#define BOOST_RT_PARAM_VALIDATE_LOGIC( b, msg ) \
if( b ) {} else BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg )
//____________________________________________________________________________//
} // namespace BOOST_RT_PARAM_NAMESPACE
} // namespace boost
#endif // BOOST_RT_VALIDATION_HPP_062604GER
<commit_msg>Using existing macros in boost.config to achieve the same result<commit_after>// (C) Copyright Gennadiy Rozental 2005-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : defines exceptions and validation tools
// ***************************************************************************
#ifndef BOOST_RT_VALIDATION_HPP_062604GER
#define BOOST_RT_VALIDATION_HPP_062604GER
// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>
// Boost.Test
#include <boost/test/utils/class_properties.hpp>
// Boost
#include <boost/shared_ptr.hpp>
// STL
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
#include <stdexcept>
#endif
namespace boost {
namespace BOOST_RT_PARAM_NAMESPACE {
// ************************************************************************** //
// ************** runtime::logic_error ************** //
// ************************************************************************** //
class logic_error
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
: public std::exception
#endif
{
typedef shared_ptr<dstring> dstring_ptr;
public:
// Constructor // !! could we eliminate shared_ptr
explicit logic_error( cstring msg ) : m_msg( new dstring( msg.begin(), msg.size() ) ) {}
~logic_error() BOOST_NOEXCEPT_OR_NOTHROW
{}
dstring const& msg() const { return *m_msg; }
virtual char_type const* what() const BOOST_NOEXCEPT_OR_NOTHROW
{ return m_msg->c_str(); }
private:
dstring_ptr m_msg;
};
// ************************************************************************** //
// ************** runtime::report_logic_error ************** //
// ************************************************************************** //
inline void
report_logic_error( format_stream& msg )
{
throw BOOST_RT_PARAM_NAMESPACE::logic_error( msg.str() );
}
//____________________________________________________________________________//
#define BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg ) \
boost::BOOST_RT_PARAM_NAMESPACE::report_logic_error( format_stream().ref() << msg )
#define BOOST_RT_PARAM_VALIDATE_LOGIC( b, msg ) \
if( b ) {} else BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg )
//____________________________________________________________________________//
} // namespace BOOST_RT_PARAM_NAMESPACE
} // namespace boost
#endif // BOOST_RT_VALIDATION_HPP_062604GER
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief Arithmetic テンプレート @n
※テキストの数式を展開して、計算結果を得る。@n
演算式解析
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "utils/bitset.hpp"
//#include "utils/order_map.hpp"
namespace utils {
template <typename VTYPE, uint16_t NUM>
class basic_symbol {
const char* table_[NUM];
VTYPE value_[NUM];
uint16_t find_(const char* name, uint8_t n) const {
for(uint16_t i = 0; i < NUM; ++i) {
if(n != 0) {
if(std::strcmp(name, table_[i]) == 0) return i;
} else {
if(std::strncmp(name, table_[i], n) == 0) return i;
}
}
return NUM;
}
public:
basic_symbol() {
for(uint16_t i = 0; i < NUM; ++i) {
table_[i] = nullptr;
}
}
bool insert(const char* name, VTYPE v) {
for(uint16_t i = 0; i < NUM; ++i) {
if(table_[i] == nullptr) {
table_[i] = name;
value_[i] = v;
return true;
}
}
return false;
}
bool erase(const char* name, uint8_t n = 0) {
auto i = find_(name, n);
if(i >= NUM) return false;
table_[i] = nullptr;
return true;
}
bool find(const char* name, uint8_t n = 0) const {
return find_(name, n) < NUM;
}
bool set(const char*name, uint8_t n, VTYPE value) {
auto i = find_(name, n);
if(i >= NUM) return false;
value_[i] = value;
return true;
}
VTYPE get(const char* name, uint8_t n = 0) const {
auto i = find_(name, n);
if(i >= NUM) {
return 0;
}
return value_[i];
}
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Arithmetic クラス
@param[in] VTYPE 基本型
@param[in] SYMBOL シンボルクラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename VTYPE, class SYMBOL = basic_symbol<VTYPE, 16> >
struct basic_arith {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エラー・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class error : uint8_t {
fatal, ///< エラー
number_fatal, ///< 数字の変換に関するエラー
zero_divide, ///< 0除算エラー
binary_fatal, ///< 2進データの変換に関するエラー
octal_fatal, ///< 8進データの変換に関するエラー
hexdecimal_fatal, ///< 16進データの変換に関するエラー
num_fatal, ///< 数値の変換に関するエラー
symbol_fatal, ///< シンボルデータの変換に関するエラー
};
typedef bitset<uint16_t, error> error_t;
private:
SYMBOL symbol_;
const char* tx_;
char ch_;
error_t error_;
VTYPE value_;
void skip_space_() {
while(ch_ == ' ' || ch_ == '\t') {
ch_ = *tx_++;
}
}
VTYPE number_() {
bool inv = false;
/// bool neg = false;
bool point = false;
uint32_t v = 0;
uint32_t fp = 0;
uint32_t fs = 1;
skip_space_();
// 符号、反転の判定
if(ch_ == '-') {
inv = true;
ch_ = *tx_++;
} else if(ch_ == '+') {
ch_ = *tx_++;
// } else if(ch_ == '!' || ch_ == '~') {
// neg = true;
// ch_ = *tx_++;
}
skip_space_();
if(ch_ == '(') {
v = factor_();
} else {
skip_space_();
if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) {
const char* src = tx_ - 1;
while(ch_ != 0) {
ch_ = *tx_++;
if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) ;
else if(ch_ >= '0' && ch_ <= '9') ;
else if(ch_ == '_') ;
else break;
}
if(!symbol_.find(src, tx_ - src)) {
error_.set(error::symbol_fatal);
return 0;
}
v = symbol_.get(src, tx_ - src);
} else {
while(ch_ != 0) {
if(ch_ == '+') break;
else if(ch_ == '-') break;
else if(ch_ == '*') break;
else if(ch_ == '/') break;
else if(ch_ == '&') break;
else if(ch_ == '^') break;
else if(ch_ == '|') break;
else if(ch_ == '%') break;
else if(ch_ == ')') break;
else if(ch_ == '<') break;
else if(ch_ == '>') break;
else if(ch_ == '!') break;
else if(ch_ == '~') break;
else if(ch_ == '.') {
if(point) {
error_.set(error::fatal);
break;
} else {
point = true;
}
} else if(ch_ >= '0' && ch_ <= '9') {
if(point) {
fp *= 10;
fp += ch_ - '0';
fs *= 10;
} else {
v *= 10;
v += ch_ - '0';
}
} else {
error_.set(error::number_fatal);
return 0;
}
ch_ = *tx_++;
}
}
}
if(inv) { v = -v; }
/// if(neg) { v = ~v; }
if(point) {
return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs);
} else {
return static_cast<VTYPE>(v);
}
}
VTYPE factor_() {
VTYPE v = 0;
if(ch_ == '(') {
ch_ = *tx_++;
v = expression_();
if(ch_ == ')') {
ch_ = *tx_++;
} else {
error_.set(error::fatal);
}
} else {
v = number_();
}
return v;
}
VTYPE term_() {
VTYPE v = factor_();
VTYPE tmp;
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '*':
ch_ = *tx_++;
v *= factor_();
break;
case '%':
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v /= tmp;
break;
case '/':
ch_ = *tx_++;
if(ch_ == '/') {
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v %= tmp;
} else {
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v /= tmp;
}
break;
case '<':
ch_ = *tx_++;
if(ch_ == '<') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
case '>':
ch_ = *tx_++;
if(ch_ == '>') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
default:
return v;
break;
}
}
return v;
}
VTYPE expression_() {
VTYPE v = term_();
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '+':
ch_ = *tx_++;
v += term_();
break;
case '-':
ch_ = *tx_++;
v -= term_();
break;
case '&':
ch_ = *tx_++;
v &= term_();
break;
case '^':
ch_ = *tx_++;
v ^= term_();
break;
case '|':
ch_ = *tx_++;
v |= term_();
break;
default:
return v;
break;
}
}
return v;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { }
//-----------------------------------------------------------------//
/*!
@brief シンボルの設定
@param[in] name シンボル名
@param[in] value 値
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool set_value(const char* name, VTYPE value) {
return symbol_.insert(name, value);
}
//-----------------------------------------------------------------//
/*!
@brief 解析を開始
@param[in] text 解析テキスト
@return 文法にエラーがあった場合、「false」
*/
//-----------------------------------------------------------------//
bool analize(const char* text) {
error_.clear();
if(text == nullptr) {
error_.set(error::fatal);
return false;
}
tx_ = text;
ch_ = *tx_++;
if(ch_ != 0) {
value_ = expression_();
} else {
error_.set(error::fatal);
}
if(error_() != 0) {
return false;
} else if(ch_ != 0) {
error_.set(error::fatal);
return false;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief エラーを受け取る
@return エラー
*/
//-----------------------------------------------------------------//
const error_t& get_error() const { return error_; }
//-----------------------------------------------------------------//
/*!
@brief 結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
VTYPE get() const { return value_; }
//-----------------------------------------------------------------//
/*!
@brief () で結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
VTYPE operator() () const { return value_; }
};
}
<commit_msg>update symbol api<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief Arithmetic テンプレート @n
※テキストの数式を展開して、計算結果を得る。@n
演算式解析
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "utils/bitset.hpp"
//#include "utils/order_map.hpp"
namespace utils {
template <typename VTYPE, uint16_t NUM>
class basic_symbol {
const char* table_[NUM];
VTYPE value_[NUM];
uint16_t find_(const char* name, uint8_t n) const {
for(uint16_t i = 0; i < NUM; ++i) {
if(n != 0) {
if(std::strcmp(name, table_[i]) == 0) return i;
} else {
if(std::strncmp(name, table_[i], n) == 0) return i;
}
}
return NUM;
}
public:
basic_symbol() {
for(uint16_t i = 0; i < NUM; ++i) {
table_[i] = nullptr;
}
}
bool insert(const char* name, VTYPE v) {
for(uint16_t i = 0; i < NUM; ++i) {
if(table_[i] == nullptr) {
table_[i] = name;
value_[i] = v;
return true;
}
}
return false;
}
bool erase(const char* name, uint8_t n = 0) {
auto i = find_(name, n);
if(i >= NUM) return false;
table_[i] = nullptr;
return true;
}
bool find(const char* name, uint8_t n = 0) const {
return find_(name, n) < NUM;
}
bool set(const char*name, uint8_t n, VTYPE value) {
auto i = find_(name, n);
if(i >= NUM) return false;
value_[i] = value;
return true;
}
VTYPE get(const char* name, uint8_t n = 0) const {
auto i = find_(name, n);
if(i >= NUM) {
return 0;
}
return value_[i];
}
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Arithmetic クラス
@param[in] VTYPE 基本型
@param[in] SYMBOL シンボルクラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename VTYPE, class SYMBOL = basic_symbol<VTYPE, 16> >
struct basic_arith {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エラー・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class error : uint8_t {
fatal, ///< エラー
number_fatal, ///< 数字の変換に関するエラー
zero_divide, ///< 0除算エラー
binary_fatal, ///< 2進データの変換に関するエラー
octal_fatal, ///< 8進データの変換に関するエラー
hexdecimal_fatal, ///< 16進データの変換に関するエラー
num_fatal, ///< 数値の変換に関するエラー
symbol_fatal, ///< シンボルデータの変換に関するエラー
};
typedef bitset<uint16_t, error> error_t;
private:
SYMBOL symbol_;
const char* tx_;
char ch_;
error_t error_;
VTYPE value_;
void skip_space_() {
while(ch_ == ' ' || ch_ == '\t') {
ch_ = *tx_++;
}
}
VTYPE number_() {
bool inv = false;
/// bool neg = false;
bool point = false;
uint32_t v = 0;
uint32_t fp = 0;
uint32_t fs = 1;
skip_space_();
// 符号、反転の判定
if(ch_ == '-') {
inv = true;
ch_ = *tx_++;
} else if(ch_ == '+') {
ch_ = *tx_++;
// } else if(ch_ == '!' || ch_ == '~') {
// neg = true;
// ch_ = *tx_++;
}
skip_space_();
if(ch_ == '(') {
v = factor_();
} else {
skip_space_();
if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) {
const char* src = tx_ - 1;
while(ch_ != 0) {
ch_ = *tx_++;
if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) ;
else if(ch_ >= '0' && ch_ <= '9') ;
else if(ch_ == '_') ;
else break;
}
if(!symbol_.find(src, tx_ - src)) {
error_.set(error::symbol_fatal);
return 0;
}
v = symbol_.get(src, tx_ - src);
} else {
while(ch_ != 0) {
if(ch_ == '+') break;
else if(ch_ == '-') break;
else if(ch_ == '*') break;
else if(ch_ == '/') break;
else if(ch_ == '&') break;
else if(ch_ == '^') break;
else if(ch_ == '|') break;
else if(ch_ == '%') break;
else if(ch_ == ')') break;
else if(ch_ == '<') break;
else if(ch_ == '>') break;
else if(ch_ == '!') break;
else if(ch_ == '~') break;
else if(ch_ == '.') {
if(point) {
error_.set(error::fatal);
break;
} else {
point = true;
}
} else if(ch_ >= '0' && ch_ <= '9') {
if(point) {
fp *= 10;
fp += ch_ - '0';
fs *= 10;
} else {
v *= 10;
v += ch_ - '0';
}
} else {
error_.set(error::number_fatal);
return 0;
}
ch_ = *tx_++;
}
}
}
if(inv) { v = -v; }
/// if(neg) { v = ~v; }
if(point) {
return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs);
} else {
return static_cast<VTYPE>(v);
}
}
VTYPE factor_() {
VTYPE v = 0;
if(ch_ == '(') {
ch_ = *tx_++;
v = expression_();
if(ch_ == ')') {
ch_ = *tx_++;
} else {
error_.set(error::fatal);
}
} else {
v = number_();
}
return v;
}
VTYPE term_() {
VTYPE v = factor_();
VTYPE tmp;
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '*':
ch_ = *tx_++;
v *= factor_();
break;
case '%':
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v /= tmp;
break;
case '/':
ch_ = *tx_++;
if(ch_ == '/') {
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v %= tmp;
} else {
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v /= tmp;
}
break;
case '<':
ch_ = *tx_++;
if(ch_ == '<') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
case '>':
ch_ = *tx_++;
if(ch_ == '>') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
default:
return v;
break;
}
}
return v;
}
VTYPE expression_() {
VTYPE v = term_();
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '+':
ch_ = *tx_++;
v += term_();
break;
case '-':
ch_ = *tx_++;
v -= term_();
break;
case '&':
ch_ = *tx_++;
v &= term_();
break;
case '^':
ch_ = *tx_++;
v ^= term_();
break;
case '|':
ch_ = *tx_++;
v |= term_();
break;
default:
return v;
break;
}
}
return v;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { }
//-----------------------------------------------------------------//
/*!
@brief シンボルの設定
@param[in] name シンボル名
@param[in] value 値
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool set_value(const char* name, VTYPE value) {
if(symbol_.find(name)) {
return symbol_.set(name, 0, value);
} else {
return symbol_.insert(name, value);
}
}
//-----------------------------------------------------------------//
/*!
@brief 解析を開始
@param[in] text 解析テキスト
@return 文法にエラーがあった場合、「false」
*/
//-----------------------------------------------------------------//
bool analize(const char* text) {
error_.clear();
if(text == nullptr) {
error_.set(error::fatal);
return false;
}
tx_ = text;
ch_ = *tx_++;
if(ch_ != 0) {
value_ = expression_();
} else {
error_.set(error::fatal);
}
if(error_() != 0) {
return false;
} else if(ch_ != 0) {
error_.set(error::fatal);
return false;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief エラーを受け取る
@return エラー
*/
//-----------------------------------------------------------------//
const error_t& get_error() const { return error_; }
//-----------------------------------------------------------------//
/*!
@brief 結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
VTYPE get() const { return value_; }
//-----------------------------------------------------------------//
/*!
@brief () で結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
VTYPE operator() () const { return value_; }
};
}
<|endoftext|> |
<commit_before>/*--------------------------------------------------------------------------
File : spi_nrf5x.cpp
Author : Hoang Nguyen Hoan Oct. 6, 2016
Desc : SPI implementation on nRF5x series MCU
Copyright (c) 2016, I-SYST inc., all rights reserved
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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include "spi_nrf52.h"
#include "nrf.h"
#include "iopinctrl.h"
#ifdef NRF52
typedef NRF_SPIM_Type NRF5X_SPI_REG; // Register map
#else
typedef NRF_SPI_Type NRF5X_SPI_REG; // Register map
#endif
#define NRF_SPI_REG_EVENTS_READY 0x108
typedef struct {
int SpiNo;
SPIDEV *pSpiDev;
uint32_t Clk;
NRF_SPIM_Type *pReg; // Register map
int CsPin; // Chip select pin, Nordic SPI has manual SS pin
} NRF5X_SPIDEV;
#define NRF5X_SPI_MAXDEV 3
static NRF5X_SPIDEV s_nRF5xDev[NRF5X_SPI_MAXDEV] = {
{
0, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM0_BASE, -1
},
{
1, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM1_BASE, -1
},
{
2, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM2_BASE, -1
},
};
bool nRF5xSPIWaitReady(NRF5X_SPIDEV *pDev, int32_t Timeout)
{
uint32_t val = 0;
do {
val = *(uint32_t*)((uint32_t)pDev->pReg + NRF_SPI_REG_EVENTS_READY);
if (val)
return true;
} while (Timeout-- > 0);
return false;
}
bool nRF5xSPIWaitDMA(NRF5X_SPIDEV *pDev, uint32_t Timeout)
{
uint32_t val = 0;
do {
if (pDev->pReg->EVENTS_END)
{
pDev->pReg->EVENTS_END = 0; // clear event
return true;
}
} while (Timeout-- > 0);
return false;
}
int nRF5xSPIGetRate(SERINTRFDEV *pDev)
{
int rate = 0;
if (pDev && pDev->pDevData)
rate = ((NRF5X_SPIDEV*)pDev->pDevData)->pSpiDev->Cfg.Rate;
return rate;
}
// Set data rate in bits/sec (Hz)
// return actual rate
int nRF5xSPISetRate(SERINTRFDEV *pDev, int DataRate)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
if (DataRate < 250000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K125;
dev->Clk = 125000;
}
else if (DataRate < 500000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K250;
dev->Clk = 250000;
}
else if (DataRate < 1000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K500;
dev->Clk = 500000;
}
else if (DataRate < 2000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M1;
dev->Clk = 1000000;
}
else if (DataRate < 4000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M2;
dev->Clk = 2000000;
}
else if (DataRate < 8000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M4;
dev->Clk = 4000000;
}
else
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M8;
dev->Clk = 8000000;
}
dev->pSpiDev->Cfg.Rate = dev->Clk;
return dev->pSpiDev->Cfg.Rate;
}
void nRF5xSPIDisable(SERINTRFDEV *pDev)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev->pDevData;
dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Disabled << SPIM_ENABLE_ENABLE_Pos);
}
void nRF5xSPIEnable(SERINTRFDEV *pDev)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev->pDevData;
dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}
// Initial receive
bool nRF5xSPIStartRx(SERINTRFDEV *pDev, int DevAddr)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
IOPinClear(0, dev->CsPin);
return true;
}
// Receive Data only, no Start/Stop condition
int nRF5xSPIRxData(SERINTRFDEV *pDev, uint8_t *pBuff, int BuffLen)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
dev->pReg->RXD.PTR = (uint32_t)pBuff;
dev->pReg->RXD.MAXCNT = BuffLen;
dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->TXD.PTR = 0;
dev->pReg->TXD.MAXCNT = 0;
dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->EVENTS_END = 0;
dev->pReg->TASKS_START = 1;
nRF5xSPIWaitDMA(dev, 100000);
return dev->pReg->RXD.AMOUNT;
}
// Stop receive
void nRF5xSPIStopRx(SERINTRFDEV *pDev)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
IOPinSet(0, dev->CsPin);
}
// Initiate transmit
bool nRF5xSPIStartTx(SERINTRFDEV *pDev, int DevAddr)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
IOPinClear(0, dev->CsPin);
return true;
}
// Transmit Data only, no Start/Stop condition
int nRF5xSPITxData(SERINTRFDEV *pDev, uint8_t *pData, int DataLen)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
dev->pReg->RXD.PTR = 0;
dev->pReg->RXD.MAXCNT = 0;
dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->TXD.PTR = (uint32_t)pData;
dev->pReg->TXD.MAXCNT = DataLen;
dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->EVENTS_END = 0;
dev->pReg->TASKS_START = 1;
nRF5xSPIWaitDMA(dev, 100000);
return dev->pReg->TXD.AMOUNT;
}
// Stop transmit
void nRF5xSPIStopTx(SERINTRFDEV *pDev)
{
NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;
IOPinSet(0, dev->CsPin);
}
bool SPIInit(SPIDEV *pDev, const SPICFG *pCfgData)
{
NRF5X_SPI_REG *reg;
uint32_t err_code;
uint32_t cfgreg = 0;
if (pCfgData->DevNo < 0 || pCfgData->DevNo > 2)
return false;
// Get the correct register map
reg = s_nRF5xDev[pCfgData->DevNo].pReg;
// Configure I/O pins
IOPinCfg(pCfgData->IOPinMap, SPI_MAX_NB_IOPIN);
reg->PSEL.SCK = pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo;
reg->PSEL.MISO = pCfgData->IOPinMap[SPI_MISO_IOPIN_IDX].PinNo;
reg->PSEL.MOSI = pCfgData->IOPinMap[SPI_MOSI_IOPIN_IDX].PinNo;
s_nRF5xDev[pCfgData->DevNo].CsPin = pCfgData->IOPinMap[SPI_SS_IOPIN_IDX].PinNo;
IOPinSet(0, s_nRF5xDev[pCfgData->DevNo].CsPin);
if (pCfgData->BitOrder == SPIDATABIT_LSB)
{
cfgreg |= SPIM_CONFIG_ORDER_LsbFirst;
}
else
{
cfgreg |= SPIM_CONFIG_ORDER_MsbFirst;
}
if (pCfgData->DataPhase == SPIDATAPHASE_SECOND_CLK)
{
cfgreg |= (SPIM_CONFIG_CPHA_Trailing << SPIM_CONFIG_CPHA_Pos);
}
else
{
cfgreg |= (SPIM_CONFIG_CPHA_Leading << SPIM_CONFIG_CPHA_Pos);
}
//config.irq_priority = APP_IRQ_PRIORITY_LOW;
if (pCfgData->ClkPol == SPICLKPOL_LOW)
{
cfgreg |= (SPI_CONFIG_CPOL_ActiveLow << SPI_CONFIG_CPOL_Pos);
IOPinSet(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
}
else
{
cfgreg |= (SPI_CONFIG_CPOL_ActiveHigh << SPI_CONFIG_CPOL_Pos);
IOPinClear(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
}
reg->CONFIG = cfgreg;
reg->ORC = 0xFF;
pDev->Cfg = *pCfgData;
s_nRF5xDev[pCfgData->DevNo].pSpiDev = pDev;
pDev->SerIntrf.pDevData = (void*)&s_nRF5xDev[pCfgData->DevNo];
nRF5xSPISetRate(&pDev->SerIntrf, pCfgData->Rate);
pDev->SerIntrf.Disable = nRF5xSPIDisable;
pDev->SerIntrf.Enable = nRF5xSPIEnable;
pDev->SerIntrf.GetRate = nRF5xSPIGetRate;
pDev->SerIntrf.SetRate = nRF5xSPISetRate;
pDev->SerIntrf.StartRx = nRF5xSPIStartRx;
pDev->SerIntrf.RxData = nRF5xSPIRxData;
pDev->SerIntrf.StopRx = nRF5xSPIStopRx;
pDev->SerIntrf.StartTx = nRF5xSPIStartTx;
pDev->SerIntrf.TxData = nRF5xSPITxData;
pDev->SerIntrf.StopTx = nRF5xSPIStopTx;
pDev->SerIntrf.IntPrio = pCfgData->IntPrio;
pDev->SerIntrf.EvtCB = pCfgData->EvtCB;
reg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}
<commit_msg>remove unsused code. Function renaming<commit_after>/*--------------------------------------------------------------------------
File : spi_nrf5x.cpp
Author : Hoang Nguyen Hoan Oct. 6, 2016
Desc : SPI implementation on nRF5x series MCU
Copyright (c) 2016, I-SYST inc., all rights reserved
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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include "nrf.h"
#include "spi_nrf52.h"
#include "iopinctrl.h"
typedef struct {
int DevNo;
SPIDEV *pSpiDev;
uint32_t Clk;
NRF_SPIM_Type *pReg; // Register map
int CsPin; // Chip select pin, Nordic SPI has manual SS pin
} NRF52_SPIDEV;
#define NRF52_SPI_MAXDEV 3
static NRF52_SPIDEV s_nRF52SPIDev[NRF52_SPI_MAXDEV] = {
{
0, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM0_BASE, -1
},
{
1, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM1_BASE, -1
},
{
2, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM2_BASE, -1
},
};
bool nRF52SPIWaitDMA(NRF52_SPIDEV *pDev, uint32_t Timeout)
{
uint32_t val = 0;
do {
if (pDev->pReg->EVENTS_END)
{
pDev->pReg->EVENTS_END = 0; // clear event
return true;
}
} while (Timeout-- > 0);
return false;
}
int nRF52SPIGetRate(SERINTRFDEV *pDev)
{
int rate = 0;
if (pDev && pDev->pDevData)
rate = ((NRF52_SPIDEV*)pDev->pDevData)->pSpiDev->Cfg.Rate;
return rate;
}
// Set data rate in bits/sec (Hz)
// return actual rate
int nRF52SPISetRate(SERINTRFDEV *pDev, int DataRate)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
if (DataRate < 250000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K125;
dev->Clk = 125000;
}
else if (DataRate < 500000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K250;
dev->Clk = 250000;
}
else if (DataRate < 1000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K500;
dev->Clk = 500000;
}
else if (DataRate < 2000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M1;
dev->Clk = 1000000;
}
else if (DataRate < 4000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M2;
dev->Clk = 2000000;
}
else if (DataRate < 8000000)
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M4;
dev->Clk = 4000000;
}
else
{
dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M8;
dev->Clk = 8000000;
}
dev->pSpiDev->Cfg.Rate = dev->Clk;
return dev->pSpiDev->Cfg.Rate;
}
void nRF52SPIDisable(SERINTRFDEV *pDev)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev->pDevData;
dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Disabled << SPIM_ENABLE_ENABLE_Pos);
}
void nRF52SPIEnable(SERINTRFDEV *pDev)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev->pDevData;
dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}
// Initial receive
bool nRF52SPIStartRx(SERINTRFDEV *pDev, int DevAddr)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
IOPinClear(0, dev->CsPin);
return true;
}
// Receive Data only, no Start/Stop condition
int nRF52SPIRxData(SERINTRFDEV *pDev, uint8_t *pBuff, int BuffLen)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
dev->pReg->RXD.PTR = (uint32_t)pBuff;
dev->pReg->RXD.MAXCNT = BuffLen;
dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->TXD.PTR = 0;
dev->pReg->TXD.MAXCNT = 0;
dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->EVENTS_END = 0;
dev->pReg->TASKS_START = 1;
nRF52SPIWaitDMA(dev, 100000);
return dev->pReg->RXD.AMOUNT;
}
// Stop receive
void nRF52SPIStopRx(SERINTRFDEV *pDev)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
IOPinSet(0, dev->CsPin);
}
// Initiate transmit
bool nRF52SPIStartTx(SERINTRFDEV *pDev, int DevAddr)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
IOPinClear(0, dev->CsPin);
return true;
}
// Transmit Data only, no Start/Stop condition
int nRF52SPITxData(SERINTRFDEV *pDev, uint8_t *pData, int DataLen)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
dev->pReg->RXD.PTR = 0;
dev->pReg->RXD.MAXCNT = 0;
dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->TXD.PTR = (uint32_t)pData;
dev->pReg->TXD.MAXCNT = DataLen;
dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
dev->pReg->EVENTS_END = 0;
dev->pReg->TASKS_START = 1;
nRF52SPIWaitDMA(dev, 100000);
return dev->pReg->TXD.AMOUNT;
}
// Stop transmit
void nRF52SPIStopTx(SERINTRFDEV *pDev)
{
NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;
IOPinSet(0, dev->CsPin);
}
bool SPIInit(SPIDEV *pDev, const SPICFG *pCfgData)
{
NRF_SPIM_Type *reg;
uint32_t err_code;
uint32_t cfgreg = 0;
if (pCfgData->DevNo < 0 || pCfgData->DevNo >= NRF52_SPI_MAXDEV)
return false;
// Get the correct register map
reg = s_nRF52SPIDev[pCfgData->DevNo].pReg;
// Configure I/O pins
IOPinCfg(pCfgData->IOPinMap, SPI_MAX_NB_IOPIN);
reg->PSEL.SCK = pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo;
reg->PSEL.MISO = pCfgData->IOPinMap[SPI_MISO_IOPIN_IDX].PinNo;
reg->PSEL.MOSI = pCfgData->IOPinMap[SPI_MOSI_IOPIN_IDX].PinNo;
s_nRF52SPIDev[pCfgData->DevNo].CsPin = pCfgData->IOPinMap[SPI_SS_IOPIN_IDX].PinNo;
IOPinSet(0, s_nRF52SPIDev[pCfgData->DevNo].CsPin);
if (pCfgData->BitOrder == SPIDATABIT_LSB)
{
cfgreg |= SPIM_CONFIG_ORDER_LsbFirst;
}
else
{
cfgreg |= SPIM_CONFIG_ORDER_MsbFirst;
}
if (pCfgData->DataPhase == SPIDATAPHASE_SECOND_CLK)
{
cfgreg |= (SPIM_CONFIG_CPHA_Trailing << SPIM_CONFIG_CPHA_Pos);
}
else
{
cfgreg |= (SPIM_CONFIG_CPHA_Leading << SPIM_CONFIG_CPHA_Pos);
}
//config.irq_priority = APP_IRQ_PRIORITY_LOW;
if (pCfgData->ClkPol == SPICLKPOL_LOW)
{
cfgreg |= (SPI_CONFIG_CPOL_ActiveLow << SPI_CONFIG_CPOL_Pos);
IOPinSet(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
}
else
{
cfgreg |= (SPI_CONFIG_CPOL_ActiveHigh << SPI_CONFIG_CPOL_Pos);
IOPinClear(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
}
reg->CONFIG = cfgreg;
reg->ORC = 0xFF;
pDev->Cfg = *pCfgData;
s_nRF52SPIDev[pCfgData->DevNo].pSpiDev = pDev;
pDev->SerIntrf.pDevData = (void*)&s_nRF52SPIDev[pCfgData->DevNo];
nRF52SPISetRate(&pDev->SerIntrf, pCfgData->Rate);
pDev->SerIntrf.Disable = nRF52SPIDisable;
pDev->SerIntrf.Enable = nRF52SPIEnable;
pDev->SerIntrf.GetRate = nRF52SPIGetRate;
pDev->SerIntrf.SetRate = nRF52SPISetRate;
pDev->SerIntrf.StartRx = nRF52SPIStartRx;
pDev->SerIntrf.RxData = nRF52SPIRxData;
pDev->SerIntrf.StopRx = nRF52SPIStopRx;
pDev->SerIntrf.StartTx = nRF52SPIStartTx;
pDev->SerIntrf.TxData = nRF52SPITxData;
pDev->SerIntrf.StopTx = nRF52SPIStopTx;
pDev->SerIntrf.IntPrio = pCfgData->IntPrio;
pDev->SerIntrf.EvtCB = pCfgData->EvtCB;
reg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}
<|endoftext|> |
<commit_before><commit_msg>Forgot to remove debugging logging<commit_after><|endoftext|> |
<commit_before><commit_msg>Improve gradient-descent algorithm to avoid tiny blocks.<commit_after><|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2015 by Xiao Liu, pertusa, caprice-j
* \file image_classification-predict.cpp
* \brief C++ predict example of mxnet
*/
//
// File: image-classification-predict.cpp
// This is a simple predictor which shows
// how to use c api for image classfication
// It uses opencv for image reading
// Created by liuxiao on 12/9/15.
// Thanks to : pertusa, caprice-j, sofiawu, tqchen, piiswrong
// Home Page: www.liuxiao.org
// E-mail: liuxiao@foxmail.com
//
#include <stdio.h>
// Path for c_predict_api
#include <mxnet/c_predict_api.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
const mx_float DEFAULT_MEAN = 117.0;
// Read file to buffer
class BufferFile {
public :
std::string file_path_;
int length_;
char* buffer_;
explicit BufferFile(std::string file_path)
:file_path_(file_path) {
std::ifstream ifs(file_path.c_str(), std::ios::in | std::ios::binary);
if (!ifs) {
std::cerr << "Can't open the file. Please check " << file_path << ". \n";
length_ = 0;
buffer_ = NULL;
return;
}
ifs.seekg(0, std::ios::end);
length_ = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::cout << file_path.c_str() << " ... "<< length_ << " bytes\n";
buffer_ = new char[sizeof(char) * length_];
ifs.read(buffer_, length_);
ifs.close();
}
int GetLength() {
return length_;
}
char* GetBuffer() {
return buffer_;
}
~BufferFile() {
if (buffer_) {
delete[] buffer_;
buffer_ = NULL;
}
}
};
void GetImageFile(const std::string image_file,
mx_float* image_data, const int channels,
const cv::Size resize_size, const mx_float* mean_data = nullptr) {
// Read all kinds of file into a BGR color 3 channels image
cv::Mat im_ori = cv::imread(image_file, cv::IMREAD_COLOR);
if (im_ori.empty()) {
std::cerr << "Can't open the image. Please check " << image_file << ". \n";
assert(false);
}
cv::Mat im;
resize(im_ori, im, resize_size);
int size = im.rows * im.cols * channels;
mx_float* ptr_image_r = image_data;
mx_float* ptr_image_g = image_data + size / 3;
mx_float* ptr_image_b = image_data + size / 3 * 2;
float mean_b, mean_g, mean_r;
mean_b = mean_g = mean_r = DEFAULT_MEAN;
for (int i = 0; i < im.rows; i++) {
uchar* data = im.ptr<uchar>(i);
for (int j = 0; j < im.cols; j++) {
if (mean_data) {
mean_r = *mean_data;
if (channels > 1) {
mean_g = *(mean_data + size / 3);
mean_b = *(mean_data + size / 3 * 2);
}
mean_data++;
}
if (channels > 1) {
*ptr_image_g++ = static_cast<mx_float>(*data++) - mean_g;
*ptr_image_b++ = static_cast<mx_float>(*data++) - mean_b;
}
*ptr_image_r++ = static_cast<mx_float>(*data++) - mean_r;;
}
}
}
// LoadSynsets
// Code from : https://github.com/pertusa/mxnet_predict_cc/blob/master/mxnet_predict.cc
std::vector<std::string> LoadSynset(std::string synset_file) {
std::ifstream fi(synset_file.c_str());
if ( !fi.is_open() ) {
std::cerr << "Error opening synset file " << synset_file << std::endl;
assert(false);
}
std::vector<std::string> output;
std::string synset, lemma;
while ( fi >> synset ) {
getline(fi, lemma);
output.push_back(lemma);
}
fi.close();
return output;
}
void PrintOutputResult(const std::vector<float>& data, const std::vector<std::string>& synset) {
if (data.size() != synset.size()) {
std::cerr << "Result data and synset size does not match!" << std::endl;
}
float best_accuracy = 0.0;
int best_idx = 0;
for ( int i = 0; i < static_cast<int>(data.size()); i++ ) {
printf("Accuracy[%d] = %.8f\n", i, data[i]);
if ( data[i] > best_accuracy ) {
best_accuracy = data[i];
best_idx = i;
}
}
printf("Best Result: [%s] id = %d, accuracy = %.8f\n",
synset[best_idx].c_str(), best_idx, best_accuracy);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "No test image here." << std::endl
<< "Usage: ./image-classification-predict apple.jpg" << std::endl;
return 0;
}
std::string test_file;
test_file = std::string(argv[1]);
// Models path for your model, you have to modify it
std::string json_file = "model/Inception/Inception-BN-symbol.json";
std::string param_file = "model/Inception/Inception-BN-0126.params";
std::string synset_file = "model/Inception/synset.txt";
std::string nd_file = "model/Inception/mean_224.nd";
BufferFile json_data(json_file);
BufferFile param_data(param_file);
// Parameters
int dev_type = 1; // 1: cpu, 2: gpu
int dev_id = 0; // arbitrary.
mx_uint num_input_nodes = 1; // 1 for feedforward
const char* input_key[1] = {"data"};
const char** input_keys = input_key;
// Image size and channels
int width = 224;
int height = 224;
int channels = 3;
const mx_uint input_shape_indptr[2] = { 0, 4 };
const mx_uint input_shape_data[4] = { 1,
static_cast<mx_uint>(channels),
static_cast<mx_uint>(height),
static_cast<mx_uint>(width)};
PredictorHandle pred_hnd = 0;
if (json_data.GetLength() == 0 ||
param_data.GetLength() == 0) {
return -1;
}
// Create Predictor
MXPredCreate((const char*)json_data.GetBuffer(),
(const char*)param_data.GetBuffer(),
static_cast<size_t>(param_data.GetLength()),
dev_type,
dev_id,
num_input_nodes,
input_keys,
input_shape_indptr,
input_shape_data,
&pred_hnd);
assert(pred_hnd);
int image_size = width * height * channels;
// Read Mean Data
const mx_float* nd_data = NULL;
NDListHandle nd_hnd = 0;
BufferFile nd_buf(nd_file);
if (nd_buf.GetLength() > 0) {
mx_uint nd_index = 0;
mx_uint nd_len;
const mx_uint* nd_shape = 0;
const char* nd_key = 0;
mx_uint nd_ndim = 0;
MXNDListCreate((const char*)nd_buf.GetBuffer(),
nd_buf.GetLength(),
&nd_hnd, &nd_len);
MXNDListGet(nd_hnd, nd_index, &nd_key, &nd_data, &nd_shape, &nd_ndim);
}
// Read Image Data
std::vector<mx_float> image_data = std::vector<mx_float>(image_size);
GetImageFile(test_file, image_data.data(),
channels, cv::Size(width, height), nd_data);
// Set Input Image
MXPredSetInput(pred_hnd, "data", image_data.data(), image_size);
// Do Predict Forward
MXPredForward(pred_hnd);
mx_uint output_index = 0;
mx_uint *shape = 0;
mx_uint shape_len;
// Get Output Result
MXPredGetOutputShape(pred_hnd, output_index, &shape, &shape_len);
size_t size = 1;
for (mx_uint i = 0; i < shape_len; ++i) size *= shape[i];
std::vector<float> data(size);
MXPredGetOutput(pred_hnd, output_index, &(data[0]), size);
// Release NDList
if (nd_hnd)
MXNDListFree(nd_hnd);
// Release Predictor
MXPredFree(pred_hnd);
// Synset path for your model, you have to modify it
std::vector<std::string> synset = LoadSynset(synset_file);
// Print Output Data
PrintOutputResult(data, synset);
return 0;
}
<commit_msg>fix bgr channel error (#8036)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2015 by Xiao Liu, pertusa, caprice-j
* \file image_classification-predict.cpp
* \brief C++ predict example of mxnet
*/
//
// File: image-classification-predict.cpp
// This is a simple predictor which shows
// how to use c api for image classfication
// It uses opencv for image reading
// Created by liuxiao on 12/9/15.
// Thanks to : pertusa, caprice-j, sofiawu, tqchen, piiswrong
// Home Page: www.liuxiao.org
// E-mail: liuxiao@foxmail.com
//
#include <stdio.h>
// Path for c_predict_api
#include <mxnet/c_predict_api.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
const mx_float DEFAULT_MEAN = 117.0;
// Read file to buffer
class BufferFile {
public :
std::string file_path_;
int length_;
char* buffer_;
explicit BufferFile(std::string file_path)
:file_path_(file_path) {
std::ifstream ifs(file_path.c_str(), std::ios::in | std::ios::binary);
if (!ifs) {
std::cerr << "Can't open the file. Please check " << file_path << ". \n";
length_ = 0;
buffer_ = NULL;
return;
}
ifs.seekg(0, std::ios::end);
length_ = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::cout << file_path.c_str() << " ... "<< length_ << " bytes\n";
buffer_ = new char[sizeof(char) * length_];
ifs.read(buffer_, length_);
ifs.close();
}
int GetLength() {
return length_;
}
char* GetBuffer() {
return buffer_;
}
~BufferFile() {
if (buffer_) {
delete[] buffer_;
buffer_ = NULL;
}
}
};
void GetImageFile(const std::string image_file,
mx_float* image_data, const int channels,
const cv::Size resize_size, const mx_float* mean_data = nullptr) {
// Read all kinds of file into a BGR color 3 channels image
cv::Mat im_ori = cv::imread(image_file, cv::IMREAD_COLOR);
if (im_ori.empty()) {
std::cerr << "Can't open the image. Please check " << image_file << ". \n";
assert(false);
}
cv::Mat im;
resize(im_ori, im, resize_size);
int size = im.rows * im.cols * channels;
mx_float* ptr_image_r = image_data;
mx_float* ptr_image_g = image_data + size / 3;
mx_float* ptr_image_b = image_data + size / 3 * 2;
float mean_b, mean_g, mean_r;
mean_b = mean_g = mean_r = DEFAULT_MEAN;
for (int i = 0; i < im.rows; i++) {
uchar* data = im.ptr<uchar>(i);
for (int j = 0; j < im.cols; j++) {
if (mean_data) {
mean_r = *mean_data;
if (channels > 1) {
mean_g = *(mean_data + size / 3);
mean_b = *(mean_data + size / 3 * 2);
}
mean_data++;
}
if (channels > 1) {
*ptr_image_b++ = static_cast<mx_float>(*data++) - mean_b;
*ptr_image_g++ = static_cast<mx_float>(*data++) - mean_g;
}
*ptr_image_r++ = static_cast<mx_float>(*data++) - mean_r;;
}
}
}
// LoadSynsets
// Code from : https://github.com/pertusa/mxnet_predict_cc/blob/master/mxnet_predict.cc
std::vector<std::string> LoadSynset(std::string synset_file) {
std::ifstream fi(synset_file.c_str());
if ( !fi.is_open() ) {
std::cerr << "Error opening synset file " << synset_file << std::endl;
assert(false);
}
std::vector<std::string> output;
std::string synset, lemma;
while ( fi >> synset ) {
getline(fi, lemma);
output.push_back(lemma);
}
fi.close();
return output;
}
void PrintOutputResult(const std::vector<float>& data, const std::vector<std::string>& synset) {
if (data.size() != synset.size()) {
std::cerr << "Result data and synset size does not match!" << std::endl;
}
float best_accuracy = 0.0;
int best_idx = 0;
for ( int i = 0; i < static_cast<int>(data.size()); i++ ) {
printf("Accuracy[%d] = %.8f\n", i, data[i]);
if ( data[i] > best_accuracy ) {
best_accuracy = data[i];
best_idx = i;
}
}
printf("Best Result: [%s] id = %d, accuracy = %.8f\n",
synset[best_idx].c_str(), best_idx, best_accuracy);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "No test image here." << std::endl
<< "Usage: ./image-classification-predict apple.jpg" << std::endl;
return 0;
}
std::string test_file;
test_file = std::string(argv[1]);
// Models path for your model, you have to modify it
std::string json_file = "model/Inception/Inception-BN-symbol.json";
std::string param_file = "model/Inception/Inception-BN-0126.params";
std::string synset_file = "model/Inception/synset.txt";
std::string nd_file = "model/Inception/mean_224.nd";
BufferFile json_data(json_file);
BufferFile param_data(param_file);
// Parameters
int dev_type = 1; // 1: cpu, 2: gpu
int dev_id = 0; // arbitrary.
mx_uint num_input_nodes = 1; // 1 for feedforward
const char* input_key[1] = {"data"};
const char** input_keys = input_key;
// Image size and channels
int width = 224;
int height = 224;
int channels = 3;
const mx_uint input_shape_indptr[2] = { 0, 4 };
const mx_uint input_shape_data[4] = { 1,
static_cast<mx_uint>(channels),
static_cast<mx_uint>(height),
static_cast<mx_uint>(width)};
PredictorHandle pred_hnd = 0;
if (json_data.GetLength() == 0 ||
param_data.GetLength() == 0) {
return -1;
}
// Create Predictor
MXPredCreate((const char*)json_data.GetBuffer(),
(const char*)param_data.GetBuffer(),
static_cast<size_t>(param_data.GetLength()),
dev_type,
dev_id,
num_input_nodes,
input_keys,
input_shape_indptr,
input_shape_data,
&pred_hnd);
assert(pred_hnd);
int image_size = width * height * channels;
// Read Mean Data
const mx_float* nd_data = NULL;
NDListHandle nd_hnd = 0;
BufferFile nd_buf(nd_file);
if (nd_buf.GetLength() > 0) {
mx_uint nd_index = 0;
mx_uint nd_len;
const mx_uint* nd_shape = 0;
const char* nd_key = 0;
mx_uint nd_ndim = 0;
MXNDListCreate((const char*)nd_buf.GetBuffer(),
nd_buf.GetLength(),
&nd_hnd, &nd_len);
MXNDListGet(nd_hnd, nd_index, &nd_key, &nd_data, &nd_shape, &nd_ndim);
}
// Read Image Data
std::vector<mx_float> image_data = std::vector<mx_float>(image_size);
GetImageFile(test_file, image_data.data(),
channels, cv::Size(width, height), nd_data);
// Set Input Image
MXPredSetInput(pred_hnd, "data", image_data.data(), image_size);
// Do Predict Forward
MXPredForward(pred_hnd);
mx_uint output_index = 0;
mx_uint *shape = 0;
mx_uint shape_len;
// Get Output Result
MXPredGetOutputShape(pred_hnd, output_index, &shape, &shape_len);
size_t size = 1;
for (mx_uint i = 0; i < shape_len; ++i) size *= shape[i];
std::vector<float> data(size);
MXPredGetOutput(pred_hnd, output_index, &(data[0]), size);
// Release NDList
if (nd_hnd)
MXNDListFree(nd_hnd);
// Release Predictor
MXPredFree(pred_hnd);
// Synset path for your model, you have to modify it
std::vector<std::string> synset = LoadSynset(synset_file);
// Print Output Data
PrintOutputResult(data, synset);
return 0;
}
<|endoftext|> |
<commit_before>#include "calendar.h"
#include <uuid.h>
#include <QtCore/qalgorithms.h>
#include <QDebug>
#include <icalformat.h>
#include <icaltimezones.h>
#include <memorycalendar.h>
#include <extendedstorage.h>
#include <extendedcalendar.h>
#include <libical/ical.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
#include <recurrencerule.h>
#include <ksystemtimezone.h>
using namespace mKCal;
using namespace KCalCore;
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant);
}
void CalendarTest::test()
{
QDateTime dt(QDate(2015, 1, 16), QTime(10, 15, 30), Qt::UTC);
qDebug() << "Test:" << dt.toString(Qt::ISODate);
#if 1
ICalTimeZones zones;
MSTimeZone msTimezone;
MSTimeZone msTimezone1;
MSTimeZone msTimezone2;
MSTimeZone msTimezone3;
initTestMsTimezone(msTimezone, 0);
initTestMsTimezone(msTimezone1, 1);
initTestMsTimezone(msTimezone2, 2);
initTestMsTimezone(msTimezone3, 3);
ICalTimeZoneSource source;
const ICalTimeZone &zone1 = source.parse(&msTimezone, zones);
const ICalTimeZone &zone2 = source.parse(&msTimezone1, zones);
const ICalTimeZone &zone3 = source.parse(&msTimezone2, zones);
const ICalTimeZone &zone4 = source.parse(&msTimezone3, zones);
qDebug() << "Zone 1:" << zone1.vtimezone();
qDebug() << "Zone 2:" << zone2.vtimezone();
qDebug() << "Zone 3:" << zone3.vtimezone();
qDebug() << "Zone 4:" << zone4.vtimezone();
const MemoryCalendar::Ptr &temp = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
temp->setTimeZones(new ICalTimeZones(zones));
ICalFormat ical;
const QByteArray &data = ical.toString( temp , QString() ).toUtf8();
qDebug() << "Calendar data:" << data;
ICalFormat ical2;
const MemoryCalendar::Ptr &temp2 = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
if (ical2.fromString(temp2 , QString::fromUtf8(data))) {
qDebug() << "Loaded timezone information";
ICalTimeZones *zones = temp->timeZones();
const int n = zones->count();
qDebug() << "Number of loaded zones:" << n;
const QMap<QString, ICalTimeZone> &loadedZones = zones->zones();
QMapIterator<QString, ICalTimeZone> it(loadedZones);
while (it.hasNext()) {
it.next();
qDebug() << "Key:" << it.key();
const ICalTimeZone &zone = it.value();
qDebug() << "Zone info:" << zone.vtimezone();
}
KDateTime original(QDate(2015, 7, 10), QTime(14, 33, 45), KDateTime::Spec::UTC());
qDebug() << "Original time:" << original.dateTime();
it = loadedZones;
while (it.hasNext()) {
it.next();
qDebug() << "Time:" << original.toZone(it.value()).dateTime();
}
} else {
qCritical() << "Failed to convert";
}
#endif
}
void CalendarTest::init()
{
uuid_t out;
uuid_generate_random(out);
}
void CalendarTest::icalTest()
{
MSTimeZone timezoneInfo;
timezoneInfo.Bias = 180;
timezoneInfo.StandardBias = 0;
timezoneInfo.DaylightBias = 0;
memset(&timezoneInfo.StandardDate, 0, sizeof (timezoneInfo.StandardDate));
memset(&timezoneInfo.DaylightDate, 0, sizeof (timezoneInfo.DaylightDate));
ICalTimeZoneSource source;
const ICalTimeZone &timezone = source.parse(&timezoneInfo);
KDateTime::Spec timezoneSpec;
timezoneSpec.setType(timezone);
KDateTime::Spec clockSpec(KDateTime::ClockTime);
KDateTime::Spec localSpec(KDateTime::LocalZone);
KCalCore::Event::Ptr event(new KCalCore::Event);
event->setSchedulingID("ffffffff-ffff-1234-5678-22d38f61a45f");
event->setLocation("Test location A1");
event->setStatus(KCalCore::Incidence::StatusConfirmed);
event->setDtStart(KDateTime::fromString("20171208T100000Z").toTimeSpec(localSpec));
ICalFormat icf;
const QString &ical = icf.createScheduleMessage(event, iTIPReply);
qDebug() << "Here is the iCalendar data:" << endl
<< "********************************************************************************" << endl
<< (const char *)ical.toLatin1().data()
<< "\r********************************************************************************";
}
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant)
{
int bias = 0;
QString name;
switch (variant) {
case 0:
bias = -180;
name = "MSK1";
break;
case 1:
bias = -180;
name = "MSK2";
break;
case 2:
bias = -240;
name = "MSK3";
break;
case 3:
bias = -240;
name = "MSK4";
break;
}
msTimezone.Bias = bias;
msTimezone.StandardName = name;
memset(&msTimezone.StandardDate, 0, sizeof (MSSystemTime));
msTimezone.StandardBias = 0;
msTimezone.DaylightName = name;
memset(&msTimezone.DaylightDate, 0, sizeof (MSSystemTime));
msTimezone.DaylightBias = 0;
}
} // namespace {
<commit_msg>Updated iCalendar generation example<commit_after>#include "calendar.h"
#include <uuid.h>
#include <QtCore/qalgorithms.h>
#include <QDebug>
#include <icalformat.h>
#include <icaltimezones.h>
#include <memorycalendar.h>
#include <extendedstorage.h>
#include <extendedcalendar.h>
#include <libical/ical.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
#include <recurrencerule.h>
#include <ksystemtimezone.h>
using namespace mKCal;
using namespace KCalCore;
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant);
}
void CalendarTest::test()
{
QDateTime dt(QDate(2015, 1, 16), QTime(10, 15, 30), Qt::UTC);
qDebug() << "Test:" << dt.toString(Qt::ISODate);
#if 1
ICalTimeZones zones;
MSTimeZone msTimezone;
MSTimeZone msTimezone1;
MSTimeZone msTimezone2;
MSTimeZone msTimezone3;
initTestMsTimezone(msTimezone, 0);
initTestMsTimezone(msTimezone1, 1);
initTestMsTimezone(msTimezone2, 2);
initTestMsTimezone(msTimezone3, 3);
ICalTimeZoneSource source;
const ICalTimeZone &zone1 = source.parse(&msTimezone, zones);
const ICalTimeZone &zone2 = source.parse(&msTimezone1, zones);
const ICalTimeZone &zone3 = source.parse(&msTimezone2, zones);
const ICalTimeZone &zone4 = source.parse(&msTimezone3, zones);
qDebug() << "Zone 1:" << zone1.vtimezone();
qDebug() << "Zone 2:" << zone2.vtimezone();
qDebug() << "Zone 3:" << zone3.vtimezone();
qDebug() << "Zone 4:" << zone4.vtimezone();
const MemoryCalendar::Ptr &temp = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
temp->setTimeZones(new ICalTimeZones(zones));
ICalFormat ical;
const QByteArray &data = ical.toString( temp , QString() ).toUtf8();
qDebug() << "Calendar data:" << data;
ICalFormat ical2;
const MemoryCalendar::Ptr &temp2 = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
if (ical2.fromString(temp2 , QString::fromUtf8(data))) {
qDebug() << "Loaded timezone information";
ICalTimeZones *zones = temp->timeZones();
const int n = zones->count();
qDebug() << "Number of loaded zones:" << n;
const QMap<QString, ICalTimeZone> &loadedZones = zones->zones();
QMapIterator<QString, ICalTimeZone> it(loadedZones);
while (it.hasNext()) {
it.next();
qDebug() << "Key:" << it.key();
const ICalTimeZone &zone = it.value();
qDebug() << "Zone info:" << zone.vtimezone();
}
KDateTime original(QDate(2015, 7, 10), QTime(14, 33, 45), KDateTime::Spec::UTC());
qDebug() << "Original time:" << original.dateTime();
it = loadedZones;
while (it.hasNext()) {
it.next();
qDebug() << "Time:" << original.toZone(it.value()).dateTime();
}
} else {
qCritical() << "Failed to convert";
}
#endif
}
void CalendarTest::init()
{
uuid_t out;
uuid_generate_random(out);
}
void CalendarTest::icalTest()
{
MSTimeZone timezoneInfo;
timezoneInfo.Bias = 180;
timezoneInfo.StandardBias = 0;
timezoneInfo.DaylightBias = 0;
memset(&timezoneInfo.StandardDate, 0, sizeof (timezoneInfo.StandardDate));
memset(&timezoneInfo.DaylightDate, 0, sizeof (timezoneInfo.DaylightDate));
ICalTimeZoneSource source;
const ICalTimeZone &timezone = source.parse(&timezoneInfo);
KDateTime::Spec timezoneSpec;
timezoneSpec.setType(timezone);
KDateTime::Spec clockSpec(KDateTime::ClockTime);
KDateTime::Spec localSpec(KDateTime::LocalZone);
KCalCore::Event::Ptr event(new KCalCore::Event);
event->setSchedulingID("ffffffff-ffff-1234-5678-22d38f61a45f");
event->setLocation("Test location A1");
event->setStatus(KCalCore::Incidence::StatusConfirmed);
event->setDtStart(KDateTime::fromString("20171208T100000Z").toTimeSpec(localSpec));
event->setDtEnd(KDateTime::fromString("20171208T103000Z").toTimeSpec(localSpec));
event->setCreated(KDateTime::fromString("20171207T103011").toTimeSpec(localSpec));
event->addComment("Test comment for test event A1");
event->setSummary("Here is some summary for test event A1", false);
event->setPriority(5);
event->setTransparency(KCalCore::Event::Opaque);
event->setRevision(1);
event->setNonKDECustomProperty("X-MICROSOFT-CDO-APPT-SEQUENCE", "0");
event->setNonKDECustomProperty("X-MICROSOFT-CDO-BUSYSTATUS", "BUSY");
event->setNonKDECustomProperty("X-MICROSOFT-CDO-INTENDEDSTATUS", "BUSY");
event->setNonKDECustomProperty("X-MICROSOFT-CDO-ALLDAYEVENT", "FALSE");
event->setNonKDECustomProperty("X-MICROSOFT-CDO-IMPORTANCE", "1");
event->setNonKDECustomProperty("X-MICROSOFT-CDO-INSTTYPE", "0");
event->setNonKDECustomProperty("X-MICROSOFT-CDO-DISALLOW-COUNTER", "FALSE");
KCalCore::Attendee::Ptr attendee(new KCalCore::Attendee(
"Test Name", "test.email@example.org",
true,
KCalCore::Attendee::Tentative,
KCalCore::Attendee::ReqParticipant));
event->addAttendee(attendee);
ICalFormat icf;
const QString &ical = icf.createScheduleMessage(event, iTIPReply);
qDebug() << "Here is the iCalendar data:" << endl
<< "********************************************************************************" << endl
<< (const char *)ical.toLatin1().data()
<< "\r********************************************************************************";
}
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant)
{
int bias = 0;
QString name;
switch (variant) {
case 0:
bias = -180;
name = "MSK1";
break;
case 1:
bias = -180;
name = "MSK2";
break;
case 2:
bias = -240;
name = "MSK3";
break;
case 3:
bias = -240;
name = "MSK4";
break;
}
msTimezone.Bias = bias;
msTimezone.StandardName = name;
memset(&msTimezone.StandardDate, 0, sizeof (MSSystemTime));
msTimezone.StandardBias = 0;
msTimezone.DaylightName = name;
memset(&msTimezone.DaylightDate, 0, sizeof (MSSystemTime));
msTimezone.DaylightBias = 0;
}
} // namespace {
<|endoftext|> |
<commit_before>#include "calendar.h"
#include <uuid.h>
#include <QtCore/qalgorithms.h>
#include <QDebug>
#include <icalformat.h>
#include <icaltimezones.h>
#include <memorycalendar.h>
#include <extendedstorage.h>
#include <extendedcalendar.h>
#include <libical/ical.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
#include <recurrencerule.h>
#include <ksystemtimezone.h>
using namespace mKCal;
using namespace KCalCore;
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant);
}
void CalendarTest::test()
{
ICalTimeZones zones;
MSTimeZone msTimezone;
MSTimeZone msTimezone1;
MSTimeZone msTimezone2;
MSTimeZone msTimezone3;
initTestMsTimezone(msTimezone, 0);
initTestMsTimezone(msTimezone1, 1);
initTestMsTimezone(msTimezone2, 2);
initTestMsTimezone(msTimezone3, 3);
ICalTimeZoneSource source;
const ICalTimeZone &zone1 = source.parse(&msTimezone, zones);
const ICalTimeZone &zone2 = source.parse(&msTimezone1, zones);
const ICalTimeZone &zone3 = source.parse(&msTimezone2, zones);
const ICalTimeZone &zone4 = source.parse(&msTimezone3, zones);
qDebug() << "Zone 1:" << zone1.vtimezone();
qDebug() << "Zone 2:" << zone2.vtimezone();
qDebug() << "Zone 3:" << zone3.vtimezone();
qDebug() << "Zone 4:" << zone4.vtimezone();
const MemoryCalendar::Ptr &temp = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
temp->setTimeZones(new ICalTimeZones(zones));
ICalFormat ical;
const QByteArray &data = ical.toString( temp , QString() ).toUtf8();
qDebug() << "Calendar data:" << data;
ICalFormat ical2;
const MemoryCalendar::Ptr &temp2 = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
if (ical2.fromString(temp2 , QString::fromUtf8(data))) {
qDebug() << "Loaded timezone information";
ICalTimeZones *zones = temp->timeZones();
const int n = zones->count();
qDebug() << "Number of loaded zones:" << n;
const QMap<QString, ICalTimeZone> &loadedZones = zones->zones();
QMapIterator<QString, ICalTimeZone> it(loadedZones);
while (it.hasNext()) {
it.next();
qDebug() << "Key:" << it.key();
const ICalTimeZone &zone = it.value();
qDebug() << "Zone info:" << zone.vtimezone();
}
} else {
qCritical() << "Failed to convert";
}
}
void CalendarTest::init()
{
uuid_t out;
uuid_generate_random(out);
}
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant)
{
int bias = 0;
QString name;
switch (variant) {
case 0:
bias = -180;
name = "MSK1";
break;
case 1:
bias = -180;
name = "MSK2";
break;
case 2:
bias = -240;
name = "MSK3";
break;
case 3:
bias = -240;
name = "MSK4";
break;
}
msTimezone.Bias = bias;
msTimezone.StandardName = name;
memset(&msTimezone.StandardDate, 0, sizeof (MSSystemTime));
msTimezone.StandardBias = 0;
msTimezone.DaylightName = name;
memset(&msTimezone.DaylightDate, 0, sizeof (MSSystemTime));
msTimezone.DaylightBias = 0;
}
} // namespace {
<commit_msg>Added testing time conversion from zone to zone<commit_after>#include "calendar.h"
#include <uuid.h>
#include <QtCore/qalgorithms.h>
#include <QDebug>
#include <icalformat.h>
#include <icaltimezones.h>
#include <memorycalendar.h>
#include <extendedstorage.h>
#include <extendedcalendar.h>
#include <libical/ical.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
#include <recurrencerule.h>
#include <ksystemtimezone.h>
using namespace mKCal;
using namespace KCalCore;
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant);
}
void CalendarTest::test()
{
ICalTimeZones zones;
MSTimeZone msTimezone;
MSTimeZone msTimezone1;
MSTimeZone msTimezone2;
MSTimeZone msTimezone3;
initTestMsTimezone(msTimezone, 0);
initTestMsTimezone(msTimezone1, 1);
initTestMsTimezone(msTimezone2, 2);
initTestMsTimezone(msTimezone3, 3);
ICalTimeZoneSource source;
const ICalTimeZone &zone1 = source.parse(&msTimezone, zones);
const ICalTimeZone &zone2 = source.parse(&msTimezone1, zones);
const ICalTimeZone &zone3 = source.parse(&msTimezone2, zones);
const ICalTimeZone &zone4 = source.parse(&msTimezone3, zones);
qDebug() << "Zone 1:" << zone1.vtimezone();
qDebug() << "Zone 2:" << zone2.vtimezone();
qDebug() << "Zone 3:" << zone3.vtimezone();
qDebug() << "Zone 4:" << zone4.vtimezone();
const MemoryCalendar::Ptr &temp = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
temp->setTimeZones(new ICalTimeZones(zones));
ICalFormat ical;
const QByteArray &data = ical.toString( temp , QString() ).toUtf8();
qDebug() << "Calendar data:" << data;
ICalFormat ical2;
const MemoryCalendar::Ptr &temp2 = MemoryCalendar::Ptr(new MemoryCalendar(KDateTime::Spec::UTC()));
if (ical2.fromString(temp2 , QString::fromUtf8(data))) {
qDebug() << "Loaded timezone information";
ICalTimeZones *zones = temp->timeZones();
const int n = zones->count();
qDebug() << "Number of loaded zones:" << n;
const QMap<QString, ICalTimeZone> &loadedZones = zones->zones();
QMapIterator<QString, ICalTimeZone> it(loadedZones);
while (it.hasNext()) {
it.next();
qDebug() << "Key:" << it.key();
const ICalTimeZone &zone = it.value();
qDebug() << "Zone info:" << zone.vtimezone();
}
KDateTime original(QDate(2015, 7, 10), QTime(14, 33, 45), KDateTime::Spec::UTC());
qDebug() << "Original time:" << original.dateTime();
it = loadedZones;
while (it.hasNext()) {
it.next();
qDebug() << "Time:" << original.toZone(it.value()).dateTime();
}
} else {
qCritical() << "Failed to convert";
}
}
void CalendarTest::init()
{
uuid_t out;
uuid_generate_random(out);
}
namespace {
void initTestMsTimezone(MSTimeZone &msTimezone, int variant)
{
int bias = 0;
QString name;
switch (variant) {
case 0:
bias = -180;
name = "MSK1";
break;
case 1:
bias = -180;
name = "MSK2";
break;
case 2:
bias = -240;
name = "MSK3";
break;
case 3:
bias = -240;
name = "MSK4";
break;
}
msTimezone.Bias = bias;
msTimezone.StandardName = name;
memset(&msTimezone.StandardDate, 0, sizeof (MSSystemTime));
msTimezone.StandardBias = 0;
msTimezone.DaylightName = name;
memset(&msTimezone.DaylightDate, 0, sizeof (MSSystemTime));
msTimezone.DaylightBias = 0;
}
} // namespace {
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/storage.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/utility.hpp>
#include <stdlib.h>
using namespace libtorrent;
int main(int argc, char* argv[])
{
if (argc != 3 && argc != 2)
{
fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n"
" fragmentation_test file\n\n");
return 1;
}
if (argc == 2)
{
error_code ec;
file f(argv[1], file::read_only, ec);
if (ec)
{
fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str());
return 1;
}
size_type off = f.phys_offset(0);
printf("physical offset of file %s: %" PRId64 "\n", argv[1], off);
return 0;
}
error_code ec;
boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec));
if (ec)
{
fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str());
return 1;
}
file_pool fp;
boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>()));
// the first field is the piece index, the second
// one is the physical location of the piece on disk
std::vector<std::pair<int, size_type> > pieces;
// make sure all the files are there
std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]);
for (int i = 0; i < ti->num_files(); ++i)
{
if (ti->file_at(i).size == files[i].first) continue;
fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n"
, ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size);
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
pieces.push_back(std::make_pair(i, st->physical_offset(i, 0)));
if (pieces.back().second == size_type(i) * ti->piece_length())
{
// this suggests that the OS doesn't support physical offset
// or that the file doesn't exist, or some other file error
fprintf(stderr, "Your operating system or filesystem "
"does not appear to support querying physical disk offset\n");
return 1;
}
}
FILE* f = fopen("fragmentation.log", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening log file: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second);
}
fclose(f);
f = fopen("fragmentation.gnuplot", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno));
return 1;
}
fprintf(f,
"set term png size 1200,800\n"
"set output \"fragmentation.png\"\n"
"set xrange [*:*]\n"
"set xlabel \"piece\"\n"
"set ylabel \"drive offset\"\n"
"set key box\n"
"set title \"fragmentation for '%s'\"\n"
"set tics nomirror\n"
"plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1, x=0\n"
, ti->name().c_str());
fclose(f);
system("gnuplot fragmentation.gnuplot");
}
<commit_msg>fix gnuplot syntax error in fragmentation test<commit_after>/*
Copyright (c) 2010, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/storage.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/utility.hpp>
#include <stdlib.h>
using namespace libtorrent;
int main(int argc, char* argv[])
{
if (argc != 3 && argc != 2)
{
fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n"
" fragmentation_test file\n\n");
return 1;
}
if (argc == 2)
{
error_code ec;
file f(argv[1], file::read_only, ec);
if (ec)
{
fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str());
return 1;
}
size_type off = f.phys_offset(0);
printf("physical offset of file %s: %" PRId64 "\n", argv[1], off);
return 0;
}
error_code ec;
boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec));
if (ec)
{
fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str());
return 1;
}
file_pool fp;
boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>()));
// the first field is the piece index, the second
// one is the physical location of the piece on disk
std::vector<std::pair<int, size_type> > pieces;
// make sure all the files are there
std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]);
for (int i = 0; i < ti->num_files(); ++i)
{
if (ti->file_at(i).size == files[i].first) continue;
fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n"
, ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size);
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
pieces.push_back(std::make_pair(i, st->physical_offset(i, 0)));
if (pieces.back().second == size_type(i) * ti->piece_length())
{
// this suggests that the OS doesn't support physical offset
// or that the file doesn't exist, or some other file error
fprintf(stderr, "Your operating system or filesystem "
"does not appear to support querying physical disk offset\n");
return 1;
}
}
FILE* f = fopen("fragmentation.log", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening log file: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second);
}
fclose(f);
f = fopen("fragmentation.gnuplot", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno));
return 1;
}
fprintf(f,
"set term png size 1200,800\n"
"set output \"fragmentation.png\"\n"
"set xrange [*:*]\n"
"set xlabel \"piece\"\n"
"set ylabel \"drive offset\"\n"
"set key box\n"
"set title \"fragmentation for '%s'\"\n"
"set tics nomirror\n"
"plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1\n"
, ti->name().c_str());
fclose(f);
system("gnuplot fragmentation.gnuplot");
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/properties/linesettingsproperty.h>
namespace inviwo {
LineSettingsProperty::LineSettingsProperty(const std::string& identifier,
const std::string& displayName,
InvalidationLevel invalidationLevel,
PropertySemantics semantics)
: CompositeProperty(identifier, displayName, invalidationLevel, semantics)
, lineWidth_("lineWidth", "Line Width (pixel)", 1.0f, 0.0f, 50.0f, 0.1f)
, antialiasing_("antialiasing", "Antialiasing (pixel)", 0.5f, 0.0f, 10.0f, 0.1f)
, miterLimit_("miterLimit", "Miter Limit", 0.8f, 0.0f, 1.0f, 0.1f)
, roundCaps_("roundCaps", "Round Caps", true)
, pseudoLighting_("pseudoLighting", "Pseudo Lighting", true,
InvalidationLevel::InvalidResources)
, roundDepthProfile_("roundDepthProfile", "Round Depth Profile", true,
InvalidationLevel::InvalidResources)
, stippling_("stippling", "Stippling") {
addProperties(lineWidth_, antialiasing_, miterLimit_, roundCaps_, pseudoLighting_,
roundDepthProfile_, stippling_);
}
LineSettingsProperty* LineSettingsProperty::clone() const { return new LineSettingsProperty(this); }
float LineSettingsProperty::getWidth() const { return lineWidth_.get(); }
float LineSettingsProperty::getAntialiasingWidth() const { return antialiasing_.get(); }
float LineSettingsProperty::getMiterLimit() const { return miterLimit_.get(); }
bool LineSettingsProperty::getRoundCaps() const { return roundCaps_.get(); }
bool LineSettingsProperty::getPseudoLighting() const { return pseudoLighting_.get(); }
bool LineSettingsProperty::getRoundDepthProfile() const { return roundDepthProfile_.get(); }
const StipplingSettingsInterface& LineSettingsProperty::getStippling() const { return stippling_; }
} // namespace inviwo
<commit_msg>LineSettings: copy method fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/properties/linesettingsproperty.h>
namespace inviwo {
LineSettingsProperty::LineSettingsProperty(const std::string& identifier,
const std::string& displayName,
InvalidationLevel invalidationLevel,
PropertySemantics semantics)
: CompositeProperty(identifier, displayName, invalidationLevel, semantics)
, lineWidth_("lineWidth", "Line Width (pixel)", 1.0f, 0.0f, 50.0f, 0.1f)
, antialiasing_("antialiasing", "Antialiasing (pixel)", 0.5f, 0.0f, 10.0f, 0.1f)
, miterLimit_("miterLimit", "Miter Limit", 0.8f, 0.0f, 1.0f, 0.1f)
, roundCaps_("roundCaps", "Round Caps", true)
, pseudoLighting_("pseudoLighting", "Pseudo Lighting", true,
InvalidationLevel::InvalidResources)
, roundDepthProfile_("roundDepthProfile", "Round Depth Profile", true,
InvalidationLevel::InvalidResources)
, stippling_("stippling", "Stippling") {
addProperties(lineWidth_, antialiasing_, miterLimit_, roundCaps_, pseudoLighting_,
roundDepthProfile_, stippling_);
}
LineSettingsProperty* LineSettingsProperty::clone() const { return new LineSettingsProperty(*this); }
float LineSettingsProperty::getWidth() const { return lineWidth_.get(); }
float LineSettingsProperty::getAntialiasingWidth() const { return antialiasing_.get(); }
float LineSettingsProperty::getMiterLimit() const { return miterLimit_.get(); }
bool LineSettingsProperty::getRoundCaps() const { return roundCaps_.get(); }
bool LineSettingsProperty::getPseudoLighting() const { return pseudoLighting_.get(); }
bool LineSettingsProperty::getRoundDepthProfile() const { return roundDepthProfile_.get(); }
const StipplingSettingsInterface& LineSettingsProperty::getStippling() const { return stippling_; }
} // namespace inviwo
<|endoftext|> |
<commit_before>#include "LdapPushReceiver.h"
#include "LdapConfigurationManager.h"
#include "json/json.h"
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <ldap.h>
#include "decode.h"
#include <fstream>
using namespace std;
/*
* LDAPPlugin
* Dataflow Scenarios:
* 1. User on the device edits his own contact information --> push to LDAP Server (ldapadd/modify ...)
* 2. User on the device queries for a specific contact --> pull from LDAP server (ldapsearch)
*/
/*
* Push Reciever Consstructor
* a) Read Configuration
* b) Connect to the LDAP Server
* TBD: where / when do we authenticate with LDAP Server with admin user credentials
*/
LdapPushReceiver::LdapPushReceiver() : ldapServer(0) {
LdapConfigurationManager *config = LdapConfigurationManager::getInstance();
string ldapAddress = config->getLdapBaseAddress();
cout << "Attempting Connection to LDAP Server @:" << ldapAddress << endl;
int ret = ldap_initialize( &ldapServer, ldapAddress.c_str() );
if (ret != LDAP_SUCCESS) {
cout << "Error Initializing LDAP Library: " << ldap_err2string(ret) << endl;
return;
}
int version = LDAP_VERSION3;
ldap_set_option(ldapServer, LDAP_OPT_PROTOCOL_VERSION, &version);
string basedn = config->getLdapUsername();
string passwd = config->getLdapPassword();
cout << "Attempting bind operation w/user : " << basedn << " ... " << endl;
LDAPControl *serverctrls=NULL, *clientctrls=NULL;
struct berval *servercredp=NULL;
struct berval creds;
creds.bv_val = strdup( passwd.c_str() );
creds.bv_len = passwd.length();
ret = ldap_sasl_bind_s( ldapServer,
basedn.c_str(),
LDAP_SASL_SIMPLE, // simple authentication
&creds,
&serverctrls,
&clientctrls,
&servercredp);
if (ret != LDAP_SUCCESS) {
cout << "Error Binding to LDAP Server: " << ldap_err2string(ret) << endl;
}
cout << "Connected to LDAP Server @" << ldapAddress << endl;
}
void LdapPushReceiver::onConnect(GatewayConnector *sender) {
}
void LdapPushReceiver::onDisconnect(GatewayConnector *sender) {
}
/*
* Data Push from the Device
* User has edited his own contact information - do an ldapadd/modify on the LDAPServer
*/
void LdapPushReceiver::onDataReceived(GatewayConnector *sender, std::string uri, std::string mimeType, std::vector<char> &data, std::string originUser) {
cout << "Got data." << endl;
cout << " URI: " << uri << endl;
cout << " Mime type: " << mimeType << endl;
if(mimeType == "application/vnd.edu.vu.isis.ammo.launcher.contact_edit") {
cout << "Extracting JSON metadata..." << endl << flush;
unsigned int jsonEnd = 0;
for(vector<char>::iterator it = data.begin(); it != data.end(); it++) {
jsonEnd++;
if((*it) == 0) {
break;
}
}
string json(&data[0], jsonEnd);
cout << "JSON string: " << json << endl;
Json::Value jsonRoot;
Json::Reader jsonReader;
bool parseSuccess = jsonReader.parse(json, jsonRoot);
if(!parseSuccess) {
cout << "JSON parsing error:" << endl;
cout << jsonReader.getFormatedErrorMessages() << endl;
return;
}
cout << "Parsed JSON: " << jsonRoot.toStyledString() << endl;
LdapContact contact;
contact.name = jsonRoot["name"].asString();
contact.middle_initial = jsonRoot["middle_initial"].asString();
contact.lastname = jsonRoot["lastname"].asString();
contact.rank = jsonRoot["rank"].asString();
contact.callsign = jsonRoot["callsign"].asString();
contact.branch = jsonRoot["branch"].asString();
contact.unit = jsonRoot["unit"].asString();
contact.email = jsonRoot["email"].asString();
contact.phone = jsonRoot["phone"].asString();
editContact(contact);
} else {
cout << "ERROR! Invalid Mime Type." << endl << flush;
}
}
/*
* Pull Request
* Query containing LDAP search parameters
*/
void LdapPushReceiver::onDataReceived(GatewayConnector *sender,
std::string requestUid, std::string pluginId,
std::string mimeType, std::string query,
std::string projection, unsigned int maxResults,
unsigned int startFromCount, bool liveQuery) {
string response = "asdf";
vector<string> jsonResults;
get(query, jsonResults);
for(vector<string>::iterator it = jsonResults.begin(); it != jsonResults.end(); it++) {
vector<char> data(it->begin(), it->end());
sender->pullResponse(requestUid, pluginId, mimeType, "ammo-demo:test-object", data);
}
}
bool LdapPushReceiver::get(std::string query, std::vector<std::string> &jsonResults) {
LdapConfigurationManager *config = LdapConfigurationManager::getInstance();
LDAPMessage *results;
std::string filter = "(& (objectClass=x-Military) (objectClass=inetOrgPerson) ";
// build the filter based on query expression
// query = comma-separated field-name / value pairs
boost::char_separator<char> sep("|");
boost::tokenizer< boost::char_separator<char> > tokens(query, sep);
BOOST_FOREACH(string t, tokens) {
string::size_type epos=t.find('=');
string attr,val;
if (epos != string::npos) {
attr = t.substr(0,epos);
val = t.substr(epos+1);
}
boost::trim(attr);
boost::trim(val);
if (attr != "" && val != "") {
filter += ( string("(") + attr + string("=") + val + string(") ") );
}
}
filter += " )";
//changed the timeout to 5 sec from 1 ... since jpeg files are taking long
struct timeval timeout = { 5, 0 };
LDAPControl *serverctrls = NULL, *clientctrls = NULL;
char *attrs[] = { "*" };
cout << "LDAP Starting Search for: " << filter << endl;
int ret = ldap_search_ext_s(ldapServer,
"dc=transapp,dc=darpa,dc=mil", /* LDAP search base dn (distinguished name) */
LDAP_SCOPE_SUBTREE, /* scope - root and all descendants */
filter.c_str(), /* filter - query expression */
attrs, /* requested attributes (white-space seperated list, * = ALL) */
0, /* attrsonly - if we only want to get attribut types */
&serverctrls,
&clientctrls,
&timeout,
-1, // number of results : -1 = unlimited
&results);
cout << "LDAP Return From Search for: " << filter << endl;
if (ret != LDAP_SUCCESS) {
cout << "LDAP Search failed for " << filter << ": " << hex << ret << " - " << ldap_err2string(ret) << endl;
return false;
} else {
cout << "LDAP Search Returned " << ldap_count_entries(ldapServer, results) << " results" << endl;
}
/* process the results */
LDAPMessage *entry = ldap_first_entry(ldapServer, results);
while(entry) {
jsonResults.push_back( jsonForObject(entry) );
entry = ldap_next_entry(ldapServer, entry);
}
return true;
}
string LdapPushReceiver::jsonForObject(LDAPMessage *entry) {
Json::Value root;
struct berval **vals;
// name
vals = ldap_get_values_len(ldapServer, entry, "cn");
string cn = vals[0]->bv_val; // there must be only one name
ldap_value_free_len(vals);
vector<string> parts;
boost::split(parts, cn, boost::is_any_of(" "));
root["name"] = parts[0];
if (parts.size() >= 2) {
root["middle_initial"] = parts[1];
root["lastname"] = parts[2];
}
// rank
vals = ldap_get_values_len(ldapServer, entry, "x-Rank");
if (vals) {
root["rank"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// callsign
vals = ldap_get_values_len(ldapServer, entry, "x-Callsign");
if (vals) {
root["callsign"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// branch
vals = ldap_get_values_len(ldapServer, entry, "x-Branch");
if (vals) {
root["branch"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// unit
vals = ldap_get_values_len(ldapServer, entry, "x-Unit");
if (vals) {
root["unit"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// email
vals = ldap_get_values_len(ldapServer, entry, "mail");
if (vals) {
root["email"] = vals[0]->bv_val; // use only the first mail
ldap_value_free_len(vals);
}
// phone
vals = ldap_get_values_len(ldapServer, entry, "mobile");
if (vals) {
root["phone"] = vals[0]->bv_val; // use only the first phone
ldap_value_free_len(vals);
}
#ifdef TEST_PHOTO
/*
char *dn = ldap_get_dn(ldapServer, entry);
char **edn = ldap_explode_dn(dn, 0);
int i = 0;
string unit;
while( edn[i] ) {
int ret = strncmp( edn[i], "ou", 2 );
if (ret != 0)
continue;
char *oval = strchr( edn[i], '=' );
unit = string(oval) + string("/") + unit;
}
root["unit"] = unit;
cout << "JSON: " << root.toStyledString() << endl;
*/
std::string ret = root.toStyledString();
// photo
vals = ldap_get_values_len(ldapServer, entry, "jpegPhoto");
if (vals) {
unsigned long len = vals[0]->bv_len; // get the length of the data
//Decode image from base64 using the libb64 lib ....
base64::decoder d;
unsigned char* image = new unsigned char [len];//allocate image buffer ...
// decode the base64 data into plain characters ...
//decode is now commented since b
//d.decode (vals[0]->bv_val,vals[0]->bv_len, image);ase64 data cannot
// be inserted into LDAP ..
//using the memcpy for now ... later will add the decode function
memcpy (image, vals[0]->bv_val, len);
cout << "Ret string" << ret.data () << endl;
int buffer_len = 1/*first null terminator*/
+ 6/*The string "photo" and a null terminator*/
+ len/*the actual data*/
+ 2*4/*the length added two times*/;
unsigned long nlen = htonl (len); // convert to maintain endianness
// form the string that stores the photo
unsigned char* photo_buf = new unsigned char [buffer_len];
photo_buf[0] = '\0'; // start the photo buffer with a null
int index = 1;
memcpy (photo_buf+index, "photo", 5);
index += 5;
photo_buf[6] = '\0';
// memcpy (photo_buf + index, "\0", 1);
index += 1;
memcpy (photo_buf + index, (unsigned char*)(&nlen), 4);
index += 4;
memcpy (photo_buf + index, image, len);
index += len;
memcpy (photo_buf + index, (unsigned char*)(&nlen), 4);
index += 4;
//cout << "After photo buf setting " << endl;
//get the length of the root_str, needed for memcpy in the end
int root_len = ret.length ();
cout << "Before Allocation " << endl;
char* root_str = new char[root_len + index];
memset (root_str, 0 , root_len + index);
//copy the string underlying root
memcpy(root_str, ret.data (), root_len);
// concat the photo data
// use the index as the length of the
//buffer since it tells the number of characters
//in the photo_buf
memcpy (root_str + root_len, photo_buf, index);
//cout << "After final root_string " << endl;
ldap_value_free_len(vals);
// added this file to check the binary nature of the
// root string sent .. will delete it later
ofstream out ("root", ifstream::binary);
out.write (root_str, root_len + index);
out.close ();
delete [] image;
delete [] photo_buf;
//need also to delete the root_str ..
ret = root_str;
}
cout << "JSON: " << root.toStyledString() << endl;
return ret;
#else
return root.toStyledString();
#endif
}
bool LdapPushReceiver::editContact(const LdapContact&) {
}
static int write_callback(char *data, size_t size, size_t nmemb, std::string *writerData) {
if(writerData == NULL) {
return 0;
}
writerData->append(data, size*nmemb);
return size * nmemb;
}
<commit_msg>Changed the pulling of lastname, middle initial, and first name from the sn, initials, and givenName fields in LDAP. The middle initial is still not working and needs to be fixed but the givenName and last name should be ok<commit_after>#include "LdapPushReceiver.h"
#include "LdapConfigurationManager.h"
#include "json/json.h"
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <ldap.h>
#include "decode.h"
#include <fstream>
using namespace std;
/*
* LDAPPlugin
* Dataflow Scenarios:
* 1. User on the device edits his own contact information --> push to LDAP Server (ldapadd/modify ...)
* 2. User on the device queries for a specific contact --> pull from LDAP server (ldapsearch)
*/
/*
* Push Reciever Consstructor
* a) Read Configuration
* b) Connect to the LDAP Server
* TBD: where / when do we authenticate with LDAP Server with admin user credentials
*/
LdapPushReceiver::LdapPushReceiver() : ldapServer(0) {
LdapConfigurationManager *config = LdapConfigurationManager::getInstance();
string ldapAddress = config->getLdapBaseAddress();
cout << "Attempting Connection to LDAP Server @:" << ldapAddress << endl;
int ret = ldap_initialize( &ldapServer, ldapAddress.c_str() );
if (ret != LDAP_SUCCESS) {
cout << "Error Initializing LDAP Library: " << ldap_err2string(ret) << endl;
return;
}
int version = LDAP_VERSION3;
ldap_set_option(ldapServer, LDAP_OPT_PROTOCOL_VERSION, &version);
string basedn = config->getLdapUsername();
string passwd = config->getLdapPassword();
cout << "Attempting bind operation w/user : " << basedn << " ... " << endl;
LDAPControl *serverctrls=NULL, *clientctrls=NULL;
struct berval *servercredp=NULL;
struct berval creds;
creds.bv_val = strdup( passwd.c_str() );
creds.bv_len = passwd.length();
ret = ldap_sasl_bind_s( ldapServer,
basedn.c_str(),
LDAP_SASL_SIMPLE, // simple authentication
&creds,
&serverctrls,
&clientctrls,
&servercredp);
if (ret != LDAP_SUCCESS) {
cout << "Error Binding to LDAP Server: " << ldap_err2string(ret) << endl;
}
cout << "Connected to LDAP Server @" << ldapAddress << endl;
}
void LdapPushReceiver::onConnect(GatewayConnector *sender) {
}
void LdapPushReceiver::onDisconnect(GatewayConnector *sender) {
}
/*
* Data Push from the Device
* User has edited his own contact information - do an ldapadd/modify on the LDAPServer
*/
void LdapPushReceiver::onDataReceived(GatewayConnector *sender, std::string uri, std::string mimeType, std::vector<char> &data, std::string originUser) {
cout << "Got data." << endl;
cout << " URI: " << uri << endl;
cout << " Mime type: " << mimeType << endl;
if(mimeType == "application/vnd.edu.vu.isis.ammo.launcher.contact_edit") {
cout << "Extracting JSON metadata..." << endl << flush;
unsigned int jsonEnd = 0;
for(vector<char>::iterator it = data.begin(); it != data.end(); it++) {
jsonEnd++;
if((*it) == 0) {
break;
}
}
string json(&data[0], jsonEnd);
cout << "JSON string: " << json << endl;
Json::Value jsonRoot;
Json::Reader jsonReader;
bool parseSuccess = jsonReader.parse(json, jsonRoot);
if(!parseSuccess) {
cout << "JSON parsing error:" << endl;
cout << jsonReader.getFormatedErrorMessages() << endl;
return;
}
cout << "Parsed JSON: " << jsonRoot.toStyledString() << endl;
LdapContact contact;
contact.name = jsonRoot["name"].asString();
contact.middle_initial = jsonRoot["middle_initial"].asString();
contact.lastname = jsonRoot["lastname"].asString();
contact.rank = jsonRoot["rank"].asString();
contact.callsign = jsonRoot["callsign"].asString();
contact.branch = jsonRoot["branch"].asString();
contact.unit = jsonRoot["unit"].asString();
contact.email = jsonRoot["email"].asString();
contact.phone = jsonRoot["phone"].asString();
editContact(contact);
} else {
cout << "ERROR! Invalid Mime Type." << endl << flush;
}
}
/*
* Pull Request
* Query containing LDAP search parameters
*/
void LdapPushReceiver::onDataReceived(GatewayConnector *sender,
std::string requestUid, std::string pluginId,
std::string mimeType, std::string query,
std::string projection, unsigned int maxResults,
unsigned int startFromCount, bool liveQuery) {
string response = "asdf";
vector<string> jsonResults;
get(query, jsonResults);
for(vector<string>::iterator it = jsonResults.begin(); it != jsonResults.end(); it++) {
vector<char> data(it->begin(), it->end());
sender->pullResponse(requestUid, pluginId, mimeType, "ammo-demo:test-object", data);
}
}
bool LdapPushReceiver::get(std::string query, std::vector<std::string> &jsonResults) {
LdapConfigurationManager *config = LdapConfigurationManager::getInstance();
LDAPMessage *results;
std::string filter = "(& (objectClass=x-Military) (objectClass=inetOrgPerson) ";
// build the filter based on query expression
// query = comma-separated field-name / value pairs
boost::char_separator<char> sep("|");
boost::tokenizer< boost::char_separator<char> > tokens(query, sep);
BOOST_FOREACH(string t, tokens) {
string::size_type epos=t.find('=');
string attr,val;
if (epos != string::npos) {
attr = t.substr(0,epos);
val = t.substr(epos+1);
}
boost::trim(attr);
boost::trim(val);
if (attr != "" && val != "") {
filter += ( string("(") + attr + string("=") + val + string(") ") );
}
}
filter += " )";
//changed the timeout to 5 sec from 1 ... since jpeg files are taking long
struct timeval timeout = { 5, 0 };
LDAPControl *serverctrls = NULL, *clientctrls = NULL;
char *attrs[] = { "*" };
cout << "LDAP Starting Search for: " << filter << endl;
int ret = ldap_search_ext_s(ldapServer,
"dc=transapp,dc=darpa,dc=mil", /* LDAP search base dn (distinguished name) */
LDAP_SCOPE_SUBTREE, /* scope - root and all descendants */
filter.c_str(), /* filter - query expression */
attrs, /* requested attributes (white-space seperated list, * = ALL) */
0, /* attrsonly - if we only want to get attribut types */
&serverctrls,
&clientctrls,
&timeout,
-1, // number of results : -1 = unlimited
&results);
cout << "LDAP Return From Search for: " << filter << endl;
if (ret != LDAP_SUCCESS) {
cout << "LDAP Search failed for " << filter << ": " << hex << ret << " - " << ldap_err2string(ret) << endl;
return false;
} else {
cout << "LDAP Search Returned " << ldap_count_entries(ldapServer, results) << " results" << endl;
}
/* process the results */
LDAPMessage *entry = ldap_first_entry(ldapServer, results);
while(entry) {
jsonResults.push_back( jsonForObject(entry) );
entry = ldap_next_entry(ldapServer, entry);
}
return true;
}
string LdapPushReceiver::jsonForObject(LDAPMessage *entry) {
Json::Value root;
struct berval **vals;
// name
vals = ldap_get_values_len(ldapServer, entry, "givenName");
if (vals) {
root["name"] = vals[0]->bv_val; // there must be only one name
ldap_value_free_len(vals);
}
vals = ldap_get_values_len(ldapServer, entry, "sn");
if (vals) {
root["lastname"] = vals[0]->bv_val; // there must be only one name
ldap_value_free_len(vals);
}
vals = ldap_get_values_len(ldapServer, entry, "initials");
if (vals) {
root["middle_initial"] = vals[0]->bv_val; // there must be only one name
ldap_value_free_len(vals);
}
// rank
vals = ldap_get_values_len(ldapServer, entry, "x-Rank");
if (vals) {
root["rank"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// callsign
vals = ldap_get_values_len(ldapServer, entry, "x-Callsign");
if (vals) {
root["callsign"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// branch
vals = ldap_get_values_len(ldapServer, entry, "x-Branch");
if (vals) {
root["branch"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// unit
vals = ldap_get_values_len(ldapServer, entry, "x-Unit");
if (vals) {
root["unit"] = vals[0]->bv_val;
ldap_value_free_len(vals);
}
// email
vals = ldap_get_values_len(ldapServer, entry, "mail");
if (vals) {
root["email"] = vals[0]->bv_val; // use only the first mail
ldap_value_free_len(vals);
}
// phone
vals = ldap_get_values_len(ldapServer, entry, "mobile");
if (vals) {
root["phone"] = vals[0]->bv_val; // use only the first phone
ldap_value_free_len(vals);
}
#ifdef TEST_PHOTO
/*
char *dn = ldap_get_dn(ldapServer, entry);
char **edn = ldap_explode_dn(dn, 0);
int i = 0;
string unit;
while( edn[i] ) {
int ret = strncmp( edn[i], "ou", 2 );
if (ret != 0)
continue;
char *oval = strchr( edn[i], '=' );
unit = string(oval) + string("/") + unit;
}
root["unit"] = unit;
cout << "JSON: " << root.toStyledString() << endl;
*/
std::string ret = root.toStyledString();
// photo
vals = ldap_get_values_len(ldapServer, entry, "jpegPhoto");
if (vals) {
unsigned long len = vals[0]->bv_len; // get the length of the data
//Decode image from base64 using the libb64 lib ....
base64::decoder d;
unsigned char* image = new unsigned char [len];//allocate image buffer ...
// decode the base64 data into plain characters ...
//decode is now commented since b
//d.decode (vals[0]->bv_val,vals[0]->bv_len, image);ase64 data cannot
// be inserted into LDAP ..
//using the memcpy for now ... later will add the decode function
memcpy (image, vals[0]->bv_val, len);
cout << "Ret string" << ret.data () << endl;
int buffer_len = 1/*first null terminator*/
+ 6/*The string "photo" and a null terminator*/
+ len/*the actual data*/
+ 2*4/*the length added two times*/;
unsigned long nlen = htonl (len); // convert to maintain endianness
// form the string that stores the photo
unsigned char* photo_buf = new unsigned char [buffer_len];
photo_buf[0] = '\0'; // start the photo buffer with a null
int index = 1;
memcpy (photo_buf+index, "photo", 5);
index += 5;
photo_buf[6] = '\0';
// memcpy (photo_buf + index, "\0", 1);
index += 1;
memcpy (photo_buf + index, (unsigned char*)(&nlen), 4);
index += 4;
memcpy (photo_buf + index, image, len);
index += len;
memcpy (photo_buf + index, (unsigned char*)(&nlen), 4);
index += 4;
//cout << "After photo buf setting " << endl;
//get the length of the root_str, needed for memcpy in the end
int root_len = ret.length ();
cout << "Before Allocation " << endl;
char* root_str = new char[root_len + index];
memset (root_str, 0 , root_len + index);
//copy the string underlying root
memcpy(root_str, ret.data (), root_len);
// concat the photo data
// use the index as the length of the
//buffer since it tells the number of characters
//in the photo_buf
memcpy (root_str + root_len, photo_buf, index);
//cout << "After final root_string " << endl;
ldap_value_free_len(vals);
// added this file to check the binary nature of the
// root string sent .. will delete it later
ofstream out ("root", ifstream::binary);
out.write (root_str, root_len + index);
out.close ();
delete [] image;
delete [] photo_buf;
//need also to delete the root_str ..
ret = root_str;
}
cout << "JSON: " << root.toStyledString() << endl;
return ret;
#else
return root.toStyledString();
#endif
}
bool LdapPushReceiver::editContact(const LdapContact&) {
}
static int write_callback(char *data, size_t size, size_t nmemb, std::string *writerData) {
if(writerData == NULL) {
return 0;
}
writerData->append(data, size*nmemb);
return size * nmemb;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include "mugen_font.h"
#include "mugen_item.h"
#include "mugen_item_content.h"
#include "mugen_section.h"
#include "mugen_reader.h"
#include "mugen_util.h"
#include "globals.h"
// If you use this, please delete the item after you use it, this isn't java ok
static MugenItemContent *getOpts( const std::string &opt ){
std::string contentHolder = "";
MugenItemContent *temp = new MugenItemContent();
const char * ignored = " \r\n";
Global::debug(1) << "Parsing string to ItemContent: " << opt << endl;
for( unsigned int i = 0; i < opt.size(); ++i ){
if( opt[i] == ';' )break;
if( opt[i] == ' ' ){
if( !contentHolder.empty() ) *temp << contentHolder;
Global::debug(1) << "Got content: " << contentHolder << endl;
contentHolder = "";
}
//Start grabbing our item
else if (! strchr(ignored, opt[i])){
contentHolder += opt[i];
}
}
if( !contentHolder.empty() ){
*temp << contentHolder;
Global::debug(1) << "Got content: " << contentHolder << endl;
}
return temp;
}
MugenFont::MugenFont( const string & file ):
type(Fixed),
width(0),
height(0),
spacingx(0),
spacingy(0),
colors(0),
offsetx(0),
offsety(0),
bmp(0){
Global::debug(1) << "[mugen font] Opening file '" << file << "'" << endl;
ifile.open( file.c_str() );
if (!ifile){
perror("cant open file");
}
myfile = file;
load();
}
MugenFont::MugenFont( const char * file ):
type(Fixed),
width(0),
height(0),
spacingx(0),
spacingy(0),
colors(0),
offsetx(0),
offsety(0),
bmp(0){
Global::debug(1) << "[mugen font] Opening file '" << file << "'" << endl;
ifile.open( file );
if (!ifile){
perror("cant open file");
}
myfile = string( file );
load();
}
MugenFont::MugenFont( const MugenFont © ){
this->type = copy.type;
this->width = copy.width;
this->height = copy.height;
this->spacingx = copy.spacingx;
this->spacingy = copy.spacingy;
this->colors = copy.colors;
this->offsetx = copy.offsetx;
this->offsety = copy.offsety;
this->bmp = copy.bmp;
}
MugenFont::~MugenFont(){
if(bmp){
delete bmp;
}
}
MugenFont & MugenFont::operator=( const MugenFont © ){
this->type = copy.type;
this->width = copy.width;
this->height = copy.height;
this->spacingx = copy.spacingx;
this->spacingy = copy.spacingy;
this->colors = copy.colors;
this->offsetx = copy.offsetx;
this->offsety = copy.offsety;
this->bmp = copy.bmp;
return *this;
}
// Implement Font stuff
void MugenFont::setSize( const int x, const int y ){
// We don't change sizes
if ( (x < 0 || y < 0) && type!=Fixed ){
return;
}
}
const int MugenFont::getSizeX() const{
return width;
}
const int MugenFont::getSizeY() const{
return height;
}
const int MugenFont::textLength( const char * text ) const{
std::string str(text);
int size =0;
for (unsigned int i = 0; i < str.size(); ++i){
std::map<char, FontLocation>::const_iterator loc = positions.find(str[i]);
if (loc!=positions.end()){
size+=loc->second.width + spacingx;
} else{
// Couldn't find a position for this character assume regular width and skip to the next character
size+=width + spacingx;
}
}
return size;
}
const int MugenFont::getHeight( const string & str ) const{
// What? I guess this is for freetype?
return getHeight();
}
const int MugenFont::getHeight() const{
return height;
}
void MugenFont::printf( int x, int y, int color, const Bitmap & work, const string & str, int marker, ... ) const{
// need to get VA List later and append it to str or whatever
int workoffsetx = 0;
for (unsigned int i = 0; i < str.size(); ++i){
std::map<char, FontLocation>::const_iterator loc = positions.find(str[i]);
if (loc!=positions.end()){
Bitmap character = Bitmap::temporaryBitmap( loc->second.width, height);
bmp->Blit( loc->second.startx + offsetx, offsety, loc->second.width, height,0,0, character );
character.draw( x + workoffsetx, y, work);
workoffsetx+=loc->second.width + spacingx;
} else{
// Couldn't find a position for this character draw nothing, assume width, and skip to the next character
workoffsetx+=width + spacingx;
}
}
}
void MugenFont::load(){
/* 16 skips the header stuff */
int location = 16;
// Lets go ahead and skip the crap -> (Elecbyte signature and version) start at the 16th byte
ifile.seekg(location,ios::beg);
unsigned long pcxlocation;
unsigned long pcxsize;
unsigned long txtlocation;
unsigned long txtsize;
unsigned char *pcx;
ifile.read( (char *)&pcxlocation, sizeof(unsigned long) );
ifile.read( (char *)&pcxsize, sizeof(unsigned long) );
ifile.read( (char *)&txtlocation, sizeof(unsigned long) );
ifile.read( (char *)&txtsize, sizeof(unsigned long) );
Global::debug(1) << "PCX Location: " << pcxlocation << " | PCX Size: " << pcxsize << endl;
Global::debug(1) << "TXT Location: " << txtlocation << " | TXT Actual location: " << pcxlocation + pcxsize << " | TXT Size: " << txtsize << endl;
// Get the pcx load our bitmap
ifile.seekg(pcxlocation,ios::beg);
pcx = new unsigned char[pcxsize];
ifile.read((char *)pcx, pcxsize);
bmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) pcx, pcxsize));
delete [] pcx;
// Get the text
ifile.seekg(pcxlocation+pcxsize, ios::beg);
std::vector<std::string> ourText;
while( !ifile.eof() ){
std::string line;
getline( ifile, line );
ourText.push_back(line);
}
std::vector< MugenSection * > collection = MugenUtil::configReader( ourText );
for( unsigned int i = 0; i < collection.size(); ++i ){
const std::string &head = collection[i]->getHeader();
if( head == "Def" ){
while( collection[i]->hasItems() ){
MugenItemContent *content = collection[i]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
MugenUtil::removeSpaces(itemhead);
// This is so we don't have any problems with crap like Name, NaMe, naMe or whatever
MugenUtil::fixCase( itemhead );
if ( itemhead.find("size")!=std::string::npos ){
*content->getNext() >> width;
*content->getNext() >> height;
} else if ( itemhead.find("spacing")!=std::string::npos ){
*content->getNext() >> spacingx;
*content->getNext() >> spacingy;
} else if ( itemhead.find("colors")!=std::string::npos ){
*content->getNext() >> colors;
} else if ( itemhead.find("offset")!=std::string::npos ){
*content->getNext() >> offsetx;
*content->getNext() >> offsety;
} else if ( itemhead.find("type")!=std::string::npos ){
std::string temp;
*content->getNext() >> temp;
MugenUtil::removeSpaces(temp);
MugenUtil::fixCase(temp);
if (temp == "variable")type = Variable;
else if (temp == "fixed")type = Fixed;
Global::debug(1) << "Type: " << temp << endl;
} //else throw MugenException( "Unhandled option in Info Section: " + itemhead );
}
Global::debug(1) << "Size X: " << width << ", Size Y: " << height << ", Spacing X: " << spacingx << ", Spacing Y: " << spacingy << ", Colors: " << colors << ", Offset X: " << offsetx << ", Offset Y: " << offsety << endl;
}
if( head == "Map" ){
bool beginParse = false;
int locationx = 0;
for (std::vector<std::string>::iterator l = ourText.begin(); l != ourText.end(); ++l){
std::string line = *l;
if (!beginParse){
if (line.find("[Map]")==std::string::npos){
continue;
} else{
beginParse = true;
continue;
}
}
MugenItemContent *opt = getOpts(line);
std::string character;
int startx = locationx;
int chrwidth = width;
*opt->getNext() >> character;
if( character == "empty" ) continue;
if (character == "0x5b") character = "[";
else if (character == "0x3b") character = ";";
if (type != Fixed){
// get other two
*opt->getNext() >> locationx;
*opt->getNext() >> width;
}
delete opt;
FontLocation loc;
loc.startx = startx;
loc.width = chrwidth;
char code = character[0];
Global::debug(1) << "Storing Character: " << code << " | startx: " << loc.startx << " | width: " << loc.width << endl;
positions[code] = loc;
locationx+=width;
}
}
}
// Time to get rid of collection
for( std::vector< MugenSection * >::iterator i = collection.begin() ; i != collection.end() ; ++i ){
if(*i)delete (*i);
}
ifile.close();
}
<commit_msg>More font fixes<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include "mugen_font.h"
#include "mugen_item.h"
#include "mugen_item_content.h"
#include "mugen_section.h"
#include "mugen_reader.h"
#include "mugen_util.h"
#include "globals.h"
// If you use this, please delete the item after you use it, this isn't java ok
static MugenItemContent *getOpts( const std::string &opt ){
std::string contentHolder = "";
MugenItemContent *temp = new MugenItemContent();
const char * ignored = " \r\n";
Global::debug(1) << "Parsing string to ItemContent: " << opt << endl;
for( unsigned int i = 0; i < opt.size(); ++i ){
if( opt[i] == ';' )break;
if( opt[i] == ' ' ){
if( !contentHolder.empty() ) *temp << contentHolder;
Global::debug(1) << "Got content: " << contentHolder << endl;
contentHolder = "";
}
//Start grabbing our item
else if (! strchr(ignored, opt[i])){
contentHolder += opt[i];
}
}
if( !contentHolder.empty() ){
*temp << contentHolder;
Global::debug(1) << "Got content: " << contentHolder << endl;
}
return temp;
}
MugenFont::MugenFont( const string & file ):
type(Fixed),
width(0),
height(0),
spacingx(0),
spacingy(0),
colors(0),
offsetx(0),
offsety(0),
bmp(0){
Global::debug(1) << "[mugen font] Opening file '" << file << "'" << endl;
ifile.open( file.c_str() );
if (!ifile){
perror("cant open file");
}
myfile = file;
load();
}
MugenFont::MugenFont( const char * file ):
type(Fixed),
width(0),
height(0),
spacingx(0),
spacingy(0),
colors(0),
offsetx(0),
offsety(0),
bmp(0){
Global::debug(1) << "[mugen font] Opening file '" << file << "'" << endl;
ifile.open( file );
if (!ifile){
perror("cant open file");
}
myfile = string( file );
load();
}
MugenFont::MugenFont( const MugenFont © ){
this->type = copy.type;
this->width = copy.width;
this->height = copy.height;
this->spacingx = copy.spacingx;
this->spacingy = copy.spacingy;
this->colors = copy.colors;
this->offsetx = copy.offsetx;
this->offsety = copy.offsety;
this->bmp = copy.bmp;
}
MugenFont::~MugenFont(){
if(bmp){
delete bmp;
}
}
MugenFont & MugenFont::operator=( const MugenFont © ){
this->type = copy.type;
this->width = copy.width;
this->height = copy.height;
this->spacingx = copy.spacingx;
this->spacingy = copy.spacingy;
this->colors = copy.colors;
this->offsetx = copy.offsetx;
this->offsety = copy.offsety;
this->bmp = copy.bmp;
return *this;
}
// Implement Font stuff
void MugenFont::setSize( const int x, const int y ){
// We don't change sizes
if ( (x < 0 || y < 0) && type!=Fixed ){
return;
}
}
const int MugenFont::getSizeX() const{
return width;
}
const int MugenFont::getSizeY() const{
return height;
}
const int MugenFont::textLength( const char * text ) const{
std::string str(text);
int size =0;
for (unsigned int i = 0; i < str.size(); ++i){
std::map<char, FontLocation>::const_iterator loc = positions.find(str[i]);
if (loc!=positions.end()){
size+=loc->second.width + spacingx;
} else{
// Couldn't find a position for this character assume regular width and skip to the next character
size+=width + spacingx;
}
}
return size;
}
const int MugenFont::getHeight( const string & str ) const{
// What? I guess this is for freetype?
return getHeight();
}
const int MugenFont::getHeight() const{
return height;
}
void MugenFont::printf( int x, int y, int color, const Bitmap & work, const string & str, int marker, ... ) const{
// need to get VA List later and append it to str or whatever
int workoffsetx = 0;
for (unsigned int i = 0; i < str.size(); ++i){
std::map<char, FontLocation>::const_iterator loc = positions.find(str[i]);
if (loc!=positions.end()){
Bitmap character = Bitmap::temporaryBitmap( loc->second.width + spacingx, height + spacingy);
bmp->Blit( loc->second.startx, 0, loc->second.width + spacingx, height + spacingy,0,0, character );
character.draw( x + workoffsetx, y, work);
workoffsetx+=loc->second.width + spacingx;
} else{
// Couldn't find a position for this character draw nothing, assume width, and skip to the next character
workoffsetx+=width + spacingx;
}
}
}
void MugenFont::load(){
/* 16 skips the header stuff */
int location = 16;
// Lets go ahead and skip the crap -> (Elecbyte signature and version) start at the 16th byte
ifile.seekg(location,ios::beg);
unsigned long pcxlocation;
unsigned long pcxsize;
unsigned long txtlocation;
unsigned long txtsize;
unsigned char *pcx;
ifile.read( (char *)&pcxlocation, sizeof(unsigned long) );
ifile.read( (char *)&pcxsize, sizeof(unsigned long) );
ifile.read( (char *)&txtlocation, sizeof(unsigned long) );
ifile.read( (char *)&txtsize, sizeof(unsigned long) );
Global::debug(1) << "PCX Location: " << pcxlocation << " | PCX Size: " << pcxsize << endl;
Global::debug(1) << "TXT Location: " << txtlocation << " | TXT Actual location: " << pcxlocation + pcxsize << " | TXT Size: " << txtsize << endl;
// Get the pcx load our bitmap
ifile.seekg(pcxlocation,ios::beg);
pcx = new unsigned char[pcxsize];
ifile.read((char *)pcx, pcxsize);
bmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) pcx, pcxsize));
delete [] pcx;
// Get the text
ifile.seekg(pcxlocation+pcxsize, ios::beg);
std::vector<std::string> ourText;
while( !ifile.eof() ){
std::string line;
getline( ifile, line );
ourText.push_back(line);
}
std::vector< MugenSection * > collection = MugenUtil::configReader( ourText );
for( unsigned int i = 0; i < collection.size(); ++i ){
const std::string &head = collection[i]->getHeader();
if( head == "Def" ){
while( collection[i]->hasItems() ){
MugenItemContent *content = collection[i]->getNext();
const MugenItem *item = content->getNext();
std::string itemhead = item->query();
MugenUtil::removeSpaces(itemhead);
// This is so we don't have any problems with crap like Name, NaMe, naMe or whatever
MugenUtil::fixCase( itemhead );
if ( itemhead.find("size")!=std::string::npos ){
*content->getNext() >> width;
*content->getNext() >> height;
} else if ( itemhead.find("spacing")!=std::string::npos ){
*content->getNext() >> spacingx;
*content->getNext() >> spacingy;
} else if ( itemhead.find("colors")!=std::string::npos ){
*content->getNext() >> colors;
} else if ( itemhead.find("offset")!=std::string::npos ){
*content->getNext() >> offsetx;
*content->getNext() >> offsety;
} else if ( itemhead.find("type")!=std::string::npos ){
std::string temp;
*content->getNext() >> temp;
MugenUtil::removeSpaces(temp);
MugenUtil::fixCase(temp);
if (temp == "variable")type = Variable;
else if (temp == "fixed")type = Fixed;
Global::debug(1) << "Type: " << temp << endl;
} //else throw MugenException( "Unhandled option in Info Section: " + itemhead );
}
Global::debug(1) << "Size X: " << width << ", Size Y: " << height << ", Spacing X: " << spacingx << ", Spacing Y: " << spacingy << ", Colors: " << colors << ", Offset X: " << offsetx << ", Offset Y: " << offsety << endl;
}
if( head == "Map" ){
bool beginParse = false;
int locationx = 0;
for (std::vector<std::string>::iterator l = ourText.begin(); l != ourText.end(); ++l){
std::string line = *l;
if (!beginParse){
if (line.find("[Map]")==std::string::npos){
continue;
} else{
beginParse = true;
continue;
}
}
MugenItemContent *opt = getOpts(line);
std::string character;
int startx = locationx;
int chrwidth = width;
*opt->getNext() >> character;
if( character == "empty" ) continue;
if (character == "0x5b") character = "[";
else if (character == "0x3b") character = ";";
if (type != Fixed){
// get other two
*opt->getNext() >> locationx;
*opt->getNext() >> width;
}
delete opt;
FontLocation loc;
loc.startx = startx;
loc.width = chrwidth;
char code = character[0];
Global::debug(1) << "Storing Character: " << code << " | startx: " << loc.startx << " | width: " << loc.width << endl;
positions[code] = loc;
locationx+=width;
}
}
}
// Time to get rid of collection
for( std::vector< MugenSection * >::iterator i = collection.begin() ; i != collection.end() ; ++i ){
if(*i)delete (*i);
}
ifile.close();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, Dan Bethell, Johannes Saam.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of RenderConnect nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include "DDImage/Iop.h"
#include "DDImage/Row.h"
#include "DDImage/Thread.h"
#include "DDImage/Knobs.h"
#include "DDImage/DDMath.h"
using namespace DD::Image;
#include "Data.h"
#include "Server.h"
// class name
static const char* const CLASS = "RenderConnect";
// help
static const char* const HELP =
"Listens for renders coming from the RenderConnect display driver.";
// our default port
const int renderconnect_default_port = 9201;
// our listener method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data);
// lightweight pixel class
class RenderColour
{
public:
RenderColour()
{
_val[0] = _val[1] = _val[2] = 0.f;
_val[3] = 1.f;
}
float& operator[](int i){ return _val[i]; }
const float& operator[](int i) const { return _val[i]; }
// data
float _val[4];
};
// our image buffer class
class RenderBuffer
{
public:
RenderBuffer() :
_width(0),
_height(0)
{
}
void init(const unsigned int width, const unsigned int height)
{
_width = width;
_height = height;
_data.resize(_width * _height);
}
RenderColour& get(unsigned int x, unsigned int y)
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const RenderColour& get(unsigned int x, unsigned int y) const
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const unsigned int size() const
{
return _data.size();
}
// data
std::vector<RenderColour> _data;
unsigned int _width;
unsigned int _height;
};
// our nuke node
class RenderConnect: public Iop
{
public:
FormatPair m_fmtp; // our buffer format (knob)
Format m_fmt; // The nuke display format
int m_port; // the port we're listening on (knob)
RenderBuffer m_buffer; // our pixel buffer
Lock m_mutex; // mutex for locking the pixel buffer
unsigned int hash_counter; // our refresh hash counter
renderconnect::Server m_server; // our renderconnect::Server
bool m_inError; // some error handling
std::string m_connectionError;
bool m_legit;
RenderConnect(Node* node) :
Iop(node),
m_port(renderconnect_default_port),
m_fmt(Format(0, 0, 1.0)),
m_inError(false),
m_connectionError(""),
m_legit(false)
{
inputs(0);
}
~RenderConnect()
{
disconnect();
}
// It seems additional instances of a node get copied/constructed upon
// very frequent calls to asapUpdate() and this causes us a few
// problems - we don't want new sockets getting opened etc.
// Fortunately attach() only gets called for nodes in the dag so we can
// use this to mark the DAG node as 'legit' and open the port accordingly.
void attach()
{
m_legit = true;
knob("m_formats_knob")->hide(); // We don't need to see the format knob
// Running python code to check if we've already our format in the script
this->script_command("bool([i.name() for i in nuke.formats() if i.name()=='Render_Connect'])", true, false);
const char * result = this->script_result();
this->script_unlock();
if (strcmp(result, "True"))
{
m_fmt.add("Render_Connect");
}
}
void detach()
{
// even though a node still exists once removed from a scene (in the
// undo stack) we should close the port and reopen if attach() gets
// called.
m_legit = false;
disconnect();
}
void flagForUpdate()
{
if ( hash_counter==UINT_MAX )
hash_counter=0;
else
hash_counter++;
asapUpdate();
}
// we can use this to change our tcp port
void changePort( int port )
{
m_inError = false;
m_connectionError = "";
// try to reconnect
disconnect();
try
{
m_server.connect( m_port );
}
catch ( ... )
{
std::stringstream ss;
ss << "Could not connect to port: " << port;
m_connectionError = ss.str();
m_inError = true;
print_name( std::cerr );
std::cerr << ": " << ss.str() << std::endl;
return;
}
// success
if ( m_server.isConnected() )
{
Thread::spawn(::renderConnectListen, 1, this);
print_name( std::cout );
std::cout << ": Connected to port " << m_server.getPort() << std::endl;
}
}
// disconnect the server for it's port
void disconnect()
{
if ( m_server.isConnected() )
{
m_server.quit();
Thread::wait(this);
print_name( std::cout );
std::cout << ": Disconnected from port " << m_server.getPort() << std::endl;
}
}
void append(Hash& hash)
{
hash.append(hash_counter);
}
void _validate(bool for_real)
{
// do we need to open a port?
if ( m_server.isConnected()==false && !m_inError && m_legit )
changePort(m_port);
// handle any connection error
if ( m_inError )
error(m_connectionError.c_str());
// setup format etc
info_.format(*m_fmtp.fullSizeFormat());
info_.full_size_format(*m_fmtp.format());
info_.channels(Mask_RGBA);
info_.set(info().format());
}
void engine(int y, int xx, int r, ChannelMask channels, Row& out)
{
float *rOut = out.writable(Chan_Red) + xx;
float *gOut = out.writable(Chan_Green) + xx;
float *bOut = out.writable(Chan_Blue) + xx;
float *aOut = out.writable(Chan_Alpha) + xx;
const float *END = rOut + (r - xx);
unsigned int xxx = static_cast<unsigned int> (xx);
unsigned int yyy = static_cast<unsigned int> (y);
// don't have a buffer yet
m_mutex.lock();
if ( m_buffer._width==0 && m_buffer._height==0 )
{
while (rOut < END)
{
*rOut = *gOut = *bOut = *aOut = 0.f;
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
else
{
while (rOut < END)
{
if ( xxx >= m_buffer._width || yyy >= m_buffer._height )
{
*rOut = *gOut = *bOut = *aOut = 0.f;
}
else
{
*rOut = m_buffer.get(xxx, yyy)[0];
*gOut = m_buffer.get(xxx, yyy)[1];
*bOut = m_buffer.get(xxx, yyy)[2];
*aOut = m_buffer.get(xxx, yyy)[3];
}
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
m_mutex.unlock();
}
void knobs(Knob_Callback f)
{
Format_knob(f, &m_fmtp, "m_formats_knob", "format");
Int_knob(f, &m_port, "port_number", "port");
}
int knob_changed(Knob* knob)
{
if (knob->is("port_number"))
{
changePort(m_port);
return 1;
}
return 0;
}
const char* Class() const { return CLASS; }
const char* displayName() const { return CLASS; }
const char* node_help() const { return HELP; }
static const Iop::Description desc;
};
//=====
//=====
// @brief our listening thread method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data)
{
bool killThread = false;
RenderConnect * node = reinterpret_cast<RenderConnect*> (data);
while (!killThread)
{
// accept incoming connections!
node->m_server.accept();
// our incoming data object
renderconnect::Data d;
// loop over incoming data
while ((d.type()==2||d.type()==9)==false)
{
// listen for some data
try
{
d = node->m_server.listen();
}
catch( ... )
{
break;
}
// handle the data we received
switch (d.type())
{
case 0: // open a new image
{
node->m_mutex.lock();
node->m_buffer.init(d.width(), d.height());
node->m_mutex.unlock();
// Set the nuke display format
node->m_fmt.set(0, 0, d.width(), d.height());
node->m_fmt.width(d.width());
node->m_fmt.height(d.height());
// Automatically set the knob to the right format
node->knob("m_formats_knob")->set_text("Render_Connect");
break;
}
case 1: // image data
{
// lock buffer
node->m_mutex.lock();
// copy data from d into node->m_buffer
int _w = node->m_buffer._width;
int _h = node->m_buffer._height;
unsigned int _x, _x0, _y, _y0, _s, offset;
_x = _x0 = _y = _y0 = _s = 0;
int _xorigin = d.x();
int _yorigin = d.y();
int _width = d.width();
int _height = d.height();
int _spp = d.spp();
const float* pixel_data = d.pixels();
for (_x = 0; _x < _width; ++_x)
for (_y = 0; _y < _height; ++_y)
{
RenderColour &pix = node->m_buffer.get(_x
+ _xorigin, _h - (_y + _yorigin + 1));
offset = (_width * _y * _spp) + (_x * _spp);
for (_s = 0; _s < _spp; ++_s)
pix[_s] = pixel_data[offset+_s];
}
// release lock
node->m_mutex.unlock();
// update the image
node->flagForUpdate();
break;
}
case 2: // close image
{
// update the image
node->flagForUpdate();
// Debug image finished
//std::cout << "Finish image" << std::endl;
break;
}
case 9: // this is sent when the parent process want to kill
// the listening thread
{
killThread = true;
std::cout << "Kill listen thread" << std::endl;
break;
}
}
}
}
}
//=====
// nuke builder stuff
static Iop* constructor(Node* node){ return new RenderConnect(node); }
const Iop::Description RenderConnect::desc(CLASS, 0, constructor);
<commit_msg>Fixed issue with format being not changed if the node was recreated<commit_after>/*
Copyright (c) 2010, Dan Bethell, Johannes Saam.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of RenderConnect nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include "DDImage/Iop.h"
#include "DDImage/Row.h"
#include "DDImage/Thread.h"
#include "DDImage/Knobs.h"
#include "DDImage/DDMath.h"
using namespace DD::Image;
#include "Data.h"
#include "Server.h"
// class name
static const char* const CLASS = "RenderConnect";
// help
static const char* const HELP =
"Listens for renders coming from the RenderConnect display driver.";
// our default port
const int renderconnect_default_port = 9201;
// our listener method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data);
// lightweight pixel class
class RenderColour
{
public:
RenderColour()
{
_val[0] = _val[1] = _val[2] = 0.f;
_val[3] = 1.f;
}
float& operator[](int i){ return _val[i]; }
const float& operator[](int i) const { return _val[i]; }
// data
float _val[4];
};
// our image buffer class
class RenderBuffer
{
public:
RenderBuffer() :
_width(0),
_height(0)
{
}
void init(const unsigned int width, const unsigned int height)
{
_width = width;
_height = height;
_data.resize(_width * _height);
}
RenderColour& get(unsigned int x, unsigned int y)
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const RenderColour& get(unsigned int x, unsigned int y) const
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const unsigned int size() const
{
return _data.size();
}
// data
std::vector<RenderColour> _data;
unsigned int _width;
unsigned int _height;
};
// our nuke node
class RenderConnect: public Iop
{
public:
FormatPair m_fmtp; // our buffer format (knob)
Format m_fmt; // The nuke display format
int m_port; // the port we're listening on (knob)
RenderBuffer m_buffer; // our pixel buffer
Lock m_mutex; // mutex for locking the pixel buffer
unsigned int hash_counter; // our refresh hash counter
renderconnect::Server m_server; // our renderconnect::Server
bool m_inError; // some error handling
bool m_formatExists;
std::string m_connectionError;
bool m_legit;
RenderConnect(Node* node) :
Iop(node),
m_port(renderconnect_default_port),
m_fmt(Format(0, 0, 1.0)),
m_inError(false),
m_formatExists(false),
m_connectionError(""),
m_legit(false)
{
inputs(0);
}
~RenderConnect()
{
disconnect();
}
// It seems additional instances of a node get copied/constructed upon
// very frequent calls to asapUpdate() and this causes us a few
// problems - we don't want new sockets getting opened etc.
// Fortunately attach() only gets called for nodes in the dag so we can
// use this to mark the DAG node as 'legit' and open the port accordingly.
void attach()
{
m_legit = true;
knob("m_formats_knob")->hide(); // We don't need to see the format knob
// Running python code to check if we've already our format in the script
script_command("bool([i.name() for i in nuke.formats() if i.name()=='Render_Connect'])");
std::string result = script_result();
script_unlock();
if (result.compare("True") != 0)
m_fmt.add("Render_Connect");
else m_formatExists = true;
}
void detach()
{
// even though a node still exists once removed from a scene (in the
// undo stack) we should close the port and reopen if attach() gets
// called.
m_legit = false;
disconnect();
}
void flagForUpdate()
{
if ( hash_counter==UINT_MAX )
hash_counter=0;
else
hash_counter++;
asapUpdate();
}
// we can use this to change our tcp port
void changePort( int port )
{
m_inError = false;
m_connectionError = "";
// try to reconnect
disconnect();
try
{
m_server.connect( m_port );
}
catch ( ... )
{
std::stringstream ss;
ss << "Could not connect to port: " << port;
m_connectionError = ss.str();
m_inError = true;
print_name( std::cerr );
std::cerr << ": " << ss.str() << std::endl;
return;
}
// success
if ( m_server.isConnected() )
{
Thread::spawn(::renderConnectListen, 1, this);
print_name( std::cout );
std::cout << ": Connected to port " << m_server.getPort() << std::endl;
}
}
// disconnect the server for it's port
void disconnect()
{
if ( m_server.isConnected() )
{
m_server.quit();
Thread::wait(this);
print_name( std::cout );
std::cout << ": Disconnected from port " << m_server.getPort() << std::endl;
}
}
void append(Hash& hash)
{
hash.append(hash_counter);
}
void _validate(bool for_real)
{
// do we need to open a port?
if ( m_server.isConnected()==false && !m_inError && m_legit )
changePort(m_port);
// handle any connection error
if ( m_inError )
error(m_connectionError.c_str());
// setup format etc
info_.format(*m_fmtp.fullSizeFormat());
info_.full_size_format(*m_fmtp.format());
info_.channels(Mask_RGBA);
info_.set(info().format());
}
void engine(int y, int xx, int r, ChannelMask channels, Row& out)
{
float *rOut = out.writable(Chan_Red) + xx;
float *gOut = out.writable(Chan_Green) + xx;
float *bOut = out.writable(Chan_Blue) + xx;
float *aOut = out.writable(Chan_Alpha) + xx;
const float *END = rOut + (r - xx);
unsigned int xxx = static_cast<unsigned int> (xx);
unsigned int yyy = static_cast<unsigned int> (y);
// don't have a buffer yet
m_mutex.lock();
if ( m_buffer._width==0 && m_buffer._height==0 )
{
while (rOut < END)
{
*rOut = *gOut = *bOut = *aOut = 0.f;
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
else
{
while (rOut < END)
{
if ( xxx >= m_buffer._width || yyy >= m_buffer._height )
{
*rOut = *gOut = *bOut = *aOut = 0.f;
}
else
{
*rOut = m_buffer.get(xxx, yyy)[0];
*gOut = m_buffer.get(xxx, yyy)[1];
*bOut = m_buffer.get(xxx, yyy)[2];
*aOut = m_buffer.get(xxx, yyy)[3];
}
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
m_mutex.unlock();
}
void knobs(Knob_Callback f)
{
Format_knob(f, &m_fmtp, "m_formats_knob", "format");
Int_knob(f, &m_port, "port_number", "port");
}
int knob_changed(Knob* knob)
{
if (knob->is("port_number"))
{
changePort(m_port);
return 1;
}
return 0;
}
const char* Class() const { return CLASS; }
const char* displayName() const { return CLASS; }
const char* node_help() const { return HELP; }
static const Iop::Description desc;
};
//=====
//=====
// @brief our listening thread method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data)
{
bool killThread = false;
RenderConnect * node = reinterpret_cast<RenderConnect*> (data);
while (!killThread)
{
// accept incoming connections!
node->m_server.accept();
// our incoming data object
renderconnect::Data d;
// loop over incoming data
while ((d.type()==2||d.type()==9)==false)
{
// listen for some data
try
{
d = node->m_server.listen();
}
catch( ... )
{
break;
}
// handle the data we received
switch (d.type())
{
case 0: // open a new image
{
node->m_mutex.lock();
node->m_buffer.init(d.width(), d.height());
node->m_mutex.unlock();
// Set the nuke display format
if (node->m_formatExists == false)
{
node->m_fmt.set(0, 0, d.width(), d.height());
node->m_fmt.width(d.width());
node->m_fmt.height(d.height());
}
else
{
Format *m_fmt_exist = nullptr;
for (int i=0; i < Format::size(); i++)
{
m_fmt_exist = Format::index(i);
if (std::string(m_fmt_exist->name()).compare("Render_Connect") == 0)
break;
}
m_fmt_exist->set(0, 0, d.width(), d.height());
m_fmt_exist->width(d.width());
m_fmt_exist->height(d.height());
}
// Automatically set the knob to the right format
node->knob("m_formats_knob")->set_text("Render_Connect");
break;
}
case 1: // image data
{
// lock buffer
node->m_mutex.lock();
// copy data from d into node->m_buffer
int _w = node->m_buffer._width;
int _h = node->m_buffer._height;
unsigned int _x, _x0, _y, _y0, _s, offset;
_x = _x0 = _y = _y0 = _s = 0;
int _xorigin = d.x();
int _yorigin = d.y();
int _width = d.width();
int _height = d.height();
int _spp = d.spp();
const float* pixel_data = d.pixels();
for (_x = 0; _x < _width; ++_x)
for (_y = 0; _y < _height; ++_y)
{
RenderColour &pix = node->m_buffer.get(_x
+ _xorigin, _h - (_y + _yorigin + 1));
offset = (_width * _y * _spp) + (_x * _spp);
for (_s = 0; _s < _spp; ++_s)
pix[_s] = pixel_data[offset+_s];
}
// release lock
node->m_mutex.unlock();
// update the image
node->flagForUpdate();
break;
}
case 2: // close image
{
// update the image
node->flagForUpdate();
// Debug image finished
//std::cout << "Finish image" << std::endl;
break;
}
case 9: // this is sent when the parent process want to kill
// the listening thread
{
killThread = true;
std::cout << "Kill listen thread" << std::endl;
break;
}
}
}
}
}
//=====
// nuke builder stuff
static Iop* constructor(Node* node){ return new RenderConnect(node); }
const Iop::Description RenderConnect::desc(CLASS, 0, constructor);
<|endoftext|> |
<commit_before>#include "jpeg.h"
const unsigned char Jpeg::header_magic[] = { 0xFF, 0xD8, 0xFF };
jmp_buf Jpeg::setjmp_buffer;
void Jpeg::mozjpeg_error_handler(j_common_ptr cinfo)
{
(*cinfo->err->output_message)(cinfo);
longjmp(setjmp_buffer, 1);
}
size_t Jpeg::Leanify(size_t size_leanified /*= 0*/)
{
struct jpeg_decompress_struct srcinfo;
struct jpeg_compress_struct dstinfo;
struct jpeg_error_mgr jsrcerr, jdsterr;
srcinfo.err = jpeg_std_error(&jsrcerr);
jsrcerr.error_exit = mozjpeg_error_handler;
if (setjmp(setjmp_buffer))
{
jpeg_destroy_compress(&dstinfo);
jpeg_destroy_decompress(&srcinfo);
return Format::Leanify(size_leanified);
}
jpeg_create_decompress(&srcinfo);
dstinfo.err = jpeg_std_error(&jdsterr);
jdsterr.error_exit = mozjpeg_error_handler;
jpeg_create_compress(&dstinfo);
if (is_verbose)
{
dstinfo.err->trace_level++;
}
if (is_fast)
{
jpeg_c_set_int_param(&dstinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
}
/* Specify data source for decompression */
jpeg_mem_src(&srcinfo, (unsigned char *)fp, size);
(void)jpeg_read_header(&srcinfo, true);
/* Read source file as DCT coefficients */
auto coef_arrays = jpeg_read_coefficients(&srcinfo);
/* Initialize destination compression parameters from source values */
jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
dstinfo.optimize_coding = true;
unsigned char *outbuffer = nullptr;
unsigned long outsize = 0;
/* Specify data destination for compression */
jpeg_mem_dest(&dstinfo, &outbuffer, &outsize);
/* Start compressor (note no image data is actually written here) */
jpeg_write_coefficients(&dstinfo, coef_arrays);
/* Finish compression and release memory */
jpeg_finish_compress(&dstinfo);
(void)jpeg_finish_decompress(&srcinfo);
jpeg_destroy_decompress(&srcinfo);
fp -= size_leanified;
// use mozjpeg result if it's smaller than original
if (outsize < size)
{
memcpy(fp, outbuffer, outsize);
size = outsize;
}
else if (size_leanified)
{
memmove(fp, fp + size_leanified, size);
}
jpeg_destroy_compress(&dstinfo);
return size;
}<commit_msg>JPEG: use arithmetic coding if input file is arithmetic coded<commit_after>#include "jpeg.h"
const unsigned char Jpeg::header_magic[] = { 0xFF, 0xD8, 0xFF };
jmp_buf Jpeg::setjmp_buffer;
void Jpeg::mozjpeg_error_handler(j_common_ptr cinfo)
{
(*cinfo->err->output_message)(cinfo);
longjmp(setjmp_buffer, 1);
}
size_t Jpeg::Leanify(size_t size_leanified /*= 0*/)
{
struct jpeg_decompress_struct srcinfo;
struct jpeg_compress_struct dstinfo;
struct jpeg_error_mgr jsrcerr, jdsterr;
srcinfo.err = jpeg_std_error(&jsrcerr);
jsrcerr.error_exit = mozjpeg_error_handler;
if (setjmp(setjmp_buffer))
{
jpeg_destroy_compress(&dstinfo);
jpeg_destroy_decompress(&srcinfo);
return Format::Leanify(size_leanified);
}
jpeg_create_decompress(&srcinfo);
dstinfo.err = jpeg_std_error(&jdsterr);
jdsterr.error_exit = mozjpeg_error_handler;
jpeg_create_compress(&dstinfo);
if (is_verbose)
{
dstinfo.err->trace_level++;
}
if (is_fast)
{
jpeg_c_set_int_param(&dstinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
}
/* Specify data source for decompression */
jpeg_mem_src(&srcinfo, (unsigned char *)fp, size);
(void)jpeg_read_header(&srcinfo, true);
/* Read source file as DCT coefficients */
auto coef_arrays = jpeg_read_coefficients(&srcinfo);
/* Initialize destination compression parameters from source values */
jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
// use arithmetic coding if input file is arithmetic coded
if (srcinfo.arith_code)
{
dstinfo.arith_code = true;
dstinfo.optimize_coding = false;
}
else
{
dstinfo.optimize_coding = true;
}
unsigned char *outbuffer = nullptr;
unsigned long outsize = 0;
/* Specify data destination for compression */
jpeg_mem_dest(&dstinfo, &outbuffer, &outsize);
/* Start compressor (note no image data is actually written here) */
jpeg_write_coefficients(&dstinfo, coef_arrays);
/* Finish compression and release memory */
jpeg_finish_compress(&dstinfo);
(void)jpeg_finish_decompress(&srcinfo);
jpeg_destroy_decompress(&srcinfo);
fp -= size_leanified;
// use mozjpeg result if it's smaller than original
if (outsize < size)
{
memcpy(fp, outbuffer, outsize);
size = outsize;
}
else if (size_leanified)
{
memmove(fp, fp + size_leanified, size);
}
jpeg_destroy_compress(&dstinfo);
return size;
}<|endoftext|> |
<commit_before>// 11 may 2015
// TODO split out winapi includes
#include "tablepriv.h"
// before we start, why is this file C++? because the following is not a valid C header file!
// namely, UIAutomationCoreApi.h forgets to typedef enum xxx { ... } xxx; and typedef struct xxx xxx; so it just uses xxx incorrectly
// and because these are enums, we can't just do typedef enum xxx xxx; here ourselves, as that's illegal in both C and C++!
// thanks, Microsoft!
// (if it was just structs I would just typedef them here but even that's not really futureproof)
#include <uiautomation.h>
// TODO
//#include <stdio.h>
extern "C" int printf(const char *,...);
// TODOs
// - make sure RPC_E_DISCONNECTED is correct; source it
// - make sure E_POINTER is correct
// well if we're stuck with C++, we might as well make the most of it
class tableAcc : public IRawElementProviderSimple/*TODO, public ITableProvider, public IGridProvider*/ {
struct table *t;
ULONG refcount;
public:
tableAcc(struct table *);
// internal methods
void Invalidate(void);
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// IRawElementProviderSimple
STDMETHODIMP GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal);
STDMETHODIMP GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal);
STDMETHODIMP get_HostRawElementProvider(IRawElementProviderSimple **pRetVal);
STDMETHODIMP get_ProviderOptions(ProviderOptions *pRetVal);
#if 0
// ITableProvider
STDMETHODIMP GetColumnHeaders(SAFEARRAY **pRetVal);
STDMETHODIMP GetRowHeaders(SAFEARRAY **pRetVal);
STDMETHODIMP get_RowOrColumnMajor(RowOrColumnMajor *pRetVal);
#endif
};
tableAcc::tableAcc(struct table *t)
{
printf("construct\n");
this->t = t;
this->refcount = 1; // first instance goes to the table
}
void tableAcc::Invalidate(void)
{
printf("invalidate\n");
// this will always be called before the tableAcc is destroyed because there's one ref given to the table itself
this->t = NULL;
}
STDMETHODIMP tableAcc::QueryInterface(REFIID riid, void **ppvObject)
{
printf("query interface\n");
if (ppvObject == NULL)
return E_POINTER;
if (IsEqualIID(riid, IID_IUnknown) ||
IsEqualIID(riid, IID_IRawElementProviderSimple)) {
this->AddRef();
*ppvObject = this;
return S_OK;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) tableAcc::AddRef(void)
{
printf("add ref\n");
// http://blogs.msdn.com/b/oldnewthing/archive/2005/09/27/474384.aspx
if (this->refcount == 0)
logLastError("tableAcc::AddRef() called during destruction");
this->refcount++;
return this->refcount;
}
STDMETHODIMP_(ULONG) tableAcc::Release(void)
{
printf("release\n");
this->refcount--;
if (this->refcount == 0) {
printf("destroy\n");
delete this;
return 0;
}
return this->refcount;
}
STDMETHODIMP tableAcc::GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal)
{
printf("get pattern provider\n");
if (pRetVal == NULL)
return E_POINTER;
//TODO if (patternId != UIA_TablePatternId) {
*pRetVal = NULL;
return S_OK;
#if 0
}
*pRetVal = xxxxx;
return S_OK;
#endif
}
STDMETHODIMP tableAcc::GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal)
{
printf("get property value\n");
BSTR bstr;
if (pRetVal == NULL)
return E_POINTER;
pRetVal->vt = VT_EMPTY; // behavior on unknown property is to keep it VT_EMPTY and return S_OK
switch (propertyId) {
case UIA_NamePropertyId:
// TODO this doesn't show up
bstr = SysAllocString(L"test string");
if (bstr == NULL)
return E_OUTOFMEMORY;
pRetVal->vt = VT_BSTR;
pRetVal->bstrVal = bstr;
break;
}
return S_OK;
}
STDMETHODIMP tableAcc::get_HostRawElementProvider(IRawElementProviderSimple **pRetVal)
{
printf("get host raw element provider\n");
if (this->t != NULL) {
if (pRetVal == NULL)
return E_POINTER;
// TODO correct?
*pRetVal = NULL;
return RPC_E_DISCONNECTED;
}
// TODO wait should we?
// return UiaHostProviderFromHwnd(this->t->hwnd, pRetVal);
*pRetVal = NULL;
return S_OK;
}
STDMETHODIMP tableAcc::get_ProviderOptions(ProviderOptions *pRetVal)
{
printf("get provider options\n");
if (pRetVal == NULL)
return E_POINTER;
// TODO ProviderOptions_UseClientCoordinates?
*pRetVal = ProviderOptions_ServerSideProvider;
return S_OK;
}
#if 0
STDMETHODIMP tableAcc::GetColumnHeaders(SAFEARRAY **pRetVal)
{
if (pRetVal == NULL)
return E_POINTER;
*pRetVal = NULL;
return E_NOTIMPL;
}
STDMETHODIMP tableAcc::GetRowHeaders(SAFEARRAY **pRetVal)
{
if (pRetVal == NULL)
return E_POINTER;
*pRetVal = NULL;
return E_NOTIMPL;
}
STDMETHODIMP tableAcc::get_RowOrColumnMajor(RowOrColumnMajor *pRetVal)
{
if (pRetVal == NULL)
return E_POINTER;
*pRetVal = RowOrColumnMajor_RowMajor;
return S_OK;
}
#endif
void initTableAcc(struct table *t)
{
tableAcc *a;
a = new tableAcc(t);
t->tableAcc = a;
}
void uninitTableAcc(struct table *t)
{
tableAcc *a;
a = (tableAcc *) (t->tableAcc);
a->Invalidate();
a->Release();
t->tableAcc = NULL;
}
HANDLER(accessibilityHandler)
{
if (uMsg != WM_GETOBJECT)
return FALSE;
// OBJID_CLIENT evaluates to an expression of type LONG
// the documentation for WM_GETOBJECT says to cast "it" to a DWORD before comparing
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd373624%28v=vs.85%29.aspx casts them both to DWORDs; let's do that
// its two siblings only cast lParam, resulting in an erroneous DWORD to LONG comparison
// The Old New Thing book does not cast anything
// Microsoft's MSAA sample casts lParam to LONG instead!
// (As you can probably tell, the biggest problem with MSAA is that its documentation is ambiguous and/or self-contradictory...)
// and https://msdn.microsoft.com/en-us/library/windows/desktop/ff625912%28v=vs.85%29.aspx casts them both to long!
// Note that we're not using Active Accessibility, but the above applies even more, because UiaRootObjectId is *NEGATIVE*!
if (((DWORD) lParam) != ((DWORD) UiaRootObjectId))
return FALSE;
*lResult = UiaReturnRawElementProvider(t->hwnd, wParam, lParam, (IRawElementProviderSimple *) (t->tableAcc));
return TRUE;
}
<commit_msg>NOW fixed tableAcc.<commit_after>// 11 may 2015
// TODO split out winapi includes
#include "tablepriv.h"
// before we start, why is this file C++? because the following is not a valid C header file!
// namely, UIAutomationCoreApi.h forgets to typedef enum xxx { ... } xxx; and typedef struct xxx xxx; so it just uses xxx incorrectly
// and because these are enums, we can't just do typedef enum xxx xxx; here ourselves, as that's illegal in both C and C++!
// thanks, Microsoft!
// (if it was just structs I would just typedef them here but even that's not really futureproof)
#include <uiautomation.h>
// TODO
//#include <stdio.h>
extern "C" int printf(const char *,...);
// TODOs
// - make sure RPC_E_DISCONNECTED is correct; source it
// - make sure E_POINTER is correct
// well if we're stuck with C++, we might as well make the most of it
class tableAcc : public IRawElementProviderSimple/*TODO, public ITableProvider, public IGridProvider*/ {
struct table *t;
ULONG refcount;
public:
tableAcc(struct table *);
// internal methods
void Invalidate(void);
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// IRawElementProviderSimple
STDMETHODIMP GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal);
STDMETHODIMP GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal);
STDMETHODIMP get_HostRawElementProvider(IRawElementProviderSimple **pRetVal);
STDMETHODIMP get_ProviderOptions(ProviderOptions *pRetVal);
#if 0
// ITableProvider
STDMETHODIMP GetColumnHeaders(SAFEARRAY **pRetVal);
STDMETHODIMP GetRowHeaders(SAFEARRAY **pRetVal);
STDMETHODIMP get_RowOrColumnMajor(RowOrColumnMajor *pRetVal);
#endif
};
tableAcc::tableAcc(struct table *t)
{
printf("construct\n");
this->t = t;
this->refcount = 1; // first instance goes to the table
}
void tableAcc::Invalidate(void)
{
printf("invalidate\n");
// this will always be called before the tableAcc is destroyed because there's one ref given to the table itself
this->t = NULL;
}
STDMETHODIMP tableAcc::QueryInterface(REFIID riid, void **ppvObject)
{
printf("query interface\n");
if (ppvObject == NULL)
return E_POINTER;
if (IsEqualIID(riid, IID_IUnknown) ||
IsEqualIID(riid, IID_IRawElementProviderSimple)) {
this->AddRef();
*ppvObject = this;
return S_OK;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) tableAcc::AddRef(void)
{
printf("add ref\n");
// http://blogs.msdn.com/b/oldnewthing/archive/2005/09/27/474384.aspx
if (this->refcount == 0)
logLastError("tableAcc::AddRef() called during destruction");
this->refcount++;
return this->refcount;
}
STDMETHODIMP_(ULONG) tableAcc::Release(void)
{
printf("release\n");
this->refcount--;
if (this->refcount == 0) {
printf("destroy\n");
delete this;
return 0;
}
return this->refcount;
}
STDMETHODIMP tableAcc::GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal)
{
printf("get pattern provider\n");
if (pRetVal == NULL)
return E_POINTER;
//TODO if (patternId != UIA_TablePatternId) {
*pRetVal = NULL;
return S_OK;
#if 0
}
*pRetVal = xxxxx;
return S_OK;
#endif
}
STDMETHODIMP tableAcc::GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal)
{
printf("get property value %d\n", (int)propertyId);
BSTR bstr;
if (pRetVal == NULL)
return E_POINTER;
pRetVal->vt = VT_EMPTY; // behavior on unknown property is to keep it VT_EMPTY and return S_OK
switch (propertyId) {
case UIA_NamePropertyId:
printf("getting name\n");
// TODO this doesn't show up
bstr = SysAllocString(L"test string");
if (bstr == NULL)
return E_OUTOFMEMORY;
pRetVal->vt = VT_BSTR;
pRetVal->bstrVal = bstr;
break;
}
return S_OK;
}
STDMETHODIMP tableAcc::get_HostRawElementProvider(IRawElementProviderSimple **pRetVal)
{
printf("get host raw element provider\n");
if (this->t == NULL) {
if (pRetVal == NULL)
return E_POINTER;
// TODO correct?
*pRetVal = NULL;
return RPC_E_DISCONNECTED;
}
// TODO wait should we?
// return UiaHostProviderFromHwnd(this->t->hwnd, pRetVal);
*pRetVal = NULL;
return S_OK;
}
STDMETHODIMP tableAcc::get_ProviderOptions(ProviderOptions *pRetVal)
{
printf("get provider options\n");
if (pRetVal == NULL)
return E_POINTER;
// TODO ProviderOptions_UseClientCoordinates?
*pRetVal = ProviderOptions_ServerSideProvider;
return S_OK;
}
#if 0
STDMETHODIMP tableAcc::GetColumnHeaders(SAFEARRAY **pRetVal)
{
if (pRetVal == NULL)
return E_POINTER;
*pRetVal = NULL;
return E_NOTIMPL;
}
STDMETHODIMP tableAcc::GetRowHeaders(SAFEARRAY **pRetVal)
{
if (pRetVal == NULL)
return E_POINTER;
*pRetVal = NULL;
return E_NOTIMPL;
}
STDMETHODIMP tableAcc::get_RowOrColumnMajor(RowOrColumnMajor *pRetVal)
{
if (pRetVal == NULL)
return E_POINTER;
*pRetVal = RowOrColumnMajor_RowMajor;
return S_OK;
}
#endif
void initTableAcc(struct table *t)
{
tableAcc *a;
a = new tableAcc(t);
t->tableAcc = a;
}
void uninitTableAcc(struct table *t)
{
tableAcc *a;
a = (tableAcc *) (t->tableAcc);
a->Invalidate();
a->Release();
t->tableAcc = NULL;
}
HANDLER(accessibilityHandler)
{
if (uMsg != WM_GETOBJECT)
return FALSE;
// OBJID_CLIENT evaluates to an expression of type LONG
// the documentation for WM_GETOBJECT says to cast "it" to a DWORD before comparing
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd373624%28v=vs.85%29.aspx casts them both to DWORDs; let's do that
// its two siblings only cast lParam, resulting in an erroneous DWORD to LONG comparison
// The Old New Thing book does not cast anything
// Microsoft's MSAA sample casts lParam to LONG instead!
// (As you can probably tell, the biggest problem with MSAA is that its documentation is ambiguous and/or self-contradictory...)
// and https://msdn.microsoft.com/en-us/library/windows/desktop/ff625912%28v=vs.85%29.aspx casts them both to long!
// Note that we're not using Active Accessibility, but the above applies even more, because UiaRootObjectId is *NEGATIVE*!
if (((DWORD) lParam) != ((DWORD) UiaRootObjectId))
return FALSE;
*lResult = UiaReturnRawElementProvider(t->hwnd, wParam, lParam, (IRawElementProviderSimple *) (t->tableAcc));
return TRUE;
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <time.h>
#include <set>
#include <fstream>
#include <unistd.h>
#include "hlt.hpp"
#include "Networking.hpp"
int main(int argc, const char ** argv) { //Ignore as main until needed.
char * path = new char[FILENAME_MAX];
getcwd(path, sizeof(char) * FILENAME_MAX);
strcat(path, "/");
strcat(path, argv[0]);
std::string sPath(path);
while(sPath.back() != '/') sPath.pop_back();
sPath.pop_back();
chdir(sPath.c_str()); //Set working directory
std::ofstream out("output.txt");
out << sPath.c_str() << std::endl;
srand(time(NULL));
std::cout.sync_with_stdio(0);
unsigned char my_tag;
hlt::Map present_map;
getInit(my_tag, present_map);
std::string s;
std::ifstream in("Responses.txt");
if(!in.is_open()) sendInitResponse("TestBot - Couldn't Open File MORECHARACTERS");
else {
std::getline(in, s);
sendInitResponse(s + std::to_string(my_tag));
}
while(true) {
getFrame(present_map);
std::getline(in, s);
detail::sendString(s);
}
out.close();
return 0;
}
<commit_msg>TestBot improvements<commit_after>#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <time.h>
#include <set>
#include <fstream>
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#else
#include <unistd.h>
#endif
#include "hlt.hpp"
#include "Networking.hpp"
int main(int argc, const char ** argv) { //Ignore as main until needed.
/*
char * path = new char[FILENAME_MAX];
#ifdef _WIN32
_getcwd(path, sizeof(char) * FILENAME_MAX);
#else
getcwd(path, sizeof(char) * FILENAME_MAX);
#endif
strcat(path, "\\");
strcat(path, argv[0]);
std::string sPath(path);
while(sPath.back() != '\\') sPath.pop_back();
sPath.pop_back();
std::replace(sPath.begin(), sPath.end(), '\\', '/');
#ifdef _WIN32
_chdir(sPath.c_str()); //Set working directory
#else
chdir(sPath.c_str()); //Set working directory
#endif
std::ofstream out("output.txt");
out << sPath.c_str() << std::endl;
out.close();
*/
srand(time(NULL));
std::cout.sync_with_stdio(0);
unsigned char my_tag;
hlt::Map present_map;
getInit(my_tag, present_map);
std::string s;
std::ifstream in("Responses.txt");
if(!in.is_open()) sendInitResponse("TestBot - Couldn't Open File MORECHARACTERS");
else {
std::getline(in, s);
sendInitResponse(s + std::to_string(my_tag));
}
while(true) {
getFrame(present_map);
std::getline(in, s);
detail::sendString(s);
}
return 0;
}
<|endoftext|> |
<commit_before>// I2C slave, responds as fake RTC device at 0x68 with some dummy data.
#include "LPC8xx.h"
#include "lpc_types.h"
#include "romapi_8xx.h"
uint32_t i2cBuffer [24];
I2C_HANDLE_T* ih;
void i2cSetupXfer(); // forward
void i2cSetup () {
LPC_SWM->PINASSIGN7 = 0x00FFFFFF; // SDA on P0
LPC_SWM->PINASSIGN8 = 0xFFFFFF04; // SCL on P4
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<5); // enable I2C clock
ih = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, i2cBuffer);
LPC_I2CD_API->i2c_set_slave_addr(ih, 0x68<<1, 0);
NVIC_EnableIRQ(I2C_IRQn);
}
extern "C" void I2C0_IRQHandler () {
LPC_I2CD_API->i2c_isr_handler(ih);
}
void i2cDone (uint32_t, uint32_t) {
i2cSetupXfer(); // restart the next transfer
}
void i2cSetupXfer() {
static uint8_t buf [] = { 0, 1, 2, 3, 4, 5, 6 };
static uint8_t seq;
static I2C_PARAM_T param;
static I2C_RESULT_T result;
buf[0] = ++seq;
buf[1] = 1; // gets overwritten by received register index
/* Setup parameters for transfer */
param.func_pt = i2cDone;
param.num_bytes_send = 8;
param.num_bytes_rec = 2;
param.buffer_ptr_send = param.buffer_ptr_rec = buf;
LPC_I2CD_API->i2c_slave_receive_intr(ih, ¶m, &result);
LPC_I2CD_API->i2c_slave_transmit_intr(ih, ¶m, &result);
}
int main () {
i2cSetup();
i2cSetupXfer();
while (true)
__WFI();
}
<commit_msg>change pin numbers<commit_after>// I2C slave, responds as fake RTC device at 0x68 with some dummy data.
#include "LPC8xx.h"
#include "lpc_types.h"
#include "romapi_8xx.h"
uint32_t i2cBuffer [24];
I2C_HANDLE_T* ih;
void i2cSetupXfer(); // forward
void i2cSetup () {
LPC_SWM->PINASSIGN7 = 0x02FFFFFF; // SDA on P2
LPC_SWM->PINASSIGN8 = 0xFFFFFF03; // SCL on P3
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<5); // enable I2C clock
ih = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, i2cBuffer);
LPC_I2CD_API->i2c_set_slave_addr(ih, 0x68<<1, 0);
NVIC_EnableIRQ(I2C_IRQn);
}
extern "C" void I2C0_IRQHandler () {
LPC_I2CD_API->i2c_isr_handler(ih);
}
void i2cDone (uint32_t, uint32_t) {
i2cSetupXfer(); // restart the next transfer
}
void i2cSetupXfer() {
static uint8_t buf [] = { 0, 1, 2, 3, 4, 5, 6 };
static uint8_t seq;
static I2C_PARAM_T param;
static I2C_RESULT_T result;
buf[0] = ++seq;
buf[1] = 1; // gets overwritten by received register index
/* Setup parameters for transfer */
param.func_pt = i2cDone;
param.num_bytes_send = 8;
param.num_bytes_rec = 2;
param.buffer_ptr_send = param.buffer_ptr_rec = buf;
LPC_I2CD_API->i2c_slave_receive_intr(ih, ¶m, &result);
LPC_I2CD_API->i2c_slave_transmit_intr(ih, ¶m, &result);
}
int main () {
i2cSetup();
i2cSetupXfer();
while (true)
__WFI();
}
<|endoftext|> |
<commit_before>class Solution {
public:
bool validMountainArray(vector<int>& A) {
if (A.size() < 3) {
return false;
}
bool climbing = true;
// must check whole array for rule, any pair can break it
for (int i = 1; i < A.size(); i++) {
// flat breaks the rule
if (A[i] == A[i-1]) {
return false;
}
// climbing after starting descent breaks the rule
if (!climbing && A[i-1] < A[i]) {
return false;
}
// in this case i-1 is the point where we reach the peak (if this is a valid mountain)
if (climbing && A[i-1] > A[i]) {
// but the peak can't be at the left edge
if (i == 1) {
return false;
}
climbing = false;
}
}
return !climbing;
}
};
<commit_msg>LeetCode: 941. Valid Mountain Array - optimization<commit_after>class Solution {
public:
bool validMountainArray(vector<int>& A) {
if (A.size() < 3 || A[0] > A[1]) {
return false;
}
bool climbing = true;
// must check whole array for rule, any pair can break it
for (int i = 1; i < A.size(); i++) {
// flat breaks the rule
if (A[i] == A[i-1]) {
return false;
}
// climbing after starting descent breaks the rule
if (!climbing && A[i-1] < A[i]) {
return false;
}
// in this case i-1 is the point where we reach the peak (if this is a valid mountain)
// (2nd edge case check makes sure the "peak" isn't i==0)
if (climbing && A[i-1] > A[i]) {
climbing = false;
}
}
return !climbing;
}
};
<|endoftext|> |
<commit_before><commit_msg>Place _init_seek_columns() in right place (#1302)<commit_after><|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/ompl_interface/detail/constrained_goal_sampler.h>
#include <moveit/ompl_interface/model_based_planning_context.h>
#include <moveit/ompl_interface/detail/state_validity_checker.h>
ompl_interface::ConstrainedGoalSampler::ConstrainedGoalSampler(const ModelBasedPlanningContext *pc,
const kinematic_constraints::KinematicConstraintSetPtr &ks,
const constraint_samplers::ConstraintSamplerPtr &cs) :
ob::GoalLazySamples(pc->getOMPLSimpleSetup().getSpaceInformation(), boost::bind(&ConstrainedGoalSampler::sampleUsingConstraintSampler, this, _1, _2), false),
planning_context_(pc), kinematic_constraint_set_(ks), constraint_sampler_(cs), work_state_(pc->getCompleteInitialRobotState()),
work_joint_group_state_(work_state_.getJointStateGroup(planning_context_->getJointModelGroupName())), verbose_display_(0)
{
if (!constraint_sampler_)
default_sampler_ = si_->allocStateSampler();
logDebug("Constructed a ConstrainedGoalSampler instance at address %p", this);
startSampling();
}
bool ompl_interface::ConstrainedGoalSampler::sampleUsingConstraintSampler(const ob::GoalLazySamples *gls, ob::State *newGoal)
{
unsigned int ma = planning_context_->getMaximumGoalSamplingAttempts();
// terminate after too many attempts
if (gls->samplingAttemptsCount() >= ma)
return false;
// terminate after a maximum number of samples
if (gls->getStateCount() >= planning_context_->getMaximumGoalSamples())
return false;
// terminate the sampling thread when a solution has been found
if (planning_context_->getOMPLSimpleSetup().getProblemDefinition()->hasSolution())
return false;
bool verbose = false;
if (gls->getStateCount() == 0 && gls->samplingAttemptsCount() >= ma/2)
if (verbose_display_ < 1)
{
verbose = true;
verbose_display_++;
}
for (unsigned int a = 0 ; a < ma && gls->isSampling() ; ++a)
if (constraint_sampler_)
{
if (constraint_sampler_->sample(work_joint_group_state_, planning_context_->getCompleteInitialRobotState(), planning_context_->getMaximumStateSamplingAttempts()))
{
if (kinematic_constraint_set_->decide(work_state_, verbose).satisfied)
{
planning_context_->getOMPLStateSpace()->copyToOMPLState(newGoal, work_joint_group_state_);
if (static_cast<const StateValidityChecker*>(si_->getStateValidityChecker().get())->isValid(newGoal, verbose))
return true;
}
}
}
else
{
default_sampler_->sampleUniform(newGoal);
if (static_cast<const StateValidityChecker*>(si_->getStateValidityChecker().get())->isValid(newGoal, verbose))
{
planning_context_->getOMPLStateSpace()->copyToKinematicState(work_joint_group_state_, newGoal);
if (kinematic_constraint_set_->decide(work_state_, verbose).satisfied)
return true;
}
}
return false;
}
<commit_msg>fix reporting of goal collisions<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/ompl_interface/detail/constrained_goal_sampler.h>
#include <moveit/ompl_interface/model_based_planning_context.h>
#include <moveit/ompl_interface/detail/state_validity_checker.h>
ompl_interface::ConstrainedGoalSampler::ConstrainedGoalSampler(const ModelBasedPlanningContext *pc,
const kinematic_constraints::KinematicConstraintSetPtr &ks,
const constraint_samplers::ConstraintSamplerPtr &cs) :
ob::GoalLazySamples(pc->getOMPLSimpleSetup().getSpaceInformation(), boost::bind(&ConstrainedGoalSampler::sampleUsingConstraintSampler, this, _1, _2), false),
planning_context_(pc), kinematic_constraint_set_(ks), constraint_sampler_(cs), work_state_(pc->getCompleteInitialRobotState()),
work_joint_group_state_(work_state_.getJointStateGroup(planning_context_->getJointModelGroupName())), verbose_display_(0)
{
if (!constraint_sampler_)
default_sampler_ = si_->allocStateSampler();
logDebug("Constructed a ConstrainedGoalSampler instance at address %p", this);
startSampling();
}
bool ompl_interface::ConstrainedGoalSampler::sampleUsingConstraintSampler(const ob::GoalLazySamples *gls, ob::State *newGoal)
{
unsigned int ma = planning_context_->getMaximumGoalSamplingAttempts();
// terminate after too many attempts
if (gls->samplingAttemptsCount() >= ma)
return false;
// terminate after a maximum number of samples
if (gls->getStateCount() >= planning_context_->getMaximumGoalSamples())
return false;
// terminate the sampling thread when a solution has been found
if (planning_context_->getOMPLSimpleSetup().getProblemDefinition()->hasSolution())
return false;
unsigned int ma2 = ma/2;
for (unsigned int a = gls->samplingAttemptsCount() ; a < ma && gls->isSampling() ; ++a)
{
bool verbose = false;
if (gls->getStateCount() == 0 && a >= ma2)
if (verbose_display_ < 1)
{
verbose = true;
verbose_display_++;
}
if (constraint_sampler_)
{
if (constraint_sampler_->sample(work_joint_group_state_, planning_context_->getCompleteInitialRobotState(), planning_context_->getMaximumStateSamplingAttempts()))
{
if (kinematic_constraint_set_->decide(work_state_, verbose).satisfied)
{
planning_context_->getOMPLStateSpace()->copyToOMPLState(newGoal, work_joint_group_state_);
if (static_cast<const StateValidityChecker*>(si_->getStateValidityChecker().get())->isValid(newGoal, verbose))
return true;
}
}
}
else
{
default_sampler_->sampleUniform(newGoal);
if (static_cast<const StateValidityChecker*>(si_->getStateValidityChecker().get())->isValid(newGoal, verbose))
{
planning_context_->getOMPLStateSpace()->copyToKinematicState(work_joint_group_state_, newGoal);
if (kinematic_constraint_set_->decide(work_state_, verbose).satisfied)
return true;
}
}
}
return false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <tuple>
#include <type_traits>
#include <utility>
namespace type_storage
{
namespace detail
{
/// Helper struct for find_index. "Empty" non specialised struct.
template<template<class, class> class P,
int i, typename U, bool cond, typename... Ts>
struct find_type
{
static_assert(i != 0, "Type not found in provided typelist");
static_assert(1 >= i , "Type not unique in provided typelist");
static_assert(sizeof...(Ts) == 0, "Ts not 0");
};
/// Helper struct for find_index, true specialisation.
/// template member index<>::value finds index based on the size of
/// remaining parameter pack Ts... when a type match has been found.
template<template<class, class> class P,
int i, typename U, typename... Ts>
struct find_type<P, i, U, true, Ts...>
: find_type<P, i+1, U, false, Ts...>
{
/// specifies the index of the found type
template<typename... Types>
struct index
{
/// describes the index of requested type in Ts...
static const size_t value = sizeof...(Types) - sizeof...(Ts) -1;
};
};
/// Helper struct for find_index, false specialization.
/// Check for type match between U and T, and inherits from correct
/// find_type specialisation. member index<>::value obtained by
/// recursion (recurses until U == T )
template<template<class, class> class P,
int i, typename U, typename T, typename... Ts>
struct find_type<P, i, U, false, T, Ts...>
: find_type<P, i, U, P<U, T>::value, Ts...>
{ };
/// Finds index of type U in template parameter pack Ts using find_type
/// with success predicate P<U, Ts>...
template<template<class, class> class P, class U, class... Ts>
struct find_index
{
/// describes the index of U in Ts...
static const size_t value =
find_type<P, 0, U, false, Ts...>::template index <Ts...>::value;
};
}
/// Get a object of specific type T from tuple regardless of its position.
/// This function is basically a simple implementation of
/// C++14 std::get<T>(std::tuple<Types>&) function, using C++11 code.
/// NB: If tuple contains more than one object of the specific type,
/// a reference to the first found object with type T is returned.
/// If type T is not contained in tuple the code cannot compile.
/// @param tup the tuple of objects to look in
template<typename T, typename... Types>
T& get(std::tuple<Types...>& tup)
{
return std::get<detail::find_index<std::is_same,
T, Types...>::value>(tup);
}
// Const version of above
template<typename T, typename... Types>
const T& get(const std::tuple<Types...>& tup)
{
return std::get<detail::find_index<std::is_same,
T, Types...>::value>(tup);
}
/// Get a object of Base type B from tuple regardless of its position.
/// This function is virtually identical to get(), however the matching
/// condition is on base types, not exact types.
/// NB: If tuple contains more than one object of a matching base type,
/// a reference to the first found object with base type B is returned.
/// If base type B is not contained in tuple the code cannot compile.
/// @param tup the tuple of objects to look in
template<typename B, typename... Types>
B& baget(std::tuple<Types...>& tup)
{
// return std::get<detail::find_base_index<B, Types...>::value>(tup);
return std::get<detail::find_index<std::is_base_of,
B, Types...>::value>(tup);
}
// Const version of above
template<typename B, typename... Types>
const B& baget(const std::tuple<Types...>& tup)
{
// return std::get<detail::find_base_index<B, Types...>::value>(tup);
return std::get<detail::find_index<std::is_base_of,
Types...>::value>(tup);
}
}
<commit_msg>Corrected error message in static assert<commit_after>// Copyright (c) 2014 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <tuple>
#include <type_traits>
#include <utility>
namespace type_storage
{
namespace detail
{
/// Helper struct for find_index. "Empty" non specialised struct.
template<template<class, class> class P,
int i, typename U, bool cond, typename... Ts>
struct find_type
{
static_assert(i != 0, "Type not found in provided typelist");
static_assert(1 >= i , "Type not unique in provided typelist");
static_assert(sizeof...(Ts) == 0, "Internal error: Ts not 0");
};
/// Helper struct for find_index, true specialisation.
/// template member index<>::value finds index based on the size of
/// remaining parameter pack Ts... when a type match has been found.
template<template<class, class> class P,
int i, typename U, typename... Ts>
struct find_type<P, i, U, true, Ts...>
: find_type<P, i+1, U, false, Ts...>
{
/// specifies the index of the found type
template<typename... Types>
struct index
{
/// describes the index of requested type in Ts...
static const size_t value = sizeof...(Types) - sizeof...(Ts) -1;
};
};
/// Helper struct for find_index, false specialization.
/// Check for type match between U and T, and inherits from correct
/// find_type specialisation. member index<>::value obtained by
/// recursion (recurses until U == T )
template<template<class, class> class P,
int i, typename U, typename T, typename... Ts>
struct find_type<P, i, U, false, T, Ts...>
: find_type<P, i, U, P<U, T>::value, Ts...>
{ };
/// Finds index of type U in template parameter pack Ts using find_type
/// with success predicate P<U, Ts>...
template<template<class, class> class P, class U, class... Ts>
struct find_index
{
/// describes the index of U in Ts...
static const size_t value =
find_type<P, 0, U, false, Ts...>::template index <Ts...>::value;
};
}
/// Get a object of specific type T from tuple regardless of its position.
/// This function is basically a simple implementation of
/// C++14 std::get<T>(std::tuple<Types>&) function, using C++11 code.
/// NB: If tuple contains more than one object of the specific type,
/// a reference to the first found object with type T is returned.
/// If type T is not contained in tuple the code cannot compile.
/// @param tup the tuple of objects to look in
template<typename T, typename... Types>
T& get(std::tuple<Types...>& tup)
{
return std::get<detail::find_index<std::is_same,
T, Types...>::value>(tup);
}
// Const version of above
template<typename T, typename... Types>
const T& get(const std::tuple<Types...>& tup)
{
return std::get<detail::find_index<std::is_same,
T, Types...>::value>(tup);
}
/// Get a object of Base type B from tuple regardless of its position.
/// This function is virtually identical to get(), however the matching
/// condition is on base types, not exact types.
/// NB: If tuple contains more than one object of a matching base type,
/// a reference to the first found object with base type B is returned.
/// If base type B is not contained in tuple the code cannot compile.
/// @param tup the tuple of objects to look in
template<typename B, typename... Types>
B& baget(std::tuple<Types...>& tup)
{
// return std::get<detail::find_base_index<B, Types...>::value>(tup);
return std::get<detail::find_index<std::is_base_of,
B, Types...>::value>(tup);
}
// Const version of above
template<typename B, typename... Types>
const B& baget(const std::tuple<Types...>& tup)
{
// return std::get<detail::find_base_index<B, Types...>::value>(tup);
return std::get<detail::find_index<std::is_base_of,
Types...>::value>(tup);
}
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2020 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
/*
Code for rendering tubes is heavily inspired by a blog post written by Philip Rideout
(Tron, Volumetric Lines, and Meshless Tubes)
at "The little grasshopper, Graphics Programming Tips"
https://prideout.net/blog/old/blog/index.html@p=61.html
*/
#include <modules/basegl/processors/tuberendering.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/openglutils.h>
#include <modules/opengl/rendering/meshdrawergl.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/algorithm/boundingbox.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo TubeRendering::processorInfo_{
"org.inviwo.TubeRendering", // Class identifier
"Tube Rendering", // Display name
"Mesh Rendering", // Category
CodeState::Stable, // Code state
Tags::GL, // Tags
};
const ProcessorInfo TubeRendering::getProcessorInfo() const { return processorInfo_; }
TubeRendering::TubeRendering()
: Processor()
, inport_("mesh")
, imageInport_("imageInport")
, outport_("outport")
, tubeProperties_("tubeProperties", "Tube Properties")
, forceRadius_("forceRadius", "Force Radius", false, InvalidationLevel::InvalidResources)
, defaultRadius_("defaultRadius", "Tube Radius", 0.01f, 0.0001f, 2.f, 0.0001f)
, forceColor_("forceColor", "Force Color", false, InvalidationLevel::InvalidResources)
, defaultColor_("defaultColor", "Default Color", vec4(0.7f, 0.7f, 0.7f, 1.0f), vec4(0.0f),
vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput,
PropertySemantics::Color)
, useMetaColor_("useMetaColor", "Use meta color mapping", false,
InvalidationLevel::InvalidResources)
, metaColor_("metaColor", "Meta Color Mapping")
, camera_("camera", "Camera", util::boundingBox(inport_))
, trackball_(&camera_)
, lighting_("lighting", "Lighting", &camera_)
, shaderItems_{{{ShaderType::Vertex, "tuberendering.vert"},
{ShaderType::Geometry, "tuberendering.geom"},
{ShaderType::Fragment, "tuberendering.frag"}}}
, shaderRequirements_{{{BufferType::PositionAttrib, MeshShaderCache::Mandatory, "vec3"},
{BufferType::ColorAttrib, MeshShaderCache::Optional, "vec4"},
{BufferType::RadiiAttrib, MeshShaderCache::Optional, "float"},
{BufferType::PickingAttrib, MeshShaderCache::Optional, "uint"},
{BufferType::ScalarMetaAttrib, MeshShaderCache::Optional, "float"}}}
, adjacencyShaders_{shaderItems_, shaderRequirements_,
[&](Shader& shader) -> void {
shader.onReload(
[this]() { invalidate(InvalidationLevel::InvalidResources); });
for (auto& obj : shader.getShaderObjects()) {
obj.addShaderDefine("HAS_ADJACENCY");
}
configureShader(shader);
}}
, shaders_{shaderItems_, shaderRequirements_, [&](Shader& shader) -> void {
shader.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
configureShader(shader);
}} {
addPort(inport_);
addPort(imageInport_).setOptional(true);
addPort(outport_);
tubeProperties_.addProperties(forceRadius_, defaultRadius_, forceColor_, defaultColor_,
useMetaColor_, metaColor_);
addProperties(tubeProperties_, camera_, lighting_, trackball_);
}
void TubeRendering::initializeResources() {
for (auto& item : shaders_.getShaders()) {
configureShader(item.second);
}
}
void TubeRendering::configureShader(Shader& shader) {
utilgl::addDefines(shader, lighting_);
shader[ShaderType::Vertex]->setShaderDefine("FORCE_RADIUS", forceRadius_);
shader[ShaderType::Vertex]->setShaderDefine("FORCE_COLOR", forceColor_);
shader[ShaderType::Vertex]->setShaderDefine("USE_SCALARMETACOLOR", useMetaColor_);
shader.build();
}
void TubeRendering::process() {
utilgl::activateTargetAndClearOrCopySource(outport_, imageInport_);
const auto hasLineAdjacency = [](Mesh::MeshInfo mi) {
return mi.dt == DrawType::Lines &&
(mi.ct == ConnectivityType::StripAdjacency || mi.ct == ConnectivityType::Adjacency);
};
const auto hasLine = [](Mesh::MeshInfo mi) {
return mi.dt == DrawType::Lines &&
(mi.ct == ConnectivityType::None || mi.ct == ConnectivityType::Strip);
};
const auto hasAnyLine = [](const Mesh& mesh, auto test) {
if (mesh.getNumberOfIndicies() > 0) {
for (size_t i = 0; i < mesh.getNumberOfIndicies(); ++i) {
if (test(mesh.getIndexMeshInfo(i))) return true;
}
} else {
if (test(mesh.getDefaultMeshInfo())) return true;
}
return false;
};
const auto draw = [this, hasAnyLine](const Mesh& mesh, Shader& shader, auto test) {
if (!hasAnyLine(mesh, test)) return;
shader.activate();
TextureUnitContainer units;
utilgl::bindAndSetUniforms(shader, units, metaColor_);
utilgl::setUniforms(shader, camera_, lighting_, defaultColor_, defaultRadius_);
utilgl::GlBoolState depthTest(GL_DEPTH_TEST, true);
MeshDrawerGL::DrawObject drawer(mesh.getRepresentation<MeshGL>(),
mesh.getDefaultMeshInfo());
utilgl::setShaderUniforms(shader, mesh, "geometry");
if (mesh.getNumberOfIndicies() > 0) {
for (size_t i = 0; i < mesh.getNumberOfIndicies(); ++i) {
const auto mi = mesh.getIndexMeshInfo(i);
if (test(mi)) {
drawer.draw(i);
}
}
} else {
// no index buffers, check mesh default draw type
const auto mi = mesh.getDefaultMeshInfo();
if (test(mi)) {
drawer.draw();
}
}
shader.deactivate();
};
for (const auto& mesh : inport_) {
draw(*mesh, adjacencyShaders_.getShader(*mesh), hasLineAdjacency);
draw(*mesh, shaders_.getShader(*mesh), hasLine);
}
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
<commit_msg>BaseGL: Fixe for tube rendering shaders not updated lighting properties<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2020 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
/*
Code for rendering tubes is heavily inspired by a blog post written by Philip Rideout
(Tron, Volumetric Lines, and Meshless Tubes)
at "The little grasshopper, Graphics Programming Tips"
https://prideout.net/blog/old/blog/index.html@p=61.html
*/
#include <modules/basegl/processors/tuberendering.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/openglutils.h>
#include <modules/opengl/rendering/meshdrawergl.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/algorithm/boundingbox.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo TubeRendering::processorInfo_{
"org.inviwo.TubeRendering", // Class identifier
"Tube Rendering", // Display name
"Mesh Rendering", // Category
CodeState::Stable, // Code state
Tags::GL, // Tags
};
const ProcessorInfo TubeRendering::getProcessorInfo() const { return processorInfo_; }
TubeRendering::TubeRendering()
: Processor()
, inport_("mesh")
, imageInport_("imageInport")
, outport_("outport")
, tubeProperties_("tubeProperties", "Tube Properties")
, forceRadius_("forceRadius", "Force Radius", false, InvalidationLevel::InvalidResources)
, defaultRadius_("defaultRadius", "Tube Radius", 0.01f, 0.0001f, 2.f, 0.0001f)
, forceColor_("forceColor", "Force Color", false, InvalidationLevel::InvalidResources)
, defaultColor_("defaultColor", "Default Color", vec4(0.7f, 0.7f, 0.7f, 1.0f), vec4(0.0f),
vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput,
PropertySemantics::Color)
, useMetaColor_("useMetaColor", "Use meta color mapping", false,
InvalidationLevel::InvalidResources)
, metaColor_("metaColor", "Meta Color Mapping")
, camera_("camera", "Camera", util::boundingBox(inport_))
, trackball_(&camera_)
, lighting_("lighting", "Lighting", &camera_)
, shaderItems_{{{ShaderType::Vertex, "tuberendering.vert"},
{ShaderType::Geometry, "tuberendering.geom"},
{ShaderType::Fragment, "tuberendering.frag"}}}
, shaderRequirements_{{{BufferType::PositionAttrib, MeshShaderCache::Mandatory, "vec3"},
{BufferType::ColorAttrib, MeshShaderCache::Optional, "vec4"},
{BufferType::RadiiAttrib, MeshShaderCache::Optional, "float"},
{BufferType::PickingAttrib, MeshShaderCache::Optional, "uint"},
{BufferType::ScalarMetaAttrib, MeshShaderCache::Optional, "float"}}}
, adjacencyShaders_{shaderItems_, shaderRequirements_,
[&](Shader& shader) -> void {
shader.onReload(
[this]() { invalidate(InvalidationLevel::InvalidResources); });
for (auto& obj : shader.getShaderObjects()) {
obj.addShaderDefine("HAS_ADJACENCY");
}
configureShader(shader);
}}
, shaders_{shaderItems_, shaderRequirements_, [&](Shader& shader) -> void {
shader.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
configureShader(shader);
}} {
addPort(inport_);
addPort(imageInport_).setOptional(true);
addPort(outport_);
tubeProperties_.addProperties(forceRadius_, defaultRadius_, forceColor_, defaultColor_,
useMetaColor_, metaColor_);
addProperties(tubeProperties_, camera_, lighting_, trackball_);
}
void TubeRendering::initializeResources() {
for (auto& item : adjacencyShaders_.getShaders()) {
configureShader(item.second);
}
for (auto& item : shaders_.getShaders()) {
configureShader(item.second);
}
}
void TubeRendering::configureShader(Shader& shader) {
utilgl::addDefines(shader, lighting_);
shader[ShaderType::Vertex]->setShaderDefine("FORCE_RADIUS", forceRadius_);
shader[ShaderType::Vertex]->setShaderDefine("FORCE_COLOR", forceColor_);
shader[ShaderType::Vertex]->setShaderDefine("USE_SCALARMETACOLOR", useMetaColor_);
shader.build();
}
void TubeRendering::process() {
utilgl::activateTargetAndClearOrCopySource(outport_, imageInport_);
const auto hasLineAdjacency = [](Mesh::MeshInfo mi) {
return mi.dt == DrawType::Lines &&
(mi.ct == ConnectivityType::StripAdjacency || mi.ct == ConnectivityType::Adjacency);
};
const auto hasLine = [](Mesh::MeshInfo mi) {
return mi.dt == DrawType::Lines &&
(mi.ct == ConnectivityType::None || mi.ct == ConnectivityType::Strip);
};
const auto hasAnyLine = [](const Mesh& mesh, auto test) {
if (mesh.getNumberOfIndicies() > 0) {
for (size_t i = 0; i < mesh.getNumberOfIndicies(); ++i) {
if (test(mesh.getIndexMeshInfo(i))) return true;
}
} else {
if (test(mesh.getDefaultMeshInfo())) return true;
}
return false;
};
const auto draw = [this, hasAnyLine](const Mesh& mesh, Shader& shader, auto test) {
if (!hasAnyLine(mesh, test)) return;
shader.activate();
TextureUnitContainer units;
utilgl::bindAndSetUniforms(shader, units, metaColor_);
utilgl::setUniforms(shader, camera_, lighting_, defaultColor_, defaultRadius_);
utilgl::GlBoolState depthTest(GL_DEPTH_TEST, true);
MeshDrawerGL::DrawObject drawer(mesh.getRepresentation<MeshGL>(),
mesh.getDefaultMeshInfo());
utilgl::setShaderUniforms(shader, mesh, "geometry");
if (mesh.getNumberOfIndicies() > 0) {
for (size_t i = 0; i < mesh.getNumberOfIndicies(); ++i) {
const auto mi = mesh.getIndexMeshInfo(i);
if (test(mi)) {
drawer.draw(i);
}
}
} else {
// no index buffers, check mesh default draw type
const auto mi = mesh.getDefaultMeshInfo();
if (test(mi)) {
drawer.draw();
}
}
shader.deactivate();
};
for (const auto& mesh : inport_) {
draw(*mesh, adjacencyShaders_.getShader(*mesh), hasLineAdjacency);
draw(*mesh, shaders_.getShader(*mesh), hasLine);
}
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "maze.h"
#include "mazedata.h"
#include "mazeprinter.h"
class TestMazePrinter : public ::testing::Test {
protected:
Maze *maze;
MazePrinter* printer;
virtual void SetUp() {
maze = new Maze(16);
maze->resetToEmptyMaze();
}
virtual void TearDown() {
delete maze;
}
virtual void copyClassicMaze(const uint8_t *mazeData) const {
for (int cell = 0; cell < this->maze->numCells(); ++cell) {
maze->copyCellFromFileData(cell, mazeData[cell]);
}
}
};
/*
* It is not clear how best to test the results of the maze printing
* except by visual inspection.
*/
TEST_F (TestMazePrinter, PrintForCoverageTesting)
{
MazePrinter::printVisitedDirs(maze);
copyClassicMaze(japan2007);
maze->flood(maze->goal());
maze->updateDirections();
MazePrinter::printDirs(maze);
MazePrinter::printPlain(maze);
MazePrinter::printCDecl(maze,"julian");
}
<commit_msg>tidy test for maze printer<commit_after>#include "gtest/gtest.h"
#include "maze.h"
#include "mazedata.h"
#include "mazeprinter.h"
class TestMazePrinter : public ::testing::Test {
protected:
Maze *maze;
virtual void SetUp() {
maze = new Maze(16);
maze->resetToEmptyMaze();
}
virtual void TearDown() {
delete maze;
}
virtual void copyClassicMaze(const uint8_t *mazeData) const {
for (int cell = 0; cell < this->maze->numCells(); ++cell) {
maze->copyCellFromFileData(cell, mazeData[cell]);
}
}
};
/*
* It is not clear how best to test the results of the maze printing
* except by visual inspection.
*/
TEST_F (TestMazePrinter, PrintForCoverageTesting)
{
MazePrinter::printVisitedDirs(maze);
copyClassicMaze(japan2007);
maze->flood(maze->goal());
maze->updateDirections();
MazePrinter::printDirs(maze);
MazePrinter::printPlain(maze);
MazePrinter::printCDecl(maze,"julian");
}
<|endoftext|> |
<commit_before><commit_msg>Add db is use to spam at application start<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/thread.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/util/bool_class.hh>
#include "mutation_fragment.hh"
#include "test/lib/mutation_source_test.hh"
#include "flat_mutation_reader.hh"
#include "mutation_writer/multishard_writer.hh"
#include "mutation_writer/timestamp_based_splitting_writer.hh"
#include "test/lib/cql_test_env.hh"
#include "test/lib/mutation_assertions.hh"
#include "test/lib/random_utils.hh"
#include "test/lib/random_schema.hh"
using namespace mutation_writer;
logging::logger tlog("mutation_writer_test");
struct generate_error_tag { };
using generate_error = bool_class<generate_error_tag>;
constexpr unsigned many_partitions() {
return
#ifndef SEASTAR_DEBUG
300
#else
10
#endif
;
}
SEASTAR_TEST_CASE(test_multishard_writer) {
return do_with_cql_env_thread([] (cql_test_env& e) {
auto test_random_streams = [] (random_mutation_generator&& gen, size_t partition_nr, generate_error error = generate_error::no) {
for (auto i = 0; i < 3; i++) {
auto muts = gen(partition_nr);
std::vector<size_t> shards_before(smp::count, 0);
std::vector<size_t> shards_after(smp::count, 0);
for (auto& m : muts) {
auto shard = dht::global_partitioner().shard_of(m.token());
shards_before[shard]++;
}
schema_ptr s = gen.schema();
auto source_reader = partition_nr > 0 ? flat_mutation_reader_from_mutations(muts) : make_empty_flat_reader(s);
size_t partitions_received = distribute_reader_and_consume_on_shards(s,
std::move(source_reader),
[&shards_after, error] (flat_mutation_reader reader) mutable {
if (error) {
return make_exception_future<>(std::runtime_error("Failed to write"));
}
return repeat([&shards_after, reader = std::move(reader), error] () mutable {
return reader(db::no_timeout).then([&shards_after, error] (mutation_fragment_opt mf_opt) mutable {
if (mf_opt) {
if (mf_opt->is_partition_start()) {
auto shard = dht::global_partitioner().shard_of(mf_opt->as_partition_start().key().token());
BOOST_REQUIRE_EQUAL(shard, engine().cpu_id());
shards_after[shard]++;
}
return make_ready_future<stop_iteration>(stop_iteration::no);
} else {
return make_ready_future<stop_iteration>(stop_iteration::yes);
}
});
});
}
).get0();
BOOST_REQUIRE_EQUAL(partitions_received, partition_nr);
BOOST_REQUIRE_EQUAL(shards_after, shards_before);
}
};
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), 0);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), 0);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), 1);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), 1);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), many_partitions());
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), many_partitions());
try {
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), many_partitions(), generate_error::yes);
BOOST_ASSERT(false);
} catch (...) {
}
try {
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), many_partitions(), generate_error::yes);
BOOST_ASSERT(false);
} catch (...) {
}
});
}
namespace {
class bucket_writer {
schema_ptr _schema;
classify_by_timestamp _classify;
std::unordered_map<int64_t, std::vector<mutation>>& _buckets;
std::optional<int64_t> _bucket_id;
mutation_opt _current_mutation;
bool _is_first_mutation = true;
private:
void check_timestamp(api::timestamp_type ts) {
const auto bucket_id = _classify(ts);
if (_bucket_id) {
BOOST_REQUIRE_EQUAL(bucket_id, *_bucket_id);
} else {
_bucket_id = bucket_id;
}
}
void verify_column_bucket_id(const atomic_cell_or_collection& cell, const column_definition& cdef) {
if (cdef.is_atomic()) {
check_timestamp(cell.as_atomic_cell(cdef).timestamp());
} else if (cdef.type->is_collection() || cdef.type->is_user_type()) {
cell.as_collection_mutation().with_deserialized(*cdef.type, [this] (collection_mutation_view_description mv) {
for (const auto& c: mv.cells) {
check_timestamp(c.second.timestamp());
}
});
} else {
BOOST_FAIL(fmt::format("Failed to verify column bucket id: column {} is of unknown type {}", cdef.name_as_text(), cdef.type->name()));
}
}
void verify_row_bucket_id(const row& r, column_kind kind) {
r.for_each_cell([this, kind] (column_id id, const atomic_cell_or_collection& cell) {
verify_column_bucket_id(cell, _schema->column_at(kind, id));
});
}
void verify_partition_tombstone(tombstone tomb) {
if (tomb) {
check_timestamp(tomb.timestamp);
}
}
void verify_static_row(const static_row& sr) {
verify_row_bucket_id(sr.cells(), column_kind::static_column);
}
void verify_clustering_row(const clustering_row& cr) {
if (!cr.marker().is_missing()) {
check_timestamp(cr.marker().timestamp());
}
if (cr.tomb()) {
check_timestamp(cr.tomb().tomb().timestamp);
}
verify_row_bucket_id(cr.cells(), column_kind::regular_column);
}
void verify_range_tombstone(const range_tombstone& rt) {
check_timestamp(rt.tomb.timestamp);
}
public:
bucket_writer(schema_ptr schema, classify_by_timestamp classify, std::unordered_map<int64_t, std::vector<mutation>>& buckets)
: _schema(std::move(schema))
, _classify(std::move(classify))
, _buckets(buckets) {
}
void consume_new_partition(const dht::decorated_key& dk) {
BOOST_REQUIRE(!_current_mutation);
_current_mutation = mutation(_schema, dk);
}
void consume(tombstone partition_tombstone) {
BOOST_REQUIRE(_current_mutation);
verify_partition_tombstone(partition_tombstone);
_current_mutation->partition().apply(partition_tombstone);
}
stop_iteration consume(static_row&& sr) {
BOOST_REQUIRE(_current_mutation);
verify_static_row(sr);
_current_mutation->apply(std::move(sr));
return stop_iteration::no;
}
stop_iteration consume(clustering_row&& cr) {
BOOST_REQUIRE(_current_mutation);
verify_clustering_row(cr);
_current_mutation->apply(std::move(cr));
return stop_iteration::no;
}
stop_iteration consume(range_tombstone&& rt) {
BOOST_REQUIRE(_current_mutation);
verify_range_tombstone(rt);
_current_mutation->apply(std::move(rt));
return stop_iteration::no;
}
stop_iteration consume_end_of_partition() {
BOOST_REQUIRE(_current_mutation);
BOOST_REQUIRE(_bucket_id);
auto& bucket = _buckets[*_bucket_id];
if (_is_first_mutation) {
BOOST_REQUIRE(bucket.empty());
_is_first_mutation = false;
}
bucket.emplace_back(std::move(*_current_mutation));
_current_mutation = std::nullopt;
return stop_iteration::no;
}
void consume_end_of_stream() {
BOOST_REQUIRE(!_current_mutation);
}
};
} // anonymous namespace
SEASTAR_THREAD_TEST_CASE(test_timestamp_based_splitting_mutation_writer) {
auto random_spec = tests::make_random_schema_specification(
get_name(),
std::uniform_int_distribution<size_t>(1, 4),
std::uniform_int_distribution<size_t>(2, 4),
std::uniform_int_distribution<size_t>(2, 8),
std::uniform_int_distribution<size_t>(2, 8));
auto random_schema = tests::random_schema{tests::random::get_int<uint32_t>(), *random_spec};
tlog.info("Random schema:\n{}", random_schema.cql());
auto ts_gen = [&, underlying = tests::default_timestamp_generator()] (std::mt19937& engine,
tests::timestamp_destination ts_dest, api::timestamp_type min_timestamp) -> api::timestamp_type {
if (ts_dest == tests::timestamp_destination::partition_tombstone ||
ts_dest == tests::timestamp_destination::row_marker ||
ts_dest == tests::timestamp_destination::row_tombstone ||
ts_dest == tests::timestamp_destination::collection_tombstone) {
if (tests::random::get_int<int>(0, 10, engine)) {
return api::missing_timestamp;
}
}
return underlying(engine, ts_dest, min_timestamp);
};
auto muts = tests::generate_random_mutations(random_schema, ts_gen).get0();
auto classify_fn = [] (api::timestamp_type ts) {
return int64_t(ts % 2);
};
std::unordered_map<int64_t, std::vector<mutation>> buckets;
auto consumer = [&] (flat_mutation_reader bucket_reader) {
return do_with(std::move(bucket_reader), [&] (flat_mutation_reader& rd) {
return rd.consume(bucket_writer(random_schema.schema(), classify_fn, buckets), db::no_timeout);
});
};
segregate_by_timestamp(flat_mutation_reader_from_mutations(muts), classify_fn, std::move(consumer)).get();
tlog.debug("Data split into {} buckets: {}", buckets.size(), boost::copy_range<std::vector<int64_t>>(buckets | boost::adaptors::map_keys));
auto bucket_readers = boost::copy_range<std::vector<flat_mutation_reader>>(buckets | boost::adaptors::map_values |
boost::adaptors::transformed([] (std::vector<mutation> muts) { return flat_mutation_reader_from_mutations(std::move(muts)); }));
auto reader = make_combined_reader(random_schema.schema(), std::move(bucket_readers), streamed_mutation::forwarding::no,
mutation_reader::forwarding::no);
const auto now = gc_clock::now();
for (auto& m : muts) {
m.partition().compact_for_compaction(*random_schema.schema(), always_gc, now);
}
std::vector<mutation> combined_mutations;
while (auto m = read_mutation_from_flat_mutation_reader(reader, db::no_timeout).get0()) {
m->partition().compact_for_compaction(*random_schema.schema(), always_gc, now);
combined_mutations.emplace_back(std::move(*m));
}
BOOST_REQUIRE_EQUAL(combined_mutations.size(), muts.size());
for (size_t i = 0; i < muts.size(); ++i) {
tlog.debug("Comparing mutation #{}", i);
assert_that(combined_mutations[i]).is_equal_to(muts[i]);
}
}
<commit_msg>mutation_writer_test: stop calling global_partitioner()<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/thread.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/util/bool_class.hh>
#include "mutation_fragment.hh"
#include "test/lib/mutation_source_test.hh"
#include "flat_mutation_reader.hh"
#include "mutation_writer/multishard_writer.hh"
#include "mutation_writer/timestamp_based_splitting_writer.hh"
#include "test/lib/cql_test_env.hh"
#include "test/lib/mutation_assertions.hh"
#include "test/lib/random_utils.hh"
#include "test/lib/random_schema.hh"
using namespace mutation_writer;
logging::logger tlog("mutation_writer_test");
struct generate_error_tag { };
using generate_error = bool_class<generate_error_tag>;
constexpr unsigned many_partitions() {
return
#ifndef SEASTAR_DEBUG
300
#else
10
#endif
;
}
SEASTAR_TEST_CASE(test_multishard_writer) {
return do_with_cql_env_thread([] (cql_test_env& e) {
auto test_random_streams = [] (random_mutation_generator&& gen, size_t partition_nr, generate_error error = generate_error::no) {
for (auto i = 0; i < 3; i++) {
auto muts = gen(partition_nr);
std::vector<size_t> shards_before(smp::count, 0);
std::vector<size_t> shards_after(smp::count, 0);
schema_ptr s = gen.schema();
for (auto& m : muts) {
auto shard = s->get_partitioner().shard_of(m.token());
shards_before[shard]++;
}
auto source_reader = partition_nr > 0 ? flat_mutation_reader_from_mutations(muts) : make_empty_flat_reader(s);
auto& partitioner = s->get_partitioner();
size_t partitions_received = distribute_reader_and_consume_on_shards(s,
std::move(source_reader),
[&partitioner, &shards_after, error] (flat_mutation_reader reader) mutable {
if (error) {
return make_exception_future<>(std::runtime_error("Failed to write"));
}
return repeat([&partitioner, &shards_after, reader = std::move(reader), error] () mutable {
return reader(db::no_timeout).then([&partitioner, &shards_after, error] (mutation_fragment_opt mf_opt) mutable {
if (mf_opt) {
if (mf_opt->is_partition_start()) {
auto shard = partitioner.shard_of(mf_opt->as_partition_start().key().token());
BOOST_REQUIRE_EQUAL(shard, engine().cpu_id());
shards_after[shard]++;
}
return make_ready_future<stop_iteration>(stop_iteration::no);
} else {
return make_ready_future<stop_iteration>(stop_iteration::yes);
}
});
});
}
).get0();
BOOST_REQUIRE_EQUAL(partitions_received, partition_nr);
BOOST_REQUIRE_EQUAL(shards_after, shards_before);
}
};
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), 0);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), 0);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), 1);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), 1);
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), many_partitions());
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), many_partitions());
try {
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::no, local_shard_only::no), many_partitions(), generate_error::yes);
BOOST_ASSERT(false);
} catch (...) {
}
try {
test_random_streams(random_mutation_generator(random_mutation_generator::generate_counters::yes, local_shard_only::no), many_partitions(), generate_error::yes);
BOOST_ASSERT(false);
} catch (...) {
}
});
}
namespace {
class bucket_writer {
schema_ptr _schema;
classify_by_timestamp _classify;
std::unordered_map<int64_t, std::vector<mutation>>& _buckets;
std::optional<int64_t> _bucket_id;
mutation_opt _current_mutation;
bool _is_first_mutation = true;
private:
void check_timestamp(api::timestamp_type ts) {
const auto bucket_id = _classify(ts);
if (_bucket_id) {
BOOST_REQUIRE_EQUAL(bucket_id, *_bucket_id);
} else {
_bucket_id = bucket_id;
}
}
void verify_column_bucket_id(const atomic_cell_or_collection& cell, const column_definition& cdef) {
if (cdef.is_atomic()) {
check_timestamp(cell.as_atomic_cell(cdef).timestamp());
} else if (cdef.type->is_collection() || cdef.type->is_user_type()) {
cell.as_collection_mutation().with_deserialized(*cdef.type, [this] (collection_mutation_view_description mv) {
for (const auto& c: mv.cells) {
check_timestamp(c.second.timestamp());
}
});
} else {
BOOST_FAIL(fmt::format("Failed to verify column bucket id: column {} is of unknown type {}", cdef.name_as_text(), cdef.type->name()));
}
}
void verify_row_bucket_id(const row& r, column_kind kind) {
r.for_each_cell([this, kind] (column_id id, const atomic_cell_or_collection& cell) {
verify_column_bucket_id(cell, _schema->column_at(kind, id));
});
}
void verify_partition_tombstone(tombstone tomb) {
if (tomb) {
check_timestamp(tomb.timestamp);
}
}
void verify_static_row(const static_row& sr) {
verify_row_bucket_id(sr.cells(), column_kind::static_column);
}
void verify_clustering_row(const clustering_row& cr) {
if (!cr.marker().is_missing()) {
check_timestamp(cr.marker().timestamp());
}
if (cr.tomb()) {
check_timestamp(cr.tomb().tomb().timestamp);
}
verify_row_bucket_id(cr.cells(), column_kind::regular_column);
}
void verify_range_tombstone(const range_tombstone& rt) {
check_timestamp(rt.tomb.timestamp);
}
public:
bucket_writer(schema_ptr schema, classify_by_timestamp classify, std::unordered_map<int64_t, std::vector<mutation>>& buckets)
: _schema(std::move(schema))
, _classify(std::move(classify))
, _buckets(buckets) {
}
void consume_new_partition(const dht::decorated_key& dk) {
BOOST_REQUIRE(!_current_mutation);
_current_mutation = mutation(_schema, dk);
}
void consume(tombstone partition_tombstone) {
BOOST_REQUIRE(_current_mutation);
verify_partition_tombstone(partition_tombstone);
_current_mutation->partition().apply(partition_tombstone);
}
stop_iteration consume(static_row&& sr) {
BOOST_REQUIRE(_current_mutation);
verify_static_row(sr);
_current_mutation->apply(std::move(sr));
return stop_iteration::no;
}
stop_iteration consume(clustering_row&& cr) {
BOOST_REQUIRE(_current_mutation);
verify_clustering_row(cr);
_current_mutation->apply(std::move(cr));
return stop_iteration::no;
}
stop_iteration consume(range_tombstone&& rt) {
BOOST_REQUIRE(_current_mutation);
verify_range_tombstone(rt);
_current_mutation->apply(std::move(rt));
return stop_iteration::no;
}
stop_iteration consume_end_of_partition() {
BOOST_REQUIRE(_current_mutation);
BOOST_REQUIRE(_bucket_id);
auto& bucket = _buckets[*_bucket_id];
if (_is_first_mutation) {
BOOST_REQUIRE(bucket.empty());
_is_first_mutation = false;
}
bucket.emplace_back(std::move(*_current_mutation));
_current_mutation = std::nullopt;
return stop_iteration::no;
}
void consume_end_of_stream() {
BOOST_REQUIRE(!_current_mutation);
}
};
} // anonymous namespace
SEASTAR_THREAD_TEST_CASE(test_timestamp_based_splitting_mutation_writer) {
auto random_spec = tests::make_random_schema_specification(
get_name(),
std::uniform_int_distribution<size_t>(1, 4),
std::uniform_int_distribution<size_t>(2, 4),
std::uniform_int_distribution<size_t>(2, 8),
std::uniform_int_distribution<size_t>(2, 8));
auto random_schema = tests::random_schema{tests::random::get_int<uint32_t>(), *random_spec};
tlog.info("Random schema:\n{}", random_schema.cql());
auto ts_gen = [&, underlying = tests::default_timestamp_generator()] (std::mt19937& engine,
tests::timestamp_destination ts_dest, api::timestamp_type min_timestamp) -> api::timestamp_type {
if (ts_dest == tests::timestamp_destination::partition_tombstone ||
ts_dest == tests::timestamp_destination::row_marker ||
ts_dest == tests::timestamp_destination::row_tombstone ||
ts_dest == tests::timestamp_destination::collection_tombstone) {
if (tests::random::get_int<int>(0, 10, engine)) {
return api::missing_timestamp;
}
}
return underlying(engine, ts_dest, min_timestamp);
};
auto muts = tests::generate_random_mutations(random_schema, ts_gen).get0();
auto classify_fn = [] (api::timestamp_type ts) {
return int64_t(ts % 2);
};
std::unordered_map<int64_t, std::vector<mutation>> buckets;
auto consumer = [&] (flat_mutation_reader bucket_reader) {
return do_with(std::move(bucket_reader), [&] (flat_mutation_reader& rd) {
return rd.consume(bucket_writer(random_schema.schema(), classify_fn, buckets), db::no_timeout);
});
};
segregate_by_timestamp(flat_mutation_reader_from_mutations(muts), classify_fn, std::move(consumer)).get();
tlog.debug("Data split into {} buckets: {}", buckets.size(), boost::copy_range<std::vector<int64_t>>(buckets | boost::adaptors::map_keys));
auto bucket_readers = boost::copy_range<std::vector<flat_mutation_reader>>(buckets | boost::adaptors::map_values |
boost::adaptors::transformed([] (std::vector<mutation> muts) { return flat_mutation_reader_from_mutations(std::move(muts)); }));
auto reader = make_combined_reader(random_schema.schema(), std::move(bucket_readers), streamed_mutation::forwarding::no,
mutation_reader::forwarding::no);
const auto now = gc_clock::now();
for (auto& m : muts) {
m.partition().compact_for_compaction(*random_schema.schema(), always_gc, now);
}
std::vector<mutation> combined_mutations;
while (auto m = read_mutation_from_flat_mutation_reader(reader, db::no_timeout).get0()) {
m->partition().compact_for_compaction(*random_schema.schema(), always_gc, now);
combined_mutations.emplace_back(std::move(*m));
}
BOOST_REQUIRE_EQUAL(combined_mutations.size(), muts.size());
for (size_t i = 0; i < muts.size(); ++i) {
tlog.debug("Comparing mutation #{}", i);
assert_that(combined_mutations[i]).is_equal_to(muts[i]);
}
}
<|endoftext|> |
<commit_before>#include <primitives/version_range.h>
#include <range_parser.h>
#include <fmt/format.h>
#include <primitives/constants.h>
#include <primitives/exceptions.h>
#include <primitives/hash_combine.h>
#include <primitives/string.h>
#include <pystring.h>
#include <algorithm>
#include <map>
const primitives::version::Version::Level minimum_level = 3;
namespace primitives::version
{
bool detail::RangePair::Side::operator<(const Version &rhs) const
{
if (strong_relation)
return v < rhs;
else
return v <= rhs;
}
bool detail::RangePair::Side::operator>(const Version &rhs) const
{
if (strong_relation)
return v > rhs;
else
return v >= rhs;
}
std::string detail::RangePair::Side::toString(VersionRangePairStringRepresentationType t) const
{
switch (t)
{
case VersionRangePairStringRepresentationType::SameDefaultLevel:
return v.toString(v.getDefaultLevel());
break;
case VersionRangePairStringRepresentationType::SameRealLevel:
return v.toString(v.getRealLevel());
break;
case VersionRangePairStringRepresentationType::IndividualRealLevel:
return v.toString(v.getRealLevel());
}
SW_UNREACHABLE;
}
detail::RangePair::RangePair(const Version &v1, bool strong_relation1, const Version &v2, bool strong_relation2)
: first{ v1, strong_relation1 }, second{ v2, strong_relation2 }
{
if (getFirst() > getSecond())
throw SW_RUNTIME_ERROR("Left version must be <= than right: " + toStringInterval());
if (getFirst() == getSecond() && (strong_relation1 || strong_relation2))
throw SW_RUNTIME_ERROR("Pair does not contain any versions: " + toStringInterval());
}
detail::RangePair::RangePair(const Side &l, const Side &r)
: first(l), second(r)
{
}
bool detail::RangePair::contains(const Version &v) const
{
// TODO: rename < and > here
return first < v && second > v;
}
std::optional<detail::RangePair> detail::RangePair::operator&(const detail::RangePair &rhs) const
{
auto &f = std::max(first, rhs.first);
auto &s = std::min(second, rhs.second);
if (0
|| f.v < s.v
|| f.v == s.v && (!f.strong_relation && !s.strong_relation)
)
return detail::RangePair(f, s);
return {};
}
std::optional<detail::RangePair> detail::RangePair::operator|(const detail::RangePair &rhs) const
{
// find intersection first
auto &f = std::max(first, rhs.first);
auto &s = std::min(second, rhs.second);
if (0
|| f.v < s.v
|| f.v == s.v && (!f.strong_relation || !s.strong_relation)
)
{
// now make a union
auto &fmin = std::min(first, rhs.first);
auto &smax = std::max(second, rhs.second);
return detail::RangePair(fmin, smax);
}
return {};
}
std::string detail::RangePair::toString(VersionRangePairStringRepresentationType t) const
{
/*
auto level = std::max(getFirst().getLevel(), getSecond().getLevel());
if (t == VersionRangePairStringRepresentationType::SameRealLevel)
level = std::max(getFirst().getRealLevel(), getSecond().getRealLevel());
if (getFirst() == getSecond())
{
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
return getFirst().toString(getFirst().getRealLevel());
else
return getFirst().toString(level);
}
std::string s;
if (getFirst() != Version::min(getFirst()))
{
s += ">=";
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
s += getFirst().toString(getFirst().getRealLevel());
else
s += getFirst().toString(level);
}
// reconsider?
// probably wrong now: 1.MAX.3
if (std::any_of(getSecond().numbers.begin(), getSecond().numbers.end(),
[](const auto &n) {return n == Version::maxNumber(); }))
{
if (getSecond() == Version::max(getSecond()))
{
if (s.empty())
return "*";
return s;
}
if (getSecond().getPatch() == Version::maxNumber() ||
getSecond().getTweak() == Version::maxNumber())
{
if (!s.empty())
s += " ";
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
{
auto nv = getSecond().getNextVersion(getSecond().getRealLevel());
return s + "<" + nv.toString(nv.getRealLevel());
}
auto nv = getSecond().getNextVersion(level);
if (t == VersionRangePairStringRepresentationType::SameRealLevel)
{
level = std::max(getFirst().getRealLevel(), nv.getRealLevel());
s.clear();
if (getFirst() != Version::min(getFirst()))
{
s += ">=";
s += getFirst().toString(level);
if (!s.empty())
s += " ";
}
}
return s + "<" + nv.toString(level);
}
}
if (!s.empty())
s += " ";
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
return s + "<=" + getSecond().toString(getSecond().getRealLevel());
else
return s + "<=" + getSecond().toString(level);*/
bool print_left = first.v > Version::min();
bool print_right = second.v < Version::max();
std::string s;
if (print_left)
{
s += ">";
if (!first.strong_relation)
s += "=";
s += first.toString(t);
}
if (print_left && print_right)
s += " ";
if (print_right)
{
s += "<";
if (!second.strong_relation)
s += "=";
s += second.toString(t);
}
if (s.empty())
return "*";
return s;
}
std::string detail::RangePair::toStringInterval() const
{
std::string s;
if (first.strong_relation)
s += "(";
else
s += "[";
s += first.toString(VersionRangePairStringRepresentationType::SameDefaultLevel);
s += ", ";
s += second.toString(VersionRangePairStringRepresentationType::SameDefaultLevel);
if (second.strong_relation)
s += ")";
else
s += "]";
return s;
}
std::optional<Version> detail::RangePair::toVersion() const
{
if (getFirst() != getSecond())
return {};
return getFirst();
}
size_t detail::RangePair::getHash() const
{
size_t h = 0;
hash_combine(h, getFirst().getHash());
hash_combine(h, getSecond().getHash());
return h;
}
VersionRange::VersionRange()
{
}
/*VersionRange::VersionRange(const Version &v1, const Version &v2)
{
range.emplace_back(v1, false, v2, false);
}*/
VersionRange::VersionRange(const char *v)
{
if (!v)
throw SW_RUNTIME_ERROR("Empty version range");
*this = std::string{ v };
}
VersionRange::VersionRange(const std::string &s)
{
auto in = detail::preprocess_input(s);
if (in.empty())
// * or throw error?
*this = VersionRange{"*"};
else if (auto r = parse(*this, in); r)
throw SW_RUNTIME_ERROR("Invalid version range: " + in + ", error: " + r.value());
}
std::optional<VersionRange> VersionRange::parse(const std::string &s)
{
VersionRange vr;
auto in = detail::preprocess_input(s);
if (in.empty())
vr = VersionRange{"*"};
else if (auto r = parse(vr, in); r)
return {};
return vr;
}
std::optional<std::string> VersionRange::parse(VersionRange &vr, const std::string &s)
{
if (s.size() > 32_KB)
return { "Range string length must be less than 32K" };
RangeParser d;
auto r = d.parse(s);
auto error = d.bb.error_msg;
if (r == 0)
{
if (auto res = d.bb.getResult<VersionRange>(); res)
{
vr = res.value();
return {};
}
else
error = "parser error: empty result";
}
return error;
}
size_t VersionRange::size() const
{
return range.size();
}
bool VersionRange::isEmpty() const
{
return range.empty();
}
bool VersionRange::contains(const Version &v) const
{
return std::any_of(range.begin(), range.end(),
[&v](const auto &r) { return r.contains(v); });
}
bool VersionRange::contains(const VersionRange &r) const
{
return (*this & r) == r;
}
std::optional<Version> VersionRange::toVersion() const
{
if (size() != 1)
return {};
return range.begin()->toVersion();
}
std::string VersionRange::toString() const
{
return toString(VersionRangePairStringRepresentationType::SameDefaultLevel);
}
std::string VersionRange::toString(VersionRangePairStringRepresentationType t) const
{
std::string s;
for (auto &p : range)
s += p.toString(t) + " || ";
if (!s.empty())
s.resize(s.size() - 4);
return s;
}
size_t VersionRange::getHash() const
{
size_t h = 0;
for (auto &n : range)
hash_combine(h, n.getHash());
return h;
}
bool VersionRange::operator==(const VersionRange &rhs) const
{
return range == rhs.range;
}
VersionRange &VersionRange::operator|=(const detail::RangePair &rhs)
{
// we can do pairs |= p
// but we still need to merge overlapped after
// so we choose simple iterative approach instead
bool added = false;
for (auto i = range.begin(); i < range.end(); i++)
{
if (!added)
{
// skip add, p is greater
if (i->getSecond() < rhs.getFirst())
continue;
// insert as is BEFORE current
else if (i->getFirst() > rhs.getSecond())
{
i = range.insert(i, rhs);
break; // no further merges requires
}
else
{
// TRY to merge overlapped
// we can fail on (1,2)|(2,3)
if (auto u = *i | rhs)
*i = *u;
else
// insert as is AFTER current
i = range.insert(++i, rhs);
added = true;
}
}
else
{
// after merging with existing entry we must ensure that
// following intervals do not require merges too
if ((i - 1)->getSecond() < i->getFirst())
break;
else if (auto u = *(i - 1) | *i)
{
*(i - 1) = *u;
i = range.erase(i) - 1;
}
}
}
if (!added)
range.push_back(rhs);
return *this;
}
VersionRange &VersionRange::operator|=(const VersionRange &rhs)
{
for (auto &rp : rhs.range)
operator|=(rp);
return *this;
}
VersionRange &VersionRange::operator&=(const VersionRange &rhs)
{
VersionRange vr;
for (auto &rp1 : range)
{
for (auto &rp2 : rhs.range)
{
if (auto o = rp1 & rp2; o)
vr |= o.value();
}
}
return *this = vr;
}
VersionRange VersionRange::operator|(const VersionRange &rhs) const
{
auto tmp = *this;
tmp |= rhs;
return tmp;
}
VersionRange VersionRange::operator&(const VersionRange &rhs) const
{
auto tmp = *this;
tmp &= rhs;
return tmp;
}
/*VersionRange VersionRange::operator~() const
{
auto tmp = *this;
throw SW_RUNTIME_ERROR("not implemented");
return tmp;
}*/
}
<commit_msg>Print equal range pair as '=version'.<commit_after>#include <primitives/version_range.h>
#include <range_parser.h>
#include <fmt/format.h>
#include <primitives/constants.h>
#include <primitives/exceptions.h>
#include <primitives/hash_combine.h>
#include <primitives/string.h>
#include <pystring.h>
#include <algorithm>
#include <map>
const primitives::version::Version::Level minimum_level = 3;
namespace primitives::version
{
bool detail::RangePair::Side::operator<(const Version &rhs) const
{
if (strong_relation)
return v < rhs;
else
return v <= rhs;
}
bool detail::RangePair::Side::operator>(const Version &rhs) const
{
if (strong_relation)
return v > rhs;
else
return v >= rhs;
}
std::string detail::RangePair::Side::toString(VersionRangePairStringRepresentationType t) const
{
switch (t)
{
case VersionRangePairStringRepresentationType::SameDefaultLevel:
return v.toString(v.getDefaultLevel());
break;
case VersionRangePairStringRepresentationType::SameRealLevel:
return v.toString(v.getRealLevel());
break;
case VersionRangePairStringRepresentationType::IndividualRealLevel:
return v.toString(v.getRealLevel());
}
SW_UNREACHABLE;
}
detail::RangePair::RangePair(const Version &v1, bool strong_relation1, const Version &v2, bool strong_relation2)
: first{ v1, strong_relation1 }, second{ v2, strong_relation2 }
{
if (getFirst() > getSecond())
throw SW_RUNTIME_ERROR("Left version must be <= than right: " + toStringInterval());
if (getFirst() == getSecond() && (strong_relation1 || strong_relation2))
throw SW_RUNTIME_ERROR("Pair does not contain any versions: " + toStringInterval());
}
detail::RangePair::RangePair(const Side &l, const Side &r)
: first(l), second(r)
{
}
bool detail::RangePair::contains(const Version &v) const
{
// TODO: rename < and > here
return first < v && second > v;
}
std::optional<detail::RangePair> detail::RangePair::operator&(const detail::RangePair &rhs) const
{
auto &f = std::max(first, rhs.first);
auto &s = std::min(second, rhs.second);
if (0
|| f.v < s.v
|| f.v == s.v && (!f.strong_relation && !s.strong_relation)
)
return detail::RangePair(f, s);
return {};
}
std::optional<detail::RangePair> detail::RangePair::operator|(const detail::RangePair &rhs) const
{
// find intersection first
auto &f = std::max(first, rhs.first);
auto &s = std::min(second, rhs.second);
if (0
|| f.v < s.v
|| f.v == s.v && (!f.strong_relation || !s.strong_relation)
)
{
// now make a union
auto &fmin = std::min(first, rhs.first);
auto &smax = std::max(second, rhs.second);
return detail::RangePair(fmin, smax);
}
return {};
}
std::string detail::RangePair::toString(VersionRangePairStringRepresentationType t) const
{
/*
auto level = std::max(getFirst().getLevel(), getSecond().getLevel());
if (t == VersionRangePairStringRepresentationType::SameRealLevel)
level = std::max(getFirst().getRealLevel(), getSecond().getRealLevel());
if (getFirst() == getSecond())
{
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
return getFirst().toString(getFirst().getRealLevel());
else
return getFirst().toString(level);
}
std::string s;
if (getFirst() != Version::min(getFirst()))
{
s += ">=";
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
s += getFirst().toString(getFirst().getRealLevel());
else
s += getFirst().toString(level);
}
// reconsider?
// probably wrong now: 1.MAX.3
if (std::any_of(getSecond().numbers.begin(), getSecond().numbers.end(),
[](const auto &n) {return n == Version::maxNumber(); }))
{
if (getSecond() == Version::max(getSecond()))
{
if (s.empty())
return "*";
return s;
}
if (getSecond().getPatch() == Version::maxNumber() ||
getSecond().getTweak() == Version::maxNumber())
{
if (!s.empty())
s += " ";
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
{
auto nv = getSecond().getNextVersion(getSecond().getRealLevel());
return s + "<" + nv.toString(nv.getRealLevel());
}
auto nv = getSecond().getNextVersion(level);
if (t == VersionRangePairStringRepresentationType::SameRealLevel)
{
level = std::max(getFirst().getRealLevel(), nv.getRealLevel());
s.clear();
if (getFirst() != Version::min(getFirst()))
{
s += ">=";
s += getFirst().toString(level);
if (!s.empty())
s += " ";
}
}
return s + "<" + nv.toString(level);
}
}
if (!s.empty())
s += " ";
if (t == VersionRangePairStringRepresentationType::IndividualRealLevel)
return s + "<=" + getSecond().toString(getSecond().getRealLevel());
else
return s + "<=" + getSecond().toString(level);*/
bool print_left = first.v > Version::min();
bool print_right = second.v < Version::max();
if (print_left && print_right
&& !first.strong_relation && !second.strong_relation
&& first.v == second.v)
{
return "=" + first.toString(t);
}
std::string s;
if (print_left)
{
s += ">";
if (!first.strong_relation)
s += "=";
s += first.toString(t);
}
if (print_left && print_right)
s += " ";
if (print_right)
{
s += "<";
if (!second.strong_relation)
s += "=";
s += second.toString(t);
}
if (s.empty())
return "*";
return s;
}
std::string detail::RangePair::toStringInterval() const
{
std::string s;
if (first.strong_relation)
s += "(";
else
s += "[";
s += first.toString(VersionRangePairStringRepresentationType::SameDefaultLevel);
s += ", ";
s += second.toString(VersionRangePairStringRepresentationType::SameDefaultLevel);
if (second.strong_relation)
s += ")";
else
s += "]";
return s;
}
std::optional<Version> detail::RangePair::toVersion() const
{
if (getFirst() != getSecond())
return {};
return getFirst();
}
size_t detail::RangePair::getHash() const
{
size_t h = 0;
hash_combine(h, getFirst().getHash());
hash_combine(h, getSecond().getHash());
return h;
}
VersionRange::VersionRange()
{
}
/*VersionRange::VersionRange(const Version &v1, const Version &v2)
{
range.emplace_back(v1, false, v2, false);
}*/
VersionRange::VersionRange(const char *v)
{
if (!v)
throw SW_RUNTIME_ERROR("Empty version range");
*this = std::string{ v };
}
VersionRange::VersionRange(const std::string &s)
{
auto in = detail::preprocess_input(s);
if (in.empty())
// * or throw error?
*this = VersionRange{"*"};
else if (auto r = parse(*this, in); r)
throw SW_RUNTIME_ERROR("Invalid version range: " + in + ", error: " + r.value());
}
std::optional<VersionRange> VersionRange::parse(const std::string &s)
{
VersionRange vr;
auto in = detail::preprocess_input(s);
if (in.empty())
vr = VersionRange{"*"};
else if (auto r = parse(vr, in); r)
return {};
return vr;
}
std::optional<std::string> VersionRange::parse(VersionRange &vr, const std::string &s)
{
if (s.size() > 32_KB)
return { "Range string length must be less than 32K" };
RangeParser d;
auto r = d.parse(s);
auto error = d.bb.error_msg;
if (r == 0)
{
if (auto res = d.bb.getResult<VersionRange>(); res)
{
vr = res.value();
return {};
}
else
error = "parser error: empty result";
}
return error;
}
size_t VersionRange::size() const
{
return range.size();
}
bool VersionRange::isEmpty() const
{
return range.empty();
}
bool VersionRange::contains(const Version &v) const
{
return std::any_of(range.begin(), range.end(),
[&v](const auto &r) { return r.contains(v); });
}
bool VersionRange::contains(const VersionRange &r) const
{
return (*this & r) == r;
}
std::optional<Version> VersionRange::toVersion() const
{
if (size() != 1)
return {};
return range.begin()->toVersion();
}
std::string VersionRange::toString() const
{
return toString(VersionRangePairStringRepresentationType::SameDefaultLevel);
}
std::string VersionRange::toString(VersionRangePairStringRepresentationType t) const
{
std::string s;
for (auto &p : range)
s += p.toString(t) + " || ";
if (!s.empty())
s.resize(s.size() - 4);
return s;
}
size_t VersionRange::getHash() const
{
size_t h = 0;
for (auto &n : range)
hash_combine(h, n.getHash());
return h;
}
bool VersionRange::operator==(const VersionRange &rhs) const
{
return range == rhs.range;
}
VersionRange &VersionRange::operator|=(const detail::RangePair &rhs)
{
// we can do pairs |= p
// but we still need to merge overlapped after
// so we choose simple iterative approach instead
bool added = false;
for (auto i = range.begin(); i < range.end(); i++)
{
if (!added)
{
// skip add, p is greater
if (i->getSecond() < rhs.getFirst())
continue;
// insert as is BEFORE current
else if (i->getFirst() > rhs.getSecond())
{
i = range.insert(i, rhs);
break; // no further merges requires
}
else
{
// TRY to merge overlapped
// we can fail on (1,2)|(2,3)
if (auto u = *i | rhs)
*i = *u;
else
// insert as is AFTER current
i = range.insert(++i, rhs);
added = true;
}
}
else
{
// after merging with existing entry we must ensure that
// following intervals do not require merges too
if ((i - 1)->getSecond() < i->getFirst())
break;
else if (auto u = *(i - 1) | *i)
{
*(i - 1) = *u;
i = range.erase(i) - 1;
}
}
}
if (!added)
range.push_back(rhs);
return *this;
}
VersionRange &VersionRange::operator|=(const VersionRange &rhs)
{
for (auto &rp : rhs.range)
operator|=(rp);
return *this;
}
VersionRange &VersionRange::operator&=(const VersionRange &rhs)
{
VersionRange vr;
for (auto &rp1 : range)
{
for (auto &rp2 : rhs.range)
{
if (auto o = rp1 & rp2; o)
vr |= o.value();
}
}
return *this = vr;
}
VersionRange VersionRange::operator|(const VersionRange &rhs) const
{
auto tmp = *this;
tmp |= rhs;
return tmp;
}
VersionRange VersionRange::operator&(const VersionRange &rhs) const
{
auto tmp = *this;
tmp &= rhs;
return tmp;
}
/*VersionRange VersionRange::operator~() const
{
auto tmp = *this;
throw SW_RUNTIME_ERROR("not implemented");
return tmp;
}*/
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "gtest/gtest.h"
#include <nomlib/graphics.hpp>
#include <nomlib/system.hpp>
namespace nom {
/// \note These unit tests target the non-typical usage of the FontCache class --
/// the non-static variant.
class FontCacheTest: public ::testing::Test
{
public:
FontCacheTest( void )
{
// ...
}
~FontCacheTest( void )
{
// ...
}
protected:
Path p;
File fp;
ResourceCache<IFont::shared_ptr> fonts_;
};
/// \fixme This test is failing on WindowsOS (Unknown file error: SEH exception).
TEST_F( FontCacheTest, CoreAPI )
{
p = Path( fp.resource_path( "org.i8degrees.nomlib" ) + p.native() + "fonts" );
#if defined( NOM_PLATFORM_OSX )
Path sys( "/System/Library/Fonts" );
Path lib( "/Library/Fonts" );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "LucidaGrande", sys.prepend("LucidaGrande.ttc"), ResourceFile::Type::TrueTypeFont ) ) );
#elif defined( NOM_PLATFORM_WINDOWS )
Path sys( "C:\\Windows\\Fonts" );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "Arial", sys.prepend("Arial.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "TimesNewRoman", sys.prepend("times.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
#endif
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "LiberationSans-Regular", p.prepend("LiberationSans-Regular.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "LiberationSerif-Regular", p.prepend("LiberationSerif-Regular.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "VIII", p.prepend("VIII.png"), ResourceFile::Type::BitmapFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "VIII_small", p.prepend("VIII_small.png"), ResourceFile::Type::BitmapFont ) ) );
// Should not exist
ASSERT_FALSE( this->fonts_.append_resource( ResourceFile( "IX", p.prepend("IX.png") ) ) );
// Should already exist.
ASSERT_FALSE( this->fonts_.append_resource( ResourceFile( "VIII", p.prepend("VIII.png") ) ) );
ResourceFile res;
ASSERT_TRUE( res == ResourceFile::null );
ASSERT_FALSE( res.exists() );
res = this->fonts_.find_resource( "VIII" );
ASSERT_TRUE( res.exists() );
EXPECT_EQ( "VIII", res.name() );
res = this->fonts_.find_resource( "VIII_small" );
ASSERT_TRUE( res.exists() );
EXPECT_EQ( "VIII_small", res.name() );
// Should not exist
res = this->fonts_.find_resource( "IX" );
ASSERT_FALSE( res.exists() );
EXPECT_EQ( "", res.name() );
EXPECT_EQ( 5, this->fonts_.size() );
this->fonts_.clear();
EXPECT_EQ( 0, this->fonts_.size() );
}
} // namespace nom
int main( int argc, char** argv )
{
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
<commit_msg>FontCacheTest: Change ResourceCache type to Font<commit_after>#include <iostream>
#include <string>
#include "gtest/gtest.h"
#include <nomlib/graphics.hpp>
#include <nomlib/system.hpp>
namespace nom {
/// \note These unit tests target the non-typical usage of the FontCache class --
/// the non-static variant.
class FontCacheTest: public ::testing::Test
{
public:
FontCacheTest( void )
{
// ...
}
~FontCacheTest( void )
{
// ...
}
protected:
Path p;
File fp;
// ResourceCache<IFont::shared_ptr> fonts_;
ResourceCache<Font> fonts_;
};
/// \fixme This test is failing on WindowsOS (Unknown file error: SEH exception).
TEST_F( FontCacheTest, CoreAPI )
{
p = Path( fp.resource_path( "org.i8degrees.nomlib" ) + p.native() + "fonts" );
#if defined( NOM_PLATFORM_OSX )
Path sys( "/System/Library/Fonts" );
Path lib( "/Library/Fonts" );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "LucidaGrande", sys.prepend("LucidaGrande.ttc"), ResourceFile::Type::TrueTypeFont ) ) );
#elif defined( NOM_PLATFORM_WINDOWS )
Path sys( "C:\\Windows\\Fonts" );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "Arial", sys.prepend("Arial.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "TimesNewRoman", sys.prepend("times.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
#endif
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "LiberationSans-Regular", p.prepend("LiberationSans-Regular.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "LiberationSerif-Regular", p.prepend("LiberationSerif-Regular.ttf"), ResourceFile::Type::TrueTypeFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "VIII", p.prepend("VIII.png"), ResourceFile::Type::BitmapFont ) ) );
ASSERT_TRUE( this->fonts_.append_resource( ResourceFile( "VIII_small", p.prepend("VIII_small.png"), ResourceFile::Type::BitmapFont ) ) );
// Should not exist
ASSERT_FALSE( this->fonts_.append_resource( ResourceFile( "IX", p.prepend("IX.png") ) ) );
// Should already exist.
ASSERT_FALSE( this->fonts_.append_resource( ResourceFile( "VIII", p.prepend("VIII.png") ) ) );
ResourceFile res;
ASSERT_TRUE( res == ResourceFile::null );
ASSERT_FALSE( res.exists() );
res = this->fonts_.find_resource( "VIII" );
ASSERT_TRUE( res.exists() );
EXPECT_EQ( "VIII", res.name() );
res = this->fonts_.find_resource( "VIII_small" );
ASSERT_TRUE( res.exists() );
EXPECT_EQ( "VIII_small", res.name() );
// Should not exist
res = this->fonts_.find_resource( "IX" );
ASSERT_FALSE( res.exists() );
EXPECT_EQ( "", res.name() );
EXPECT_EQ( 5, this->fonts_.size() );
this->fonts_.clear();
EXPECT_EQ( 0, this->fonts_.size() );
}
} // namespace nom
int main( int argc, char** argv )
{
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkMultiThreader.h"
#include "itkTimeProbe.h"
void* execute(void *ptr)
{
// Here - get any args from ptr.
//std::cout << std::endl << "Thread fn starting.." << std::endl;
int *data = reinterpret_cast<int *>(ptr);
int m = 100;
std::cout << "Ptr received :" << ptr
<< "Value " << *data << std::endl;
int n = 10;
double sum = 1.0;
for( int j = 0; j < m; j++ )
{
sum = 1.0;
for( int i = 1; i <= n; i++ )
{
sum = sum + i + j;
}
}
//std::cout << std::endl << "Thread fn DONE" << std::endl;
return ITK_NULLPTR;
}
int itkThreadPoolTest(int argc, char* argv[])
{
#if defined(_WIN32) || defined(_WIN64)
#else
int count = 1000000;
if( argc > 1 )
{
const int nt = atoi( argv[1] );
if(nt > 1)
{
count = nt;
}
}
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
if(threader.IsNull())
{
return EXIT_FAILURE;
}
itk::TimeProbe timeProbe;
itk::TimeProbe::TimeStampType startTime = timeProbe.GetInstantValue();
int data = 100;
for(int i=0; i<count;i++)
{
threader->SetSingleMethod(&execute,(void *)&data);
threader->SingleMethodExecute();
}
itk::TimeProbe::TimeStampType elapsed = timeProbe.GetInstantValue() - startTime;
std::cout<<std::endl <<" Thread pool test : Time elapsed : " << elapsed << std::endl;
#endif
return EXIT_SUCCESS;
}
<commit_msg>COMP: Removed unused parameters in itkThreadPoolTest.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkMultiThreader.h"
#include "itkTimeProbe.h"
void* execute(void *ptr)
{
// Here - get any args from ptr.
//std::cout << std::endl << "Thread fn starting.." << std::endl;
int *data = reinterpret_cast<int *>(ptr);
int m = 100;
std::cout << "Ptr received :" << ptr
<< "Value " << *data << std::endl;
int n = 10;
double sum = 1.0;
for( int j = 0; j < m; j++ )
{
sum = 1.0;
for( int i = 1; i <= n; i++ )
{
sum = sum + i + j;
}
}
//std::cout << std::endl << "Thread fn DONE" << std::endl;
return ITK_NULLPTR;
}
#if defined(_WIN32) || defined(_WIN64)
int itkThreadPoolTest(int, char* [])
{
#else
int itkThreadPoolTest(int argc, char* argv[])
{
int count = 1000000;
if( argc > 1 )
{
const int nt = atoi( argv[1] );
if(nt > 1)
{
count = nt;
}
}
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
if(threader.IsNull())
{
return EXIT_FAILURE;
}
itk::TimeProbe timeProbe;
itk::TimeProbe::TimeStampType startTime = timeProbe.GetInstantValue();
int data = 100;
for(int i=0; i<count;i++)
{
threader->SetSingleMethod(&execute,(void *)&data);
threader->SingleMethodExecute();
}
itk::TimeProbe::TimeStampType elapsed = timeProbe.GetInstantValue() - startTime;
std::cout<<std::endl <<" Thread pool test : Time elapsed : " << elapsed << std::endl;
#endif
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 - Mozy, Inc.
#include "namedpipe.h"
#include "mordor/assert.h"
#include "mordor/exception.h"
#include "mordor/log.h"
#include "mordor/runtime_linking.h"
#include "mordor/string.h"
namespace Mordor {
static Logger::ptr g_log = Log::lookup("mordor:streams::namedpipe");
NamedPipeStream::NamedPipeStream(const std::string &name, Flags flags, IOManager *ioManager, Scheduler *scheduler, DWORD pipeModeFlags)
{
init(toUtf16(name), flags, pipeModeFlags,ioManager, scheduler);
}
NamedPipeStream::NamedPipeStream(const std::wstring &name, Flags flags, IOManager *ioManager, Scheduler *scheduler, DWORD pipeModeFlags)
{
init(name, flags, pipeModeFlags, ioManager, scheduler);
}
void NamedPipeStream::init(const std::wstring &name, Flags flags, DWORD pipeModeFlags, IOManager *ioManager, Scheduler *scheduler)
{
if (pipeModeFlags == (DWORD)-1) {
pipeModeFlags = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT;
}
HANDLE hPipe = CreateNamedPipeW(name.c_str(),
(DWORD)flags | (ioManager ? FILE_FLAG_OVERLAPPED : 0),
pipeModeFlags,
PIPE_UNLIMITED_INSTANCES,
0, 0, 0, NULL);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, hPipe == INVALID_HANDLE_VALUE ? Log::ERROR : Log::VERBOSE)
<< this << " CreateNamedPipeW(" << toUtf8(name) << ", " << flags
<< "): " << hPipe << " (" << error << ")";
if (hPipe == INVALID_HANDLE_VALUE)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "CreateNamedPipeW");
HandleStream::init(hPipe, ioManager, scheduler);
m_supportsRead = !!(flags & READ);
m_supportsWrite = !!(flags & WRITE);
}
void
NamedPipeStream::close(CloseType type)
{
if (m_hFile != INVALID_HANDLE_VALUE) {
SchedulerSwitcher switcher(m_scheduler);
BOOL ret = DisconnectNamedPipe(m_hFile);
error_t error = lastError();
MORDOR_LOG_VERBOSE(g_log) << this << " DisconnectNamedPipe(" << m_hFile
<< "): " << ret << " (" << error << ")";
if (!ret)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "DisconnectNamedPipe");
}
HandleStream::close(type);
}
void
NamedPipeStream::accept()
{
if (m_cancelRead)
MORDOR_THROW_EXCEPTION(OperationAbortedException());
SchedulerSwitcher switcher(m_ioManager ? NULL : m_scheduler);
OVERLAPPED *overlapped = NULL;
if (m_ioManager) {
MORDOR_ASSERT(Scheduler::getThis());
m_ioManager->registerEvent(&m_readEvent);
overlapped = &m_readEvent.overlapped;
}
BOOL ret = ConnectNamedPipe(m_hFile, overlapped);
Log::Level level = Log::INFO;
if (!ret) {
if (lastError() == ERROR_PIPE_CONNECTED) {
} else if (m_ioManager) {
if (lastError() == ERROR_IO_PENDING)
level = Log::TRACE;
else
level = Log::ERROR;
} else {
level = Log::ERROR;
}
}
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, level) << this
<< " ConnectNamedPipe(" << m_hFile << "): " << ret << " ("
<< error << ")";
if (m_ioManager) {
if (!ret && error == ERROR_PIPE_CONNECTED) {
m_ioManager->unregisterEvent(&m_readEvent);
return;
}
if (!ret && error != ERROR_IO_PENDING) {
m_ioManager->unregisterEvent(&m_readEvent);
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("ConnectNamedPipe");
}
if (ret && m_skipCompletionPortOnSuccess)
m_ioManager->unregisterEvent(&m_readEvent);
else
Scheduler::yieldTo();
error_t error = pRtlNtStatusToDosError((NTSTATUS)m_readEvent.overlapped.Internal);
MORDOR_LOG_LEVEL(g_log, error ? Log::ERROR : Log::INFO) << this
<< " ConnectNamedPipe(" << m_hFile << "): (" << error
<< ")";
if (error)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "ConnectNamedPipe");
} else {
if (!ret && error == ERROR_PIPE_CONNECTED)
return;
if (!ret)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "ConnectNamedPipe");
}
}
void
NamedPipeStream::cancelAccept()
{
m_cancelRead = true;
if (m_ioManager) {
m_ioManager->cancelEvent(m_hFile, &m_readEvent);
} else {
MORDOR_ASSERT(supportsCancel());
if (!pCancelIoEx(m_hFile, NULL))
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("CancelIoEx");
}
}
void
NamedPipeStream::disconnectClient()
{
// Prepare for reuse of the named pipe handle
FlushFileBuffers(m_hFile);
DisconnectNamedPipe(m_hFile);
}
}
<commit_msg>Dial down logging from NamedPipe<commit_after>// Copyright (c) 2009 - Mozy, Inc.
#include "namedpipe.h"
#include "mordor/assert.h"
#include "mordor/exception.h"
#include "mordor/log.h"
#include "mordor/runtime_linking.h"
#include "mordor/string.h"
namespace Mordor {
static Logger::ptr g_log = Log::lookup("mordor:streams::namedpipe");
NamedPipeStream::NamedPipeStream(const std::string &name, Flags flags, IOManager *ioManager, Scheduler *scheduler, DWORD pipeModeFlags)
{
init(toUtf16(name), flags, pipeModeFlags,ioManager, scheduler);
}
NamedPipeStream::NamedPipeStream(const std::wstring &name, Flags flags, IOManager *ioManager, Scheduler *scheduler, DWORD pipeModeFlags)
{
init(name, flags, pipeModeFlags, ioManager, scheduler);
}
void NamedPipeStream::init(const std::wstring &name, Flags flags, DWORD pipeModeFlags, IOManager *ioManager, Scheduler *scheduler)
{
if (pipeModeFlags == (DWORD)-1) {
pipeModeFlags = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT;
}
HANDLE hPipe = CreateNamedPipeW(name.c_str(),
(DWORD)flags | (ioManager ? FILE_FLAG_OVERLAPPED : 0),
pipeModeFlags,
PIPE_UNLIMITED_INSTANCES,
0, 0, 0, NULL);
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, hPipe == INVALID_HANDLE_VALUE ? Log::ERROR : Log::VERBOSE)
<< this << " CreateNamedPipeW(" << toUtf8(name) << ", " << flags
<< "): " << hPipe << " (" << error << ")";
if (hPipe == INVALID_HANDLE_VALUE)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "CreateNamedPipeW");
HandleStream::init(hPipe, ioManager, scheduler);
m_supportsRead = !!(flags & READ);
m_supportsWrite = !!(flags & WRITE);
}
void
NamedPipeStream::close(CloseType type)
{
if (m_hFile != INVALID_HANDLE_VALUE) {
SchedulerSwitcher switcher(m_scheduler);
BOOL ret = DisconnectNamedPipe(m_hFile);
error_t error = lastError();
MORDOR_LOG_VERBOSE(g_log) << this << " DisconnectNamedPipe(" << m_hFile
<< "): " << ret << " (" << error << ")";
if (!ret)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "DisconnectNamedPipe");
}
HandleStream::close(type);
}
void
NamedPipeStream::accept()
{
if (m_cancelRead)
MORDOR_THROW_EXCEPTION(OperationAbortedException());
SchedulerSwitcher switcher(m_ioManager ? NULL : m_scheduler);
OVERLAPPED *overlapped = NULL;
if (m_ioManager) {
MORDOR_ASSERT(Scheduler::getThis());
m_ioManager->registerEvent(&m_readEvent);
overlapped = &m_readEvent.overlapped;
}
BOOL ret = ConnectNamedPipe(m_hFile, overlapped);
Log::Level level = Log::DEBUG;
if (!ret) {
if (lastError() == ERROR_PIPE_CONNECTED) {
} else if (m_ioManager) {
if (lastError() == ERROR_IO_PENDING)
level = Log::TRACE;
else
level = Log::ERROR;
} else {
level = Log::ERROR;
}
}
error_t error = lastError();
MORDOR_LOG_LEVEL(g_log, level) << this
<< " ConnectNamedPipe(" << m_hFile << "): " << ret << " ("
<< error << ")";
if (m_ioManager) {
if (!ret && error == ERROR_PIPE_CONNECTED) {
m_ioManager->unregisterEvent(&m_readEvent);
return;
}
if (!ret && error != ERROR_IO_PENDING) {
m_ioManager->unregisterEvent(&m_readEvent);
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("ConnectNamedPipe");
}
if (ret && m_skipCompletionPortOnSuccess)
m_ioManager->unregisterEvent(&m_readEvent);
else
Scheduler::yieldTo();
error_t error = pRtlNtStatusToDosError((NTSTATUS)m_readEvent.overlapped.Internal);
MORDOR_LOG_LEVEL(g_log, error ? Log::ERROR : Log::DEBUG) << this
<< " ConnectNamedPipe(" << m_hFile << "): (" << error
<< ")";
if (error)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "ConnectNamedPipe");
} else {
if (!ret && error == ERROR_PIPE_CONNECTED)
return;
if (!ret)
MORDOR_THROW_EXCEPTION_FROM_ERROR_API(error, "ConnectNamedPipe");
}
}
void
NamedPipeStream::cancelAccept()
{
m_cancelRead = true;
if (m_ioManager) {
m_ioManager->cancelEvent(m_hFile, &m_readEvent);
} else {
MORDOR_ASSERT(supportsCancel());
if (!pCancelIoEx(m_hFile, NULL))
MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("CancelIoEx");
}
}
void
NamedPipeStream::disconnectClient()
{
// Prepare for reuse of the named pipe handle
FlushFileBuffers(m_hFile);
DisconnectNamedPipe(m_hFile);
}
}
<|endoftext|> |
<commit_before>/*
* qmqtt_network.cpp - qmqtt network
*
* Copyright (c) 2013 Ery Lee <ery.lee at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of mqttc nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QDataStream>
#include "qmqtt_network_p.h"
#include "qmqtt_socket_p.h"
#include "qmqtt_ssl_socket_p.h"
#include "qmqtt_timer_p.h"
const QString DEFAULT_HOST_NAME = QStringLiteral("localhost");
const QHostAddress DEFAULT_HOST = QHostAddress::LocalHost;
const quint16 DEFAULT_PORT = 1883;
const quint16 DEFAULT_SSL_PORT = 8883;
const bool DEFAULT_AUTORECONNECT = false;
const int DEFAULT_AUTORECONNECT_INTERVAL_MS = 5000;
QMQTT::Network::Network(QObject* parent)
: NetworkInterface(parent)
, _port(DEFAULT_PORT)
, _host(DEFAULT_HOST)
, _autoReconnect(DEFAULT_AUTORECONNECT)
, _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)
, _socket(new QMQTT::Socket)
, _autoReconnectTimer(new QMQTT::Timer)
, _readState(Header)
{
initialize();
}
#ifndef QT_NO_SSL
QMQTT::Network::Network(const QSslConfiguration &config, bool ignoreSelfSigned, QObject *parent)
: NetworkInterface(parent)
, _port(DEFAULT_SSL_PORT)
, _hostName(DEFAULT_HOST_NAME)
, _autoReconnect(DEFAULT_AUTORECONNECT)
, _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)
, _socket(new QMQTT::SslSocket(config, ignoreSelfSigned))
, _autoReconnectTimer(new QMQTT::Timer)
, _readState(Header)
{
initialize();
}
#endif // QT_NO_SSL
QMQTT::Network::Network(SocketInterface* socketInterface, TimerInterface* timerInterface,
QObject* parent)
: NetworkInterface(parent)
, _port(DEFAULT_PORT)
, _host(DEFAULT_HOST)
, _autoReconnect(DEFAULT_AUTORECONNECT)
, _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)
, _socket(socketInterface)
, _autoReconnectTimer(timerInterface)
, _readState(Header)
{
initialize();
}
void QMQTT::Network::initialize()
{
_socket->setParent(this);
_autoReconnectTimer->setParent(this);
_autoReconnectTimer->setSingleShot(true);
_autoReconnectTimer->setInterval(_autoReconnectInterval);
QObject::connect(_socket, &SocketInterface::connected, this, &Network::connected);
QObject::connect(_socket, &SocketInterface::disconnected, this, &Network::onDisconnected);
QObject::connect(_socket->ioDevice(), &QIODevice::readyRead, this, &Network::onSocketReadReady);
QObject::connect(
_autoReconnectTimer, &TimerInterface::timeout,
this, static_cast<void (Network::*)()>(&Network::connectToHost));
QObject::connect(_socket,
static_cast<void (SocketInterface::*)(QAbstractSocket::SocketError)>(&SocketInterface::error),
this, &Network::onSocketError);
}
QMQTT::Network::~Network()
{
}
bool QMQTT::Network::isConnectedToHost() const
{
return _socket->state() == QAbstractSocket::ConnectedState;
}
void QMQTT::Network::connectToHost(const QHostAddress& host, const quint16 port)
{
_host = host;
_port = port;
connectToHost();
}
void QMQTT::Network::connectToHost(const QString& hostName, const quint16 port)
{
_hostName = hostName;
_port = port;
connectToHost();
}
void QMQTT::Network::connectToHost()
{
_readState = Header;
if (_hostName.isEmpty())
{
_socket->connectToHost(_host, _port);
}
else
{
_socket->connectToHost(_hostName, _port);
}
}
void QMQTT::Network::onSocketError(QAbstractSocket::SocketError socketError)
{
emit error(socketError);
if(_autoReconnect)
{
_autoReconnectTimer->start();
}
}
void QMQTT::Network::sendFrame(Frame& frame)
{
if(_socket->state() == QAbstractSocket::ConnectedState)
{
QDataStream out(_socket->ioDevice());
frame.write(out);
}
}
void QMQTT::Network::disconnectFromHost()
{
_socket->disconnectFromHost();
}
QAbstractSocket::SocketState QMQTT::Network::state() const
{
return _socket->state();
}
bool QMQTT::Network::autoReconnect() const
{
return _autoReconnect;
}
void QMQTT::Network::setAutoReconnect(const bool autoReconnect)
{
_autoReconnect = autoReconnect;
}
int QMQTT::Network::autoReconnectInterval() const
{
return _autoReconnectInterval;
}
void QMQTT::Network::setAutoReconnectInterval(const int autoReconnectInterval)
{
_autoReconnectInterval = autoReconnectInterval;
_autoReconnectTimer->setInterval(_autoReconnectInterval);
}
void QMQTT::Network::onSocketReadReady()
{
QIODevice *ioDevice = _socket->ioDevice();
// Only read the available (cached) bytes, so the read will never block.
QByteArray data = ioDevice->read(ioDevice->bytesAvailable());
foreach(char byte, data) {
switch (_readState) {
case Header:
_header = static_cast<quint8>(byte);
_readState = Length;
_length = 0;
_shift = 0;
break;
case Length:
_length |= (byte & 0x7F) << _shift;
_shift += 7;
if ((byte & 0x80) != 0)
break;
if (_length == 0) {
_readState = Header;
Frame frame(_header, _data);
emit received(frame);
break;
}
_readState = PayLoad;
_data.clear();
break;
case PayLoad:
_data.append(byte);
--_length;
if (_length > 0)
break;
_readState = Header;
Frame frame(_header, _data);
emit received(frame);
break;
}
}
}
void QMQTT::Network::onDisconnected()
{
emit disconnected();
if(_autoReconnect)
{
_autoReconnectTimer->start();
}
}
<commit_msg>Fix the received Frame parser<commit_after>/*
* qmqtt_network.cpp - qmqtt network
*
* Copyright (c) 2013 Ery Lee <ery.lee at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of mqttc nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QDataStream>
#include "qmqtt_network_p.h"
#include "qmqtt_socket_p.h"
#include "qmqtt_ssl_socket_p.h"
#include "qmqtt_timer_p.h"
const QString DEFAULT_HOST_NAME = QStringLiteral("localhost");
const QHostAddress DEFAULT_HOST = QHostAddress::LocalHost;
const quint16 DEFAULT_PORT = 1883;
const quint16 DEFAULT_SSL_PORT = 8883;
const bool DEFAULT_AUTORECONNECT = false;
const int DEFAULT_AUTORECONNECT_INTERVAL_MS = 5000;
QMQTT::Network::Network(QObject* parent)
: NetworkInterface(parent)
, _port(DEFAULT_PORT)
, _host(DEFAULT_HOST)
, _autoReconnect(DEFAULT_AUTORECONNECT)
, _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)
, _socket(new QMQTT::Socket)
, _autoReconnectTimer(new QMQTT::Timer)
, _readState(Header)
{
initialize();
}
#ifndef QT_NO_SSL
QMQTT::Network::Network(const QSslConfiguration &config, bool ignoreSelfSigned, QObject *parent)
: NetworkInterface(parent)
, _port(DEFAULT_SSL_PORT)
, _hostName(DEFAULT_HOST_NAME)
, _autoReconnect(DEFAULT_AUTORECONNECT)
, _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)
, _socket(new QMQTT::SslSocket(config, ignoreSelfSigned))
, _autoReconnectTimer(new QMQTT::Timer)
, _readState(Header)
{
initialize();
}
#endif // QT_NO_SSL
QMQTT::Network::Network(SocketInterface* socketInterface, TimerInterface* timerInterface,
QObject* parent)
: NetworkInterface(parent)
, _port(DEFAULT_PORT)
, _host(DEFAULT_HOST)
, _autoReconnect(DEFAULT_AUTORECONNECT)
, _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)
, _socket(socketInterface)
, _autoReconnectTimer(timerInterface)
, _readState(Header)
{
initialize();
}
void QMQTT::Network::initialize()
{
_socket->setParent(this);
_autoReconnectTimer->setParent(this);
_autoReconnectTimer->setSingleShot(true);
_autoReconnectTimer->setInterval(_autoReconnectInterval);
QObject::connect(_socket, &SocketInterface::connected, this, &Network::connected);
QObject::connect(_socket, &SocketInterface::disconnected, this, &Network::onDisconnected);
QObject::connect(_socket->ioDevice(), &QIODevice::readyRead, this, &Network::onSocketReadReady);
QObject::connect(
_autoReconnectTimer, &TimerInterface::timeout,
this, static_cast<void (Network::*)()>(&Network::connectToHost));
QObject::connect(_socket,
static_cast<void (SocketInterface::*)(QAbstractSocket::SocketError)>(&SocketInterface::error),
this, &Network::onSocketError);
}
QMQTT::Network::~Network()
{
}
bool QMQTT::Network::isConnectedToHost() const
{
return _socket->state() == QAbstractSocket::ConnectedState;
}
void QMQTT::Network::connectToHost(const QHostAddress& host, const quint16 port)
{
_host = host;
_port = port;
connectToHost();
}
void QMQTT::Network::connectToHost(const QString& hostName, const quint16 port)
{
_hostName = hostName;
_port = port;
connectToHost();
}
void QMQTT::Network::connectToHost()
{
_readState = Header;
if (_hostName.isEmpty())
{
_socket->connectToHost(_host, _port);
}
else
{
_socket->connectToHost(_hostName, _port);
}
}
void QMQTT::Network::onSocketError(QAbstractSocket::SocketError socketError)
{
emit error(socketError);
if(_autoReconnect)
{
_autoReconnectTimer->start();
}
}
void QMQTT::Network::sendFrame(Frame& frame)
{
if(_socket->state() == QAbstractSocket::ConnectedState)
{
QDataStream out(_socket->ioDevice());
frame.write(out);
}
}
void QMQTT::Network::disconnectFromHost()
{
_socket->disconnectFromHost();
}
QAbstractSocket::SocketState QMQTT::Network::state() const
{
return _socket->state();
}
bool QMQTT::Network::autoReconnect() const
{
return _autoReconnect;
}
void QMQTT::Network::setAutoReconnect(const bool autoReconnect)
{
_autoReconnect = autoReconnect;
}
int QMQTT::Network::autoReconnectInterval() const
{
return _autoReconnectInterval;
}
void QMQTT::Network::setAutoReconnectInterval(const int autoReconnectInterval)
{
_autoReconnectInterval = autoReconnectInterval;
_autoReconnectTimer->setInterval(_autoReconnectInterval);
}
void QMQTT::Network::onSocketReadReady()
{
QIODevice *ioDevice = _socket->ioDevice();
// Only read the available (cached) bytes, so the read will never block.
QByteArray data = ioDevice->read(ioDevice->bytesAvailable());
foreach(char byte, data) {
switch (_readState) {
case Header:
_header = static_cast<quint8>(byte);
_readState = Length;
_length = 0;
_shift = 0;
_data.clear();
break;
case Length:
_length |= (byte & 0x7F) << _shift;
_shift += 7;
if ((byte & 0x80) != 0)
break;
if (_length == 0) {
_readState = Header;
Frame frame(_header, _data);
emit received(frame);
break;
}
_readState = PayLoad;
break;
case PayLoad:
_data.append(byte);
--_length;
if (_length > 0)
break;
_readState = Header;
Frame frame(_header, _data);
emit received(frame);
break;
}
}
}
void QMQTT::Network::onDisconnected()
{
emit disconnected();
if(_autoReconnect)
{
_autoReconnectTimer->start();
}
}
<|endoftext|> |
<commit_before>#include "glyphcellrenderer.h"
#include "wxcontext.h"
#include <wx/dcclient.h>
#include <wx/graphics.h>
#include <wx/settings.h>
#include <memory>
GlyphCellRenderer::GlyphCellRenderer(const std::map<wxString, SvgGlyph> &glyphs, int fontSize): glyphs(glyphs)
{
labelFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
glyphColor = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
hlColor = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE);
labelColor = glyphColor.ChangeLightness(150);
SetFontSize(fontSize);
}
wxGridCellRenderer *GlyphCellRenderer::Clone() const
{
return nullptr;
}
void GlyphCellRenderer::SetHighlightCell(const wxGridCellCoords &coords)
{
hlCellCoords = coords;
}
const wxGridCellCoords &GlyphCellRenderer::GetHighlightCell() const
{
return hlCellCoords;
}
void GlyphCellRenderer::SetFontSize(int size)
{
if (fontSize != size)
{
fontSize = size;
glyphCache.clear();
padding = std::max(4, size / 4);
}
}
int GlyphCellRenderer::GetFontSize() const
{
return fontSize;
}
void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected)
{
wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, false);
wxString value = grid.GetTable()->GetValue(row, col);
wxString label;
auto it = glyphs.find(value);
if (it == glyphs.end()) return;
const SvgGlyph &glyph = it->second;
if (!glyph.IsOk())
return;
label.Printf("%04x", glyph.unicode[0]);
std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc)));
wxRect newRect = rect;
// replace with gc->GetRenderer()->GetName() == L"cairo" after wx 3.1
bool isCairo = false;
#if wxUSE_CAIRO
isCairo = true;
#endif
// Oh, crap
if (isCairo)
{
newRect.x += dc.GetDeviceOrigin().x;
newRect.y += dc.GetDeviceOrigin().y;
}
std::map<wxString, wxBitmap>::iterator findIt = glyphCache.find(glyph.unicode);
if (findIt == glyphCache.end())
{
bool result;
std::tie(findIt, result) = glyphCache.emplace(glyph.unicode, GetBitmapForGlyph(glyph, fontSize, glyphColor));
if (!result) return;
}
if (hlCellCoords.GetCol() == col && hlCellCoords.GetRow() == row)
{
gc->SetPen(wxPen(hlColor, 1));
gc->DrawRoundedRectangle(newRect.x + 1, newRect.y + 1, newRect.width - 2, newRect.height - 2, 5);
}
newRect.height -= labelFont.GetPixelSize().GetHeight() + 2 * padding;
const wxBitmap &glyphBitmap = findIt->second;
gc->DrawBitmap(glyphBitmap,
newRect.x + (newRect.width - glyphBitmap.GetWidth()) / 2,
newRect.y + (newRect.height - glyphBitmap.GetHeight()) / 2,
glyphBitmap.GetWidth(), glyphBitmap.GetHeight());
double width, height, descent, externalLeading;
gc->SetFont(labelFont, labelColor);
gc->GetTextExtent(label, &width, &height, &descent, &externalLeading);
gc->DrawText(label, newRect.x + (newRect.width - width) / 2, newRect.y + newRect.height + padding);
}
wxSize GlyphCellRenderer::GetBestSize(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col)
{
return wxSize(fontSize + padding, fontSize + labelFont.GetPixelSize().GetHeight() + 3 * padding);
}
<commit_msg>draw only good bitmaps in GlyphCellRenderer<commit_after>#include "glyphcellrenderer.h"
#include "wxcontext.h"
#include <wx/dcclient.h>
#include <wx/graphics.h>
#include <wx/settings.h>
#include <memory>
GlyphCellRenderer::GlyphCellRenderer(const std::map<wxString, SvgGlyph> &glyphs, int fontSize): glyphs(glyphs)
{
labelFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
glyphColor = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
hlColor = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE);
labelColor = glyphColor.ChangeLightness(150);
SetFontSize(fontSize);
}
wxGridCellRenderer *GlyphCellRenderer::Clone() const
{
return nullptr;
}
void GlyphCellRenderer::SetHighlightCell(const wxGridCellCoords &coords)
{
hlCellCoords = coords;
}
const wxGridCellCoords &GlyphCellRenderer::GetHighlightCell() const
{
return hlCellCoords;
}
void GlyphCellRenderer::SetFontSize(int size)
{
if (fontSize != size)
{
fontSize = size;
glyphCache.clear();
padding = std::max(4, size / 4);
}
}
int GlyphCellRenderer::GetFontSize() const
{
return fontSize;
}
void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected)
{
wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, false);
wxString value = grid.GetTable()->GetValue(row, col);
wxString label;
auto it = glyphs.find(value);
if (it == glyphs.end()) return;
const SvgGlyph &glyph = it->second;
if (!glyph.IsOk())
return;
label.Printf("%04x", glyph.unicode[0]);
std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc)));
wxRect newRect = rect;
// replace with gc->GetRenderer()->GetName() == L"cairo" after wx 3.1
bool isCairo = false;
#if wxUSE_CAIRO
isCairo = true;
#endif
// Oh, crap
if (isCairo)
{
newRect.x += dc.GetDeviceOrigin().x;
newRect.y += dc.GetDeviceOrigin().y;
}
std::map<wxString, wxBitmap>::iterator findIt = glyphCache.find(glyph.unicode);
if (findIt == glyphCache.end())
{
bool result;
std::tie(findIt, result) = glyphCache.emplace(glyph.unicode, GetBitmapForGlyph(glyph, fontSize, glyphColor));
if (!result) return;
}
if (hlCellCoords.GetCol() == col && hlCellCoords.GetRow() == row)
{
gc->SetPen(wxPen(hlColor, 1));
gc->DrawRoundedRectangle(newRect.x + 1, newRect.y + 1, newRect.width - 2, newRect.height - 2, 5);
}
newRect.height -= labelFont.GetPixelSize().GetHeight() + 2 * padding;
const wxBitmap &glyphBitmap = findIt->second;
if (glyphBitmap.IsOk())
{
gc->DrawBitmap(glyphBitmap,
newRect.x + (newRect.width - glyphBitmap.GetWidth()) / 2,
newRect.y + (newRect.height - glyphBitmap.GetHeight()) / 2,
glyphBitmap.GetWidth(), glyphBitmap.GetHeight());
}
double width, height, descent, externalLeading;
gc->SetFont(labelFont, labelColor);
gc->GetTextExtent(label, &width, &height, &descent, &externalLeading);
gc->DrawText(label, newRect.x + (newRect.width - width) / 2, newRect.y + newRect.height + padding);
}
wxSize GlyphCellRenderer::GetBestSize(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col)
{
return wxSize(fontSize + padding, fontSize + labelFont.GetPixelSize().GetHeight() + 3 * padding);
}
<|endoftext|> |
<commit_before>//===--- MinGWToolChain.cpp - MinGWToolChain Implementation
//-----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ToolChains.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Options.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
using namespace clang::diag;
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang;
using namespace llvm::opt;
MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
: ToolChain(D, Triple, Args) {
getProgramPaths().push_back(getDriver().getInstalledDir());
if (getDriver().SysRoot.size())
Base = getDriver().SysRoot;
else if (llvm::ErrorOr<std::string> GPPName =
llvm::sys::findProgramByName("gcc"))
Base = llvm::sys::path::parent_path(
llvm::sys::path::parent_path(GPPName.get()));
else
Base = llvm::sys::path::parent_path(getDriver().getInstalledDir());
Base += llvm::sys::path::get_separator();
llvm::SmallString<1024> LibDir(Base);
llvm::sys::path::append(LibDir, "lib", "gcc");
LibDir += llvm::sys::path::get_separator();
// First look for mingw-w64.
Arch = getTriple().getArchName();
Arch += "-w64-mingw32";
std::error_code EC;
llvm::sys::fs::directory_iterator MingW64Entry(LibDir + Arch, EC);
if (!EC) {
GccLibDir = MingW64Entry->path();
Ver = llvm::sys::path::filename(GccLibDir);
} else {
// If mingw-w64 not found, try looking for mingw.org.
Arch = "mingw32";
llvm::sys::fs::directory_iterator MingwOrgEntry(LibDir + Arch, EC);
if (!EC)
GccLibDir = MingwOrgEntry->path();
}
Arch += llvm::sys::path::get_separator();
// GccLibDir must precede Base/lib so that the
// correct crtbegin.o ,cetend.o would be found.
getFilePaths().push_back(GccLibDir);
getFilePaths().push_back(Base + "lib");
getFilePaths().push_back(Base + Arch + "lib");
}
bool MinGW::IsIntegratedAssemblerDefault() const { return true; }
Tool *MinGW::getTool(Action::ActionClass AC) const {
switch (AC) {
case Action::PreprocessJobClass:
if (!Preprocessor)
Preprocessor.reset(new tools::gcc::Preprocessor(*this));
return Preprocessor.get();
case Action::CompileJobClass:
if (!Compiler)
Compiler.reset(new tools::gcc::Compiler(*this));
return Compiler.get();
default:
return ToolChain::getTool(AC);
}
}
Tool *MinGW::buildAssembler() const {
return new tools::MinGW::Assembler(*this);
}
Tool *MinGW::buildLinker() const { return new tools::MinGW::Linker(*this); }
bool MinGW::IsUnwindTablesDefault() const {
return getArch() == llvm::Triple::x86_64;
}
bool MinGW::isPICDefault() const { return getArch() == llvm::Triple::x86_64; }
bool MinGW::isPIEDefault() const { return false; }
bool MinGW::isPICDefaultForced() const {
return getArch() == llvm::Triple::x86_64;
}
bool MinGW::UseSEHExceptions() const {
return getArch() == llvm::Triple::x86_64;
}
void MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
if (DriverArgs.hasArg(options::OPT_nostdinc))
return;
if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
SmallString<1024> P(getDriver().ResourceDir);
llvm::sys::path::append(P, "include");
addSystemInclude(DriverArgs, CC1Args, P.str());
}
if (DriverArgs.hasArg(options::OPT_nostdlibinc))
return;
llvm::SmallString<1024> IncludeDir(GccLibDir);
llvm::sys::path::append(IncludeDir, "include");
addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str());
IncludeDir += "-fixed";
addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str());
addSystemInclude(DriverArgs, CC1Args, Base + Arch + "include");
addSystemInclude(DriverArgs, CC1Args, Base + "include");
}
void MinGW::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
DriverArgs.hasArg(options::OPT_nostdincxx))
return;
// C++ includes may be found in several locations depending on distribution.
// mingw-w64 mingw-builds: $sysroot/i686-w64-mingw32/include/c++.
// mingw-w64 msys2: $sysroot/include/c++/4.9.2
// mingw.org: GccLibDir/include/c++
llvm::SmallVector<llvm::SmallString<1024>, 3> CppIncludeBases;
CppIncludeBases.emplace_back(Base);
llvm::sys::path::append(CppIncludeBases[0], Arch, "include", "c++");
CppIncludeBases.emplace_back(Base);
llvm::sys::path::append(CppIncludeBases[1], "include", "c++", Ver);
CppIncludeBases.emplace_back(GccLibDir);
llvm::sys::path::append(CppIncludeBases[2], "include", "c++");
for (auto &CppIncludeBase : CppIncludeBases) {
CppIncludeBase += llvm::sys::path::get_separator();
addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + Arch);
addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
}
}
<commit_msg>Fix first line comment format, NFC.<commit_after>//===--- MinGWToolChain.cpp - MinGWToolChain Implementation ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ToolChains.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Options.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
using namespace clang::diag;
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang;
using namespace llvm::opt;
MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
: ToolChain(D, Triple, Args) {
getProgramPaths().push_back(getDriver().getInstalledDir());
if (getDriver().SysRoot.size())
Base = getDriver().SysRoot;
else if (llvm::ErrorOr<std::string> GPPName =
llvm::sys::findProgramByName("gcc"))
Base = llvm::sys::path::parent_path(
llvm::sys::path::parent_path(GPPName.get()));
else
Base = llvm::sys::path::parent_path(getDriver().getInstalledDir());
Base += llvm::sys::path::get_separator();
llvm::SmallString<1024> LibDir(Base);
llvm::sys::path::append(LibDir, "lib", "gcc");
LibDir += llvm::sys::path::get_separator();
// First look for mingw-w64.
Arch = getTriple().getArchName();
Arch += "-w64-mingw32";
std::error_code EC;
llvm::sys::fs::directory_iterator MingW64Entry(LibDir + Arch, EC);
if (!EC) {
GccLibDir = MingW64Entry->path();
Ver = llvm::sys::path::filename(GccLibDir);
} else {
// If mingw-w64 not found, try looking for mingw.org.
Arch = "mingw32";
llvm::sys::fs::directory_iterator MingwOrgEntry(LibDir + Arch, EC);
if (!EC)
GccLibDir = MingwOrgEntry->path();
}
Arch += llvm::sys::path::get_separator();
// GccLibDir must precede Base/lib so that the
// correct crtbegin.o ,cetend.o would be found.
getFilePaths().push_back(GccLibDir);
getFilePaths().push_back(Base + "lib");
getFilePaths().push_back(Base + Arch + "lib");
}
bool MinGW::IsIntegratedAssemblerDefault() const { return true; }
Tool *MinGW::getTool(Action::ActionClass AC) const {
switch (AC) {
case Action::PreprocessJobClass:
if (!Preprocessor)
Preprocessor.reset(new tools::gcc::Preprocessor(*this));
return Preprocessor.get();
case Action::CompileJobClass:
if (!Compiler)
Compiler.reset(new tools::gcc::Compiler(*this));
return Compiler.get();
default:
return ToolChain::getTool(AC);
}
}
Tool *MinGW::buildAssembler() const {
return new tools::MinGW::Assembler(*this);
}
Tool *MinGW::buildLinker() const { return new tools::MinGW::Linker(*this); }
bool MinGW::IsUnwindTablesDefault() const {
return getArch() == llvm::Triple::x86_64;
}
bool MinGW::isPICDefault() const { return getArch() == llvm::Triple::x86_64; }
bool MinGW::isPIEDefault() const { return false; }
bool MinGW::isPICDefaultForced() const {
return getArch() == llvm::Triple::x86_64;
}
bool MinGW::UseSEHExceptions() const {
return getArch() == llvm::Triple::x86_64;
}
void MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
if (DriverArgs.hasArg(options::OPT_nostdinc))
return;
if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
SmallString<1024> P(getDriver().ResourceDir);
llvm::sys::path::append(P, "include");
addSystemInclude(DriverArgs, CC1Args, P.str());
}
if (DriverArgs.hasArg(options::OPT_nostdlibinc))
return;
llvm::SmallString<1024> IncludeDir(GccLibDir);
llvm::sys::path::append(IncludeDir, "include");
addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str());
IncludeDir += "-fixed";
addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str());
addSystemInclude(DriverArgs, CC1Args, Base + Arch + "include");
addSystemInclude(DriverArgs, CC1Args, Base + "include");
}
void MinGW::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
DriverArgs.hasArg(options::OPT_nostdincxx))
return;
// C++ includes may be found in several locations depending on distribution.
// mingw-w64 mingw-builds: $sysroot/i686-w64-mingw32/include/c++.
// mingw-w64 msys2: $sysroot/include/c++/4.9.2
// mingw.org: GccLibDir/include/c++
llvm::SmallVector<llvm::SmallString<1024>, 3> CppIncludeBases;
CppIncludeBases.emplace_back(Base);
llvm::sys::path::append(CppIncludeBases[0], Arch, "include", "c++");
CppIncludeBases.emplace_back(Base);
llvm::sys::path::append(CppIncludeBases[1], "include", "c++", Ver);
CppIncludeBases.emplace_back(GccLibDir);
llvm::sys::path::append(CppIncludeBases[2], "include", "c++");
for (auto &CppIncludeBase : CppIncludeBases) {
CppIncludeBase += llvm::sys::path::get_separator();
addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + Arch);
addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <Halide.h>
// Test the simplifier in Halide by testing for equivalence of randomly generated expressions.
using namespace std;
using namespace Halide;
using namespace Halide::Internal;
const int fuzz_var_count = 5;
Type fuzz_types[] = { UInt(1), UInt(8), UInt(16), UInt(32), Int(8), Int(16), Int(32) };
const int fuzz_type_count = sizeof(fuzz_types)/sizeof(fuzz_types[0]);
std::string fuzz_var(int i) {
return std::string(1, 'a' + i);
}
Expr random_var() {
return Variable::make(Int(0), fuzz_var(rand()%fuzz_var_count));
}
Type random_type(int width) {
Type T = fuzz_types[rand()%fuzz_type_count];
if (width > 1) {
T = T.vector_of(width);
}
return T;
}
Expr random_leaf(Type T, bool imm_only = false) {
if (T.is_scalar()) {
int var = rand()%fuzz_var_count + 1;
if (!imm_only && var < fuzz_var_count) {
return cast(T, random_var());
} else {
if (T == Int(32)) {
// For Int(32), we don't care about correctness during
// overflow, so just use numbers that are unlikely to
// overflow.
return cast(T, rand()%256 - 128);
} else {
return cast(T, rand() - RAND_MAX/2);
}
}
} else {
if (rand() % 2 == 0) {
return Ramp::make(random_leaf(T.element_of()), random_leaf(T.element_of()), T.width);
} else {
return Broadcast::make(random_leaf(T.element_of()), T.width);
}
}
}
Expr random_expr(Type T, int depth);
Expr random_condition(Type T, int depth) {
typedef Expr (*make_bin_op_fn)(Expr, Expr);
static make_bin_op_fn make_bin_op[] = {
EQ::make,
NE::make,
LT::make,
LE::make,
GT::make,
GE::make,
};
const int op_count = sizeof(make_bin_op)/sizeof(make_bin_op[0]);
Expr a = random_expr(T, depth);
Expr b = random_expr(T, depth);
int op = rand()%op_count;
return make_bin_op[op](a, b);
}
Expr random_expr(Type T, int depth) {
typedef Expr (*make_bin_op_fn)(Expr, Expr);
static make_bin_op_fn make_bin_op[] = {
Add::make,
Sub::make,
Mul::make,
Min::make,
Max::make,
Div::make,
Mod::make,
};
static make_bin_op_fn make_bool_bin_op[] = {
And::make,
Or::make,
};
if (depth-- <= 0) {
return random_leaf(T);
}
const int bin_op_count = sizeof(make_bin_op) / sizeof(make_bin_op[0]);
const int bool_bin_op_count = sizeof(make_bool_bin_op) / sizeof(make_bool_bin_op[0]);
const int op_count = bin_op_count + bool_bin_op_count + 5;
int op = rand() % op_count;
switch(op) {
case 0: return random_leaf(T);
case 1: return Select::make(random_condition(T, depth),
random_expr(T, depth),
random_expr(T, depth));
case 2:
if (T.width != 1) {
return Broadcast::make(random_expr(T.element_of(), depth),
T.width);
}
break;
case 3:
if (T.width != 1) {
return Ramp::make(random_expr(T.element_of(), depth),
random_expr(T.element_of(), depth),
T.width);
}
break;
case 4:
if (T.is_bool()) {
return Not::make(random_expr(T, depth));
}
break;
case 5:
// When generating boolean expressions, maybe throw in a condition on non-bool types.
if (T.is_bool()) {
return random_condition(T, depth);
}
break;
case 6:
// Get a random type that isn't T or int32 (int32 can overflow and we don't care about that).
Type subT;
do {
subT = random_type(T.width);
} while (subT == T || (subT.is_int() && subT.bits == 32));
return Cast::make(T, random_expr(subT, depth));
default:
make_bin_op_fn maker;
if (T.is_bool()) {
maker = make_bool_bin_op[op%bool_bin_op_count];
} else {
maker = make_bin_op[op%bin_op_count];
}
Expr a = random_expr(T, depth);
Expr b = random_expr(T, depth);
return maker(a, b);
}
// If we got here, try again.
return random_expr(T, depth);
}
bool test_simplification(Expr a, Expr b, Type T, const map<string, Expr> &vars) {
for (int j = 0; j < T.width; j++) {
Expr a_j = a;
Expr b_j = b;
if (T.width != 1) {
a_j = extract_lane(a, j);
b_j = extract_lane(b, j);
}
Expr a_j_v = simplify(substitute(vars, a_j));
Expr b_j_v = simplify(substitute(vars, b_j));
// If the simplifier didn't produce constants, there must be
// undefined behavior in this expression. Ignore it.
if (!is_const(a_j_v) || !is_const(b_j_v)) {
continue;
}
if (!equal(a_j_v, b_j_v)) {
for(map<string, Expr>::const_iterator i = vars.begin(); i != vars.end(); i++) {
std::cout << i->first << " = " << i->second << '\n';
}
std::cout << a << '\n';
std::cout << b << '\n';
std::cout << "In vector lane " << j << ":\n";
std::cout << a_j << " -> " << a_j_v << '\n';
std::cout << b_j << " -> " << b_j_v << '\n';
return false;
}
}
return true;
}
bool test_expression(Expr test, int samples) {
Expr simplified = simplify(test);
map<string, Expr> vars;
for (int i = 0; i < fuzz_var_count; i++) {
vars[fuzz_var(i)] = Expr();
}
for (int i = 0; i < samples; i++) {
for (std::map<string, Expr>::iterator v = vars.begin(); v != vars.end(); v++) {
v->second = random_leaf(test.type().element_of(), true);
}
if (!test_simplification(test, simplified, test.type(), vars)) {
return false;
}
}
return true;
}
Expr ramp(Expr b, Expr s, int w) { return Ramp::make(b, s, w); }
Expr x1(Expr x) { return Broadcast::make(x, 2); }
Expr x2(Expr x) { return Broadcast::make(x, 2); }
Expr x4(Expr x) { return Broadcast::make(x, 2); }
Expr uint1(Expr x) { return Cast::make(UInt(1), x); }
Expr uint8(Expr x) { return Cast::make(UInt(8), x); }
Expr uint16(Expr x) { return Cast::make(UInt(16), x); }
Expr uint32(Expr x) { return Cast::make(UInt(32), x); }
Expr int8(Expr x) { return Cast::make(Int(8), x); }
Expr int16(Expr x) { return Cast::make(Int(16), x); }
Expr int32(Expr x) { return Cast::make(Int(32), x); }
Expr uint1x2(Expr x) { return Cast::make(UInt(1).vector_of(2), x); }
Expr uint8x2(Expr x) { return Cast::make(UInt(8).vector_of(2), x); }
Expr uint16x2(Expr x) { return Cast::make(UInt(16).vector_of(2), x); }
Expr uint32x2(Expr x) { return Cast::make(UInt(32).vector_of(2), x); }
Expr int8x2(Expr x) { return Cast::make(Int(8).vector_of(2), x); }
Expr int16x2(Expr x) { return Cast::make(Int(16).vector_of(2), x); }
Expr int32x2(Expr x) { return Cast::make(Int(32).vector_of(2), x); }
Expr a(Variable::make(Int(0), fuzz_var(0)));
Expr b(Variable::make(Int(0), fuzz_var(1)));
Expr c(Variable::make(Int(0), fuzz_var(2)));
Expr d(Variable::make(Int(0), fuzz_var(3)));
Expr e(Variable::make(Int(0), fuzz_var(4)));
int main(int argc, char **argv) {
// Number of random expressions to test.
const int count = 1000;
// Depth of the randomly generated expression trees.
const int depth = 5;
// Number of samples to test the generated expressions for.
const int samples = 3;
// We want different fuzz tests every time, to increase coverage.
// We also report the seed to enable reproducing failures.
int fuzz_seed = time(NULL);
srand(fuzz_seed);
std::cout << "Simplify fuzz test seed: " << fuzz_seed << '\n';
int max_fuzz_vector_width = 4;
for (size_t i = 0; i < fuzz_type_count; i++) {
Type T = fuzz_types[i];
for (int w = 1; w < max_fuzz_vector_width; w *= 2) {
Type VT = T.vector_of(w);
for (int n = 0; n < count; n++) {
// Generate a random expr...
Expr test = random_expr(VT, depth);
if (!test_expression(test, samples)) {
return -1;
}
}
}
}
std::cout << "Success!" << std::endl;
return 0;
}
<commit_msg>Fix ambiguous symbol resolution with libc++<commit_after>#include <stdio.h>
#include <Halide.h>
// Test the simplifier in Halide by testing for equivalence of randomly generated expressions.
using namespace std;
using namespace Halide;
using namespace Halide::Internal;
const int fuzz_var_count = 5;
Type fuzz_types[] = { UInt(1), UInt(8), UInt(16), UInt(32), Int(8), Int(16), Int(32) };
const int fuzz_type_count = sizeof(fuzz_types)/sizeof(fuzz_types[0]);
std::string fuzz_var(int i) {
return std::string(1, 'a' + i);
}
Expr random_var() {
return Variable::make(Int(0), fuzz_var(rand()%fuzz_var_count));
}
Type random_type(int width) {
Type T = fuzz_types[rand()%fuzz_type_count];
if (width > 1) {
T = T.vector_of(width);
}
return T;
}
Expr random_leaf(Type T, bool imm_only = false) {
if (T.is_scalar()) {
int var = rand()%fuzz_var_count + 1;
if (!imm_only && var < fuzz_var_count) {
return cast(T, random_var());
} else {
if (T == Int(32)) {
// For Int(32), we don't care about correctness during
// overflow, so just use numbers that are unlikely to
// overflow.
return cast(T, rand()%256 - 128);
} else {
return cast(T, rand() - RAND_MAX/2);
}
}
} else {
if (rand() % 2 == 0) {
return Ramp::make(random_leaf(T.element_of()), random_leaf(T.element_of()), T.width);
} else {
return Broadcast::make(random_leaf(T.element_of()), T.width);
}
}
}
Expr random_expr(Type T, int depth);
Expr random_condition(Type T, int depth) {
typedef Expr (*make_bin_op_fn)(Expr, Expr);
static make_bin_op_fn make_bin_op[] = {
EQ::make,
NE::make,
LT::make,
LE::make,
GT::make,
GE::make,
};
const int op_count = sizeof(make_bin_op)/sizeof(make_bin_op[0]);
Expr a = random_expr(T, depth);
Expr b = random_expr(T, depth);
int op = rand()%op_count;
return make_bin_op[op](a, b);
}
Expr random_expr(Type T, int depth) {
typedef Expr (*make_bin_op_fn)(Expr, Expr);
static make_bin_op_fn make_bin_op[] = {
Add::make,
Sub::make,
Mul::make,
Min::make,
Max::make,
Div::make,
Mod::make,
};
static make_bin_op_fn make_bool_bin_op[] = {
And::make,
Or::make,
};
if (depth-- <= 0) {
return random_leaf(T);
}
const int bin_op_count = sizeof(make_bin_op) / sizeof(make_bin_op[0]);
const int bool_bin_op_count = sizeof(make_bool_bin_op) / sizeof(make_bool_bin_op[0]);
const int op_count = bin_op_count + bool_bin_op_count + 5;
int op = rand() % op_count;
switch(op) {
case 0: return random_leaf(T);
case 1: return Select::make(random_condition(T, depth),
random_expr(T, depth),
random_expr(T, depth));
case 2:
if (T.width != 1) {
return Broadcast::make(random_expr(T.element_of(), depth),
T.width);
}
break;
case 3:
if (T.width != 1) {
return Ramp::make(random_expr(T.element_of(), depth),
random_expr(T.element_of(), depth),
T.width);
}
break;
case 4:
if (T.is_bool()) {
return Not::make(random_expr(T, depth));
}
break;
case 5:
// When generating boolean expressions, maybe throw in a condition on non-bool types.
if (T.is_bool()) {
return random_condition(T, depth);
}
break;
case 6:
// Get a random type that isn't T or int32 (int32 can overflow and we don't care about that).
Type subT;
do {
subT = random_type(T.width);
} while (subT == T || (subT.is_int() && subT.bits == 32));
return Cast::make(T, random_expr(subT, depth));
default:
make_bin_op_fn maker;
if (T.is_bool()) {
maker = make_bool_bin_op[op%bool_bin_op_count];
} else {
maker = make_bin_op[op%bin_op_count];
}
Expr a = random_expr(T, depth);
Expr b = random_expr(T, depth);
return maker(a, b);
}
// If we got here, try again.
return random_expr(T, depth);
}
bool test_simplification(Expr a, Expr b, Type T, const map<string, Expr> &vars) {
for (int j = 0; j < T.width; j++) {
Expr a_j = a;
Expr b_j = b;
if (T.width != 1) {
a_j = extract_lane(a, j);
b_j = extract_lane(b, j);
}
Expr a_j_v = simplify(substitute(vars, a_j));
Expr b_j_v = simplify(substitute(vars, b_j));
// If the simplifier didn't produce constants, there must be
// undefined behavior in this expression. Ignore it.
if (!Internal::is_const(a_j_v) || !Internal::is_const(b_j_v)) {
continue;
}
if (!equal(a_j_v, b_j_v)) {
for(map<string, Expr>::const_iterator i = vars.begin(); i != vars.end(); i++) {
std::cout << i->first << " = " << i->second << '\n';
}
std::cout << a << '\n';
std::cout << b << '\n';
std::cout << "In vector lane " << j << ":\n";
std::cout << a_j << " -> " << a_j_v << '\n';
std::cout << b_j << " -> " << b_j_v << '\n';
return false;
}
}
return true;
}
bool test_expression(Expr test, int samples) {
Expr simplified = simplify(test);
map<string, Expr> vars;
for (int i = 0; i < fuzz_var_count; i++) {
vars[fuzz_var(i)] = Expr();
}
for (int i = 0; i < samples; i++) {
for (std::map<string, Expr>::iterator v = vars.begin(); v != vars.end(); v++) {
v->second = random_leaf(test.type().element_of(), true);
}
if (!test_simplification(test, simplified, test.type(), vars)) {
return false;
}
}
return true;
}
Expr ramp(Expr b, Expr s, int w) { return Ramp::make(b, s, w); }
Expr x1(Expr x) { return Broadcast::make(x, 2); }
Expr x2(Expr x) { return Broadcast::make(x, 2); }
Expr x4(Expr x) { return Broadcast::make(x, 2); }
Expr uint1(Expr x) { return Cast::make(UInt(1), x); }
Expr uint8(Expr x) { return Cast::make(UInt(8), x); }
Expr uint16(Expr x) { return Cast::make(UInt(16), x); }
Expr uint32(Expr x) { return Cast::make(UInt(32), x); }
Expr int8(Expr x) { return Cast::make(Int(8), x); }
Expr int16(Expr x) { return Cast::make(Int(16), x); }
Expr int32(Expr x) { return Cast::make(Int(32), x); }
Expr uint1x2(Expr x) { return Cast::make(UInt(1).vector_of(2), x); }
Expr uint8x2(Expr x) { return Cast::make(UInt(8).vector_of(2), x); }
Expr uint16x2(Expr x) { return Cast::make(UInt(16).vector_of(2), x); }
Expr uint32x2(Expr x) { return Cast::make(UInt(32).vector_of(2), x); }
Expr int8x2(Expr x) { return Cast::make(Int(8).vector_of(2), x); }
Expr int16x2(Expr x) { return Cast::make(Int(16).vector_of(2), x); }
Expr int32x2(Expr x) { return Cast::make(Int(32).vector_of(2), x); }
Expr a(Variable::make(Int(0), fuzz_var(0)));
Expr b(Variable::make(Int(0), fuzz_var(1)));
Expr c(Variable::make(Int(0), fuzz_var(2)));
Expr d(Variable::make(Int(0), fuzz_var(3)));
Expr e(Variable::make(Int(0), fuzz_var(4)));
int main(int argc, char **argv) {
// Number of random expressions to test.
const int count = 1000;
// Depth of the randomly generated expression trees.
const int depth = 5;
// Number of samples to test the generated expressions for.
const int samples = 3;
// We want different fuzz tests every time, to increase coverage.
// We also report the seed to enable reproducing failures.
int fuzz_seed = time(NULL);
srand(fuzz_seed);
std::cout << "Simplify fuzz test seed: " << fuzz_seed << '\n';
int max_fuzz_vector_width = 4;
for (size_t i = 0; i < fuzz_type_count; i++) {
Type T = fuzz_types[i];
for (int w = 1; w < max_fuzz_vector_width; w *= 2) {
Type VT = T.vector_of(w);
for (int n = 0; n < count; n++) {
// Generate a random expr...
Expr test = random_expr(VT, depth);
if (!test_expression(test, samples)) {
return -1;
}
}
}
}
std::cout << "Success!" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "AutowiringBenchmarkTest.h"
#include "TestFixtures/SimpleObject.h"
#include <boost/chrono/system_clocks.hpp>
TEST_F(AutowiringBenchmarkTest, VerifySimplePerformance) {
const size_t n = 10000;
// Insert the object:
AutoRequired<SimpleObject>();
// Time n hash map hits, in order to get a baseline:
std::unordered_map<int, int> ref;
ref[0] = 212;
ref[1] = 21;
boost::chrono::nanoseconds baseline;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
ref[i % 2];
baseline = boost::chrono::high_resolution_clock::now() - start;
}
// Time n autowirings:
boost::chrono::nanoseconds benchmark;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
Autowired<SimpleObject>();
benchmark = (boost::chrono::high_resolution_clock::now() - start) / n;
}
EXPECT_GT(baseline * 3. / 2., benchmark) << "Average time to autowire one member was more than 3/2 of a hash map lookup";
}
template<int N>
struct dummy:
public virtual ContextMember
{};
TEST_F(AutowiringBenchmarkTest, VerifyAutowiringCache) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
auto inj = [] {
Autowired<dummy<1>>();
Autowired<dummy<2>>();
Autowired<dummy<3>>();
Autowired<dummy<4>>();
Autowired<dummy<5>>();
Autowired<dummy<6>>();
Autowired<dummy<7>>();
Autowired<dummy<8>>();
Autowired<dummy<9>>();
Autowired<dummy<10>>();
Autowired<dummy<11>>();
Autowired<dummy<12>>();
Autowired<dummy<13>>();
Autowired<dummy<14>>();
Autowired<dummy<15>>();
Autowired<dummy<16>>();
Autowired<dummy<17>>();
Autowired<dummy<18>>();
Autowired<dummy<19>>();
Autowired<dummy<20>>();
Autowired<dummy<21>>();
Autowired<dummy<22>>();
Autowired<dummy<23>>();
Autowired<dummy<24>>();
Autowired<dummy<25>>();
};
for(int i = 0; i<100; ++i) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
auto startBase = boost::chrono::high_resolution_clock::now();
inj();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
inj();
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark) << "Autowiring cache not improving performance on subsequent autowirings";
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFast) {
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<dummy<1>> foo;
AutowiredFast<dummy<1>> bar;
ASSERT_TRUE(foo) << "AutoRequred member not created";
EXPECT_TRUE(bar) << "AutowiredFast not satisfied";
}
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutowiredFast<dummy<1>> fast;
Autowired<dummy<1>> wired;
AutoRequired<dummy<1>> required;
ASSERT_TRUE(required) << "AutoRequired member not created";
EXPECT_TRUE(wired.IsAutowired()) << "Deferred Autowiring wasn't satisfied";
EXPECT_FALSE(fast) << "AutowiredFast member was deferred";
}
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFastPerformance) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
{
for (int i=0; i<500; ++i){
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
auto startBase = boost::chrono::high_resolution_clock::now();
Autowired<dummy<1>>();
Autowired<dummy<2>>();
Autowired<dummy<3>>();
Autowired<dummy<4>>();
Autowired<dummy<5>>();
Autowired<dummy<6>>();
Autowired<dummy<7>>();
Autowired<dummy<8>>();
Autowired<dummy<9>>();
Autowired<dummy<10>>();
Autowired<dummy<11>>();
Autowired<dummy<12>>();
Autowired<dummy<13>>();
Autowired<dummy<14>>();
Autowired<dummy<15>>();
Autowired<dummy<16>>();
Autowired<dummy<17>>();
Autowired<dummy<18>>();
Autowired<dummy<19>>();
Autowired<dummy<20>>();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
AutowiredFast<dummy<21>>();
AutowiredFast<dummy<22>>();
AutowiredFast<dummy<23>>();
AutowiredFast<dummy<24>>();
AutowiredFast<dummy<25>>();
AutowiredFast<dummy<26>>();
AutowiredFast<dummy<27>>();
AutowiredFast<dummy<28>>();
AutowiredFast<dummy<29>>();
AutowiredFast<dummy<30>>();
AutowiredFast<dummy<31>>();
AutowiredFast<dummy<32>>();
AutowiredFast<dummy<33>>();
AutowiredFast<dummy<34>>();
AutowiredFast<dummy<35>>();
AutowiredFast<dummy<36>>();
AutowiredFast<dummy<37>>();
AutowiredFast<dummy<38>>();
AutowiredFast<dummy<39>>();
AutowiredFast<dummy<40>>();
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
}
EXPECT_GT(baseline, benchmark*1.75) << "Fast autowiring is slower than ordinary autowiring";
}
<commit_msg>Focusing AutowiringBenchmarkTest on already-memoized entries<commit_after>#include "stdafx.h"
#include "AutowiringBenchmarkTest.h"
#include "TestFixtures/SimpleObject.h"
#include <boost/chrono/system_clocks.hpp>
TEST_F(AutowiringBenchmarkTest, VerifySimplePerformance) {
const size_t n = 10000;
// Insert the object:
AutoRequired<SimpleObject>();
// Time n hash map hits, in order to get a baseline:
std::unordered_map<int, int> ref;
ref[0] = 212;
ref[1] = 21;
boost::chrono::nanoseconds baseline;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
ref[i % 2];
baseline = boost::chrono::high_resolution_clock::now() - start;
}
// Time n autowirings:
boost::chrono::nanoseconds benchmark;
{
auto start = boost::chrono::high_resolution_clock::now();
for(size_t i = n; i--;)
Autowired<SimpleObject>();
benchmark = (boost::chrono::high_resolution_clock::now() - start) / n;
}
EXPECT_GT(baseline * 3. / 2., benchmark) << "Average time to autowire one member was more than 3/2 of a hash map lookup";
}
template<int N>
struct dummy:
public virtual ContextMember
{};
void InjectDummy(void) {
Autowired<dummy<1>>();
Autowired<dummy<2>>();
Autowired<dummy<3>>();
Autowired<dummy<4>>();
Autowired<dummy<5>>();
Autowired<dummy<6>>();
Autowired<dummy<7>>();
Autowired<dummy<8>>();
Autowired<dummy<9>>();
Autowired<dummy<10>>();
Autowired<dummy<11>>();
Autowired<dummy<12>>();
Autowired<dummy<13>>();
Autowired<dummy<14>>();
Autowired<dummy<15>>();
Autowired<dummy<16>>();
Autowired<dummy<17>>();
Autowired<dummy<18>>();
Autowired<dummy<19>>();
Autowired<dummy<20>>();
Autowired<dummy<21>>();
Autowired<dummy<22>>();
Autowired<dummy<23>>();
Autowired<dummy<24>>();
Autowired<dummy<25>>();
};
TEST_F(AutowiringBenchmarkTest, VerifyAutowiringCache) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
for(int i = 0; i<100; ++i) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
auto startBase = boost::chrono::high_resolution_clock::now();
InjectDummy();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
InjectDummy();
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark) << "Autowiring cache not improving performance on subsequent autowirings";
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFast) {
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<dummy<1>> foo;
AutowiredFast<dummy<1>> bar;
ASSERT_TRUE(foo) << "AutoRequred member not created";
EXPECT_TRUE(bar) << "AutowiredFast not satisfied";
}
{
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutowiredFast<dummy<1>> fast;
Autowired<dummy<1>> wired;
AutoRequired<dummy<1>> required;
ASSERT_TRUE(required) << "AutoRequired member not created";
EXPECT_TRUE(wired.IsAutowired()) << "Deferred Autowiring wasn't satisfied";
EXPECT_FALSE(fast) << "AutowiredFast member was deferred";
}
}
TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFastPerformance) {
boost::chrono::nanoseconds baseline(0);
boost::chrono::nanoseconds benchmark(0);
{
// All of these tests will operate in the same context:
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
// Prime all memos:
InjectDummy();
// Test simple autowiring first:
auto startBase = boost::chrono::high_resolution_clock::now();
for(int i = 0; i < 500; ++i)
InjectDummy();
baseline += boost::chrono::high_resolution_clock::now() - startBase;
auto startBench = boost::chrono::high_resolution_clock::now();
for(int i = 0; i < 500; ++i) {
AutowiredFast<dummy<1>>();
AutowiredFast<dummy<2>>();
AutowiredFast<dummy<3>>();
AutowiredFast<dummy<4>>();
AutowiredFast<dummy<5>>();
AutowiredFast<dummy<6>>();
AutowiredFast<dummy<7>>();
AutowiredFast<dummy<8>>();
AutowiredFast<dummy<9>>();
AutowiredFast<dummy<10>>();
AutowiredFast<dummy<11>>();
AutowiredFast<dummy<12>>();
AutowiredFast<dummy<13>>();
AutowiredFast<dummy<14>>();
AutowiredFast<dummy<15>>();
AutowiredFast<dummy<16>>();
AutowiredFast<dummy<17>>();
AutowiredFast<dummy<18>>();
AutowiredFast<dummy<19>>();
AutowiredFast<dummy<20>>();
}
benchmark += boost::chrono::high_resolution_clock::now() - startBench;
}
EXPECT_GT(baseline, benchmark*1.75) << "Fast autowiring is slower than ordinary autowiring";
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <folly/init/Init.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/gen-cpp2/DeserializationBench_types.h>
folly::Random::DefaultGenerator rng_(12345);
const int32_t kNumOfInserts = 250;
std::vector<int32_t> getRandomVector() {
std::vector<int32_t> v;
for (int i = 0; i < kNumOfInserts; ++i) {
v.push_back(i);
}
return v;
}
std::set<int32_t> getRandomSet() {
std::set<int32_t> s;
for (int i = 0; i < kNumOfInserts; ++i) {
s.insert(i);
}
return s;
}
std::map<int32_t, std::string> getRandomMap() {
std::map<int32_t, std::string> m;
for (int i = 0; i < kNumOfInserts; ++i) {
m.emplace(i, std::to_string(i));
}
return m;
}
folly::sorted_vector_set<int32_t> getRandomFollySet() {
folly::sorted_vector_set<int32_t> s;
for (int i = 0; i < kNumOfInserts; ++i) {
s.insert(i);
}
return s;
}
folly::sorted_vector_map<int32_t, std::string> getRandomFollyMap() {
folly::sorted_vector_map<int32_t, std::string> m;
for (int i = 0; i < kNumOfInserts; ++i) {
m[std::move(i)] = std::to_string(i);
}
return m;
}
void buildRandomStructA(cpp2::StructA& obj) {
obj.fieldA = folly::Random::rand32(rng_) % 2;
obj.fieldB = folly::Random::rand32(rng_);
obj.fieldC = std::to_string(folly::Random::rand32(rng_));
obj.fieldD = getRandomVector();
obj.fieldE = getRandomSet();
obj.fieldF = getRandomMap();
for (int32_t i = 0; i < kNumOfInserts; ++i) {
std::vector<std::vector<int32_t>> g1;
std::set<std::set<int32_t>> h1;
std::vector<std::set<int32_t>> j1;
std::set<std::vector<int32_t>> j2;
for (int32_t j = 0; j < kNumOfInserts; ++j) {
g1.push_back(getRandomVector());
h1.insert(getRandomSet());
j1.push_back(getRandomSet());
j2.insert(getRandomVector());
}
obj.fieldG.push_back(g1);
obj.fieldH.insert(h1);
obj.fieldI.emplace(getRandomMap(), getRandomMap());
obj.fieldJ.emplace(j1, j2);
}
}
void buildRandomStructB(cpp2::StructB& obj) {
obj.fieldA = folly::Random::rand32(rng_) % 2;
obj.fieldB = folly::Random::rand32(rng_);
obj.fieldC = std::to_string(folly::Random::rand32(rng_));
obj.fieldD = getRandomVector();
obj.fieldE = getRandomFollySet();
obj.fieldF = getRandomFollyMap();
for (int32_t i = 0; i < kNumOfInserts; ++i) {
std::vector<std::vector<int32_t>> g1;
folly::sorted_vector_set<folly::sorted_vector_set<int32_t>> h1;
std::vector<folly::sorted_vector_set<int32_t>> j1;
folly::sorted_vector_set<std::vector<int32_t>> j2;
for (int32_t j = 0; j < kNumOfInserts; ++j) {
g1.push_back(getRandomVector());
h1.insert(getRandomFollySet());
j1.push_back(getRandomFollySet());
j2.insert(getRandomVector());
}
obj.fieldG.push_back(g1);
obj.fieldH.insert(h1);
obj.fieldI[std::move(getRandomFollyMap())] = getRandomFollyMap();
obj.fieldJ[std::move(j1)] = j2;
}
}
BENCHMARK(CompactSerialization_custom_container, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructB obj;
buildRandomStructB(obj);
// Serialize, timed:
braces.dismissing([&] { serializer::serialize<folly::IOBufQueue>(obj); });
}
}
BENCHMARK(CompactDeserialization_custom_container, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructB obj;
buildRandomStructB(obj);
// Serialize, untimed:
auto buf = serializer::serialize<folly::IOBufQueue>(obj).move();
buf->coalesce(); // so we can ignore serialization artifacts later
// Deserialize, timed:
cpp2::StructB obj2;
braces.dismissing([&] { serializer::deserialize(buf.get(), obj2); });
}
}
BENCHMARK(CompactSerialization, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, timed:
braces.dismissing([&] { serializer::serialize<folly::IOBufQueue>(obj); });
}
}
BENCHMARK(CompactDeserialization, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, untimed:
auto buf = serializer::serialize<folly::IOBufQueue>(obj).move();
buf->coalesce(); // so we can ignore serialization artifacts later
// Deserialize, timed:
cpp2::StructA obj2;
braces.dismissing([&] {
serializer::deserialize(buf.get(), obj2);
});
}
}
BENCHMARK(JsonSerialization, iters) {
using serializer = apache::thrift::SimpleJSONSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, timed:
braces.dismissing([&] { serializer::serialize<folly::IOBufQueue>(obj); });
}
}
BENCHMARK(JsonDeserialization, iters) {
using serializer = apache::thrift::SimpleJSONSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, untimed:
auto buf = serializer::serialize<folly::IOBufQueue>(obj).move();
buf->coalesce(); // so we can ignore serialization artifacts later
// Deserialize, timed:
cpp2::StructA obj2;
braces.dismissing([&] { serializer::deserialize(buf.get(), obj2); });
}
}
int main(int argc, char** argv) {
folly::init(&argc, &argv);
folly::runBenchmarks();
return 0;
}
/*
============================================================================
thrift/test/DeserializationBench.cpp relative time/iter iters/s
============================================================================
CompactSerialization_custom_container 2.76s 362.93m
CompactDeserialization_custom_container 728.59ms 1.37
CompactSerialization 2.71s 368.92m
CompactDeserialization 760.46ms 1.31
JsonSerialization 6.02s 166.06m
JsonDeserialization 11.17s 89.49m
============================================================================
*/
<commit_msg>Deserialization Test: Fix incorrect move<commit_after>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <folly/init/Init.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/gen-cpp2/DeserializationBench_types.h>
folly::Random::DefaultGenerator rng_(12345);
const int32_t kNumOfInserts = 250;
std::vector<int32_t> getRandomVector() {
std::vector<int32_t> v;
for (int i = 0; i < kNumOfInserts; ++i) {
v.push_back(i);
}
return v;
}
std::set<int32_t> getRandomSet() {
std::set<int32_t> s;
for (int i = 0; i < kNumOfInserts; ++i) {
s.insert(i);
}
return s;
}
std::map<int32_t, std::string> getRandomMap() {
std::map<int32_t, std::string> m;
for (int i = 0; i < kNumOfInserts; ++i) {
m.emplace(i, std::to_string(i));
}
return m;
}
folly::sorted_vector_set<int32_t> getRandomFollySet() {
folly::sorted_vector_set<int32_t> s;
for (int i = 0; i < kNumOfInserts; ++i) {
s.insert(i);
}
return s;
}
folly::sorted_vector_map<int32_t, std::string> getRandomFollyMap() {
folly::sorted_vector_map<int32_t, std::string> m;
for (int i = 0; i < kNumOfInserts; ++i) {
m[i] = std::to_string(i);
}
return m;
}
void buildRandomStructA(cpp2::StructA& obj) {
obj.fieldA = folly::Random::rand32(rng_) % 2;
obj.fieldB = folly::Random::rand32(rng_);
obj.fieldC = std::to_string(folly::Random::rand32(rng_));
obj.fieldD = getRandomVector();
obj.fieldE = getRandomSet();
obj.fieldF = getRandomMap();
for (int32_t i = 0; i < kNumOfInserts; ++i) {
std::vector<std::vector<int32_t>> g1;
std::set<std::set<int32_t>> h1;
std::vector<std::set<int32_t>> j1;
std::set<std::vector<int32_t>> j2;
for (int32_t j = 0; j < kNumOfInserts; ++j) {
g1.push_back(getRandomVector());
h1.insert(getRandomSet());
j1.push_back(getRandomSet());
j2.insert(getRandomVector());
}
obj.fieldG.push_back(g1);
obj.fieldH.insert(h1);
obj.fieldI.emplace(getRandomMap(), getRandomMap());
obj.fieldJ.emplace(j1, j2);
}
}
void buildRandomStructB(cpp2::StructB& obj) {
obj.fieldA = folly::Random::rand32(rng_) % 2;
obj.fieldB = folly::Random::rand32(rng_);
obj.fieldC = std::to_string(folly::Random::rand32(rng_));
obj.fieldD = getRandomVector();
obj.fieldE = getRandomFollySet();
obj.fieldF = getRandomFollyMap();
for (int32_t i = 0; i < kNumOfInserts; ++i) {
std::vector<std::vector<int32_t>> g1;
folly::sorted_vector_set<folly::sorted_vector_set<int32_t>> h1;
std::vector<folly::sorted_vector_set<int32_t>> j1;
folly::sorted_vector_set<std::vector<int32_t>> j2;
for (int32_t j = 0; j < kNumOfInserts; ++j) {
g1.push_back(getRandomVector());
h1.insert(getRandomFollySet());
j1.push_back(getRandomFollySet());
j2.insert(getRandomVector());
}
obj.fieldG.push_back(g1);
obj.fieldH.insert(h1);
obj.fieldI[std::move(getRandomFollyMap())] = getRandomFollyMap();
obj.fieldJ[std::move(j1)] = j2;
}
}
BENCHMARK(CompactSerialization_custom_container, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructB obj;
buildRandomStructB(obj);
// Serialize, timed:
braces.dismissing([&] { serializer::serialize<folly::IOBufQueue>(obj); });
}
}
BENCHMARK(CompactDeserialization_custom_container, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructB obj;
buildRandomStructB(obj);
// Serialize, untimed:
auto buf = serializer::serialize<folly::IOBufQueue>(obj).move();
buf->coalesce(); // so we can ignore serialization artifacts later
// Deserialize, timed:
cpp2::StructB obj2;
braces.dismissing([&] { serializer::deserialize(buf.get(), obj2); });
}
}
BENCHMARK(CompactSerialization, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, timed:
braces.dismissing([&] { serializer::serialize<folly::IOBufQueue>(obj); });
}
}
BENCHMARK(CompactDeserialization, iters) {
using serializer = apache::thrift::CompactSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, untimed:
auto buf = serializer::serialize<folly::IOBufQueue>(obj).move();
buf->coalesce(); // so we can ignore serialization artifacts later
// Deserialize, timed:
cpp2::StructA obj2;
braces.dismissing([&] {
serializer::deserialize(buf.get(), obj2);
});
}
}
BENCHMARK(JsonSerialization, iters) {
using serializer = apache::thrift::SimpleJSONSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, timed:
braces.dismissing([&] { serializer::serialize<folly::IOBufQueue>(obj); });
}
}
BENCHMARK(JsonDeserialization, iters) {
using serializer = apache::thrift::SimpleJSONSerializer;
folly::BenchmarkSuspender braces; // stop the clock by default
for (size_t i = 0; i < iters; ++i) {
// Prep, untimed:
cpp2::StructA obj;
buildRandomStructA(obj);
// Serialize, untimed:
auto buf = serializer::serialize<folly::IOBufQueue>(obj).move();
buf->coalesce(); // so we can ignore serialization artifacts later
// Deserialize, timed:
cpp2::StructA obj2;
braces.dismissing([&] { serializer::deserialize(buf.get(), obj2); });
}
}
int main(int argc, char** argv) {
folly::init(&argc, &argv);
folly::runBenchmarks();
return 0;
}
/*
============================================================================
thrift/test/DeserializationBench.cpp relative time/iter iters/s
============================================================================
CompactSerialization_custom_container 2.76s 362.93m
CompactDeserialization_custom_container 728.59ms 1.37
CompactSerialization 2.71s 368.92m
CompactDeserialization 760.46ms 1.31
JsonSerialization 6.02s 166.06m
JsonDeserialization 11.17s 89.49m
============================================================================
*/
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015-2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <fstream>
#include <memory>
#include <sstream>
#include <thread>
#include <gflags/gflags.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/transport/byte_stream.h"
#include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h"
#include "test/cpp/interop/server_helper.h"
#include "test/cpp/util/test_config.h"
DEFINE_bool(use_alts, false,
"Whether to use alts. Enable alts will disable tls.");
DEFINE_bool(use_tls, false, "Whether to use tls.");
DEFINE_string(custom_credentials_type, "", "User provided credentials type.");
DEFINE_int32(port, 0, "Server port.");
DEFINE_int32(max_send_message_size, -1, "The maximum send message size.");
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCredentials;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::SslServerCredentialsOptions;
using grpc::Status;
using grpc::WriteOptions;
using grpc::testing::InteropServerContextInspector;
using grpc::testing::Payload;
using grpc::testing::SimpleRequest;
using grpc::testing::SimpleResponse;
using grpc::testing::StreamingInputCallRequest;
using grpc::testing::StreamingInputCallResponse;
using grpc::testing::StreamingOutputCallRequest;
using grpc::testing::StreamingOutputCallResponse;
using grpc::testing::TestService;
const char kEchoInitialMetadataKey[] = "x-grpc-test-echo-initial";
const char kEchoTrailingBinMetadataKey[] = "x-grpc-test-echo-trailing-bin";
const char kEchoUserAgentKey[] = "x-grpc-test-echo-useragent";
void MaybeEchoMetadata(ServerContext* context) {
const auto& client_metadata = context->client_metadata();
GPR_ASSERT(client_metadata.count(kEchoInitialMetadataKey) <= 1);
GPR_ASSERT(client_metadata.count(kEchoTrailingBinMetadataKey) <= 1);
auto iter = client_metadata.find(kEchoInitialMetadataKey);
if (iter != client_metadata.end()) {
context->AddInitialMetadata(
kEchoInitialMetadataKey,
grpc::string(iter->second.begin(), iter->second.end()));
}
iter = client_metadata.find(kEchoTrailingBinMetadataKey);
if (iter != client_metadata.end()) {
context->AddTrailingMetadata(
kEchoTrailingBinMetadataKey,
grpc::string(iter->second.begin(), iter->second.end()));
}
// Check if client sent a magic key in the header that makes us echo
// back the user-agent (for testing purpose)
iter = client_metadata.find(kEchoUserAgentKey);
if (iter != client_metadata.end()) {
iter = client_metadata.find("user-agent");
if (iter != client_metadata.end()) {
context->AddInitialMetadata(
kEchoUserAgentKey,
grpc::string(iter->second.begin(), iter->second.end()));
}
}
}
bool SetPayload(int size, Payload* payload) {
std::unique_ptr<char[]> body(new char[size]());
payload->set_body(body.get(), size);
return true;
}
bool CheckExpectedCompression(const ServerContext& context,
const bool compression_expected) {
const InteropServerContextInspector inspector(context);
const grpc_compression_algorithm received_compression =
inspector.GetCallCompressionAlgorithm();
if (compression_expected) {
if (received_compression == GRPC_COMPRESS_NONE) {
// Expected some compression, got NONE. This is an error.
gpr_log(GPR_ERROR,
"Expected compression but got uncompressed request from client.");
return false;
}
if (!(inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS)) {
gpr_log(GPR_ERROR,
"Failure: Requested compression in a compressable request, but "
"compression bit in message flags not set.");
return false;
}
} else {
// Didn't expect compression -> make sure the request is uncompressed
if (inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS) {
gpr_log(GPR_ERROR,
"Failure: Didn't requested compression, but compression bit in "
"message flags set.");
return false;
}
}
return true;
}
class TestServiceImpl : public TestService::Service {
public:
Status EmptyCall(ServerContext* context, const grpc::testing::Empty* request,
grpc::testing::Empty* response) {
MaybeEchoMetadata(context);
return Status::OK;
}
// Response contains current timestamp. We ignore everything in the request.
Status CacheableUnaryCall(ServerContext* context,
const SimpleRequest* request,
SimpleResponse* response) {
gpr_timespec ts = gpr_now(GPR_CLOCK_PRECISE);
std::string timestamp = std::to_string((long long unsigned)ts.tv_nsec);
response->mutable_payload()->set_body(timestamp.c_str(), timestamp.size());
context->AddInitialMetadata("cache-control", "max-age=60, public");
return Status::OK;
}
Status UnaryCall(ServerContext* context, const SimpleRequest* request,
SimpleResponse* response) {
MaybeEchoMetadata(context);
if (request->has_response_compressed()) {
const bool compression_requested = request->response_compressed().value();
gpr_log(GPR_DEBUG, "Request for compression (%s) present for %s",
compression_requested ? "enabled" : "disabled", __func__);
if (compression_requested) {
// Any level would do, let's go for HIGH because we are overachievers.
context->set_compression_level(GRPC_COMPRESS_LEVEL_HIGH);
} else {
context->set_compression_level(GRPC_COMPRESS_LEVEL_NONE);
}
}
if (!CheckExpectedCompression(*context,
request->expect_compressed().value())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Compressed request expectation not met.");
}
if (request->response_size() > 0) {
if (!SetPayload(request->response_size(), response->mutable_payload())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Error creating payload.");
}
}
if (request->has_response_status()) {
return Status(
static_cast<grpc::StatusCode>(request->response_status().code()),
request->response_status().message());
}
return Status::OK;
}
Status StreamingOutputCall(
ServerContext* context, const StreamingOutputCallRequest* request,
ServerWriter<StreamingOutputCallResponse>* writer) {
StreamingOutputCallResponse response;
bool write_success = true;
for (int i = 0; write_success && i < request->response_parameters_size();
i++) {
if (!SetPayload(request->response_parameters(i).size(),
response.mutable_payload())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Error creating payload.");
}
WriteOptions wopts;
if (request->response_parameters(i).has_compressed()) {
// Compress by default. Disabled on a per-message basis.
context->set_compression_level(GRPC_COMPRESS_LEVEL_HIGH);
const bool compression_requested =
request->response_parameters(i).compressed().value();
gpr_log(GPR_DEBUG, "Request for compression (%s) present for %s",
compression_requested ? "enabled" : "disabled", __func__);
if (!compression_requested) {
wopts.set_no_compression();
} // else, compression is already enabled via the context.
}
int time_us;
if ((time_us = request->response_parameters(i).interval_us()) > 0) {
// Sleep before response if needed
gpr_timespec sleep_time =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(time_us, GPR_TIMESPAN));
gpr_sleep_until(sleep_time);
}
write_success = writer->Write(response, wopts);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status StreamingInputCall(ServerContext* context,
ServerReader<StreamingInputCallRequest>* reader,
StreamingInputCallResponse* response) {
StreamingInputCallRequest request;
int aggregated_payload_size = 0;
while (reader->Read(&request)) {
if (!CheckExpectedCompression(*context,
request.expect_compressed().value())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Compressed request expectation not met.");
}
if (request.has_payload()) {
aggregated_payload_size += request.payload().body().size();
}
}
response->set_aggregated_payload_size(aggregated_payload_size);
return Status::OK;
}
Status FullDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
MaybeEchoMetadata(context);
StreamingOutputCallRequest request;
StreamingOutputCallResponse response;
bool write_success = true;
while (write_success && stream->Read(&request)) {
if (request.has_response_status()) {
return Status(
static_cast<grpc::StatusCode>(request.response_status().code()),
request.response_status().message());
}
if (request.response_parameters_size() != 0) {
response.mutable_payload()->set_type(request.payload().type());
response.mutable_payload()->set_body(
grpc::string(request.response_parameters(0).size(), '\0'));
int time_us;
if ((time_us = request.response_parameters(0).interval_us()) > 0) {
// Sleep before response if needed
gpr_timespec sleep_time =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(time_us, GPR_TIMESPAN));
gpr_sleep_until(sleep_time);
}
write_success = stream->Write(response);
}
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status HalfDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
std::vector<StreamingOutputCallRequest> requests;
StreamingOutputCallRequest request;
while (stream->Read(&request)) {
requests.push_back(request);
}
StreamingOutputCallResponse response;
bool write_success = true;
for (unsigned int i = 0; write_success && i < requests.size(); i++) {
response.mutable_payload()->set_type(requests[i].payload().type());
if (requests[i].response_parameters_size() == 0) {
return Status(grpc::StatusCode::INTERNAL,
"Request does not have response parameters.");
}
response.mutable_payload()->set_body(
grpc::string(requests[i].response_parameters(0).size(), '\0'));
write_success = stream->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
};
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds) {
RunServer(creds, FLAGS_port, nullptr, nullptr);
}
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds,
std::unique_ptr<std::vector<std::unique_ptr<ServerBuilderOption>>>
server_options) {
RunServer(creds, FLAGS_port, nullptr, std::move(server_options));
}
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds, const int port,
ServerStartedCondition* server_started_condition) {
RunServer(creds, FLAGS_port, server_started_condition, nullptr);
}
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds, const int port,
ServerStartedCondition* server_started_condition,
std::unique_ptr<std::vector<std::unique_ptr<ServerBuilderOption>>>
server_options) {
GPR_ASSERT(port != 0);
std::ostringstream server_address;
server_address << "0.0.0.0:" << port;
TestServiceImpl service;
SimpleRequest request;
SimpleResponse response;
ServerBuilder builder;
builder.RegisterService(&service);
builder.AddListeningPort(server_address.str(), creds);
if (server_options != nullptr) {
for (size_t i = 0; i < server_options->size(); i++) {
builder.SetOption(std::move((*server_options)[i]));
}
}
if (FLAGS_max_send_message_size >= 0) {
builder.SetMaxSendMessageSize(FLAGS_max_send_message_size);
}
std::unique_ptr<Server> server(builder.BuildAndStart());
gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str());
// Signal that the server has started.
if (server_started_condition) {
std::unique_lock<std::mutex> lock(server_started_condition->mutex);
server_started_condition->server_started = true;
server_started_condition->condition.notify_all();
}
while (!gpr_atm_no_barrier_load(&g_got_sigint)) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_seconds(5, GPR_TIMESPAN)));
}
}
<commit_msg>Fix bug in RunServer()<commit_after>/*
*
* Copyright 2015-2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <fstream>
#include <memory>
#include <sstream>
#include <thread>
#include <gflags/gflags.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/transport/byte_stream.h"
#include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h"
#include "test/cpp/interop/server_helper.h"
#include "test/cpp/util/test_config.h"
DEFINE_bool(use_alts, false,
"Whether to use alts. Enable alts will disable tls.");
DEFINE_bool(use_tls, false, "Whether to use tls.");
DEFINE_string(custom_credentials_type, "", "User provided credentials type.");
DEFINE_int32(port, 0, "Server port.");
DEFINE_int32(max_send_message_size, -1, "The maximum send message size.");
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCredentials;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::SslServerCredentialsOptions;
using grpc::Status;
using grpc::WriteOptions;
using grpc::testing::InteropServerContextInspector;
using grpc::testing::Payload;
using grpc::testing::SimpleRequest;
using grpc::testing::SimpleResponse;
using grpc::testing::StreamingInputCallRequest;
using grpc::testing::StreamingInputCallResponse;
using grpc::testing::StreamingOutputCallRequest;
using grpc::testing::StreamingOutputCallResponse;
using grpc::testing::TestService;
const char kEchoInitialMetadataKey[] = "x-grpc-test-echo-initial";
const char kEchoTrailingBinMetadataKey[] = "x-grpc-test-echo-trailing-bin";
const char kEchoUserAgentKey[] = "x-grpc-test-echo-useragent";
void MaybeEchoMetadata(ServerContext* context) {
const auto& client_metadata = context->client_metadata();
GPR_ASSERT(client_metadata.count(kEchoInitialMetadataKey) <= 1);
GPR_ASSERT(client_metadata.count(kEchoTrailingBinMetadataKey) <= 1);
auto iter = client_metadata.find(kEchoInitialMetadataKey);
if (iter != client_metadata.end()) {
context->AddInitialMetadata(
kEchoInitialMetadataKey,
grpc::string(iter->second.begin(), iter->second.end()));
}
iter = client_metadata.find(kEchoTrailingBinMetadataKey);
if (iter != client_metadata.end()) {
context->AddTrailingMetadata(
kEchoTrailingBinMetadataKey,
grpc::string(iter->second.begin(), iter->second.end()));
}
// Check if client sent a magic key in the header that makes us echo
// back the user-agent (for testing purpose)
iter = client_metadata.find(kEchoUserAgentKey);
if (iter != client_metadata.end()) {
iter = client_metadata.find("user-agent");
if (iter != client_metadata.end()) {
context->AddInitialMetadata(
kEchoUserAgentKey,
grpc::string(iter->second.begin(), iter->second.end()));
}
}
}
bool SetPayload(int size, Payload* payload) {
std::unique_ptr<char[]> body(new char[size]());
payload->set_body(body.get(), size);
return true;
}
bool CheckExpectedCompression(const ServerContext& context,
const bool compression_expected) {
const InteropServerContextInspector inspector(context);
const grpc_compression_algorithm received_compression =
inspector.GetCallCompressionAlgorithm();
if (compression_expected) {
if (received_compression == GRPC_COMPRESS_NONE) {
// Expected some compression, got NONE. This is an error.
gpr_log(GPR_ERROR,
"Expected compression but got uncompressed request from client.");
return false;
}
if (!(inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS)) {
gpr_log(GPR_ERROR,
"Failure: Requested compression in a compressable request, but "
"compression bit in message flags not set.");
return false;
}
} else {
// Didn't expect compression -> make sure the request is uncompressed
if (inspector.GetMessageFlags() & GRPC_WRITE_INTERNAL_COMPRESS) {
gpr_log(GPR_ERROR,
"Failure: Didn't requested compression, but compression bit in "
"message flags set.");
return false;
}
}
return true;
}
class TestServiceImpl : public TestService::Service {
public:
Status EmptyCall(ServerContext* context, const grpc::testing::Empty* request,
grpc::testing::Empty* response) {
MaybeEchoMetadata(context);
return Status::OK;
}
// Response contains current timestamp. We ignore everything in the request.
Status CacheableUnaryCall(ServerContext* context,
const SimpleRequest* request,
SimpleResponse* response) {
gpr_timespec ts = gpr_now(GPR_CLOCK_PRECISE);
std::string timestamp = std::to_string((long long unsigned)ts.tv_nsec);
response->mutable_payload()->set_body(timestamp.c_str(), timestamp.size());
context->AddInitialMetadata("cache-control", "max-age=60, public");
return Status::OK;
}
Status UnaryCall(ServerContext* context, const SimpleRequest* request,
SimpleResponse* response) {
MaybeEchoMetadata(context);
if (request->has_response_compressed()) {
const bool compression_requested = request->response_compressed().value();
gpr_log(GPR_DEBUG, "Request for compression (%s) present for %s",
compression_requested ? "enabled" : "disabled", __func__);
if (compression_requested) {
// Any level would do, let's go for HIGH because we are overachievers.
context->set_compression_level(GRPC_COMPRESS_LEVEL_HIGH);
} else {
context->set_compression_level(GRPC_COMPRESS_LEVEL_NONE);
}
}
if (!CheckExpectedCompression(*context,
request->expect_compressed().value())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Compressed request expectation not met.");
}
if (request->response_size() > 0) {
if (!SetPayload(request->response_size(), response->mutable_payload())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Error creating payload.");
}
}
if (request->has_response_status()) {
return Status(
static_cast<grpc::StatusCode>(request->response_status().code()),
request->response_status().message());
}
return Status::OK;
}
Status StreamingOutputCall(
ServerContext* context, const StreamingOutputCallRequest* request,
ServerWriter<StreamingOutputCallResponse>* writer) {
StreamingOutputCallResponse response;
bool write_success = true;
for (int i = 0; write_success && i < request->response_parameters_size();
i++) {
if (!SetPayload(request->response_parameters(i).size(),
response.mutable_payload())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Error creating payload.");
}
WriteOptions wopts;
if (request->response_parameters(i).has_compressed()) {
// Compress by default. Disabled on a per-message basis.
context->set_compression_level(GRPC_COMPRESS_LEVEL_HIGH);
const bool compression_requested =
request->response_parameters(i).compressed().value();
gpr_log(GPR_DEBUG, "Request for compression (%s) present for %s",
compression_requested ? "enabled" : "disabled", __func__);
if (!compression_requested) {
wopts.set_no_compression();
} // else, compression is already enabled via the context.
}
int time_us;
if ((time_us = request->response_parameters(i).interval_us()) > 0) {
// Sleep before response if needed
gpr_timespec sleep_time =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(time_us, GPR_TIMESPAN));
gpr_sleep_until(sleep_time);
}
write_success = writer->Write(response, wopts);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status StreamingInputCall(ServerContext* context,
ServerReader<StreamingInputCallRequest>* reader,
StreamingInputCallResponse* response) {
StreamingInputCallRequest request;
int aggregated_payload_size = 0;
while (reader->Read(&request)) {
if (!CheckExpectedCompression(*context,
request.expect_compressed().value())) {
return Status(grpc::StatusCode::INVALID_ARGUMENT,
"Compressed request expectation not met.");
}
if (request.has_payload()) {
aggregated_payload_size += request.payload().body().size();
}
}
response->set_aggregated_payload_size(aggregated_payload_size);
return Status::OK;
}
Status FullDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
MaybeEchoMetadata(context);
StreamingOutputCallRequest request;
StreamingOutputCallResponse response;
bool write_success = true;
while (write_success && stream->Read(&request)) {
if (request.has_response_status()) {
return Status(
static_cast<grpc::StatusCode>(request.response_status().code()),
request.response_status().message());
}
if (request.response_parameters_size() != 0) {
response.mutable_payload()->set_type(request.payload().type());
response.mutable_payload()->set_body(
grpc::string(request.response_parameters(0).size(), '\0'));
int time_us;
if ((time_us = request.response_parameters(0).interval_us()) > 0) {
// Sleep before response if needed
gpr_timespec sleep_time =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_micros(time_us, GPR_TIMESPAN));
gpr_sleep_until(sleep_time);
}
write_success = stream->Write(response);
}
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
Status HalfDuplexCall(
ServerContext* context,
ServerReaderWriter<StreamingOutputCallResponse,
StreamingOutputCallRequest>* stream) {
std::vector<StreamingOutputCallRequest> requests;
StreamingOutputCallRequest request;
while (stream->Read(&request)) {
requests.push_back(request);
}
StreamingOutputCallResponse response;
bool write_success = true;
for (unsigned int i = 0; write_success && i < requests.size(); i++) {
response.mutable_payload()->set_type(requests[i].payload().type());
if (requests[i].response_parameters_size() == 0) {
return Status(grpc::StatusCode::INTERNAL,
"Request does not have response parameters.");
}
response.mutable_payload()->set_body(
grpc::string(requests[i].response_parameters(0).size(), '\0'));
write_success = stream->Write(response);
}
if (write_success) {
return Status::OK;
} else {
return Status(grpc::StatusCode::INTERNAL, "Error writing response.");
}
}
};
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds) {
RunServer(creds, FLAGS_port, nullptr, nullptr);
}
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds,
std::unique_ptr<std::vector<std::unique_ptr<ServerBuilderOption>>>
server_options) {
RunServer(creds, FLAGS_port, nullptr, std::move(server_options));
}
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds, const int port,
ServerStartedCondition* server_started_condition) {
RunServer(creds, port, server_started_condition, nullptr);
}
void grpc::testing::interop::RunServer(
std::shared_ptr<ServerCredentials> creds, const int port,
ServerStartedCondition* server_started_condition,
std::unique_ptr<std::vector<std::unique_ptr<ServerBuilderOption>>>
server_options) {
GPR_ASSERT(port != 0);
std::ostringstream server_address;
server_address << "0.0.0.0:" << port;
TestServiceImpl service;
SimpleRequest request;
SimpleResponse response;
ServerBuilder builder;
builder.RegisterService(&service);
builder.AddListeningPort(server_address.str(), creds);
if (server_options != nullptr) {
for (size_t i = 0; i < server_options->size(); i++) {
builder.SetOption(std::move((*server_options)[i]));
}
}
if (FLAGS_max_send_message_size >= 0) {
builder.SetMaxSendMessageSize(FLAGS_max_send_message_size);
}
std::unique_ptr<Server> server(builder.BuildAndStart());
gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str());
// Signal that the server has started.
if (server_started_condition) {
std::unique_lock<std::mutex> lock(server_started_condition->mutex);
server_started_condition->server_started = true;
server_started_condition->condition.notify_all();
}
while (!gpr_atm_no_barrier_load(&g_got_sigint)) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_seconds(5, GPR_TIMESPAN)));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 <unistd.h>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <random>
#include <thread>
#include "gtest/gtest.h"
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/trace_config.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/base/test/test_task_runner.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "src/tracing/ipc/default_socket.h"
#include "test/task_runner_thread.h"
#include "test/task_runner_thread_delegates.h"
#include "test/test_helper.h"
#include "perfetto/trace/trace_packet.pb.h"
#include "perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
class PerfettoTest : public ::testing::Test {
public:
void SetUp() override {
// TODO(primiano): refactor this, it's copy/pasted in three places now.
size_t index = 0;
constexpr auto kTracingPaths = FtraceController::kTracingPaths;
while (!ftrace_procfs_ && kTracingPaths[index]) {
ftrace_procfs_ = FtraceProcfs::Create(kTracingPaths[index++]);
}
if (!ftrace_procfs_)
return;
ftrace_procfs_->SetTracingOn(false);
}
void TearDown() override {
if (ftrace_procfs_)
ftrace_procfs_->SetTracingOn(false);
}
std::unique_ptr<FtraceProcfs> ftrace_procfs_;
};
} // namespace
// If we're building on Android and starting the daemons ourselves,
// create the sockets in a world-writable location.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && \
PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
#define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer"
#else
#define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket()
#endif
// TODO(b/73453011): reenable on more platforms (including standalone Android).
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
#define TreeHuggerOnly(x) x
#else
#define TreeHuggerOnly(x) DISABLED_##x
#endif
TEST_F(PerfettoTest, TreeHuggerOnly(TestFtraceProducer)) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
TaskRunnerThread producer_thread("perfetto.prd");
producer_thread.Start(std::unique_ptr<ProbesProducerDelegate>(
new ProbesProducerDelegate(TEST_PRODUCER_SOCK_NAME)));
#endif
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(1024);
trace_config.set_duration_ms(3000);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("linux.ftrace");
ds_config->set_target_buffer(0);
auto* ftrace_config = ds_config->mutable_ftrace_config();
*ftrace_config->add_ftrace_events() = "sched_switch";
*ftrace_config->add_ftrace_events() = "bar";
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_GT(packets.size(), 0u);
for (const auto& packet : packets) {
for (int ev = 0; ev < packet.ftrace_events().event_size(); ev++) {
ASSERT_TRUE(packet.ftrace_events().event(ev).has_sched_switch());
}
}
}
TEST_F(PerfettoTest, TreeHuggerOnly(TestFtraceFlush)) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
TaskRunnerThread producer_thread("perfetto.prd");
producer_thread.Start(std::unique_ptr<ProbesProducerDelegate>(
new ProbesProducerDelegate(TEST_PRODUCER_SOCK_NAME)));
#endif
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
const uint32_t kTestTimeoutMs = 30000;
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(16);
trace_config.set_duration_ms(kTestTimeoutMs);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("linux.ftrace");
auto* ftrace_config = ds_config->mutable_ftrace_config();
*ftrace_config->add_ftrace_events() = "print";
helper.StartTracing(trace_config);
// Do a first flush just to synchronize with the producer. The problem here
// is that, on a Linux workstation, the producer can take several seconds just
// to get to the point where ftrace is ready. We use the flush ack as a
// synchronization point.
helper.FlushAndWait(kTestTimeoutMs);
EXPECT_TRUE(ftrace_procfs_->IsTracingEnabled());
const char kMarker[] = "just_one_event";
EXPECT_TRUE(ftrace_procfs_->WriteTraceMarker(kMarker));
// This is the real flush we are testing.
helper.FlushAndWait(kTestTimeoutMs);
helper.DisableTracing();
helper.WaitForTracingDisabled(kTestTimeoutMs);
helper.ReadData();
helper.WaitForReadData();
int marker_found = 0;
for (const auto& packet : helper.trace()) {
for (int i = 0; i < packet.ftrace_events().event_size(); i++) {
const auto& ev = packet.ftrace_events().event(i);
if (ev.has_print() && ev.print().buf().find(kMarker) != std::string::npos)
marker_found++;
}
}
ASSERT_EQ(marker_found, 1);
}
TEST_F(PerfettoTest, TreeHuggerOnly(TestBatteryTracing)) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
TaskRunnerThread producer_thread("perfetto.prd");
producer_thread.Start(std::unique_ptr<ProbesProducerDelegate>(
new ProbesProducerDelegate(TEST_PRODUCER_SOCK_NAME)));
#else
base::ignore_result(TEST_PRODUCER_SOCK_NAME);
#endif
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(128);
trace_config.set_duration_ms(3000);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.power");
ds_config->set_target_buffer(0);
auto* power_config = ds_config->mutable_android_power_config();
power_config->set_battery_poll_ms(250);
*power_config->add_battery_counters() =
AndroidPowerConfig::BATTERY_COUNTER_CHARGE;
*power_config->add_battery_counters() =
AndroidPowerConfig::BATTERY_COUNTER_CAPACITY_PERCENT;
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_GT(packets.size(), 0u);
bool has_battery_packet = false;
for (const auto& packet : packets) {
if (!packet.has_battery())
continue;
has_battery_packet = true;
EXPECT_GE(packet.battery().charge_counter_uah(), 0);
EXPECT_GE(packet.battery().capacity_percent(), 0);
EXPECT_LE(packet.battery().capacity_percent(), 100);
}
ASSERT_TRUE(has_battery_packet);
}
TEST_F(PerfettoTest, TestFakeProducer) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(1024);
trace_config.set_duration_ms(200);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
static constexpr size_t kNumPackets = 10;
static constexpr uint32_t kRandomSeed = 42;
static constexpr uint32_t kMsgSize = 1024;
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(kNumPackets);
ds_config->mutable_for_testing()->set_message_size(kMsgSize);
ds_config->mutable_for_testing()->set_send_batch_on_register(true);
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_EQ(packets.size(), kNumPackets);
std::minstd_rand0 rnd_engine(kRandomSeed);
for (const auto& packet : packets) {
ASSERT_TRUE(packet.has_for_testing());
ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
}
}
TEST_F(PerfettoTest, VeryLargePackets) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(4096 * 10);
trace_config.set_duration_ms(500);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
static constexpr size_t kNumPackets = 5;
static constexpr uint32_t kRandomSeed = 42;
static constexpr uint32_t kMsgSize = 1024 * 1024 - 42;
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(kNumPackets);
ds_config->mutable_for_testing()->set_message_size(kMsgSize);
ds_config->mutable_for_testing()->set_send_batch_on_register(true);
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_EQ(packets.size(), kNumPackets);
std::minstd_rand0 rnd_engine(kRandomSeed);
for (const auto& packet : packets) {
ASSERT_TRUE(packet.has_for_testing());
ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
size_t msg_size = packet.for_testing().str().size();
ASSERT_EQ(kMsgSize, msg_size);
for (size_t i = 0; i < msg_size; i++)
ASSERT_EQ(i < msg_size - 1 ? '.' : 0, packet.for_testing().str()[i]);
}
}
} // namespace perfetto
<commit_msg>Remove charge counter assertions in tests am: 61804c04b3 am: 6cc6a48c42<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 <unistd.h>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <random>
#include <thread>
#include "gtest/gtest.h"
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/trace_config.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/base/test/test_task_runner.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "src/tracing/ipc/default_socket.h"
#include "test/task_runner_thread.h"
#include "test/task_runner_thread_delegates.h"
#include "test/test_helper.h"
#include "perfetto/trace/trace_packet.pb.h"
#include "perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
class PerfettoTest : public ::testing::Test {
public:
void SetUp() override {
// TODO(primiano): refactor this, it's copy/pasted in three places now.
size_t index = 0;
constexpr auto kTracingPaths = FtraceController::kTracingPaths;
while (!ftrace_procfs_ && kTracingPaths[index]) {
ftrace_procfs_ = FtraceProcfs::Create(kTracingPaths[index++]);
}
if (!ftrace_procfs_)
return;
ftrace_procfs_->SetTracingOn(false);
}
void TearDown() override {
if (ftrace_procfs_)
ftrace_procfs_->SetTracingOn(false);
}
std::unique_ptr<FtraceProcfs> ftrace_procfs_;
};
} // namespace
// If we're building on Android and starting the daemons ourselves,
// create the sockets in a world-writable location.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && \
PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
#define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer"
#else
#define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket()
#endif
// TODO(b/73453011): reenable on more platforms (including standalone Android).
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
#define TreeHuggerOnly(x) x
#else
#define TreeHuggerOnly(x) DISABLED_##x
#endif
TEST_F(PerfettoTest, TreeHuggerOnly(TestFtraceProducer)) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
TaskRunnerThread producer_thread("perfetto.prd");
producer_thread.Start(std::unique_ptr<ProbesProducerDelegate>(
new ProbesProducerDelegate(TEST_PRODUCER_SOCK_NAME)));
#endif
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(1024);
trace_config.set_duration_ms(3000);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("linux.ftrace");
ds_config->set_target_buffer(0);
auto* ftrace_config = ds_config->mutable_ftrace_config();
*ftrace_config->add_ftrace_events() = "sched_switch";
*ftrace_config->add_ftrace_events() = "bar";
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_GT(packets.size(), 0u);
for (const auto& packet : packets) {
for (int ev = 0; ev < packet.ftrace_events().event_size(); ev++) {
ASSERT_TRUE(packet.ftrace_events().event(ev).has_sched_switch());
}
}
}
TEST_F(PerfettoTest, TreeHuggerOnly(TestFtraceFlush)) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
TaskRunnerThread producer_thread("perfetto.prd");
producer_thread.Start(std::unique_ptr<ProbesProducerDelegate>(
new ProbesProducerDelegate(TEST_PRODUCER_SOCK_NAME)));
#endif
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
const uint32_t kTestTimeoutMs = 30000;
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(16);
trace_config.set_duration_ms(kTestTimeoutMs);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("linux.ftrace");
auto* ftrace_config = ds_config->mutable_ftrace_config();
*ftrace_config->add_ftrace_events() = "print";
helper.StartTracing(trace_config);
// Do a first flush just to synchronize with the producer. The problem here
// is that, on a Linux workstation, the producer can take several seconds just
// to get to the point where ftrace is ready. We use the flush ack as a
// synchronization point.
helper.FlushAndWait(kTestTimeoutMs);
EXPECT_TRUE(ftrace_procfs_->IsTracingEnabled());
const char kMarker[] = "just_one_event";
EXPECT_TRUE(ftrace_procfs_->WriteTraceMarker(kMarker));
// This is the real flush we are testing.
helper.FlushAndWait(kTestTimeoutMs);
helper.DisableTracing();
helper.WaitForTracingDisabled(kTestTimeoutMs);
helper.ReadData();
helper.WaitForReadData();
int marker_found = 0;
for (const auto& packet : helper.trace()) {
for (int i = 0; i < packet.ftrace_events().event_size(); i++) {
const auto& ev = packet.ftrace_events().event(i);
if (ev.has_print() && ev.print().buf().find(kMarker) != std::string::npos)
marker_found++;
}
}
ASSERT_EQ(marker_found, 1);
}
TEST_F(PerfettoTest, TreeHuggerOnly(TestBatteryTracing)) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
TaskRunnerThread producer_thread("perfetto.prd");
producer_thread.Start(std::unique_ptr<ProbesProducerDelegate>(
new ProbesProducerDelegate(TEST_PRODUCER_SOCK_NAME)));
#else
base::ignore_result(TEST_PRODUCER_SOCK_NAME);
#endif
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(128);
trace_config.set_duration_ms(3000);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.power");
ds_config->set_target_buffer(0);
auto* power_config = ds_config->mutable_android_power_config();
power_config->set_battery_poll_ms(250);
*power_config->add_battery_counters() =
AndroidPowerConfig::BATTERY_COUNTER_CHARGE;
*power_config->add_battery_counters() =
AndroidPowerConfig::BATTERY_COUNTER_CAPACITY_PERCENT;
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_GT(packets.size(), 0u);
bool has_battery_packet = false;
for (const auto& packet : packets) {
if (!packet.has_battery())
continue;
has_battery_packet = true;
// Unfortunately we cannot make any assertions on the charge counter.
// On some devices it can reach negative values (b/64685329).
EXPECT_GE(packet.battery().capacity_percent(), 0);
EXPECT_LE(packet.battery().capacity_percent(), 100);
}
ASSERT_TRUE(has_battery_packet);
}
TEST_F(PerfettoTest, TestFakeProducer) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(1024);
trace_config.set_duration_ms(200);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
static constexpr size_t kNumPackets = 10;
static constexpr uint32_t kRandomSeed = 42;
static constexpr uint32_t kMsgSize = 1024;
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(kNumPackets);
ds_config->mutable_for_testing()->set_message_size(kMsgSize);
ds_config->mutable_for_testing()->set_send_batch_on_register(true);
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_EQ(packets.size(), kNumPackets);
std::minstd_rand0 rnd_engine(kRandomSeed);
for (const auto& packet : packets) {
ASSERT_TRUE(packet.has_for_testing());
ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
}
}
TEST_F(PerfettoTest, VeryLargePackets) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(4096 * 10);
trace_config.set_duration_ms(500);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
static constexpr size_t kNumPackets = 5;
static constexpr uint32_t kRandomSeed = 42;
static constexpr uint32_t kMsgSize = 1024 * 1024 - 42;
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(kNumPackets);
ds_config->mutable_for_testing()->set_message_size(kMsgSize);
ds_config->mutable_for_testing()->set_send_batch_on_register(true);
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled();
helper.ReadData();
helper.WaitForReadData();
const auto& packets = helper.trace();
ASSERT_EQ(packets.size(), kNumPackets);
std::minstd_rand0 rnd_engine(kRandomSeed);
for (const auto& packet : packets) {
ASSERT_TRUE(packet.has_for_testing());
ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
size_t msg_size = packet.for_testing().str().size();
ASSERT_EQ(kMsgSize, msg_size);
for (size_t i = 0; i < msg_size; i++)
ASSERT_EQ(i < msg_size - 1 ? '.' : 0, packet.for_testing().str()[i]);
}
}
} // namespace perfetto
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/core/distributed.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/print.hh>
#include <seastar/util/defer.hh>
#include <seastar/util/closeable.hh>
#include <seastar/util/later.hh>
#include <mutex>
using namespace seastar;
using namespace std::chrono_literals;
struct async_service : public seastar::async_sharded_service<async_service> {
thread_local static bool deleted;
~async_service() {
deleted = true;
}
void run() {
auto ref = shared_from_this();
// Wait a while and check.
(void)sleep(std::chrono::milliseconds(100 + 100 * this_shard_id())).then([this, ref] {
check();
});
}
virtual void check() {
assert(!deleted);
}
future<> stop() { return make_ready_future<>(); }
};
thread_local bool async_service::deleted = false;
struct X {
sstring echo(sstring arg) {
return arg;
}
int cpu_id_squared() const {
auto id = this_shard_id();
return id * id;
}
future<> stop() { return make_ready_future<>(); }
};
template <typename T, typename Func>
future<> do_with_distributed(Func&& func) {
auto x = make_shared<distributed<T>>();
return func(*x).finally([x] {
return x->stop();
}).finally([x]{});
}
SEASTAR_TEST_CASE(test_that_each_core_gets_the_arguments) {
return do_with_distributed<X>([] (auto& x) {
return x.start().then([&x] {
return x.map_reduce([] (sstring msg){
if (msg != "hello") {
throw std::runtime_error("wrong message");
}
}, &X::echo, sstring("hello"));
});
});
}
SEASTAR_TEST_CASE(test_functor_version) {
return do_with_distributed<X>([] (auto& x) {
return x.start().then([&x] {
return x.map_reduce([] (sstring msg){
if (msg != "hello") {
throw std::runtime_error("wrong message");
}
}, [] (X& x) { return x.echo("hello"); });
});
});
}
struct Y {
sstring s;
Y(sstring s) : s(std::move(s)) {}
future<> stop() { return make_ready_future<>(); }
};
SEASTAR_TEST_CASE(test_constructor_argument_is_passed_to_each_core) {
return do_with_distributed<Y>([] (auto& y) {
return y.start(sstring("hello")).then([&y] {
return y.invoke_on_all([] (Y& y) {
if (y.s != "hello") {
throw std::runtime_error(format("expected message mismatch, is \"%s\"", y.s));
}
});
});
});
}
SEASTAR_TEST_CASE(test_map_reduce) {
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return x.map_reduce0(std::mem_fn(&X::cpu_id_squared),
0,
std::plus<int>()).then([] (int result) {
int n = smp::count - 1;
if (result != (n * (n + 1) * (2*n + 1)) / 6) {
throw std::runtime_error("map_reduce failed");
}
});
});
});
}
SEASTAR_TEST_CASE(test_map_reduce_lifetime) {
struct map {
bool destroyed = false;
~map() {
destroyed = true;
}
auto operator()(const X& x) {
return yield().then([this, &x] {
BOOST_REQUIRE(!destroyed);
return x.cpu_id_squared();
});
}
};
struct reduce {
long& res;
bool destroyed = false;
~reduce() {
destroyed = true;
}
auto operator()(int x) {
return yield().then([this, x] {
BOOST_REQUIRE(!destroyed);
res += x;
});
}
};
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return do_with(0L, [&x] (auto& result) {
return x.map_reduce(reduce{result}, map{}).then([&result] {
long n = smp::count - 1;
long expected = (n * (n + 1) * (2*n + 1)) / 6;
BOOST_REQUIRE_EQUAL(result, expected);
});
});
});
});
}
SEASTAR_TEST_CASE(test_map_reduce0_lifetime) {
struct map {
bool destroyed = false;
~map() {
destroyed = true;
}
auto operator()(const X& x) const {
return yield().then([this, &x] {
BOOST_REQUIRE(!destroyed);
return x.cpu_id_squared();
});
}
};
struct reduce {
bool destroyed = false;
~reduce() {
destroyed = true;
}
auto operator()(long res, int x) {
BOOST_REQUIRE(!destroyed);
return res + x;
}
};
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return x.map_reduce0(map{}, 0L, reduce{}).then([] (long result) {
long n = smp::count - 1;
long expected = (n * (n + 1) * (2*n + 1)) / 6;
BOOST_REQUIRE_EQUAL(result, expected);
});
});
});
}
SEASTAR_TEST_CASE(test_async) {
return do_with_distributed<async_service>([] (distributed<async_service>& x) {
return x.start().then([&x] {
return x.invoke_on_all(&async_service::run);
});
}).then([] {
return sleep(std::chrono::milliseconds(100 * (smp::count + 1)));
});
}
SEASTAR_TEST_CASE(test_invoke_on_others) {
return seastar::async([] {
struct my_service {
int counter = 0;
void up() { ++counter; }
future<> stop() { return make_ready_future<>(); }
};
for (unsigned c = 0; c < smp::count; ++c) {
smp::submit_to(c, [c] {
return seastar::async([c] {
sharded<my_service> s;
s.start().get();
s.invoke_on_others([](auto& s) { s.up(); }).get();
if (s.local().counter != 0) {
throw std::runtime_error("local modified");
}
s.invoke_on_all([c](auto& remote) {
if (this_shard_id() != c) {
if (remote.counter != 1) {
throw std::runtime_error("remote not modified");
}
}
}).get();
s.stop().get();
});
}).get();
}
});
}
SEASTAR_TEST_CASE(test_smp_invoke_on_others) {
return seastar::async([] {
std::vector<std::vector<int>> calls;
calls.reserve(smp::count);
for (unsigned i = 0; i < smp::count; i++) {
auto& sv = calls.emplace_back();
sv.reserve(smp::count);
}
smp::invoke_on_all([&calls] {
return smp::invoke_on_others([&calls, from = this_shard_id()] {
calls[this_shard_id()].emplace_back(from);
});
}).get();
for (unsigned i = 0; i < smp::count; i++) {
BOOST_REQUIRE_EQUAL(calls[i].size(), smp::count - 1);
for (unsigned f = 0; f < smp::count; f++) {
auto r = std::find(calls[i].begin(), calls[i].end(), f);
BOOST_REQUIRE_EQUAL(r == calls[i].end(), i == f);
}
}
});
}
struct remote_worker {
unsigned current = 0;
unsigned max_concurrent_observed = 0;
unsigned expected_max;
semaphore sem{0};
remote_worker(unsigned expected_max) : expected_max(expected_max) {
}
future<> do_work() {
++current;
max_concurrent_observed = std::max(current, max_concurrent_observed);
if (max_concurrent_observed >= expected_max && sem.current() == 0) {
sem.signal(semaphore::max_counter());
}
return sem.wait().then([this] {
// Sleep a bit to check if the concurrency goes over the max
return sleep(100ms).then([this] {
max_concurrent_observed = std::max(current, max_concurrent_observed);
--current;
});
});
}
future<> do_remote_work(shard_id t, smp_service_group ssg) {
return smp::submit_to(t, ssg, [this] {
return do_work();
});
}
};
SEASTAR_TEST_CASE(test_smp_service_groups) {
return async([] {
smp_service_group_config ssgc1;
ssgc1.max_nonlocal_requests = 1;
auto ssg1 = create_smp_service_group(ssgc1).get0();
smp_service_group_config ssgc2;
ssgc2.max_nonlocal_requests = 1000;
auto ssg2 = create_smp_service_group(ssgc2).get0();
shard_id other_shard = smp::count - 1;
remote_worker rm1(1);
remote_worker rm2(1000);
auto bunch1 = parallel_for_each(boost::irange(0, 20), [&] (int ignore) { return rm1.do_remote_work(other_shard, ssg1); });
auto bunch2 = parallel_for_each(boost::irange(0, 2000), [&] (int ignore) { return rm2.do_remote_work(other_shard, ssg2); });
bunch1.get();
bunch2.get();
if (smp::count > 1) {
assert(rm1.max_concurrent_observed == 1);
assert(rm2.max_concurrent_observed == 1000);
}
destroy_smp_service_group(ssg1).get();
destroy_smp_service_group(ssg2).get();
});
}
SEASTAR_TEST_CASE(test_smp_service_groups_re_construction) {
// During development of the feature, we saw a bug where the vector
// holding the groups did not expand correctly. This test triggers the
// bug.
return async([] {
auto ssg1 = create_smp_service_group({}).get0();
auto ssg2 = create_smp_service_group({}).get0();
destroy_smp_service_group(ssg1).get();
auto ssg3 = create_smp_service_group({}).get0();
destroy_smp_service_group(ssg2).get();
destroy_smp_service_group(ssg3).get();
});
}
SEASTAR_TEST_CASE(test_smp_timeout) {
return async([] {
smp_service_group_config ssgc1;
ssgc1.max_nonlocal_requests = 1;
auto ssg1 = create_smp_service_group(ssgc1).get0();
auto _ = defer([ssg1] () noexcept {
destroy_smp_service_group(ssg1).get();
});
const shard_id other_shard = smp::count - 1;
// Ugly but beats using sleeps.
std::mutex mut;
std::unique_lock<std::mutex> lk(mut);
// Submitted to the remote shard.
auto fut1 = smp::submit_to(other_shard, ssg1, [&mut] {
std::cout << "Running request no. 1" << std::endl;
std::unique_lock<std::mutex> lk(mut);
std::cout << "Request no. 1 done" << std::endl;
});
// Consume the only unit from the semaphore.
auto fut2 = smp::submit_to(other_shard, ssg1, [] {
std::cout << "Running request no. 2 - done" << std::endl;
});
auto fut_timedout = smp::submit_to(other_shard, smp_submit_to_options(ssg1, smp_timeout_clock::now() + 10ms), [] {
std::cout << "Running timed-out request - done" << std::endl;
});
{
auto notify = defer([lk = std::move(lk)] () noexcept { });
try {
fut_timedout.get();
throw std::runtime_error("smp::submit_to() didn't timeout as expected");
} catch (semaphore_timed_out& e) {
std::cout << "Expected timeout received: " << e.what() << std::endl;
} catch (...) {
std::throw_with_nested(std::runtime_error("smp::submit_to() failed with unexpected exception"));
}
}
fut1.get();
fut2.get();
});
}
SEASTAR_THREAD_TEST_CASE(test_sharded_parameter) {
struct dependency {
unsigned val = this_shard_id() * 7;
};
struct some_service {
bool ok = false;
some_service(unsigned non_shard_dependent, unsigned shard_dependent, dependency& dep, unsigned shard_dependent_2) {
ok =
non_shard_dependent == 43
&& shard_dependent == this_shard_id() * 3
&& dep.val == this_shard_id() * 7
&& shard_dependent_2 == -dep.val;
}
};
sharded<dependency> s_dep;
s_dep.start().get();
auto undo1 = deferred_stop(s_dep);
sharded<some_service> s_service;
s_service.start(
43, // should be copied verbatim
sharded_parameter([] { return this_shard_id() * 3; }),
std::ref(s_dep),
sharded_parameter([] (dependency& d) { return -d.val; }, std::ref(s_dep))
).get();
auto undo2 = deferred_stop(s_service);
auto all_ok = s_service.map_reduce0(std::mem_fn(&some_service::ok), true, std::multiplies<>()).get0();
BOOST_REQUIRE(all_ok);
}
<commit_msg>tests: distributed_test: add test_map_lifetime<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/core/distributed.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/print.hh>
#include <seastar/util/defer.hh>
#include <seastar/util/closeable.hh>
#include <seastar/util/later.hh>
#include <mutex>
using namespace seastar;
using namespace std::chrono_literals;
struct async_service : public seastar::async_sharded_service<async_service> {
thread_local static bool deleted;
~async_service() {
deleted = true;
}
void run() {
auto ref = shared_from_this();
// Wait a while and check.
(void)sleep(std::chrono::milliseconds(100 + 100 * this_shard_id())).then([this, ref] {
check();
});
}
virtual void check() {
assert(!deleted);
}
future<> stop() { return make_ready_future<>(); }
};
thread_local bool async_service::deleted = false;
struct X {
sstring echo(sstring arg) {
return arg;
}
int cpu_id_squared() const {
auto id = this_shard_id();
return id * id;
}
future<> stop() { return make_ready_future<>(); }
};
template <typename T, typename Func>
future<> do_with_distributed(Func&& func) {
auto x = make_shared<distributed<T>>();
return func(*x).finally([x] {
return x->stop();
}).finally([x]{});
}
SEASTAR_TEST_CASE(test_that_each_core_gets_the_arguments) {
return do_with_distributed<X>([] (auto& x) {
return x.start().then([&x] {
return x.map_reduce([] (sstring msg){
if (msg != "hello") {
throw std::runtime_error("wrong message");
}
}, &X::echo, sstring("hello"));
});
});
}
SEASTAR_TEST_CASE(test_functor_version) {
return do_with_distributed<X>([] (auto& x) {
return x.start().then([&x] {
return x.map_reduce([] (sstring msg){
if (msg != "hello") {
throw std::runtime_error("wrong message");
}
}, [] (X& x) { return x.echo("hello"); });
});
});
}
struct Y {
sstring s;
Y(sstring s) : s(std::move(s)) {}
future<> stop() { return make_ready_future<>(); }
};
SEASTAR_TEST_CASE(test_constructor_argument_is_passed_to_each_core) {
return do_with_distributed<Y>([] (auto& y) {
return y.start(sstring("hello")).then([&y] {
return y.invoke_on_all([] (Y& y) {
if (y.s != "hello") {
throw std::runtime_error(format("expected message mismatch, is \"%s\"", y.s));
}
});
});
});
}
SEASTAR_TEST_CASE(test_map_reduce) {
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return x.map_reduce0(std::mem_fn(&X::cpu_id_squared),
0,
std::plus<int>()).then([] (int result) {
int n = smp::count - 1;
if (result != (n * (n + 1) * (2*n + 1)) / 6) {
throw std::runtime_error("map_reduce failed");
}
});
});
});
}
SEASTAR_TEST_CASE(test_map_reduce_lifetime) {
struct map {
bool destroyed = false;
~map() {
destroyed = true;
}
auto operator()(const X& x) {
return yield().then([this, &x] {
BOOST_REQUIRE(!destroyed);
return x.cpu_id_squared();
});
}
};
struct reduce {
long& res;
bool destroyed = false;
~reduce() {
destroyed = true;
}
auto operator()(int x) {
return yield().then([this, x] {
BOOST_REQUIRE(!destroyed);
res += x;
});
}
};
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return do_with(0L, [&x] (auto& result) {
return x.map_reduce(reduce{result}, map{}).then([&result] {
long n = smp::count - 1;
long expected = (n * (n + 1) * (2*n + 1)) / 6;
BOOST_REQUIRE_EQUAL(result, expected);
});
});
});
});
}
SEASTAR_TEST_CASE(test_map_reduce0_lifetime) {
struct map {
bool destroyed = false;
~map() {
destroyed = true;
}
auto operator()(const X& x) const {
return yield().then([this, &x] {
BOOST_REQUIRE(!destroyed);
return x.cpu_id_squared();
});
}
};
struct reduce {
bool destroyed = false;
~reduce() {
destroyed = true;
}
auto operator()(long res, int x) {
BOOST_REQUIRE(!destroyed);
return res + x;
}
};
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return x.map_reduce0(map{}, 0L, reduce{}).then([] (long result) {
long n = smp::count - 1;
long expected = (n * (n + 1) * (2*n + 1)) / 6;
BOOST_REQUIRE_EQUAL(result, expected);
});
});
});
}
SEASTAR_TEST_CASE(test_map_lifetime) {
struct map {
bool destroyed = false;
~map() {
destroyed = true;
}
auto operator()(const X& x) const {
return yield().then([this, &x] {
BOOST_REQUIRE(!destroyed);
return x.cpu_id_squared();
});
}
};
return do_with_distributed<X>([] (distributed<X>& x) {
return x.start().then([&x] {
return x.map(map{}).then([] (std::vector<int> result) {
BOOST_REQUIRE_EQUAL(result.size(), smp::count);
for (size_t i = 0; i < (size_t)smp::count; i++) {
BOOST_REQUIRE_EQUAL(result[i], i * i);
}
});
});
});
}
SEASTAR_TEST_CASE(test_async) {
return do_with_distributed<async_service>([] (distributed<async_service>& x) {
return x.start().then([&x] {
return x.invoke_on_all(&async_service::run);
});
}).then([] {
return sleep(std::chrono::milliseconds(100 * (smp::count + 1)));
});
}
SEASTAR_TEST_CASE(test_invoke_on_others) {
return seastar::async([] {
struct my_service {
int counter = 0;
void up() { ++counter; }
future<> stop() { return make_ready_future<>(); }
};
for (unsigned c = 0; c < smp::count; ++c) {
smp::submit_to(c, [c] {
return seastar::async([c] {
sharded<my_service> s;
s.start().get();
s.invoke_on_others([](auto& s) { s.up(); }).get();
if (s.local().counter != 0) {
throw std::runtime_error("local modified");
}
s.invoke_on_all([c](auto& remote) {
if (this_shard_id() != c) {
if (remote.counter != 1) {
throw std::runtime_error("remote not modified");
}
}
}).get();
s.stop().get();
});
}).get();
}
});
}
SEASTAR_TEST_CASE(test_smp_invoke_on_others) {
return seastar::async([] {
std::vector<std::vector<int>> calls;
calls.reserve(smp::count);
for (unsigned i = 0; i < smp::count; i++) {
auto& sv = calls.emplace_back();
sv.reserve(smp::count);
}
smp::invoke_on_all([&calls] {
return smp::invoke_on_others([&calls, from = this_shard_id()] {
calls[this_shard_id()].emplace_back(from);
});
}).get();
for (unsigned i = 0; i < smp::count; i++) {
BOOST_REQUIRE_EQUAL(calls[i].size(), smp::count - 1);
for (unsigned f = 0; f < smp::count; f++) {
auto r = std::find(calls[i].begin(), calls[i].end(), f);
BOOST_REQUIRE_EQUAL(r == calls[i].end(), i == f);
}
}
});
}
struct remote_worker {
unsigned current = 0;
unsigned max_concurrent_observed = 0;
unsigned expected_max;
semaphore sem{0};
remote_worker(unsigned expected_max) : expected_max(expected_max) {
}
future<> do_work() {
++current;
max_concurrent_observed = std::max(current, max_concurrent_observed);
if (max_concurrent_observed >= expected_max && sem.current() == 0) {
sem.signal(semaphore::max_counter());
}
return sem.wait().then([this] {
// Sleep a bit to check if the concurrency goes over the max
return sleep(100ms).then([this] {
max_concurrent_observed = std::max(current, max_concurrent_observed);
--current;
});
});
}
future<> do_remote_work(shard_id t, smp_service_group ssg) {
return smp::submit_to(t, ssg, [this] {
return do_work();
});
}
};
SEASTAR_TEST_CASE(test_smp_service_groups) {
return async([] {
smp_service_group_config ssgc1;
ssgc1.max_nonlocal_requests = 1;
auto ssg1 = create_smp_service_group(ssgc1).get0();
smp_service_group_config ssgc2;
ssgc2.max_nonlocal_requests = 1000;
auto ssg2 = create_smp_service_group(ssgc2).get0();
shard_id other_shard = smp::count - 1;
remote_worker rm1(1);
remote_worker rm2(1000);
auto bunch1 = parallel_for_each(boost::irange(0, 20), [&] (int ignore) { return rm1.do_remote_work(other_shard, ssg1); });
auto bunch2 = parallel_for_each(boost::irange(0, 2000), [&] (int ignore) { return rm2.do_remote_work(other_shard, ssg2); });
bunch1.get();
bunch2.get();
if (smp::count > 1) {
assert(rm1.max_concurrent_observed == 1);
assert(rm2.max_concurrent_observed == 1000);
}
destroy_smp_service_group(ssg1).get();
destroy_smp_service_group(ssg2).get();
});
}
SEASTAR_TEST_CASE(test_smp_service_groups_re_construction) {
// During development of the feature, we saw a bug where the vector
// holding the groups did not expand correctly. This test triggers the
// bug.
return async([] {
auto ssg1 = create_smp_service_group({}).get0();
auto ssg2 = create_smp_service_group({}).get0();
destroy_smp_service_group(ssg1).get();
auto ssg3 = create_smp_service_group({}).get0();
destroy_smp_service_group(ssg2).get();
destroy_smp_service_group(ssg3).get();
});
}
SEASTAR_TEST_CASE(test_smp_timeout) {
return async([] {
smp_service_group_config ssgc1;
ssgc1.max_nonlocal_requests = 1;
auto ssg1 = create_smp_service_group(ssgc1).get0();
auto _ = defer([ssg1] () noexcept {
destroy_smp_service_group(ssg1).get();
});
const shard_id other_shard = smp::count - 1;
// Ugly but beats using sleeps.
std::mutex mut;
std::unique_lock<std::mutex> lk(mut);
// Submitted to the remote shard.
auto fut1 = smp::submit_to(other_shard, ssg1, [&mut] {
std::cout << "Running request no. 1" << std::endl;
std::unique_lock<std::mutex> lk(mut);
std::cout << "Request no. 1 done" << std::endl;
});
// Consume the only unit from the semaphore.
auto fut2 = smp::submit_to(other_shard, ssg1, [] {
std::cout << "Running request no. 2 - done" << std::endl;
});
auto fut_timedout = smp::submit_to(other_shard, smp_submit_to_options(ssg1, smp_timeout_clock::now() + 10ms), [] {
std::cout << "Running timed-out request - done" << std::endl;
});
{
auto notify = defer([lk = std::move(lk)] () noexcept { });
try {
fut_timedout.get();
throw std::runtime_error("smp::submit_to() didn't timeout as expected");
} catch (semaphore_timed_out& e) {
std::cout << "Expected timeout received: " << e.what() << std::endl;
} catch (...) {
std::throw_with_nested(std::runtime_error("smp::submit_to() failed with unexpected exception"));
}
}
fut1.get();
fut2.get();
});
}
SEASTAR_THREAD_TEST_CASE(test_sharded_parameter) {
struct dependency {
unsigned val = this_shard_id() * 7;
};
struct some_service {
bool ok = false;
some_service(unsigned non_shard_dependent, unsigned shard_dependent, dependency& dep, unsigned shard_dependent_2) {
ok =
non_shard_dependent == 43
&& shard_dependent == this_shard_id() * 3
&& dep.val == this_shard_id() * 7
&& shard_dependent_2 == -dep.val;
}
};
sharded<dependency> s_dep;
s_dep.start().get();
auto undo1 = deferred_stop(s_dep);
sharded<some_service> s_service;
s_service.start(
43, // should be copied verbatim
sharded_parameter([] { return this_shard_id() * 3; }),
std::ref(s_dep),
sharded_parameter([] (dependency& d) { return -d.val; }, std::ref(s_dep))
).get();
auto undo2 = deferred_stop(s_service);
auto all_ok = s_service.map_reduce0(std::mem_fn(&some_service::ok), true, std::multiplies<>()).get0();
BOOST_REQUIRE(all_ok);
}
<|endoftext|> |
<commit_before>/**
* Self-Organizing Maps on a cluster
* Copyright (C) 2013 Peter Wittek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <cmath>
#include <sstream>
#include <iostream>
#include <fstream>
#include "somoclu.h"
using namespace std;
/** Save a SOM codebook
* @param cbFileName - name of the file to save
* @param codebook - the codebook to save
* @param nSomX - dimensions of SOM map in the x direction
* @param nSomY - dimensions of SOM map in the y direction
* @param nDimensions - dimensions of a data instance
*/
int saveCodebook(char* cbFileName, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions)
{
char temp[80];
cout << " Codebook file = " << cbFileName << endl;
ofstream mapFile2(cbFileName);
cout << " Saving Codebook..." << endl;
if (mapFile2.is_open()) {
for (unsigned int som_y = 0; som_y < nSomY; som_y++) {
for (unsigned int som_x = 0; som_x < nSomX; som_x++) {
for (unsigned int d = 0; d < nDimensions; d++) {
sprintf(temp, "%0.10f", codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]);
mapFile2 << temp << "\t";
}
}
mapFile2 << endl;
}
mapFile2.close();
return 0;
}
else
{
return 1;
}
}
/** Euclidean distance between vec1 and vec2
* @param vec1
* @param vec2
* @param nDimensions
* @return distance
*/
float get_distance(const float* vec1, const float* vec2,
unsigned int nDimensions)
{
float distance = 0.0f;
for (unsigned int d = 0; d < nDimensions; d++)
distance += (vec1[d] - vec2[d]) * (vec1[d] - vec2[d]);
return sqrt(distance);
}
/** Get weight vector from a codebook using x, y index
* @param codebook - the codebook to save
* @param som_y - y coordinate of a node in the map
* @param som_x - x coordinate of a node in the map
* @param nSomX - dimensions of SOM map in the x direction
* @param nSomY - dimensions of SOM map in the y direction
* @param nDimensions - dimensions of a data instance
* @return the weight vector
*/
float* get_wvec(float *codebook, unsigned int som_y, unsigned int som_x,
unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions)
{
float* wvec = new float[nDimensions];
for (unsigned int d = 0; d < nDimensions; d++)
wvec[d] = codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]; /// CAUTION: (y,x) order
return wvec;
}
/** Save u-matrix
* @param fname
* @param codebook - the codebook to save
* @param nSomX - dimensions of SOM map in the x direction
* @param nSomY - dimensions of SOM map in the y direction
* @param nDimensions - dimensions of a data instance
*/
int saveUMat(char* fname, float *codebook, unsigned int nSomX,
unsigned int nSomY, unsigned int nDimensions)
{
unsigned int D = 2;
float min_dist = 1.5f;
FILE* fp = fopen(fname, "wt");
if (fp != 0) {
for (unsigned int som_y1 = 0; som_y1 < nSomY; som_y1++) {
for (unsigned int som_x1 = 0; som_x1 < nSomX; som_x1++) {
float dist = 0.0f;
unsigned int nodes_number = 0;
int coords1[2];
coords1[0] = som_x1;
coords1[1] = som_y1;
for (unsigned int som_y2 = 0; som_y2 < nSomY; som_y2++) {
for (unsigned int som_x2 = 0; som_x2 < nSomX; som_x2++) {
unsigned int coords2[2];
coords2[0] = som_x2;
coords2[1] = som_y2;
if (som_x1 == som_x2 && som_y1 == som_y2) continue;
float tmp = 0.0;
for (unsigned int d = 0; d < D; d++) {
tmp += pow(coords1[d] - coords2[d], 2.0f);
}
tmp = sqrt(tmp);
if (tmp <= min_dist) {
nodes_number++;
float* vec1 = get_wvec(codebook, som_y1, som_x1, nSomX, nSomY, nDimensions);
float* vec2 = get_wvec(codebook, som_y2, som_x2, nSomX, nSomY, nDimensions);
dist += get_distance(vec1, vec2, nDimensions);
delete [] vec1;
delete [] vec2;
}
}
}
dist /= (float)nodes_number;
fprintf(fp, " %f", dist);
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
else
return -2;
}
/** Reads a matrix
* @param inFileNae
* @param nRows - returns the number of rows
* @param nColumns - returns the number of columns
* @return the matrix
*/
float *readMatrix(const char *inFileName, unsigned int &nRows, unsigned int &nColumns)
{
ifstream file;
file.open(inFileName);
string line;
int elements = 0;
float tmp;
while(getline(file,line)){
stringstream linestream(line);
string value;
while(getline(linestream,value,' ')){
//&& EOF != sscanf(str_float, "%f", &tmp)
if(value.length()>0){
istringstream myStream(value);
myStream >> tmp;
if (!myStream.fail()){
elements++;
}
}
}
if (nRows==0){
nColumns=elements;
}
nRows++;
}
float *data=new float[elements];
file.close();file.open(inFileName);
int j=0;
while(getline(file,line)){
stringstream linestream(line);
string value;
while(getline(linestream,value,' ')){
if (value.length()>0){
istringstream myStream(value);
myStream >> tmp;
if (!myStream.fail()){
data[j++]=tmp;
}
}
}
}
file.close();
return data;
}
void readSparseMatrixDimensions(const char *filename, unsigned int &nRows,
unsigned int &nColumns) {
ifstream file;
file.open(filename);
string line;
int max_index=-1;
while(getline(file,line)) {
stringstream linestream(line);
string value;
int dummy_index;
while(getline(linestream,value,' ')) {
int separator=value.find(":");
istringstream myStream(value.substr(0,separator));
myStream >> dummy_index;
if(dummy_index > max_index){
max_index = dummy_index;
}
}
++nRows;
}
nColumns=max_index+1;
file.close();
}
svm_node** readSparseMatrixChunk(const char *filename, unsigned int nRows,
unsigned int nRowsToRead,
unsigned int rowOffset) {
ifstream file;
file.open(filename);
string line;
for (unsigned int i=0; i<rowOffset; i++) {
getline(file, line);
}
/* while(getline(file,line)) {
stringstream linestream(line);
string value;
while(getline(linestream,value,' ')) {
elements++;
}
elements++; // To account for the dummy row-closing element
++nRows;
}
file.close();file.open(filename);*/
if (rowOffset+nRowsToRead >= nRows) {
nRowsToRead = nRows-rowOffset;
}
svm_node **x_matrix = new svm_node *[nRowsToRead];
for(unsigned int i=0;i<nRowsToRead;i++) {
getline(file, line);
stringstream tmplinestream(line);
string value;
int elements = 0;
while(getline(tmplinestream,value,' ')) {
elements++;
}
elements++; // To account for the closing dummy node in the row
x_matrix[i] = new svm_node[elements];
stringstream linestream(line);
int j=0;
while(getline(linestream,value,' ')) {
int separator=value.find(":");
istringstream myStream(value.substr(0,separator));
myStream >> x_matrix[i][j].index;
istringstream myStream2(value.substr(separator+1));
myStream2 >> x_matrix[i][j].value;
j++;
}
x_matrix[i][j].index = -1;
}
file.close();
return x_matrix;
}
<commit_msg>Codebook saving function fixed<commit_after>/**
* Self-Organizing Maps on a cluster
* Copyright (C) 2013 Peter Wittek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <cmath>
#include <sstream>
#include <iostream>
#include <fstream>
#include "somoclu.h"
using namespace std;
/** Save a SOM codebook
* @param cbFileName - name of the file to save
* @param codebook - the codebook to save
* @param nSomX - dimensions of SOM map in the x direction
* @param nSomY - dimensions of SOM map in the y direction
* @param nDimensions - dimensions of a data instance
*/
int saveCodebook(char* cbFileName, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions)
{
char temp[80];
cout << " Codebook file = " << cbFileName << endl;
ofstream mapFile(cbFileName);
cout << " Saving Codebook..." << endl;
if (mapFile.is_open()) {
for (unsigned int som_y = 0; som_y < nSomY; som_y++) {
for (unsigned int som_x = 0; som_x < nSomX; som_x++) {
for (unsigned int d = 0; d < nDimensions; d++) {
sprintf(temp, "%0.10f", codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]);
mapFile << temp << " ";
}
}
mapFile << endl;
}
mapFile.close();
return 0;
}
else
{
return 1;
}
}
/** Euclidean distance between vec1 and vec2
* @param vec1
* @param vec2
* @param nDimensions
* @return distance
*/
float get_distance(const float* vec1, const float* vec2,
unsigned int nDimensions)
{
float distance = 0.0f;
for (unsigned int d = 0; d < nDimensions; d++)
distance += (vec1[d] - vec2[d]) * (vec1[d] - vec2[d]);
return sqrt(distance);
}
/** Get weight vector from a codebook using x, y index
* @param codebook - the codebook to save
* @param som_y - y coordinate of a node in the map
* @param som_x - x coordinate of a node in the map
* @param nSomX - dimensions of SOM map in the x direction
* @param nSomY - dimensions of SOM map in the y direction
* @param nDimensions - dimensions of a data instance
* @return the weight vector
*/
float* get_wvec(float *codebook, unsigned int som_y, unsigned int som_x,
unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions)
{
float* wvec = new float[nDimensions];
for (unsigned int d = 0; d < nDimensions; d++)
wvec[d] = codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]; /// CAUTION: (y,x) order
return wvec;
}
/** Save u-matrix
* @param fname
* @param codebook - the codebook to save
* @param nSomX - dimensions of SOM map in the x direction
* @param nSomY - dimensions of SOM map in the y direction
* @param nDimensions - dimensions of a data instance
*/
int saveUMat(char* fname, float *codebook, unsigned int nSomX,
unsigned int nSomY, unsigned int nDimensions)
{
unsigned int D = 2;
float min_dist = 1.5f;
FILE* fp = fopen(fname, "wt");
if (fp != 0) {
for (unsigned int som_y1 = 0; som_y1 < nSomY; som_y1++) {
for (unsigned int som_x1 = 0; som_x1 < nSomX; som_x1++) {
float dist = 0.0f;
unsigned int nodes_number = 0;
int coords1[2];
coords1[0] = som_x1;
coords1[1] = som_y1;
for (unsigned int som_y2 = 0; som_y2 < nSomY; som_y2++) {
for (unsigned int som_x2 = 0; som_x2 < nSomX; som_x2++) {
unsigned int coords2[2];
coords2[0] = som_x2;
coords2[1] = som_y2;
if (som_x1 == som_x2 && som_y1 == som_y2) continue;
float tmp = 0.0;
for (unsigned int d = 0; d < D; d++) {
tmp += pow(coords1[d] - coords2[d], 2.0f);
}
tmp = sqrt(tmp);
if (tmp <= min_dist) {
nodes_number++;
float* vec1 = get_wvec(codebook, som_y1, som_x1, nSomX, nSomY, nDimensions);
float* vec2 = get_wvec(codebook, som_y2, som_x2, nSomX, nSomY, nDimensions);
dist += get_distance(vec1, vec2, nDimensions);
delete [] vec1;
delete [] vec2;
}
}
}
dist /= (float)nodes_number;
fprintf(fp, " %f", dist);
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
else
return -2;
}
/** Reads a matrix
* @param inFileNae
* @param nRows - returns the number of rows
* @param nColumns - returns the number of columns
* @return the matrix
*/
float *readMatrix(const char *inFileName, unsigned int &nRows, unsigned int &nColumns)
{
ifstream file;
file.open(inFileName);
string line;
int elements = 0;
float tmp;
while(getline(file,line)){
stringstream linestream(line);
string value;
while(getline(linestream,value,' ')){
//&& EOF != sscanf(str_float, "%f", &tmp)
if(value.length()>0){
istringstream myStream(value);
myStream >> tmp;
if (!myStream.fail()){
elements++;
}
}
}
if (nRows==0){
nColumns=elements;
}
nRows++;
}
float *data=new float[elements];
file.close();file.open(inFileName);
int j=0;
while(getline(file,line)){
stringstream linestream(line);
string value;
while(getline(linestream,value,' ')){
if (value.length()>0){
istringstream myStream(value);
myStream >> tmp;
if (!myStream.fail()){
data[j++]=tmp;
}
}
}
}
file.close();
return data;
}
void readSparseMatrixDimensions(const char *filename, unsigned int &nRows,
unsigned int &nColumns) {
ifstream file;
file.open(filename);
string line;
int max_index=-1;
while(getline(file,line)) {
stringstream linestream(line);
string value;
int dummy_index;
while(getline(linestream,value,' ')) {
int separator=value.find(":");
istringstream myStream(value.substr(0,separator));
myStream >> dummy_index;
if(dummy_index > max_index){
max_index = dummy_index;
}
}
++nRows;
}
nColumns=max_index+1;
file.close();
}
svm_node** readSparseMatrixChunk(const char *filename, unsigned int nRows,
unsigned int nRowsToRead,
unsigned int rowOffset) {
ifstream file;
file.open(filename);
string line;
for (unsigned int i=0; i<rowOffset; i++) {
getline(file, line);
}
/* while(getline(file,line)) {
stringstream linestream(line);
string value;
while(getline(linestream,value,' ')) {
elements++;
}
elements++; // To account for the dummy row-closing element
++nRows;
}
file.close();file.open(filename);*/
if (rowOffset+nRowsToRead >= nRows) {
nRowsToRead = nRows-rowOffset;
}
svm_node **x_matrix = new svm_node *[nRowsToRead];
for(unsigned int i=0;i<nRowsToRead;i++) {
getline(file, line);
stringstream tmplinestream(line);
string value;
int elements = 0;
while(getline(tmplinestream,value,' ')) {
elements++;
}
elements++; // To account for the closing dummy node in the row
x_matrix[i] = new svm_node[elements];
stringstream linestream(line);
int j=0;
while(getline(linestream,value,' ')) {
int separator=value.find(":");
istringstream myStream(value.substr(0,separator));
myStream >> x_matrix[i][j].index;
istringstream myStream2(value.substr(separator+1));
myStream2 >> x_matrix[i][j].value;
j++;
}
x_matrix[i][j].index = -1;
}
file.close();
return x_matrix;
}
<|endoftext|> |
<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
* @file exception_assertion_tests.cpp
* @brief iutest test 例外アサーションテスト
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014-2016, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "../include/gtest/iutest_spi_switch.hpp"
#if IUTEST_HAS_EXCEPTIONS
static void ExceptionFunction(int i)
{
switch( i )
{
case 0:
return;
case 1:
throw 2;
break;
case 2:
throw ::std::bad_exception();
break;
case 3:
throw "error";
case 4:
throw ::std::string("error");
case 5:
throw 0.1f;
default:
break;
}
}
IUTEST(Exception, Throw)
{
//IUTEST_ASSERT_THROW(throw ::std::bad_exception(), ::std::bad_exception);
IUTEST_ASSERT_THROW(ExceptionFunction(2), ::std::bad_exception);
IUTEST_EXPECT_THROW(ExceptionFunction(2), ::std::bad_exception);
IUTEST_INFORM_THROW(ExceptionFunction(2), ::std::bad_exception);
IUTEST_ASSUME_THROW(ExceptionFunction(2), ::std::bad_exception);
}
IUTEST(Exception, AnyThrow)
{
IUTEST_ASSERT_ANY_THROW(throw ::std::bad_exception());
IUTEST_ASSERT_ANY_THROW(throw 1);
IUTEST_ASSERT_ANY_THROW(ExceptionFunction(1));
IUTEST_EXPECT_ANY_THROW(ExceptionFunction(1));
IUTEST_INFORM_ANY_THROW(ExceptionFunction(1));
IUTEST_ASSUME_ANY_THROW(ExceptionFunction(1));
}
IUTEST(Exception, NoThrow)
{
IUTEST_ASSERT_NO_THROW((void)0);
IUTEST_ASSERT_NO_THROW(ExceptionFunction(0));
IUTEST_EXPECT_NO_THROW(ExceptionFunction(0));
IUTEST_INFORM_NO_THROW(ExceptionFunction(0));
IUTEST_ASSUME_NO_THROW(ExceptionFunction(0));
}
IUTEST(Exception, ValueEQ)
{
IUTEST_ASSERT_THROW_VALUE_EQ(throw 2, int, 2);
IUTEST_ASSERT_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
IUTEST_EXPECT_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
IUTEST_INFORM_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
IUTEST_ASSUME_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
}
IUTEST(Exception, ValueNE)
{
IUTEST_ASSERT_THROW_VALUE_NE(throw 2, int, 0);
IUTEST_ASSERT_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
IUTEST_EXPECT_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
IUTEST_INFORM_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
IUTEST_ASSUME_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
}
IUTEST(Exception, ValueSTREQ)
{
IUTEST_ASSERT_THROW_VALUE_STREQ(throw "error", const char *, "error");
IUTEST_ASSERT_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_EXPECT_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_INFORM_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_ASSUME_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_ASSERT_THROW_VALUE_STREQ(throw ::std::string("error"), ::std::string, "error");
IUTEST_ASSERT_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
IUTEST_EXPECT_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
IUTEST_INFORM_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
IUTEST_ASSUME_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
}
IUTEST(Exception, ValueSTRCASEEQ)
{
IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error");
IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
IUTEST_INFORM_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
IUTEST_ASSUME_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
}
IUTEST(Exception, ValueFormat)
{
IUTEST_ASSERT_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float>, ExceptionFunction(5), float, 0.1f);
}
IUTEST(ExceptionFailure, Throw)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW(throw "test", int), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW(throw "test", int), "" );
}
IUTEST(ExceptionFailure, AnyThrow)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_ANY_THROW((void)0), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_ANY_THROW((void)0), "" );
}
IUTEST(ExceptionFailure, NoThrow)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_NO_THROW(throw 1), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_NO_THROW(throw "error"), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_NO_THROW(throw ::std::bad_exception()), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_NO_THROW(throw 1), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_NO_THROW(throw "error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_NO_THROW(throw ::std::bad_exception()), "" );
}
IUTEST(ExceptionFailure, ValueEQ)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_EQ(throw 2, char, 2), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_EQ(throw 2, int, 0), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_EQ(throw 2, char, 2), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_EQ(throw 2, int, 0), "" );
}
IUTEST(ExceptionFailure, ValueSTREQ)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STREQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STREQ(throw "error", const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STREQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STREQ(throw "error", const char*, "Error"), "" );
}
IUTEST(ExceptionFailure, ValueSTRCASEEQ)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw "test", const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(throw "test", const char*, "Error"), "" );
}
#if IUTEST_HAS_NOEXCEPT && 0
void Noexcept() IUTEST_CXX_NOEXCEPT_SPEC
{
throw 1;
}
IUTEST(NoThrowFailure, Noexcept)
{
IUTEST_ASSERT_FATAL_FAILURE( IUTEST_ASSERT_NO_THROW(Noexcept()), "" );
}
#endif
#endif
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
IUTEST_INIT(&argc, argv);
return IUTEST_RUN_ALL_TESTS();
}
<commit_msg>update tes<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
* @file exception_assertion_tests.cpp
* @brief iutest test 例外アサーションテスト
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014-2016, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "../include/gtest/iutest_spi_switch.hpp"
#if IUTEST_HAS_EXCEPTIONS
static void ExceptionFunction(int i)
{
switch( i )
{
case 0:
return;
case 1:
throw 2;
break;
case 2:
throw ::std::bad_exception();
break;
case 3:
throw "error";
case 4:
throw ::std::string("error");
case 5:
throw 0.1f;
case -1:
{
int* p = reinterpret_cast<int*>(0x1234);
*p = 1;
}
break;
default:
break;
}
}
IUTEST(Exception, Throw)
{
//IUTEST_ASSERT_THROW(throw ::std::bad_exception(), ::std::bad_exception);
IUTEST_ASSERT_THROW(ExceptionFunction(2), ::std::bad_exception);
IUTEST_EXPECT_THROW(ExceptionFunction(2), ::std::bad_exception);
IUTEST_INFORM_THROW(ExceptionFunction(2), ::std::bad_exception);
IUTEST_ASSUME_THROW(ExceptionFunction(2), ::std::bad_exception);
}
IUTEST(Exception, AnyThrow)
{
IUTEST_ASSERT_ANY_THROW(throw ::std::bad_exception());
IUTEST_ASSERT_ANY_THROW(throw 1);
IUTEST_ASSERT_ANY_THROW(ExceptionFunction(1));
IUTEST_EXPECT_ANY_THROW(ExceptionFunction(1));
IUTEST_INFORM_ANY_THROW(ExceptionFunction(1));
IUTEST_ASSUME_ANY_THROW(ExceptionFunction(1));
}
IUTEST(Exception, NoThrow)
{
IUTEST_ASSERT_NO_THROW((void)0);
IUTEST_ASSERT_NO_THROW(ExceptionFunction(0));
IUTEST_EXPECT_NO_THROW(ExceptionFunction(0));
IUTEST_INFORM_NO_THROW(ExceptionFunction(0));
IUTEST_ASSUME_NO_THROW(ExceptionFunction(0));
}
IUTEST(Exception, ValueEQ)
{
IUTEST_ASSERT_THROW_VALUE_EQ(throw 2, int, 2);
IUTEST_ASSERT_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
IUTEST_EXPECT_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
IUTEST_INFORM_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
IUTEST_ASSUME_THROW_VALUE_EQ(ExceptionFunction(1), int, 2);
}
IUTEST(Exception, ValueNE)
{
IUTEST_ASSERT_THROW_VALUE_NE(throw 2, int, 0);
IUTEST_ASSERT_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
IUTEST_EXPECT_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
IUTEST_INFORM_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
IUTEST_ASSUME_THROW_VALUE_NE(ExceptionFunction(1), int, 0);
}
IUTEST(Exception, ValueSTREQ)
{
IUTEST_ASSERT_THROW_VALUE_STREQ(throw "error", const char *, "error");
IUTEST_ASSERT_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_EXPECT_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_INFORM_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_ASSUME_THROW_VALUE_STREQ(ExceptionFunction(3), const char *, "error");
IUTEST_ASSERT_THROW_VALUE_STREQ(throw ::std::string("error"), ::std::string, "error");
IUTEST_ASSERT_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
IUTEST_EXPECT_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
IUTEST_INFORM_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
IUTEST_ASSUME_THROW_VALUE_STREQ(ExceptionFunction(4), ::std::string, "error");
}
IUTEST(Exception, ValueSTRCASEEQ)
{
IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error");
IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
IUTEST_INFORM_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
IUTEST_ASSUME_THROW_VALUE_STRCASEEQ(ExceptionFunction(3), const char *, "Error");
}
IUTEST(Exception, ValueFormat)
{
IUTEST_ASSERT_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float>, ExceptionFunction(5), float, 0.1f);
}
#if IUTEST_HAS_CATCH_SEH_EXCEPTION_ASERRTION
IUTEST(Exception, SEH)
{
IUTEST_ASSERT_ANY_THROW(ExceptionFunction(-1));
IUTEST_EXPECT_ANY_THROW(ExceptionFunction(-1));
IUTEST_INFORM_ANY_THROW(ExceptionFunction(-1));
IUTEST_ASSUME_ANY_THROW(ExceptionFunction(-1));
}
#endif
IUTEST(ExceptionFailure, Throw)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW(throw "test", int), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW(throw "test", int), "" );
}
IUTEST(ExceptionFailure, AnyThrow)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_ANY_THROW((void)0), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_ANY_THROW((void)0), "" );
}
IUTEST(ExceptionFailure, NoThrow)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_NO_THROW(throw 1), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_NO_THROW(throw "error"), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_NO_THROW(throw ::std::bad_exception()), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_NO_THROW(throw 1), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_NO_THROW(throw "error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_NO_THROW(throw ::std::bad_exception()), "" );
}
IUTEST(ExceptionFailure, ValueEQ)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_EQ(throw 2, char, 2), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_EQ(throw 2, int, 0), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_EQ(throw 2, char, 2), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_EQ(throw 2, int, 0), "" );
}
IUTEST(ExceptionFailure, ValueSTREQ)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STREQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STREQ(throw "error", const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STREQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STREQ(throw "error", const char*, "Error"), "" );
}
IUTEST(ExceptionFailure, ValueSTRCASEEQ)
{
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_FATAL_FAILURE ( IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw "test", const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(throw 1, const char*, "Error"), "" );
IUTEST_ASSERT_NONFATAL_FAILURE( IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(throw "test", const char*, "Error"), "" );
}
#if IUTEST_HAS_NOEXCEPT && 0
void Noexcept() IUTEST_CXX_NOEXCEPT_SPEC
{
throw 1;
}
IUTEST(NoThrowFailure, Noexcept)
{
IUTEST_ASSERT_FATAL_FAILURE( IUTEST_ASSERT_NO_THROW(Noexcept()), "" );
}
#endif
#endif
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
IUTEST_INIT(&argc, argv);
return IUTEST_RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
#include "enums.h"
extern "C" {
#include <ocstack.h>
}
using namespace v8;
// The rest of this file is generated
void InitConstants(Handle<Object> exports) {
// ocstackconfig.h: Stack configuration
SET_CONSTANT_MEMBER(exports, Number, DEV_ADDR_SIZE_MAX);
SET_CONSTANT_MEMBER(exports, Number, MAX_CB_TIMEOUT_SECONDS);
SET_CONSTANT_MEMBER(exports, Number, MAX_CONTAINED_RESOURCES);
SET_CONSTANT_MEMBER(exports, Number, MAX_HEADER_OPTION_DATA_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_HEADER_OPTIONS);
SET_CONSTANT_MEMBER(exports, Number, MAX_MANUFACTURER_NAME_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_MANUFACTURER_URL_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_QUERY_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_REQUEST_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_RESPONSE_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_URI_LENGTH);
// octypes.h: Definitions
SET_CONSTANT_MEMBER(exports, Number, OC_DEFAULT_PRESENCE_TTL_SECONDS);
SET_CONSTANT_MEMBER(exports, Number, OC_MAX_PRESENCE_TTL_SECONDS);
SET_CONSTANT_MEMBER(exports, Number, OC_MULTICAST_PORT);
SET_CONSTANT_MEMBER(exports, String, OC_EXPLICIT_DEVICE_DISCOVERY_URI);
SET_CONSTANT_MEMBER(exports, String, OC_MULTICAST_DISCOVERY_URI);
SET_CONSTANT_MEMBER(exports, String, OC_MULTICAST_IP);
SET_CONSTANT_MEMBER(exports, String, OC_MULTICAST_PREFIX);
SET_CONSTANT_MEMBER(exports, String, OC_PRESENCE_URI);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_CONTENT_TYPE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_DEVICE_ID);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_DEVICE_NAME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_FIRMWARE_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_FW_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HARDWARE_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HOSTING_PORT);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HOST_NAME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HREF);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_BATCH);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_DEFAULT);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_GROUP);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_LL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MFG_DATE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MFG_NAME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MFG_URL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MODEL_NUM);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_OBSERVABLE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_OC);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_OS_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PAYLOAD);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PLATFORM_ID);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PLATFORM_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PROPERTY);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_REPRESENTATION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_RESOURCE_TYPE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_RESOURCE_TYPE_PRESENCE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SECURE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SERVER_INSTANCE_ID);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SUPPORT_URL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SYSTEM_TIME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_WELL_KNOWN_QUERY);
}
<commit_msg>Constants: Update to 809b1b1<commit_after>#include <node.h>
#include <nan.h>
#include "enums.h"
extern "C" {
#include <ocstack.h>
}
using namespace v8;
// The rest of this file is generated
void InitConstants(Handle<Object> exports) {
// ocstackconfig.h: Stack configuration
SET_CONSTANT_MEMBER(exports, Number, DEV_ADDR_SIZE_MAX);
SET_CONSTANT_MEMBER(exports, Number, MAX_CB_TIMEOUT_SECONDS);
SET_CONSTANT_MEMBER(exports, Number, MAX_CONTAINED_RESOURCES);
SET_CONSTANT_MEMBER(exports, Number, MAX_HEADER_OPTION_DATA_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_HEADER_OPTIONS);
SET_CONSTANT_MEMBER(exports, Number, MAX_MANUFACTURER_NAME_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_MANUFACTURER_URL_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_QUERY_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_REQUEST_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_RESPONSE_LENGTH);
SET_CONSTANT_MEMBER(exports, Number, MAX_URI_LENGTH);
// octypes.h: Definitions
SET_CONSTANT_MEMBER(exports, Number, OC_DEFAULT_PRESENCE_TTL_SECONDS);
SET_CONSTANT_MEMBER(exports, Number, OC_MAX_PRESENCE_TTL_SECONDS);
SET_CONSTANT_MEMBER(exports, Number, OC_MULTICAST_PORT);
SET_CONSTANT_MEMBER(exports, String, OC_DATA_MODEL_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_EXPLICIT_DEVICE_DISCOVERY_URI);
SET_CONSTANT_MEMBER(exports, String, OC_MULTICAST_DISCOVERY_URI);
SET_CONSTANT_MEMBER(exports, String, OC_MULTICAST_IP);
SET_CONSTANT_MEMBER(exports, String, OC_MULTICAST_PREFIX);
SET_CONSTANT_MEMBER(exports, String, OC_PRESENCE_URI);
SET_CONSTANT_MEMBER(exports, String, OC_QUERY_SEPARATOR);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_CONTENT_TYPE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_DATA_MODEL_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_DEVICE_ID);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_DEVICE_NAME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_FIRMWARE_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_FW_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HARDWARE_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HOSTING_PORT);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HOST_NAME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_HREF);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_BATCH);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_DEFAULT);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_GROUP);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_INTERFACE_LL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MFG_DATE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MFG_NAME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MFG_URL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_MODEL_NUM);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_NONCE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_OBSERVABLE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_OC);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_OS_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PAYLOAD);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PLATFORM_ID);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PLATFORM_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_PROPERTY);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_REPRESENTATION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_RESOURCE_TYPE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_RESOURCE_TYPE_PRESENCE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SECURE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SERVER_INSTANCE_ID);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SPEC_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SUPPORT_URL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_SYSTEM_TIME);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_TRIGGER);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_TRIGGER_CHANGE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_TRIGGER_CREATE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_TRIGGER_DELETE);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_TTL);
SET_CONSTANT_MEMBER(exports, String, OC_RSRVD_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_SPEC_VERSION);
SET_CONSTANT_MEMBER(exports, String, OC_WELL_KNOWN_QUERY);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <thrift/compiler/parse/lexer.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <thrift/compiler/diagnostic.h>
namespace apache {
namespace thrift {
namespace compiler {
namespace {
bool is_whitespace(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
bool is_letter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
bool is_bin_digit(char c) {
return c == '0' || c == '1';
}
bool is_oct_digit(char c) {
return c >= '0' && c <= '7';
}
bool is_dec_digit(char c) {
return c >= '0' && c <= '9';
}
bool is_hex_digit(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
}
bool is_identifier_char(char c) {
return is_letter(c) || is_dec_digit(c) || c == '_' || c == '.';
}
// Lexes a decimal constant of the form [0-9]+. Returns a pointer past the end
// if the constant has been lexed; `none` otherwise.
const char* lex_dec_literal(const char* p, const char* none = nullptr) {
if (!is_dec_digit(*p)) {
return none;
}
do {
++p;
} while (is_dec_digit(*p));
return p;
}
// Lexes a float exponent of the form [eE][+-]?[0-9]+. Returns a pointer past
// the end if the exponent has been lexed; `none` otherwise.
const char* lex_float_exponent(const char* p, const char* none = nullptr) {
if (*p != 'e' && *p != 'E') {
return none;
}
++p; // Consume 'e' or 'E'.
if (*p == '+' || *p == '-') {
++p; // Consume the sign.
}
return lex_dec_literal(p);
}
// Lexes a float constant in the form [0-9]+ followed by an optional exponent.
// Returns a pointer past the end if the constant has been lexed; nullptr
// otherwise.
const char* lex_float_literal(const char* p) {
p = lex_dec_literal(p);
return p ? lex_float_exponent(p, p) : nullptr;
}
const std::unordered_map<std::string, tok> keywords = {
{"false", tok::bool_literal},
{"true", tok::bool_literal},
{"include", tok::kw_include},
{"cpp_include", tok::kw_cpp_include},
{"hs_include", tok::kw_hs_include},
{"package", tok::kw_package},
{"namespace", tok::kw_namespace},
{"void", tok::kw_void},
{"bool", tok::kw_bool},
{"byte", tok::kw_byte},
{"i16", tok::kw_i16},
{"i32", tok::kw_i32},
{"i64", tok::kw_i64},
{"double", tok::kw_double},
{"float", tok::kw_float},
{"string", tok::kw_string},
{"binary", tok::kw_binary},
{"map", tok::kw_map},
{"list", tok::kw_list},
{"set", tok::kw_set},
{"sink", tok::kw_sink},
{"stream", tok::kw_stream},
{"interaction", tok::kw_interaction},
{"performs", tok::kw_performs},
{"oneway", tok::kw_oneway},
{"idempotent", tok::kw_idempotent},
{"readonly", tok::kw_readonly},
{"safe", tok::kw_safe},
{"transient", tok::kw_transient},
{"stateful", tok::kw_stateful},
{"permanent", tok::kw_permanent},
{"server", tok::kw_server},
{"client", tok::kw_client},
{"typedef", tok::kw_typedef},
{"struct", tok::kw_struct},
{"union", tok::kw_union},
{"exception", tok::kw_exception},
{"extends", tok::kw_extends},
{"throws", tok::kw_throws},
{"service", tok::kw_service},
{"enum", tok::kw_enum},
{"const", tok::kw_const},
{"required", tok::kw_required},
{"optional", tok::kw_optional},
};
} // namespace
lexer::lexer(source src, lex_handler& handler, diagnostics_engine& diags)
: source_(src.text), start_(src.start), handler_(&handler), diags_(&diags) {
ptr_ = source_.data();
token_start_ = ptr_;
}
token lexer::make_int_literal(int offset, int base) {
fmt::string_view text = token_text();
errno = 0;
char* end = nullptr;
uint64_t val = strtoull(text.data() + offset, &end, base);
assert(end == text.data() + text.size());
return errno != ERANGE
? token::make_int_literal(token_source_range(), val)
: report_error("integer constant {} is too large", text);
}
token lexer::make_float_literal() {
fmt::string_view text = token_text();
errno = 0;
double val = strtod(std::string(text.data(), text.size()).c_str(), nullptr);
if (errno == ERANGE) {
if (val == 0) {
return report_error(
"magnitude of floating-point constant {} is too small", text);
} else if (val == HUGE_VAL || val == -HUGE_VAL) {
return report_error("floating-point constant {} is out of range", text);
}
// Allow subnormals.
}
return token::make_float_literal(token_source_range(), val);
}
template <typename... T>
token lexer::report_error(fmt::format_string<T...> msg, T&&... args) {
diags_->report(
location(token_start_),
diagnostic_level::error,
msg,
std::forward<T>(args)...);
return token(tok::error, token_source_range());
}
token lexer::unexpected_token() {
return report_error("unexpected token in input: {}", token_text());
}
void lexer::skip_line_comment() {
ptr_ = std::find(ptr_, end(), '\n');
}
bool lexer::lex_doc_comment() {
assert(strncmp(ptr_, "///", 3) == 0);
start_token();
bool is_inline = ptr_[3] == '<';
const char* prefix = ptr_;
size_t prefix_size = is_inline ? 4 : 3;
do {
if (!is_inline && ptr_[3] == '/') {
break;
}
ptr_ += prefix_size; // Skip "///" or "///<".
skip_line_comment();
while (is_whitespace(*ptr_)) {
++ptr_;
}
} while (strncmp(ptr_, prefix, prefix_size) == 0);
if (!is_inline) {
handler_->on_doc_comment(token_text(), location(ptr_));
}
return is_inline;
}
lexer::comment_lex_result lexer::lex_block_comment() {
assert(strncmp(ptr_, "/*", 2) == 0);
const char* p = ptr_ + 2; // Skip "/*".
start_token();
do {
p = std::find(p, end(), '*');
if (!*p) { // EOF while lexing a block comment.
return comment_lex_result::unterminated;
}
++p; // Skip '*'.
} while (*p != '/');
ptr_ = p + 1; // Skip '/'.
if (token_start_[2] == '*') {
if (token_start_[3] == '<') {
return comment_lex_result::doc_comment;
}
// Ignore comments containing only '*'s.
auto non_star = std::find_if(
token_start_ + 2, ptr_ - 1, [](char c) { return c != '*'; });
if (non_star != ptr_ - 1) {
handler_->on_doc_comment(token_text(), location(ptr_));
}
}
return comment_lex_result::skipped;
}
lexer::comment_lex_result lexer::lex_whitespace_or_comment() {
for (;;) {
switch (*ptr_) {
case '\n':
case ' ':
case '\t':
case '\r':
++ptr_;
break;
case '/':
if (ptr_[1] == '/') {
if (ptr_[2] == '/' && ptr_[3] != '/') {
if (lex_doc_comment()) {
return comment_lex_result::doc_comment;
}
continue;
}
ptr_ += 2; // Skip "//".
skip_line_comment();
break;
}
if (ptr_[1] == '*') {
comment_lex_result res = lex_block_comment();
if (res != comment_lex_result::skipped) {
return res;
}
continue;
}
return comment_lex_result::skipped;
case '#':
++ptr_;
skip_line_comment();
break;
default:
return comment_lex_result::skipped;
}
}
}
token lexer::get_next_token() {
if (lex_whitespace_or_comment() == comment_lex_result::doc_comment) {
return token::make_inline_doc(token_source_range(), token_text());
}
start_token();
char c = *ptr_++;
if (is_letter(c) || c == '_') {
// Lex an identifier or a keyword.
while (is_identifier_char(*ptr_)) {
++ptr_;
}
auto text = token_text();
auto it = keywords.find(std::string(text.data(), text.size()));
if (it != keywords.end()) {
return it->second == tok::bool_literal
? token::make_bool_literal(token_source_range(), it->first == "true")
: token(it->second, token_source_range());
}
return token::make_identifier(token_source_range(), text);
} else if (c == '.') {
if (const char* p = lex_float_literal(ptr_)) {
ptr_ = p;
return make_float_literal();
}
} else if (is_dec_digit(c)) {
if (c == '0') {
switch (*ptr_) {
case 'x':
case 'X':
// Lex a hexadecimal constant.
if (!is_hex_digit(ptr_[1])) {
return unexpected_token();
}
ptr_ += 2;
while (is_hex_digit(*ptr_)) {
++ptr_;
}
return make_int_literal(2, 16);
case 'b':
case 'B':
// Lex a binary constant.
if (!is_bin_digit(ptr_[1])) {
return unexpected_token();
}
ptr_ += 2;
while (is_bin_digit(*ptr_)) {
++ptr_;
}
return make_int_literal(2, 2);
}
}
// Lex a decimal, octal or floating-point constant.
ptr_ = lex_dec_literal(ptr_, ptr_);
switch (*ptr_) {
case '.':
if (const char* p = lex_float_literal(ptr_ + 1)) {
ptr_ = p;
return make_float_literal();
}
break;
case 'e':
case 'E':
if (const char* p = lex_float_exponent(ptr_)) {
ptr_ = p;
return make_float_literal();
}
break;
}
if (c != '0') {
// Lex a decimal constant.
return make_int_literal(0, 10);
}
// Lex an octal constant.
const char* p = std::find_if(
token_start_, ptr_, [](char c) { return !is_oct_digit(c); });
if (p != ptr_) {
return unexpected_token();
}
return ptr_ - token_start_ != 1
? make_int_literal(1, 8)
: token::make_int_literal(token_source_range(), 0);
} else if (c == '"' || c == '\'') {
// Lex a string literal.
const char* p = std::find(ptr_, end(), c);
if (*p) {
ptr_ = p + 1;
const char* begin = token_start_ + 1;
return token::make_string_literal(
token_source_range(), {begin, static_cast<size_t>(p - begin)});
}
} else if (!c && ptr_ > end()) {
--ptr_; // Put '\0' back in case get_next_token() is called again.
return token(tok::eof, token_source_range());
}
// Lex operators and punctuators.
auto kind = detail::to_tok(c);
return kind != tok::error ? token(kind, token_source_range())
: unexpected_token();
}
} // namespace compiler
} // namespace thrift
} // namespace apache
<commit_msg>Make lexing of literals more robust<commit_after>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <thrift/compiler/parse/lexer.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <thrift/compiler/diagnostic.h>
namespace apache {
namespace thrift {
namespace compiler {
namespace {
bool is_whitespace(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
bool is_letter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
bool is_bin_digit(char c) {
return c == '0' || c == '1';
}
bool is_oct_digit(char c) {
return c >= '0' && c <= '7';
}
bool is_dec_digit(char c) {
return c >= '0' && c <= '9';
}
bool is_hex_digit(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
}
bool is_identifier_char(char c) {
return is_letter(c) || is_dec_digit(c) || c == '_' || c == '.';
}
// Lexes a decimal constant of the form [0-9]+. Returns a pointer past the end
// if the constant has been lexed; `none` otherwise.
const char* lex_dec_literal(const char* p, const char* none = nullptr) {
if (!is_dec_digit(*p)) {
return none;
}
do {
++p;
} while (is_dec_digit(*p));
return p;
}
// Lexes a float exponent of the form [eE][+-]?[0-9]+. Returns a pointer past
// the end if the exponent has been lexed; `none` otherwise.
const char* lex_float_exponent(const char* p, const char* none = nullptr) {
if (*p != 'e' && *p != 'E') {
return none;
}
++p; // Consume 'e' or 'E'.
if (*p == '+' || *p == '-') {
++p; // Consume the sign.
}
return lex_dec_literal(p);
}
// Lexes a float constant in the form [0-9]+ followed by an optional exponent.
// Returns a pointer past the end if the constant has been lexed; nullptr
// otherwise.
const char* lex_float_literal(const char* p) {
p = lex_dec_literal(p);
return p ? lex_float_exponent(p, p) : nullptr;
}
const std::unordered_map<std::string, tok> keywords = {
{"false", tok::bool_literal},
{"true", tok::bool_literal},
{"include", tok::kw_include},
{"cpp_include", tok::kw_cpp_include},
{"hs_include", tok::kw_hs_include},
{"package", tok::kw_package},
{"namespace", tok::kw_namespace},
{"void", tok::kw_void},
{"bool", tok::kw_bool},
{"byte", tok::kw_byte},
{"i16", tok::kw_i16},
{"i32", tok::kw_i32},
{"i64", tok::kw_i64},
{"double", tok::kw_double},
{"float", tok::kw_float},
{"string", tok::kw_string},
{"binary", tok::kw_binary},
{"map", tok::kw_map},
{"list", tok::kw_list},
{"set", tok::kw_set},
{"sink", tok::kw_sink},
{"stream", tok::kw_stream},
{"interaction", tok::kw_interaction},
{"performs", tok::kw_performs},
{"oneway", tok::kw_oneway},
{"idempotent", tok::kw_idempotent},
{"readonly", tok::kw_readonly},
{"safe", tok::kw_safe},
{"transient", tok::kw_transient},
{"stateful", tok::kw_stateful},
{"permanent", tok::kw_permanent},
{"server", tok::kw_server},
{"client", tok::kw_client},
{"typedef", tok::kw_typedef},
{"struct", tok::kw_struct},
{"union", tok::kw_union},
{"exception", tok::kw_exception},
{"extends", tok::kw_extends},
{"throws", tok::kw_throws},
{"service", tok::kw_service},
{"enum", tok::kw_enum},
{"const", tok::kw_const},
{"required", tok::kw_required},
{"optional", tok::kw_optional},
};
} // namespace
lexer::lexer(source src, lex_handler& handler, diagnostics_engine& diags)
: source_(src.text), start_(src.start), handler_(&handler), diags_(&diags) {
ptr_ = source_.data();
token_start_ = ptr_;
}
token lexer::make_int_literal(int offset, int base) {
fmt::string_view text = token_text();
errno = 0;
char* end = nullptr;
uint64_t val = strtoull(text.data() + offset, &end, base);
if (end != text.data() + text.size()) {
return report_error("internal error when lexing an int literal");
}
return errno != ERANGE
? token::make_int_literal(token_source_range(), val)
: report_error("integer constant {} is too large", text);
}
token lexer::make_float_literal() {
fmt::string_view text = token_text();
errno = 0;
char* end = nullptr;
double val = strtod(text.data(), &end);
if (errno == ERANGE) {
if (val == 0) {
return report_error(
"magnitude of floating-point constant {} is too small", text);
} else if (val == HUGE_VAL || val == -HUGE_VAL) {
return report_error("floating-point constant {} is out of range", text);
}
// Allow subnormals.
}
if (end != text.data() + text.size()) {
return report_error("internal error when lexing a float literal");
}
return token::make_float_literal(token_source_range(), val);
}
template <typename... T>
token lexer::report_error(fmt::format_string<T...> msg, T&&... args) {
diags_->report(
location(token_start_),
diagnostic_level::error,
msg,
std::forward<T>(args)...);
return token(tok::error, token_source_range());
}
token lexer::unexpected_token() {
return report_error("unexpected token in input: {}", token_text());
}
void lexer::skip_line_comment() {
ptr_ = std::find(ptr_, end(), '\n');
}
bool lexer::lex_doc_comment() {
assert(strncmp(ptr_, "///", 3) == 0);
start_token();
bool is_inline = ptr_[3] == '<';
const char* prefix = ptr_;
size_t prefix_size = is_inline ? 4 : 3;
do {
if (!is_inline && ptr_[3] == '/') {
break;
}
ptr_ += prefix_size; // Skip "///" or "///<".
skip_line_comment();
while (is_whitespace(*ptr_)) {
++ptr_;
}
} while (strncmp(ptr_, prefix, prefix_size) == 0);
if (!is_inline) {
handler_->on_doc_comment(token_text(), location(ptr_));
}
return is_inline;
}
lexer::comment_lex_result lexer::lex_block_comment() {
assert(strncmp(ptr_, "/*", 2) == 0);
const char* p = ptr_ + 2; // Skip "/*".
start_token();
do {
p = std::find(p, end(), '*');
if (!*p) { // EOF while lexing a block comment.
return comment_lex_result::unterminated;
}
++p; // Skip '*'.
} while (*p != '/');
ptr_ = p + 1; // Skip '/'.
if (token_start_[2] == '*') {
if (token_start_[3] == '<') {
return comment_lex_result::doc_comment;
}
// Ignore comments containing only '*'s.
auto non_star = std::find_if(
token_start_ + 2, ptr_ - 1, [](char c) { return c != '*'; });
if (non_star != ptr_ - 1) {
handler_->on_doc_comment(token_text(), location(ptr_));
}
}
return comment_lex_result::skipped;
}
lexer::comment_lex_result lexer::lex_whitespace_or_comment() {
for (;;) {
switch (*ptr_) {
case '\n':
case ' ':
case '\t':
case '\r':
++ptr_;
break;
case '/':
if (ptr_[1] == '/') {
if (ptr_[2] == '/' && ptr_[3] != '/') {
if (lex_doc_comment()) {
return comment_lex_result::doc_comment;
}
continue;
}
ptr_ += 2; // Skip "//".
skip_line_comment();
break;
}
if (ptr_[1] == '*') {
comment_lex_result res = lex_block_comment();
if (res != comment_lex_result::skipped) {
return res;
}
continue;
}
return comment_lex_result::skipped;
case '#':
++ptr_;
skip_line_comment();
break;
default:
return comment_lex_result::skipped;
}
}
}
token lexer::get_next_token() {
if (lex_whitespace_or_comment() == comment_lex_result::doc_comment) {
return token::make_inline_doc(token_source_range(), token_text());
}
start_token();
char c = *ptr_++;
if (is_letter(c) || c == '_') {
// Lex an identifier or a keyword.
while (is_identifier_char(*ptr_)) {
++ptr_;
}
auto text = token_text();
auto it = keywords.find(std::string(text.data(), text.size()));
if (it != keywords.end()) {
return it->second == tok::bool_literal
? token::make_bool_literal(token_source_range(), it->first == "true")
: token(it->second, token_source_range());
}
return token::make_identifier(token_source_range(), text);
} else if (c == '.') {
if (const char* p = lex_float_literal(ptr_)) {
ptr_ = p;
return make_float_literal();
}
} else if (is_dec_digit(c)) {
if (c == '0') {
switch (*ptr_) {
case 'x':
case 'X':
// Lex a hexadecimal constant.
if (!is_hex_digit(ptr_[1])) {
return unexpected_token();
}
ptr_ += 2;
while (is_hex_digit(*ptr_)) {
++ptr_;
}
return make_int_literal(2, 16);
case 'b':
case 'B':
// Lex a binary constant.
if (!is_bin_digit(ptr_[1])) {
return unexpected_token();
}
ptr_ += 2;
while (is_bin_digit(*ptr_)) {
++ptr_;
}
return make_int_literal(2, 2);
}
}
// Lex a decimal, octal or floating-point constant.
ptr_ = lex_dec_literal(ptr_, ptr_);
switch (*ptr_) {
case '.':
if (const char* p = lex_float_literal(ptr_ + 1)) {
ptr_ = p;
return make_float_literal();
}
break;
case 'e':
case 'E':
if (const char* p = lex_float_exponent(ptr_)) {
ptr_ = p;
return make_float_literal();
}
break;
}
if (c != '0') {
// Lex a decimal constant.
return make_int_literal(0, 10);
}
// Lex an octal constant.
const char* p = std::find_if(
token_start_, ptr_, [](char c) { return !is_oct_digit(c); });
if (p != ptr_) {
return unexpected_token();
}
return ptr_ - token_start_ != 1
? make_int_literal(1, 8)
: token::make_int_literal(token_source_range(), 0);
} else if (c == '"' || c == '\'') {
// Lex a string literal.
const char* p = std::find(ptr_, end(), c);
if (*p) {
ptr_ = p + 1;
const char* begin = token_start_ + 1;
return token::make_string_literal(
token_source_range(), {begin, static_cast<size_t>(p - begin)});
}
} else if (!c && ptr_ > end()) {
--ptr_; // Put '\0' back in case get_next_token() is called again.
return token(tok::eof, token_source_range());
}
// Lex operators and punctuators.
auto kind = detail::to_tok(c);
return kind != tok::error ? token(kind, token_source_range())
: unexpected_token();
}
} // namespace compiler
} // namespace thrift
} // namespace apache
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 "MaterialParser.h"
#include <filaflat/BlobDictionary.h>
#include <filaflat/ChunkContainer.h>
#include <filaflat/MaterialChunk.h>
#include <filaflat/ShaderBuilder.h>
#include <filaflat/DictionaryReader.h>
#include <filaflat/Unflattener.h>
#include <filament/MaterialChunkType.h>
#include <private/filament/SamplerInterfaceBlock.h>
#include <private/filament/UniformInterfaceBlock.h>
#include <utils/CString.h>
#include <stdlib.h>
using namespace utils;
using namespace filament::driver;
using namespace filaflat;
using namespace filamat;
namespace filament {
// Make a copy of content and own the allocated memory.
class ManagedBuffer {
void* mStart = nullptr;
size_t mSize = 0;
public:
explicit ManagedBuffer(const void* start, size_t size)
: mStart(malloc(size)), mSize(size) {
memcpy(mStart, start, size);
}
~ManagedBuffer() noexcept {
free(mStart);
}
ManagedBuffer(ManagedBuffer const& rhs) = delete;
ManagedBuffer& operator=(ManagedBuffer const& rhs) = delete;
void* data() const noexcept { return mStart; }
void* begin() const noexcept { return mStart; }
void* end() const noexcept { return (uint8_t*)mStart + mSize; }
size_t size() const noexcept { return mSize; }
};
// ------------------------------------------------------------------------------------------------
struct MaterialParserDetails {
MaterialParserDetails(Backend backend, const void* data, size_t size)
: mManagedBuffer(data, size),
mChunkContainer(mManagedBuffer.data(), mManagedBuffer.size()),
mMaterialChunk(mChunkContainer) {
switch (backend) {
case Backend::OPENGL:
mMaterialTag = ChunkType::MaterialGlsl;
mDictionaryTag = ChunkType::DictionaryGlsl;
break;
case Backend::METAL:
mMaterialTag = ChunkType::MaterialMetal;
mDictionaryTag = ChunkType::DictionaryMetal;
break;
case Backend::VULKAN:
mMaterialTag = ChunkType::MaterialSpirv;
mDictionaryTag = ChunkType::DictionarySpirv;
break;
default:
break;
}
}
template<typename T>
bool getFromSimpleChunk(filamat::ChunkType type, T* value) const noexcept;
private:
friend class MaterialParser;
ManagedBuffer mManagedBuffer;
ChunkContainer mChunkContainer;
// Keep MaterialChunk alive between calls to getShader to avoid reload the shader index.
MaterialChunk mMaterialChunk;
BlobDictionary mBlobDictionary;
ChunkType mMaterialTag = ChunkType::Unknown;
ChunkType mDictionaryTag = ChunkType::Unknown;
};
template<typename T>
bool MaterialParserDetails::getFromSimpleChunk(filamat::ChunkType type, T* value) const noexcept {
if (mChunkContainer.hasChunk(type)) {
Unflattener unflattener(
mChunkContainer.getChunkStart(type),
mChunkContainer.getChunkEnd(type));
return unflattener.read(value);
}
return false;
}
// ------------------------------------------------------------------------------------------------
MaterialParser::MaterialParser(Backend backend, const void* data, size_t size)
: mImpl(new MaterialParserDetails(backend, data, size)) {
}
MaterialParser::~MaterialParser() {
delete mImpl;
}
ChunkContainer& MaterialParser::getChunkContainer() noexcept {
return mImpl->mChunkContainer;
}
ChunkContainer const& MaterialParser::getChunkContainer() const noexcept {
return mImpl->mChunkContainer;
}
bool MaterialParser::parse() noexcept {
ChunkContainer& cc = getChunkContainer();
if (cc.parse()) {
if (!cc.hasChunk(mImpl->mMaterialTag) || !cc.hasChunk(mImpl->mDictionaryTag)) {
return false;
}
if (!DictionaryReader::unflatten(cc, mImpl->mDictionaryTag, mImpl->mBlobDictionary)) {
return false;
}
if (!mImpl->mMaterialChunk.readIndex(mImpl->mMaterialTag)) {
return false;
}
}
return true;
}
bool MaterialParser::isShadingMaterial() const noexcept {
ChunkContainer const& cc = getChunkContainer();
return cc.hasChunk(MaterialName) &&
cc.hasChunk(MaterialVersion) &&
cc.hasChunk(MaterialUib) &&
cc.hasChunk(MaterialSib) &&
(cc.hasChunk(MaterialGlsl) || cc.hasChunk(MaterialSpirv) || cc.hasChunk(MaterialMetal)) &&
cc.hasChunk(MaterialShaderModels);
}
bool MaterialParser::isPostProcessMaterial() const noexcept {
ChunkContainer const& cc = getChunkContainer();
return cc.hasChunk(PostProcessVersion) &&
((cc.hasChunk(MaterialSpirv) && cc.hasChunk(DictionarySpirv)) ||
(cc.hasChunk(MaterialGlsl) && cc.hasChunk(DictionaryGlsl)) ||
(cc.hasChunk(MaterialMetal) && cc.hasChunk(DictionaryMetal)));
}
// Accessors
bool MaterialParser::getMaterialVersion(uint32_t* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialVersion, value);
}
bool MaterialParser::getPostProcessVersion(uint32_t* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::PostProcessVersion, value);
}
bool MaterialParser::getName(utils::CString* cstring) const noexcept {
ChunkType type = ChunkType::MaterialName;
const uint8_t* start = mImpl->mChunkContainer.getChunkStart(type);
const uint8_t* end = mImpl->mChunkContainer.getChunkEnd(type);
Unflattener unflattener(start, end);
return unflattener.read(cstring);
}
bool MaterialParser::getUIB(UniformInterfaceBlock* uib) const noexcept {
auto type = MaterialUib;
const uint8_t* start = mImpl->mChunkContainer.getChunkStart(type);
const uint8_t* end = mImpl->mChunkContainer.getChunkEnd(type);
Unflattener unflattener(start, end);
return ChunkUniformInterfaceBlock::unflatten(unflattener, uib);
}
bool MaterialParser::getSIB(SamplerInterfaceBlock* sib) const noexcept {
auto type = MaterialSib;
const uint8_t* start = mImpl->mChunkContainer.getChunkStart(type);
const uint8_t* end = mImpl->mChunkContainer.getChunkEnd(type);
Unflattener unflattener(start, end);
return ChunkSamplerInterfaceBlock::unflatten(unflattener, sib);
}
bool MaterialParser::getShaderModels(uint32_t* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialShaderModels, value);
}
bool MaterialParser::getDepthWriteSet(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDepthWriteSet, value);
}
bool MaterialParser::getDepthWrite(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDepthWrite, value);
}
bool MaterialParser::getDoubleSidedSet(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDoubleSidedSet, value);
}
bool MaterialParser::getDoubleSided(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDoubleSided, value);
}
bool MaterialParser::getColorWrite(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialColorWrite, value);
}
bool MaterialParser::getDepthTest(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDepthTest, value);
}
bool MaterialParser::getCullingMode(CullingMode* value) const noexcept {
static_assert(sizeof(CullingMode) == sizeof(uint8_t),
"CullingMode expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialCullingMode, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getTransparencyMode(TransparencyMode* value) const noexcept {
static_assert(sizeof(TransparencyMode) == sizeof(uint8_t),
"TransparencyMode expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialTransparencyMode,
reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getInterpolation(Interpolation* value) const noexcept {
static_assert(sizeof(Interpolation) == sizeof(uint8_t),
"Interpolation expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialInterpolation, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getVertexDomain(VertexDomain* value) const noexcept {
static_assert(sizeof(VertexDomain) == sizeof(uint8_t),
"VertexDomain expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialVertexDomain, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getBlendingMode(BlendingMode* value) const noexcept {
static_assert(sizeof(BlendingMode) == sizeof(uint8_t),
"BlendingMode expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialBlendingMode, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getMaskThreshold(float* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialMaskThreshold, value);
}
bool MaterialParser::hasShadowMultiplier(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialShadowMultiplier, value);
}
bool MaterialParser::getShading(Shading* value) const noexcept {
static_assert(sizeof(Shading) == sizeof(uint8_t),
"Shading expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialShading, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::hasCustomDepthShader(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialHasCustomDepthShader, value);
}
bool MaterialParser::getRequiredAttributes(AttributeBitset* value) const noexcept {
uint32_t rawAttributes = 0;
if (!mImpl->getFromSimpleChunk(ChunkType::MaterialRequiredAttributes, &rawAttributes)) {
return false;
}
*value = AttributeBitset();
value->setValue(rawAttributes);
return true;
}
bool MaterialParser::getShader(ShaderBuilder& shader,
ShaderModel shaderModel, uint8_t variant, ShaderType stage) noexcept {
return mImpl->mMaterialChunk.getShader(shader,
mImpl->mBlobDictionary, (uint8_t)shaderModel, variant, stage);
}
// ------------------------------------------------------------------------------------------------
bool ChunkUniformInterfaceBlock::unflatten(Unflattener& unflattener,
filament::UniformInterfaceBlock* uib) {
UniformInterfaceBlock::Builder builder = UniformInterfaceBlock::Builder();
CString name;
if (!unflattener.read(&name)) {
return false;
}
builder.name(std::move(name));
// Read number of fields.
uint64_t numFields = 0;
if (!unflattener.read(&numFields)) {
return false;
}
for (uint64_t i = 0; i < numFields; i++) {
CString fieldName;
uint64_t fieldSize;
uint8_t fieldType;
uint8_t fieldPrecision;
if (!unflattener.read(&fieldName)) {
return false;
}
if (!unflattener.read(&fieldSize)) {
return false;
}
if (!unflattener.read(&fieldType)) {
return false;
}
if (!unflattener.read(&fieldPrecision)) {
return false;
}
builder.add(fieldName, fieldSize, UniformInterfaceBlock::Type(fieldType),
UniformInterfaceBlock::Precision(fieldPrecision));
}
*uib = builder.build();
return true;
}
bool ChunkSamplerInterfaceBlock::unflatten(Unflattener& unflattener,
filament::SamplerInterfaceBlock* sib) {
SamplerInterfaceBlock::Builder builder = SamplerInterfaceBlock::Builder();
CString name;
if (!unflattener.read(&name)) {
return false;
}
builder.name(name);
// Read number of fields.
uint64_t numFields = 0;
if (!unflattener.read(&numFields)) {
return false;
}
for (uint64_t i = 0; i < numFields; i++) {
CString fieldName;
uint8_t fieldType;
uint8_t fieldFormat;
uint8_t fieldPrecision;
bool fieldMultisample;
if (!unflattener.read(&fieldName)) {
return false;
}
if (!unflattener.read(&fieldType)) {
return false;
}
if (!unflattener.read(&fieldFormat)) {
return false;
}
if (!unflattener.read(&fieldPrecision)) {
return false;
}
if (!unflattener.read(&fieldMultisample)) {
return false;
}
builder.add(fieldName, SamplerInterfaceBlock::Type(fieldType),
SamplerInterfaceBlock::Format(fieldFormat),
SamplerInterfaceBlock::Precision(fieldPrecision),
fieldMultisample);
}
*sib = builder.build();
return true;
}
} // namespace filaflat
<commit_msg>fix filameshio test<commit_after>/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 "MaterialParser.h"
#include <filaflat/BlobDictionary.h>
#include <filaflat/ChunkContainer.h>
#include <filaflat/MaterialChunk.h>
#include <filaflat/ShaderBuilder.h>
#include <filaflat/DictionaryReader.h>
#include <filaflat/Unflattener.h>
#include <filament/MaterialChunkType.h>
#include <private/filament/SamplerInterfaceBlock.h>
#include <private/filament/UniformInterfaceBlock.h>
#include <utils/CString.h>
#include <stdlib.h>
using namespace utils;
using namespace filament::driver;
using namespace filaflat;
using namespace filamat;
namespace filament {
// Make a copy of content and own the allocated memory.
class ManagedBuffer {
void* mStart = nullptr;
size_t mSize = 0;
public:
explicit ManagedBuffer(const void* start, size_t size)
: mStart(malloc(size)), mSize(size) {
memcpy(mStart, start, size);
}
~ManagedBuffer() noexcept {
free(mStart);
}
ManagedBuffer(ManagedBuffer const& rhs) = delete;
ManagedBuffer& operator=(ManagedBuffer const& rhs) = delete;
void* data() const noexcept { return mStart; }
void* begin() const noexcept { return mStart; }
void* end() const noexcept { return (uint8_t*)mStart + mSize; }
size_t size() const noexcept { return mSize; }
};
// ------------------------------------------------------------------------------------------------
struct MaterialParserDetails {
MaterialParserDetails(Backend backend, const void* data, size_t size)
: mManagedBuffer(data, size),
mChunkContainer(mManagedBuffer.data(), mManagedBuffer.size()),
mMaterialChunk(mChunkContainer) {
switch (backend) {
case Backend::OPENGL:
mMaterialTag = ChunkType::MaterialGlsl;
mDictionaryTag = ChunkType::DictionaryGlsl;
break;
case Backend::METAL:
mMaterialTag = ChunkType::MaterialMetal;
mDictionaryTag = ChunkType::DictionaryMetal;
break;
case Backend::VULKAN:
mMaterialTag = ChunkType::MaterialSpirv;
mDictionaryTag = ChunkType::DictionarySpirv;
break;
default:
// this is for testing purpose -- for e.g.: with the NoopDriver
mMaterialTag = ChunkType::MaterialGlsl;
mDictionaryTag = ChunkType::DictionaryGlsl;
break;
}
}
template<typename T>
bool getFromSimpleChunk(filamat::ChunkType type, T* value) const noexcept;
private:
friend class MaterialParser;
ManagedBuffer mManagedBuffer;
ChunkContainer mChunkContainer;
// Keep MaterialChunk alive between calls to getShader to avoid reload the shader index.
MaterialChunk mMaterialChunk;
BlobDictionary mBlobDictionary;
ChunkType mMaterialTag = ChunkType::Unknown;
ChunkType mDictionaryTag = ChunkType::Unknown;
};
template<typename T>
bool MaterialParserDetails::getFromSimpleChunk(filamat::ChunkType type, T* value) const noexcept {
if (mChunkContainer.hasChunk(type)) {
Unflattener unflattener(
mChunkContainer.getChunkStart(type),
mChunkContainer.getChunkEnd(type));
return unflattener.read(value);
}
return false;
}
// ------------------------------------------------------------------------------------------------
MaterialParser::MaterialParser(Backend backend, const void* data, size_t size)
: mImpl(new MaterialParserDetails(backend, data, size)) {
}
MaterialParser::~MaterialParser() {
delete mImpl;
}
ChunkContainer& MaterialParser::getChunkContainer() noexcept {
return mImpl->mChunkContainer;
}
ChunkContainer const& MaterialParser::getChunkContainer() const noexcept {
return mImpl->mChunkContainer;
}
bool MaterialParser::parse() noexcept {
ChunkContainer& cc = getChunkContainer();
if (cc.parse()) {
if (!cc.hasChunk(mImpl->mMaterialTag) || !cc.hasChunk(mImpl->mDictionaryTag)) {
return false;
}
if (!DictionaryReader::unflatten(cc, mImpl->mDictionaryTag, mImpl->mBlobDictionary)) {
return false;
}
if (!mImpl->mMaterialChunk.readIndex(mImpl->mMaterialTag)) {
return false;
}
}
return true;
}
bool MaterialParser::isShadingMaterial() const noexcept {
ChunkContainer const& cc = getChunkContainer();
return cc.hasChunk(MaterialName) &&
cc.hasChunk(MaterialVersion) &&
cc.hasChunk(MaterialUib) &&
cc.hasChunk(MaterialSib) &&
(cc.hasChunk(MaterialGlsl) || cc.hasChunk(MaterialSpirv) || cc.hasChunk(MaterialMetal)) &&
cc.hasChunk(MaterialShaderModels);
}
bool MaterialParser::isPostProcessMaterial() const noexcept {
ChunkContainer const& cc = getChunkContainer();
return cc.hasChunk(PostProcessVersion) &&
((cc.hasChunk(MaterialSpirv) && cc.hasChunk(DictionarySpirv)) ||
(cc.hasChunk(MaterialGlsl) && cc.hasChunk(DictionaryGlsl)) ||
(cc.hasChunk(MaterialMetal) && cc.hasChunk(DictionaryMetal)));
}
// Accessors
bool MaterialParser::getMaterialVersion(uint32_t* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialVersion, value);
}
bool MaterialParser::getPostProcessVersion(uint32_t* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::PostProcessVersion, value);
}
bool MaterialParser::getName(utils::CString* cstring) const noexcept {
ChunkType type = ChunkType::MaterialName;
const uint8_t* start = mImpl->mChunkContainer.getChunkStart(type);
const uint8_t* end = mImpl->mChunkContainer.getChunkEnd(type);
Unflattener unflattener(start, end);
return unflattener.read(cstring);
}
bool MaterialParser::getUIB(UniformInterfaceBlock* uib) const noexcept {
auto type = MaterialUib;
const uint8_t* start = mImpl->mChunkContainer.getChunkStart(type);
const uint8_t* end = mImpl->mChunkContainer.getChunkEnd(type);
Unflattener unflattener(start, end);
return ChunkUniformInterfaceBlock::unflatten(unflattener, uib);
}
bool MaterialParser::getSIB(SamplerInterfaceBlock* sib) const noexcept {
auto type = MaterialSib;
const uint8_t* start = mImpl->mChunkContainer.getChunkStart(type);
const uint8_t* end = mImpl->mChunkContainer.getChunkEnd(type);
Unflattener unflattener(start, end);
return ChunkSamplerInterfaceBlock::unflatten(unflattener, sib);
}
bool MaterialParser::getShaderModels(uint32_t* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialShaderModels, value);
}
bool MaterialParser::getDepthWriteSet(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDepthWriteSet, value);
}
bool MaterialParser::getDepthWrite(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDepthWrite, value);
}
bool MaterialParser::getDoubleSidedSet(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDoubleSidedSet, value);
}
bool MaterialParser::getDoubleSided(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDoubleSided, value);
}
bool MaterialParser::getColorWrite(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialColorWrite, value);
}
bool MaterialParser::getDepthTest(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialDepthTest, value);
}
bool MaterialParser::getCullingMode(CullingMode* value) const noexcept {
static_assert(sizeof(CullingMode) == sizeof(uint8_t),
"CullingMode expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialCullingMode, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getTransparencyMode(TransparencyMode* value) const noexcept {
static_assert(sizeof(TransparencyMode) == sizeof(uint8_t),
"TransparencyMode expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialTransparencyMode,
reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getInterpolation(Interpolation* value) const noexcept {
static_assert(sizeof(Interpolation) == sizeof(uint8_t),
"Interpolation expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialInterpolation, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getVertexDomain(VertexDomain* value) const noexcept {
static_assert(sizeof(VertexDomain) == sizeof(uint8_t),
"VertexDomain expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialVertexDomain, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getBlendingMode(BlendingMode* value) const noexcept {
static_assert(sizeof(BlendingMode) == sizeof(uint8_t),
"BlendingMode expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialBlendingMode, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::getMaskThreshold(float* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialMaskThreshold, value);
}
bool MaterialParser::hasShadowMultiplier(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialShadowMultiplier, value);
}
bool MaterialParser::getShading(Shading* value) const noexcept {
static_assert(sizeof(Shading) == sizeof(uint8_t),
"Shading expected size is wrong");
return mImpl->getFromSimpleChunk(ChunkType::MaterialShading, reinterpret_cast<uint8_t*>(value));
}
bool MaterialParser::hasCustomDepthShader(bool* value) const noexcept {
return mImpl->getFromSimpleChunk(ChunkType::MaterialHasCustomDepthShader, value);
}
bool MaterialParser::getRequiredAttributes(AttributeBitset* value) const noexcept {
uint32_t rawAttributes = 0;
if (!mImpl->getFromSimpleChunk(ChunkType::MaterialRequiredAttributes, &rawAttributes)) {
return false;
}
*value = AttributeBitset();
value->setValue(rawAttributes);
return true;
}
bool MaterialParser::getShader(ShaderBuilder& shader,
ShaderModel shaderModel, uint8_t variant, ShaderType stage) noexcept {
return mImpl->mMaterialChunk.getShader(shader,
mImpl->mBlobDictionary, (uint8_t)shaderModel, variant, stage);
}
// ------------------------------------------------------------------------------------------------
bool ChunkUniformInterfaceBlock::unflatten(Unflattener& unflattener,
filament::UniformInterfaceBlock* uib) {
UniformInterfaceBlock::Builder builder = UniformInterfaceBlock::Builder();
CString name;
if (!unflattener.read(&name)) {
return false;
}
builder.name(std::move(name));
// Read number of fields.
uint64_t numFields = 0;
if (!unflattener.read(&numFields)) {
return false;
}
for (uint64_t i = 0; i < numFields; i++) {
CString fieldName;
uint64_t fieldSize;
uint8_t fieldType;
uint8_t fieldPrecision;
if (!unflattener.read(&fieldName)) {
return false;
}
if (!unflattener.read(&fieldSize)) {
return false;
}
if (!unflattener.read(&fieldType)) {
return false;
}
if (!unflattener.read(&fieldPrecision)) {
return false;
}
builder.add(fieldName, fieldSize, UniformInterfaceBlock::Type(fieldType),
UniformInterfaceBlock::Precision(fieldPrecision));
}
*uib = builder.build();
return true;
}
bool ChunkSamplerInterfaceBlock::unflatten(Unflattener& unflattener,
filament::SamplerInterfaceBlock* sib) {
SamplerInterfaceBlock::Builder builder = SamplerInterfaceBlock::Builder();
CString name;
if (!unflattener.read(&name)) {
return false;
}
builder.name(name);
// Read number of fields.
uint64_t numFields = 0;
if (!unflattener.read(&numFields)) {
return false;
}
for (uint64_t i = 0; i < numFields; i++) {
CString fieldName;
uint8_t fieldType;
uint8_t fieldFormat;
uint8_t fieldPrecision;
bool fieldMultisample;
if (!unflattener.read(&fieldName)) {
return false;
}
if (!unflattener.read(&fieldType)) {
return false;
}
if (!unflattener.read(&fieldFormat)) {
return false;
}
if (!unflattener.read(&fieldPrecision)) {
return false;
}
if (!unflattener.read(&fieldMultisample)) {
return false;
}
builder.add(fieldName, SamplerInterfaceBlock::Type(fieldType),
SamplerInterfaceBlock::Format(fieldFormat),
SamplerInterfaceBlock::Precision(fieldPrecision),
fieldMultisample);
}
*sib = builder.build();
return true;
}
} // namespace filaflat
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <pqView.h>
#include <vtkSMSourceProxy.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkDataArray.h>
#include <vtkAlgorithm.h>
#include <QPointer>
#include <QPushButton>
#include <QMainWindow>
namespace tomviz
{
class DataPropertiesPanel::DPPInternals
{
public:
Ui::DataPropertiesPanel Ui;
QPointer<DataSource> CurrentDataSource;
QPointer<pqProxyWidget> ColorMapWidget;
QPointer<QWidget> TiltAnglesSeparator;
DPPInternals(QWidget* parent)
{
Ui::DataPropertiesPanel& ui = this->Ui;
ui.setupUi(parent);
QVBoxLayout* l = ui.verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", parent);
l->insertWidget(l->indexOf(ui.FileName), separator);
separator = pqProxyWidget::newGroupLabelWidget("Original Dimensions & Range",
parent);
l->insertWidget(l->indexOf(ui.OriginalDataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Transformed Dimensions & Range",
parent);
l->insertWidget(l->indexOf(ui.TransformedDataRange), separator);
this->TiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", parent);
l->insertWidget(l->indexOf(ui.SetTiltAnglesButton), this->TiltAnglesSeparator);
this->clear();
}
void clear()
{
Ui::DataPropertiesPanel& ui = this->Ui;
ui.FileName->setText("");
ui.OriginalDataRange->setText("");
ui.OriginalDataType->setText("Type:");
ui.TransformedDataRange->setText("");
ui.TransformedDataType->setText("Type:");
if (this->ColorMapWidget)
{
ui.verticalLayout->removeWidget(this->ColorMapWidget);
delete this->ColorMapWidget;
}
this->TiltAnglesSeparator->hide();
ui.SetTiltAnglesButton->hide();
ui.TiltAnglesTable->clear();
ui.TiltAnglesTable->setRowCount(0);
ui.TiltAnglesTable->hide();
}
};
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: Superclass(parentObject),
Internals(new DataPropertiesPanel::DPPInternals(this))
{
this->connect(&ActiveObjects::instance(),
SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
this->connect(this->Internals->Ui.SetTiltAnglesButton, SIGNAL(clicked()),
SLOT(setTiltAngles()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent *e)
{
this->updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (this->Internals->CurrentDataSource)
{
this->disconnect(this->Internals->CurrentDataSource);
}
this->Internals->CurrentDataSource = dsource;
if (dsource)
{
this->connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
this->updateNeeded = true;
}
namespace {
QString getDataExtentAndRangeString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString = QString("%1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
if (vtkPVArrayInformation* scalarInfo = tomviz::scalarArrayInformation(proxy))
{
return QString("(%1)\t%2 : %3").arg(extentString)
.arg(scalarInfo->GetComponentRange(0)[0])
.arg(scalarInfo->GetComponentRange(0)[1]);
}
else
{
return QString("(%1)\t? : ? (type: ?)").arg(extentString);
}
}
QString getDataTypeString(vtkSMSourceProxy* proxy)
{
if (vtkPVArrayInformation* scalarInfo = tomviz::scalarArrayInformation(proxy))
{
return QString("Type: %1").arg(vtkImageScalarTypeNameMacro(
scalarInfo->GetDataType()));
}
else
{
return QString("Type: ?");
}
}
}
void DataPropertiesPanel::updateData()
{
if (!this->updateNeeded)
{
return;
}
this->disconnect(this->Internals->Ui.TiltAnglesTable,
SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
this->Internals->clear();
DataSource* dsource = this->Internals->CurrentDataSource;
if (!dsource)
{
return;
}
Ui::DataPropertiesPanel& ui = this->Internals->Ui;
ui.FileName->setText(dsource->filename());
ui.OriginalDataRange->setText(getDataExtentAndRangeString(
dsource->originalDataSource()));
ui.OriginalDataType->setText(getDataTypeString(
dsource->originalDataSource()));
ui.TransformedDataRange->setText(getDataExtentAndRangeString(
dsource->producer()));
ui.TransformedDataType->setText(getDataTypeString(
dsource->producer()));
// display tilt series data
if (dsource->type() == DataSource::TiltSeries)
{
this->Internals->TiltAnglesSeparator->show();
ui.SetTiltAnglesButton->show();
ui.TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
ui.TiltAnglesTable->setRowCount(tiltAngles.size());
ui.TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i)
{
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
ui.TiltAnglesTable->setItem(i, 0, item);
}
}
else
{
this->Internals->TiltAnglesSeparator->hide();
ui.SetTiltAnglesButton->hide();
ui.TiltAnglesTable->hide();
}
this->connect(this->Internals->Ui.TiltAnglesTable,
SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
this->updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = this->Internals->CurrentDataSource;
QTableWidgetItem* item = this->Internals->Ui.TiltAnglesTable->item(row,
column);
QString str = item->data(Qt::DisplayRole).toString();
if (dsource->type() == DataSource::TiltSeries)
{
QVector<double> tiltAngles = dsource->getTiltAngles();
bool ok;
double value = str.toDouble(&ok);
if (ok)
{
tiltAngles[row] = value;
dsource->setTiltAngles(tiltAngles);
}
else
{
std::cerr << "Invalid tilt angle: " << str.toStdString() << std::endl;
}
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = this->Internals->CurrentDataSource;
QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
this->updateNeeded = true;
}
}
<commit_msg>Make sure we update when the panel is visible<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <pqView.h>
#include <vtkSMSourceProxy.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkDataArray.h>
#include <vtkAlgorithm.h>
#include <QPointer>
#include <QPushButton>
#include <QMainWindow>
namespace tomviz
{
class DataPropertiesPanel::DPPInternals
{
public:
Ui::DataPropertiesPanel Ui;
QPointer<DataSource> CurrentDataSource;
QPointer<pqProxyWidget> ColorMapWidget;
QPointer<QWidget> TiltAnglesSeparator;
DPPInternals(QWidget* parent)
{
Ui::DataPropertiesPanel& ui = this->Ui;
ui.setupUi(parent);
QVBoxLayout* l = ui.verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", parent);
l->insertWidget(l->indexOf(ui.FileName), separator);
separator = pqProxyWidget::newGroupLabelWidget("Original Dimensions & Range",
parent);
l->insertWidget(l->indexOf(ui.OriginalDataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Transformed Dimensions & Range",
parent);
l->insertWidget(l->indexOf(ui.TransformedDataRange), separator);
this->TiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", parent);
l->insertWidget(l->indexOf(ui.SetTiltAnglesButton), this->TiltAnglesSeparator);
this->clear();
}
void clear()
{
Ui::DataPropertiesPanel& ui = this->Ui;
ui.FileName->setText("");
ui.OriginalDataRange->setText("");
ui.OriginalDataType->setText("Type:");
ui.TransformedDataRange->setText("");
ui.TransformedDataType->setText("Type:");
if (this->ColorMapWidget)
{
ui.verticalLayout->removeWidget(this->ColorMapWidget);
delete this->ColorMapWidget;
}
this->TiltAnglesSeparator->hide();
ui.SetTiltAnglesButton->hide();
ui.TiltAnglesTable->clear();
ui.TiltAnglesTable->setRowCount(0);
ui.TiltAnglesTable->hide();
}
};
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: Superclass(parentObject),
Internals(new DataPropertiesPanel::DPPInternals(this))
{
this->connect(&ActiveObjects::instance(),
SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
this->connect(this->Internals->Ui.SetTiltAnglesButton, SIGNAL(clicked()),
SLOT(setTiltAngles()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent *e)
{
this->updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (this->Internals->CurrentDataSource)
{
this->disconnect(this->Internals->CurrentDataSource);
}
this->Internals->CurrentDataSource = dsource;
if (dsource)
{
this->connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
this->scheduleUpdate();
}
namespace {
QString getDataExtentAndRangeString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString = QString("%1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
if (vtkPVArrayInformation* scalarInfo = tomviz::scalarArrayInformation(proxy))
{
return QString("(%1)\t%2 : %3").arg(extentString)
.arg(scalarInfo->GetComponentRange(0)[0])
.arg(scalarInfo->GetComponentRange(0)[1]);
}
else
{
return QString("(%1)\t? : ? (type: ?)").arg(extentString);
}
}
QString getDataTypeString(vtkSMSourceProxy* proxy)
{
if (vtkPVArrayInformation* scalarInfo = tomviz::scalarArrayInformation(proxy))
{
return QString("Type: %1").arg(vtkImageScalarTypeNameMacro(
scalarInfo->GetDataType()));
}
else
{
return QString("Type: ?");
}
}
}
void DataPropertiesPanel::updateData()
{
if (!this->updateNeeded)
{
return;
}
this->disconnect(this->Internals->Ui.TiltAnglesTable,
SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
this->Internals->clear();
DataSource* dsource = this->Internals->CurrentDataSource;
if (!dsource)
{
return;
}
Ui::DataPropertiesPanel& ui = this->Internals->Ui;
ui.FileName->setText(dsource->filename());
ui.OriginalDataRange->setText(getDataExtentAndRangeString(
dsource->originalDataSource()));
ui.OriginalDataType->setText(getDataTypeString(
dsource->originalDataSource()));
ui.TransformedDataRange->setText(getDataExtentAndRangeString(
dsource->producer()));
ui.TransformedDataType->setText(getDataTypeString(
dsource->producer()));
// display tilt series data
if (dsource->type() == DataSource::TiltSeries)
{
this->Internals->TiltAnglesSeparator->show();
ui.SetTiltAnglesButton->show();
ui.TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
ui.TiltAnglesTable->setRowCount(tiltAngles.size());
ui.TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i)
{
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
ui.TiltAnglesTable->setItem(i, 0, item);
}
}
else
{
this->Internals->TiltAnglesSeparator->hide();
ui.SetTiltAnglesButton->hide();
ui.TiltAnglesTable->hide();
}
this->connect(this->Internals->Ui.TiltAnglesTable,
SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
this->updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = this->Internals->CurrentDataSource;
QTableWidgetItem* item = this->Internals->Ui.TiltAnglesTable->item(row,
column);
QString str = item->data(Qt::DisplayRole).toString();
if (dsource->type() == DataSource::TiltSeries)
{
QVector<double> tiltAngles = dsource->getTiltAngles();
bool ok;
double value = str.toDouble(&ok);
if (ok)
{
tiltAngles[row] = value;
dsource->setTiltAngles(tiltAngles);
}
else
{
std::cerr << "Invalid tilt angle: " << str.toStdString() << std::endl;
}
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = this->Internals->CurrentDataSource;
QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
this->updateNeeded = true;
if (this->isVisible())
{
this->updateData();
}
}
}
<|endoftext|> |
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pdffilter.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-07-13 11:14:33 $
*
* 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
*
************************************************************************/
#include "pdffilter.hxx"
#include "pdfexport.hxx"
#include <vcl/svapp.hxx>
#include <vcl/window.hxx>
#include <svtools/outstrm.hxx>
#include <svtools/FilterConfigItem.hxx>
// -------------
// - PDFFilter -
// -------------
PDFFilter::PDFFilter( const Reference< XMultiServiceFactory > &rxMSF ) :
mxMSF( rxMSF )
{
}
// -----------------------------------------------------------------------------
PDFFilter::~PDFFilter()
{
}
// -----------------------------------------------------------------------------
sal_Bool PDFFilter::implExport( const Sequence< PropertyValue >& rDescriptor )
{
Reference< XOutputStream > xOStm;
Sequence< PropertyValue > aFilterData;
sal_Int32 nLength = rDescriptor.getLength();
const PropertyValue* pValue = rDescriptor.getConstArray();
sal_Bool bRet = sal_False;
Reference< task::XStatusIndicator > xStatusIndicator;
for ( sal_Int32 i = 0 ; ( i < nLength ) && !xOStm.is(); ++i)
{
if( pValue[ i ].Name.equalsAscii( "OutputStream" ) )
pValue[ i ].Value >>= xOStm;
else if( pValue[ i ].Name.equalsAscii( "FilterData" ) )
pValue[ i ].Value >>= aFilterData;
else if ( pValue[ i ].Name.equalsAscii( "StatusIndicator" ) )
pValue[ i ].Value >>= xStatusIndicator;
}
/* we don't get FilterData if we are exporting directly
to pdf, but we have to use the last user settings (especially for the CompressMode) */
if ( !aFilterData.getLength() )
{
FilterConfigItem aCfgItem( String( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/PDF/Export/" ) ) );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "UseLosslessCompression" ) ), sal_False );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Quality" ) ), 90 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "ReduceImageResolution" ) ), sal_False );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "MaxImageResolution" ) ), 300 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "UseTaggedPDF" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "ExportNotes" ) ), sal_True );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "UseTransitionEffects" ) ), sal_True );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "IsSkipEmptyPages" ) ), sal_False );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "FormsType" ) ), 0 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "HideViewerToolbar" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "HideViewerMenubar" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "HideViewerWindowControls" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "ResizeWindowToInitialPage" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "CenterWindow" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "OpenInFullScreenMode" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "DisplayPDFDocumentTitle" ) ), sal_True );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "InitialView" ) ), 0 );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Magnification" ) ), 0 );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "PageLayout" ) ), 0 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "FirstPageOnLeft" ) ), sal_False );
//the encryption is not available when exporting directly, since the encryption is off by default and the selection
// (encrypt or not) is not persistent; it's available through macro though,
// provided the correct property values are set, see help
aFilterData = aCfgItem.GetFilterData();
}
if( mxSrcDoc.is() && xOStm.is() )
{
PDFExport aExport( mxSrcDoc, xStatusIndicator );
::utl::TempFile aTempFile;
aTempFile.EnableKillingFile();
bRet = aExport.Export( aTempFile.GetURL(), aFilterData );
if( bRet )
{
SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( aTempFile.GetURL(), STREAM_READ );
if( pIStm )
{
SvOutputStream aOStm( xOStm );
aOStm << *pIStm;
bRet = ( aOStm.Tell() && ( aOStm.GetError() == ERRCODE_NONE ) );
delete pIStm;
}
}
}
return bRet;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL PDFFilter::filter( const Sequence< PropertyValue >& rDescriptor )
throw (RuntimeException)
{
Window* pFocusWindow = Application::GetFocusWindow();
if( pFocusWindow )
pFocusWindow->EnterWait();
const sal_Bool bRet = implExport( rDescriptor );
if( pFocusWindow )
pFocusWindow->LeaveWait();
return bRet;
}
// -----------------------------------------------------------------------------
void SAL_CALL PDFFilter::cancel( ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL PDFFilter::setSourceDocument( const Reference< XComponent >& xDoc )
throw (IllegalArgumentException, RuntimeException)
{
mxSrcDoc = xDoc;
}
// -----------------------------------------------------------------------------
void SAL_CALL PDFFilter::initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& )
throw (Exception, RuntimeException)
{
}
// -----------------------------------------------------------------------------
OUString PDFFilter_getImplementationName ()
throw (RuntimeException)
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.PDF.PDFFilter" ) );
}
// -----------------------------------------------------------------------------
#define SERVICE_NAME "com.sun.star.document.PDFFilter"
sal_Bool SAL_CALL PDFFilter_supportsService( const OUString& ServiceName )
throw (RuntimeException)
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
}
// -----------------------------------------------------------------------------
Sequence< OUString > SAL_CALL PDFFilter_getSupportedServiceNames( ) throw (RuntimeException)
{
Sequence < OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
// -----------------------------------------------------------------------------
Reference< XInterface > SAL_CALL PDFFilter_createInstance( const Reference< XMultiServiceFactory > & rSMgr) throw( Exception )
{
return (cppu::OWeakObject*) new PDFFilter( rSMgr );
}
// -----------------------------------------------------------------------------
OUString SAL_CALL PDFFilter::getImplementationName()
throw (RuntimeException)
{
return PDFFilter_getImplementationName();
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL PDFFilter::supportsService( const OUString& rServiceName )
throw (RuntimeException)
{
return PDFFilter_supportsService( rServiceName );
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< OUString > SAL_CALL PDFFilter::getSupportedServiceNames( ) throw (RuntimeException)
{
return PDFFilter_getSupportedServiceNames();
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.24); FILE MERGED 2006/09/01 17:27:12 kaib 1.9.24.1: #i68856# Added header markers and pch files<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pdffilter.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-17 07:42:44 $
*
* 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_filter.hxx"
#include "pdffilter.hxx"
#include "pdfexport.hxx"
#include <vcl/svapp.hxx>
#include <vcl/window.hxx>
#include <svtools/outstrm.hxx>
#include <svtools/FilterConfigItem.hxx>
// -------------
// - PDFFilter -
// -------------
PDFFilter::PDFFilter( const Reference< XMultiServiceFactory > &rxMSF ) :
mxMSF( rxMSF )
{
}
// -----------------------------------------------------------------------------
PDFFilter::~PDFFilter()
{
}
// -----------------------------------------------------------------------------
sal_Bool PDFFilter::implExport( const Sequence< PropertyValue >& rDescriptor )
{
Reference< XOutputStream > xOStm;
Sequence< PropertyValue > aFilterData;
sal_Int32 nLength = rDescriptor.getLength();
const PropertyValue* pValue = rDescriptor.getConstArray();
sal_Bool bRet = sal_False;
Reference< task::XStatusIndicator > xStatusIndicator;
for ( sal_Int32 i = 0 ; ( i < nLength ) && !xOStm.is(); ++i)
{
if( pValue[ i ].Name.equalsAscii( "OutputStream" ) )
pValue[ i ].Value >>= xOStm;
else if( pValue[ i ].Name.equalsAscii( "FilterData" ) )
pValue[ i ].Value >>= aFilterData;
else if ( pValue[ i ].Name.equalsAscii( "StatusIndicator" ) )
pValue[ i ].Value >>= xStatusIndicator;
}
/* we don't get FilterData if we are exporting directly
to pdf, but we have to use the last user settings (especially for the CompressMode) */
if ( !aFilterData.getLength() )
{
FilterConfigItem aCfgItem( String( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/PDF/Export/" ) ) );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "UseLosslessCompression" ) ), sal_False );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Quality" ) ), 90 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "ReduceImageResolution" ) ), sal_False );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "MaxImageResolution" ) ), 300 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "UseTaggedPDF" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "ExportNotes" ) ), sal_True );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "UseTransitionEffects" ) ), sal_True );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "IsSkipEmptyPages" ) ), sal_False );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "FormsType" ) ), 0 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "HideViewerToolbar" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "HideViewerMenubar" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "HideViewerWindowControls" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "ResizeWindowToInitialPage" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "CenterWindow" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "OpenInFullScreenMode" ) ), sal_False );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "DisplayPDFDocumentTitle" ) ), sal_True );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "InitialView" ) ), 0 );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Magnification" ) ), 0 );
aCfgItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "PageLayout" ) ), 0 );
aCfgItem.ReadBool( String( RTL_CONSTASCII_USTRINGPARAM( "FirstPageOnLeft" ) ), sal_False );
//the encryption is not available when exporting directly, since the encryption is off by default and the selection
// (encrypt or not) is not persistent; it's available through macro though,
// provided the correct property values are set, see help
aFilterData = aCfgItem.GetFilterData();
}
if( mxSrcDoc.is() && xOStm.is() )
{
PDFExport aExport( mxSrcDoc, xStatusIndicator );
::utl::TempFile aTempFile;
aTempFile.EnableKillingFile();
bRet = aExport.Export( aTempFile.GetURL(), aFilterData );
if( bRet )
{
SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( aTempFile.GetURL(), STREAM_READ );
if( pIStm )
{
SvOutputStream aOStm( xOStm );
aOStm << *pIStm;
bRet = ( aOStm.Tell() && ( aOStm.GetError() == ERRCODE_NONE ) );
delete pIStm;
}
}
}
return bRet;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL PDFFilter::filter( const Sequence< PropertyValue >& rDescriptor )
throw (RuntimeException)
{
Window* pFocusWindow = Application::GetFocusWindow();
if( pFocusWindow )
pFocusWindow->EnterWait();
const sal_Bool bRet = implExport( rDescriptor );
if( pFocusWindow )
pFocusWindow->LeaveWait();
return bRet;
}
// -----------------------------------------------------------------------------
void SAL_CALL PDFFilter::cancel( ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL PDFFilter::setSourceDocument( const Reference< XComponent >& xDoc )
throw (IllegalArgumentException, RuntimeException)
{
mxSrcDoc = xDoc;
}
// -----------------------------------------------------------------------------
void SAL_CALL PDFFilter::initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& )
throw (Exception, RuntimeException)
{
}
// -----------------------------------------------------------------------------
OUString PDFFilter_getImplementationName ()
throw (RuntimeException)
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.PDF.PDFFilter" ) );
}
// -----------------------------------------------------------------------------
#define SERVICE_NAME "com.sun.star.document.PDFFilter"
sal_Bool SAL_CALL PDFFilter_supportsService( const OUString& ServiceName )
throw (RuntimeException)
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
}
// -----------------------------------------------------------------------------
Sequence< OUString > SAL_CALL PDFFilter_getSupportedServiceNames( ) throw (RuntimeException)
{
Sequence < OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
// -----------------------------------------------------------------------------
Reference< XInterface > SAL_CALL PDFFilter_createInstance( const Reference< XMultiServiceFactory > & rSMgr) throw( Exception )
{
return (cppu::OWeakObject*) new PDFFilter( rSMgr );
}
// -----------------------------------------------------------------------------
OUString SAL_CALL PDFFilter::getImplementationName()
throw (RuntimeException)
{
return PDFFilter_getImplementationName();
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL PDFFilter::supportsService( const OUString& rServiceName )
throw (RuntimeException)
{
return PDFFilter_supportsService( rServiceName );
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< OUString > SAL_CALL PDFFilter::getSupportedServiceNames( ) throw (RuntimeException)
{
return PDFFilter_getSupportedServiceNames();
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* groups_editor.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "groups_editor.h"
#include "scene/gui/box_container.h"
#include "scene/gui/label.h"
#include "editor_node.h"
void GroupsEditor::_add_group(const String& p_group) {
if (!node)
return;
String name = group_name->get_text();
if (name.strip_edges()=="")
return;
if (node->is_in_group(name))
return;
undo_redo->create_action(TTR("Add to Group"));
undo_redo->add_do_method(node,"add_to_group",name,true);
undo_redo->add_do_method(this,"update_tree");
undo_redo->add_undo_method(node,"remove_from_group",name);
undo_redo->add_undo_method(this,"update_tree");
undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
group_name->clear();
}
void GroupsEditor::_remove_group(Object *p_item, int p_column, int p_id) {
if (!node)
return;
TreeItem *ti = p_item->cast_to<TreeItem>();
if (!ti)
return;
String name = ti->get_text(0);
undo_redo->create_action(TTR("Remove from Group"));
undo_redo->add_do_method(node,"remove_from_group",name);
undo_redo->add_do_method(this,"update_tree");
undo_redo->add_undo_method(node,"add_to_group",name,true);
undo_redo->add_undo_method(this,"update_tree");
undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
}
struct _GroupInfoComparator {
bool operator()(const Node::GroupInfo& p_a, const Node::GroupInfo& p_b) const {
return p_a.name.operator String() < p_b.name.operator String();
}
};
void GroupsEditor::update_tree() {
tree->clear();
if (!node)
return;
List<Node::GroupInfo> groups;
node->get_groups(&groups);
groups.sort_custom<_GroupInfoComparator>();
TreeItem *root=tree->create_item();
for(List<GroupInfo>::Element *E=groups.front();E;E=E->next()) {
Node::GroupInfo gi = E->get();
if (!gi.persistent)
continue;
TreeItem *item=tree->create_item(root);
item->set_text(0, gi.name);
item->add_button(0, get_icon("Remove", "EditorIcons"), 0);
}
}
void GroupsEditor::set_current(Node* p_node) {
node=p_node;
update_tree();
}
void GroupsEditor::_bind_methods() {
ObjectTypeDB::bind_method("_add_group",&GroupsEditor::_add_group);
ObjectTypeDB::bind_method("_remove_group",&GroupsEditor::_remove_group);
ObjectTypeDB::bind_method("update_tree",&GroupsEditor::update_tree);
}
GroupsEditor::GroupsEditor() {
node=NULL;
VBoxContainer *vbc = this;
HBoxContainer *hbc = memnew( HBoxContainer );
vbc->add_child(hbc);
group_name = memnew( LineEdit );
group_name->set_h_size_flags(SIZE_EXPAND_FILL);
hbc->add_child(group_name);
group_name->connect("text_entered",this,"_add_group");
add = memnew( Button );
add->set_text(TTR("Add"));
hbc->add_child(add);
add->connect("pressed", this,"_add_group", varray(String()));
tree = memnew( Tree );
tree->set_hide_root(true);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
vbc->add_child(tree);
tree->connect("button_pressed",this,"_remove_group");
add_constant_override("separation",3*EDSCALE);
}
GroupsEditor::~GroupsEditor()
{
}
<commit_msg>do not allow removal of groups that come from instanced/inherited scene, closes #5505<commit_after>/*************************************************************************/
/* groups_editor.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "groups_editor.h"
#include "scene/gui/box_container.h"
#include "scene/gui/label.h"
#include "editor_node.h"
#include "scene/resources/packed_scene.h"
void GroupsEditor::_add_group(const String& p_group) {
if (!node)
return;
String name = group_name->get_text();
if (name.strip_edges()=="")
return;
if (node->is_in_group(name))
return;
undo_redo->create_action(TTR("Add to Group"));
undo_redo->add_do_method(node,"add_to_group",name,true);
undo_redo->add_do_method(this,"update_tree");
undo_redo->add_undo_method(node,"remove_from_group",name);
undo_redo->add_undo_method(this,"update_tree");
undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
group_name->clear();
}
void GroupsEditor::_remove_group(Object *p_item, int p_column, int p_id) {
if (!node)
return;
TreeItem *ti = p_item->cast_to<TreeItem>();
if (!ti)
return;
String name = ti->get_text(0);
undo_redo->create_action(TTR("Remove from Group"));
undo_redo->add_do_method(node,"remove_from_group",name);
undo_redo->add_do_method(this,"update_tree");
undo_redo->add_undo_method(node,"add_to_group",name,true);
undo_redo->add_undo_method(this,"update_tree");
undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
}
struct _GroupInfoComparator {
bool operator()(const Node::GroupInfo& p_a, const Node::GroupInfo& p_b) const {
return p_a.name.operator String() < p_b.name.operator String();
}
};
void GroupsEditor::update_tree() {
tree->clear();
if (!node)
return;
List<Node::GroupInfo> groups;
node->get_groups(&groups);
groups.sort_custom<_GroupInfoComparator>();
TreeItem *root=tree->create_item();
for(List<GroupInfo>::Element *E=groups.front();E;E=E->next()) {
Node::GroupInfo gi = E->get();
if (!gi.persistent)
continue;
Node *n = node;
bool can_be_deleted=true;
while(n) {
Ref<SceneState> ss = (n==EditorNode::get_singleton()->get_edited_scene()) ? n->get_scene_inherited_state() : n->get_scene_instance_state();
if (ss.is_valid()) {
int path = ss->find_node_by_path(n->get_path_to(node));
if (path!=-1) {
if (ss->is_node_in_group(path,gi.name)) {
can_be_deleted=false;
}
}
}
n=n->get_owner();
}
TreeItem *item=tree->create_item(root);
item->set_text(0, gi.name);
if (can_be_deleted) {
item->add_button(0, get_icon("Remove", "EditorIcons"), 0);
} else {
item->set_selectable(0,false);
}
}
}
void GroupsEditor::set_current(Node* p_node) {
node=p_node;
update_tree();
}
void GroupsEditor::_bind_methods() {
ObjectTypeDB::bind_method("_add_group",&GroupsEditor::_add_group);
ObjectTypeDB::bind_method("_remove_group",&GroupsEditor::_remove_group);
ObjectTypeDB::bind_method("update_tree",&GroupsEditor::update_tree);
}
GroupsEditor::GroupsEditor() {
node=NULL;
VBoxContainer *vbc = this;
HBoxContainer *hbc = memnew( HBoxContainer );
vbc->add_child(hbc);
group_name = memnew( LineEdit );
group_name->set_h_size_flags(SIZE_EXPAND_FILL);
hbc->add_child(group_name);
group_name->connect("text_entered",this,"_add_group");
add = memnew( Button );
add->set_text(TTR("Add"));
hbc->add_child(add);
add->connect("pressed", this,"_add_group", varray(String()));
tree = memnew( Tree );
tree->set_hide_root(true);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
vbc->add_child(tree);
tree->connect("button_pressed",this,"_remove_group");
add_constant_override("separation",3*EDSCALE);
}
GroupsEditor::~GroupsEditor()
{
}
<|endoftext|> |
<commit_before>// PC implementation of the framework.
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <ShellAPI.h>
#else
#include <pwd.h>
#include <unistd.h>
#endif
#include <string>
#include "SDL/SDL.h"
#include "SDL/SDL_timer.h"
#include "SDL/SDL_audio.h"
#include "SDL/SDL_video.h"
#include "base/display.h"
#include "base/logging.h"
#include "base/timeutil.h"
#include "gfx_es2/glsl_program.h"
#include "file/zip_read.h"
#include "input/input_state.h"
#include "base/NativeApp.h"
#include "net/resolve.h"
// Simple implementations of System functions
void SystemToast(const char *text) {
#ifdef _WIN32
MessageBox(0, text, "Toast!", MB_ICONINFORMATION);
#else
puts(text);
#endif
}
void ShowAd(int x, int y, bool center_x) {
// Ignore ads on PC
}
void ShowKeyboard() {
// Irrelevant on PC
}
void Vibrate(int length_ms) {
// Ignore on PC
}
void LaunchBrowser(const char *url)
{
#ifdef _WIN32
ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
#else
ILOG("Would have gone to %s but LaunchBrowser is not implemented on this platform", url);
#endif
}
void LaunchMarket(const char *url)
{
#ifdef _WIN32
ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
#else
ILOG("Would have gone to %s but LaunchMarket is not implemented on this platform", url);
#endif
}
void LaunchEmail(const char *email_address)
{
#ifdef _WIN32
ShellExecute(NULL, "open", (std::string("mailto:") + email_address).c_str(), NULL, NULL, SW_SHOWNORMAL);
#else
ILOG("Would have opened your email client for %s but LaunchEmail is not implemented on this platform", email_address);
#endif
}
const int buttonMappings[14] = {
SDLK_x, //A
SDLK_s, //B
SDLK_z, //X
SDLK_a, //Y
SDLK_w, //LBUMPER
SDLK_q, //RBUMPER
SDLK_1, //START
SDLK_2, //SELECT
SDLK_UP, //UP
SDLK_DOWN, //DOWN
SDLK_LEFT, //LEFT
SDLK_RIGHT, //RIGHT
SDLK_m, //MENU
SDLK_BACKSPACE, //BACK
};
void SimulateGamepad(const uint8 *keys, InputState *input) {
input->pad_buttons = 0;
input->pad_lstick_x = 0;
input->pad_lstick_y = 0;
input->pad_rstick_x = 0;
input->pad_rstick_y = 0;
for (int b = 0; b < 14; b++) {
if (keys[buttonMappings[b]])
input->pad_buttons |= (1<<b);
}
if (keys[SDLK_i])
input->pad_lstick_y=1;
else if (keys[SDLK_k])
input->pad_lstick_y=-1;
if (keys[SDLK_j])
input->pad_lstick_x=-1;
else if (keys[SDLK_l])
input->pad_lstick_x=1;
if (keys[SDLK_KP8])
input->pad_rstick_y=1;
else if (keys[SDLK_KP2])
input->pad_rstick_y=-1;
if (keys[SDLK_KP4])
input->pad_rstick_x=-1;
else if (keys[SDLK_KP6])
input->pad_rstick_x=1;
}
extern void mixaudio(void *userdata, Uint8 *stream, int len) {
NativeMix((short *)stream, len / 4);
}
#ifdef _WIN32
#undef main
#endif
int main(int argc, char *argv[]) {
std::string app_name;
std::string app_name_nice;
float zoom = 1.0f;
bool tablet = false;
const char *zoomenv = getenv("ZOOM");
const char *tabletenv = getenv("TABLET");
if (zoomenv) {
zoom = atof(zoomenv);
}
if (tabletenv) {
tablet = (bool)atoi(tabletenv);
}
bool landscape;
NativeGetAppInfo(&app_name, &app_name_nice, &landscape);
tablet = false;
if (landscape) {
if (tablet) {
pixel_xres = 1280 * zoom;
pixel_yres = 800 * zoom;
} else {
pixel_xres = 800 * zoom;
pixel_yres = 480 * zoom;
}
} else {
// PC development hack for more space
//pixel_xres = 1580 * zoom;
//pixel_yres = 1000 * zoom;
if (tablet) {
pixel_xres = 800 * zoom;
pixel_yres = 1280 * zoom;
} else {
pixel_xres = 480 * zoom;
pixel_yres = 800 * zoom;
}
}
net::Init();
#ifdef __APPLE__
// Make sure to request a somewhat modern GL context at least - the
// latest supported by MacOSX (really, really sad...)
// Requires SDL 2.0 (which is even more sad, as that hasn't been released yet)
//SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
//SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
#endif
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
if (SDL_SetVideoMode(pixel_xres, pixel_yres, 0, SDL_OPENGL) == NULL) {
fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError());
SDL_Quit();
return(2);
}
SDL_WM_SetCaption(app_name_nice.c_str(), NULL);
if (GLEW_OK != glewInit()) {
printf("Failed to initialize glew!\n");
return 1;
}
if (GLEW_VERSION_2_0) {
printf("OpenGL 2.0 or higher.\n");
} else {
printf("Sorry, this program requires OpenGL 2.0.\n");
return 1;
}
#ifdef _MSC_VER
// VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\"));
TCHAR path[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path);
PathAppend(path, (app_name + "\\").c_str());
#else
// Mac / Linux
char path[512];
const char *the_path = getenv("HOME");
if (!the_path) {
struct passwd* pwd = getpwuid(getuid());
if (pwd)
the_path = pwd->pw_dir;
}
strcpy(path, the_path);
if (path[strlen(path)-1] != '/')
strcat(path, "/");
#endif
#ifdef _WIN32
NativeInit(argc, (const char **)argv, path, "D:\\", "BADCOFFEE");
#else
NativeInit(argc, (const char **)argv, path, "/tmp", "BADCOFFEE");
#endif
float density = 1.0f;
dp_xres = (float)pixel_xres * density / zoom;
dp_yres = (float)pixel_yres * density / zoom;
pixel_in_dps = (float)pixel_xres / dp_xres;
NativeInitGraphics();
float dp_xscale = (float)dp_xres / pixel_xres;
float dp_yscale = (float)dp_yres / pixel_yres;
printf("Pixels: %i x %i\n", pixel_xres, pixel_yres);
printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres);
SDL_AudioSpec fmt;
fmt.freq = 44100;
fmt.format = AUDIO_S16;
fmt.channels = 2;
fmt.samples = 1024;
fmt.callback = &mixaudio;
fmt.userdata = (void *)0;
if (SDL_OpenAudio(&fmt, NULL) < 0) {
ELOG("Failed to open audio: %s", SDL_GetError());
return 1;
}
// Audio must be unpaused _after_ NativeInit()
SDL_PauseAudio(0);
InputState input_state;
int framecount = 0;
bool nextFrameMD = 0;
float t = 0;
while (true) {
input_state.accelerometer_valid = false;
input_state.mouse_valid = true;
int quitRequested = 0;
SDL_Event event;
while (SDL_PollEvent(&event)) {
float mx = event.motion.x * dp_xscale;
float my = event.motion.y * dp_yscale;
if (event.type == SDL_QUIT) {
quitRequested = 1;
} else if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_ESCAPE) {
quitRequested = 1;
}
} else if (event.type == SDL_MOUSEMOTION) {
input_state.pointer_x[0] = mx;
input_state.pointer_y[0] = my;
NativeTouch(0, mx, my, 0, TOUCH_MOVE);
} else if (event.type == SDL_MOUSEBUTTONDOWN) {
if (event.button.button == SDL_BUTTON_LEFT) {
//input_state.mouse_buttons_down = 1;
input_state.pointer_down[0] = true;
nextFrameMD = true;
NativeTouch(0, mx, my, 0, TOUCH_DOWN);
}
} else if (event.type == SDL_MOUSEBUTTONUP) {
if (event.button.button == SDL_BUTTON_LEFT) {
input_state.pointer_down[0] = false;
nextFrameMD = false;
//input_state.mouse_buttons_up = 1;
NativeTouch(0, mx, my, 0, TOUCH_UP);
}
}
}
if (quitRequested)
break;
const uint8 *keys = (const uint8 *)SDL_GetKeyState(NULL);
if (keys[SDLK_ESCAPE])
break;
SimulateGamepad(keys, &input_state);
UpdateInputState(&input_state);
NativeUpdate(input_state);
NativeRender();
EndInputState(&input_state);
if (framecount % 60 == 0) {
// glsl_refresh(); // auto-reloads modified GLSL shaders once per second.
}
SDL_GL_SwapBuffers();
// Simple frame rate limiting
while (time_now() < t + 1.0f/60.0f) {
sleep_ms(0);
time_update();
}
time_update();
t = time_now();
framecount++;
}
// Faster exit, thanks to the OS. Remove this if you want to debug shutdown
// The speed difference is only really noticable on Linux. On Windows you do notice it though
// exit(0);
NativeShutdownGraphics();
SDL_PauseAudio(1);
SDL_CloseAudio();
NativeShutdown();
SDL_Quit();
net::Shutdown();
exit(0);
return 0;
}
<commit_msg>Include SDL.h instead of SDL/SDL.h<commit_after>// PC implementation of the framework.
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <ShellAPI.h>
#else
#include <pwd.h>
#include <unistd.h>
#endif
#include <string>
#include "SDL.h"
#include "SDL_timer.h"
#include "SDL_audio.h"
#include "SDL_video.h"
#include "base/display.h"
#include "base/logging.h"
#include "base/timeutil.h"
#include "gfx_es2/glsl_program.h"
#include "file/zip_read.h"
#include "input/input_state.h"
#include "base/NativeApp.h"
#include "net/resolve.h"
// Simple implementations of System functions
void SystemToast(const char *text) {
#ifdef _WIN32
MessageBox(0, text, "Toast!", MB_ICONINFORMATION);
#else
puts(text);
#endif
}
void ShowAd(int x, int y, bool center_x) {
// Ignore ads on PC
}
void ShowKeyboard() {
// Irrelevant on PC
}
void Vibrate(int length_ms) {
// Ignore on PC
}
void LaunchBrowser(const char *url)
{
#ifdef _WIN32
ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
#else
ILOG("Would have gone to %s but LaunchBrowser is not implemented on this platform", url);
#endif
}
void LaunchMarket(const char *url)
{
#ifdef _WIN32
ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
#else
ILOG("Would have gone to %s but LaunchMarket is not implemented on this platform", url);
#endif
}
void LaunchEmail(const char *email_address)
{
#ifdef _WIN32
ShellExecute(NULL, "open", (std::string("mailto:") + email_address).c_str(), NULL, NULL, SW_SHOWNORMAL);
#else
ILOG("Would have opened your email client for %s but LaunchEmail is not implemented on this platform", email_address);
#endif
}
const int buttonMappings[14] = {
SDLK_x, //A
SDLK_s, //B
SDLK_z, //X
SDLK_a, //Y
SDLK_w, //LBUMPER
SDLK_q, //RBUMPER
SDLK_1, //START
SDLK_2, //SELECT
SDLK_UP, //UP
SDLK_DOWN, //DOWN
SDLK_LEFT, //LEFT
SDLK_RIGHT, //RIGHT
SDLK_m, //MENU
SDLK_BACKSPACE, //BACK
};
void SimulateGamepad(const uint8 *keys, InputState *input) {
input->pad_buttons = 0;
input->pad_lstick_x = 0;
input->pad_lstick_y = 0;
input->pad_rstick_x = 0;
input->pad_rstick_y = 0;
for (int b = 0; b < 14; b++) {
if (keys[buttonMappings[b]])
input->pad_buttons |= (1<<b);
}
if (keys[SDLK_i])
input->pad_lstick_y=1;
else if (keys[SDLK_k])
input->pad_lstick_y=-1;
if (keys[SDLK_j])
input->pad_lstick_x=-1;
else if (keys[SDLK_l])
input->pad_lstick_x=1;
if (keys[SDLK_KP8])
input->pad_rstick_y=1;
else if (keys[SDLK_KP2])
input->pad_rstick_y=-1;
if (keys[SDLK_KP4])
input->pad_rstick_x=-1;
else if (keys[SDLK_KP6])
input->pad_rstick_x=1;
}
extern void mixaudio(void *userdata, Uint8 *stream, int len) {
NativeMix((short *)stream, len / 4);
}
#ifdef _WIN32
#undef main
#endif
int main(int argc, char *argv[]) {
std::string app_name;
std::string app_name_nice;
float zoom = 1.0f;
bool tablet = false;
const char *zoomenv = getenv("ZOOM");
const char *tabletenv = getenv("TABLET");
if (zoomenv) {
zoom = atof(zoomenv);
}
if (tabletenv) {
tablet = (bool)atoi(tabletenv);
}
bool landscape;
NativeGetAppInfo(&app_name, &app_name_nice, &landscape);
tablet = false;
if (landscape) {
if (tablet) {
pixel_xres = 1280 * zoom;
pixel_yres = 800 * zoom;
} else {
pixel_xres = 800 * zoom;
pixel_yres = 480 * zoom;
}
} else {
// PC development hack for more space
//pixel_xres = 1580 * zoom;
//pixel_yres = 1000 * zoom;
if (tablet) {
pixel_xres = 800 * zoom;
pixel_yres = 1280 * zoom;
} else {
pixel_xres = 480 * zoom;
pixel_yres = 800 * zoom;
}
}
net::Init();
#ifdef __APPLE__
// Make sure to request a somewhat modern GL context at least - the
// latest supported by MacOSX (really, really sad...)
// Requires SDL 2.0 (which is even more sad, as that hasn't been released yet)
//SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
//SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
#endif
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
if (SDL_SetVideoMode(pixel_xres, pixel_yres, 0, SDL_OPENGL) == NULL) {
fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError());
SDL_Quit();
return(2);
}
SDL_WM_SetCaption(app_name_nice.c_str(), NULL);
if (GLEW_OK != glewInit()) {
printf("Failed to initialize glew!\n");
return 1;
}
if (GLEW_VERSION_2_0) {
printf("OpenGL 2.0 or higher.\n");
} else {
printf("Sorry, this program requires OpenGL 2.0.\n");
return 1;
}
#ifdef _MSC_VER
// VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\"));
TCHAR path[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path);
PathAppend(path, (app_name + "\\").c_str());
#else
// Mac / Linux
char path[512];
const char *the_path = getenv("HOME");
if (!the_path) {
struct passwd* pwd = getpwuid(getuid());
if (pwd)
the_path = pwd->pw_dir;
}
strcpy(path, the_path);
if (path[strlen(path)-1] != '/')
strcat(path, "/");
#endif
#ifdef _WIN32
NativeInit(argc, (const char **)argv, path, "D:\\", "BADCOFFEE");
#else
NativeInit(argc, (const char **)argv, path, "/tmp", "BADCOFFEE");
#endif
float density = 1.0f;
dp_xres = (float)pixel_xres * density / zoom;
dp_yres = (float)pixel_yres * density / zoom;
pixel_in_dps = (float)pixel_xres / dp_xres;
NativeInitGraphics();
float dp_xscale = (float)dp_xres / pixel_xres;
float dp_yscale = (float)dp_yres / pixel_yres;
printf("Pixels: %i x %i\n", pixel_xres, pixel_yres);
printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres);
SDL_AudioSpec fmt;
fmt.freq = 44100;
fmt.format = AUDIO_S16;
fmt.channels = 2;
fmt.samples = 1024;
fmt.callback = &mixaudio;
fmt.userdata = (void *)0;
if (SDL_OpenAudio(&fmt, NULL) < 0) {
ELOG("Failed to open audio: %s", SDL_GetError());
return 1;
}
// Audio must be unpaused _after_ NativeInit()
SDL_PauseAudio(0);
InputState input_state;
int framecount = 0;
bool nextFrameMD = 0;
float t = 0;
while (true) {
input_state.accelerometer_valid = false;
input_state.mouse_valid = true;
int quitRequested = 0;
SDL_Event event;
while (SDL_PollEvent(&event)) {
float mx = event.motion.x * dp_xscale;
float my = event.motion.y * dp_yscale;
if (event.type == SDL_QUIT) {
quitRequested = 1;
} else if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_ESCAPE) {
quitRequested = 1;
}
} else if (event.type == SDL_MOUSEMOTION) {
input_state.pointer_x[0] = mx;
input_state.pointer_y[0] = my;
NativeTouch(0, mx, my, 0, TOUCH_MOVE);
} else if (event.type == SDL_MOUSEBUTTONDOWN) {
if (event.button.button == SDL_BUTTON_LEFT) {
//input_state.mouse_buttons_down = 1;
input_state.pointer_down[0] = true;
nextFrameMD = true;
NativeTouch(0, mx, my, 0, TOUCH_DOWN);
}
} else if (event.type == SDL_MOUSEBUTTONUP) {
if (event.button.button == SDL_BUTTON_LEFT) {
input_state.pointer_down[0] = false;
nextFrameMD = false;
//input_state.mouse_buttons_up = 1;
NativeTouch(0, mx, my, 0, TOUCH_UP);
}
}
}
if (quitRequested)
break;
const uint8 *keys = (const uint8 *)SDL_GetKeyState(NULL);
if (keys[SDLK_ESCAPE])
break;
SimulateGamepad(keys, &input_state);
UpdateInputState(&input_state);
NativeUpdate(input_state);
NativeRender();
EndInputState(&input_state);
if (framecount % 60 == 0) {
// glsl_refresh(); // auto-reloads modified GLSL shaders once per second.
}
SDL_GL_SwapBuffers();
// Simple frame rate limiting
while (time_now() < t + 1.0f/60.0f) {
sleep_ms(0);
time_update();
}
time_update();
t = time_now();
framecount++;
}
// Faster exit, thanks to the OS. Remove this if you want to debug shutdown
// The speed difference is only really noticable on Linux. On Windows you do notice it though
// exit(0);
NativeShutdownGraphics();
SDL_PauseAudio(1);
SDL_CloseAudio();
NativeShutdown();
SDL_Quit();
net::Shutdown();
exit(0);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __INTMATH_HH__
#define __INTMATH_HH__
#include <assert.h>
#include "sim/host.hh"
// Returns the prime number one less than n.
int PrevPrime(int n);
// Determine if a number is prime
template <class T>
inline bool
IsPrime(T n)
{
T i;
if (n == 2 || n == 3)
return true;
// Don't try every odd number to prove if it is a prime.
// Toggle between every 2nd and 4th number.
// (This is because every 6th odd number is divisible by 3.)
for (i = 5; i*i <= n; i += 6) {
if (((n % i) == 0 ) || ((n % (i + 2)) == 0) ) {
return false;
}
}
return true;
}
template <class T>
inline T
LeastSigBit(T n)
{
return n & ~(n - 1);
}
template <class T>
inline bool
IsPowerOf2(T n)
{
return n != 0 && LeastSigBit(n) == n;
}
inline int
FloorLog2(uint32_t x)
{
assert(x > 0);
int y = 0;
if (x & 0xffff0000) { y += 16; x >>= 16; }
if (x & 0x0000ff00) { y += 8; x >>= 8; }
if (x & 0x000000f0) { y += 4; x >>= 4; }
if (x & 0x0000000c) { y += 2; x >>= 2; }
if (x & 0x00000002) { y += 1; }
return y;
}
inline int
FloorLog2(uint64_t x)
{
assert(x > 0);
int y = 0;
if (x & ULL(0xffffffff00000000)) { y += 32; x >>= 32; }
if (x & ULL(0x00000000ffff0000)) { y += 16; x >>= 16; }
if (x & ULL(0x000000000000ff00)) { y += 8; x >>= 8; }
if (x & ULL(0x00000000000000f0)) { y += 4; x >>= 4; }
if (x & ULL(0x000000000000000c)) { y += 2; x >>= 2; }
if (x & ULL(0x0000000000000002)) { y += 1; }
return y;
}
inline int
FloorLog2(int32_t x)
{
assert(x > 0);
return FloorLog2(x);
}
inline int
FloorLog2(int64_t x)
{
assert(x > 0);
return FloorLog2(x);
}
template <class T>
inline int
CeilLog2(T n)
{
if (n == 1)
return 0;
return FloorLog2(n - (T)1) + 1;
}
template <class T>
inline T
FloorPow2(T n)
{
return (T)1 << FloorLog2(n);
}
template <class T>
inline T
CeilPow2(T n)
{
return (T)1 << CeilLog2(n);
}
template <class T>
inline T
DivCeil(T a, T b)
{
return (a + b - 1) / b;
}
template <class T>
inline T
RoundUp(T val, T align)
{
T mask = align - 1;
return (val + mask) & ~mask;
}
template <class T>
inline T
RoundDown(T val, T align)
{
T mask = align - 1;
return val & ~mask;
}
inline bool
IsHex(char c)
{
return c >= '0' && c <= '9' ||
c >= 'A' && c <= 'F' ||
c >= 'a' && c <= 'f';
}
inline bool
IsOct(char c)
{
return c >= '0' && c <= '7';
}
inline bool
IsDec(char c)
{
return c >= '0' && c <= '9';
}
inline int
Hex2Int(char c)
{
if (c >= '0' && c <= '9')
return (c - '0');
if (c >= 'A' && c <= 'F')
return (c - 'A') + 10;
if (c >= 'a' && c <= 'f')
return (c - 'a') + 10;
return 0;
}
#endif // __INTMATH_HH__
<commit_msg>Need to cast to avoid infinite recursion.<commit_after>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __INTMATH_HH__
#define __INTMATH_HH__
#include <assert.h>
#include "sim/host.hh"
// Returns the prime number one less than n.
int PrevPrime(int n);
// Determine if a number is prime
template <class T>
inline bool
IsPrime(T n)
{
T i;
if (n == 2 || n == 3)
return true;
// Don't try every odd number to prove if it is a prime.
// Toggle between every 2nd and 4th number.
// (This is because every 6th odd number is divisible by 3.)
for (i = 5; i*i <= n; i += 6) {
if (((n % i) == 0 ) || ((n % (i + 2)) == 0) ) {
return false;
}
}
return true;
}
template <class T>
inline T
LeastSigBit(T n)
{
return n & ~(n - 1);
}
template <class T>
inline bool
IsPowerOf2(T n)
{
return n != 0 && LeastSigBit(n) == n;
}
inline int
FloorLog2(uint32_t x)
{
assert(x > 0);
int y = 0;
if (x & 0xffff0000) { y += 16; x >>= 16; }
if (x & 0x0000ff00) { y += 8; x >>= 8; }
if (x & 0x000000f0) { y += 4; x >>= 4; }
if (x & 0x0000000c) { y += 2; x >>= 2; }
if (x & 0x00000002) { y += 1; }
return y;
}
inline int
FloorLog2(uint64_t x)
{
assert(x > 0);
int y = 0;
if (x & ULL(0xffffffff00000000)) { y += 32; x >>= 32; }
if (x & ULL(0x00000000ffff0000)) { y += 16; x >>= 16; }
if (x & ULL(0x000000000000ff00)) { y += 8; x >>= 8; }
if (x & ULL(0x00000000000000f0)) { y += 4; x >>= 4; }
if (x & ULL(0x000000000000000c)) { y += 2; x >>= 2; }
if (x & ULL(0x0000000000000002)) { y += 1; }
return y;
}
inline int
FloorLog2(int32_t x)
{
assert(x > 0);
return FloorLog2((uint32_t)x);
}
inline int
FloorLog2(int64_t x)
{
assert(x > 0);
return FloorLog2((uint64_t)x);
}
template <class T>
inline int
CeilLog2(T n)
{
if (n == 1)
return 0;
return FloorLog2(n - (T)1) + 1;
}
template <class T>
inline T
FloorPow2(T n)
{
return (T)1 << FloorLog2(n);
}
template <class T>
inline T
CeilPow2(T n)
{
return (T)1 << CeilLog2(n);
}
template <class T>
inline T
DivCeil(T a, T b)
{
return (a + b - 1) / b;
}
template <class T>
inline T
RoundUp(T val, T align)
{
T mask = align - 1;
return (val + mask) & ~mask;
}
template <class T>
inline T
RoundDown(T val, T align)
{
T mask = align - 1;
return val & ~mask;
}
inline bool
IsHex(char c)
{
return c >= '0' && c <= '9' ||
c >= 'A' && c <= 'F' ||
c >= 'a' && c <= 'f';
}
inline bool
IsOct(char c)
{
return c >= '0' && c <= '7';
}
inline bool
IsDec(char c)
{
return c >= '0' && c <= '9';
}
inline int
Hex2Int(char c)
{
if (c >= '0' && c <= '9')
return (c - '0');
if (c >= 'A' && c <= 'F')
return (c - 'A') + 10;
if (c >= 'a' && c <= 'f')
return (c - 'a') + 10;
return 0;
}
#endif // __INTMATH_HH__
<|endoftext|> |
<commit_before>//============================================================================
// Name : brainfuck_rpc_emulator.cpp
// Author : Artem Kashkanov
// Version :
// Copyright :
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <cstring>
#include "Console.h"
#include <fstream>
#include <vector>
#include "bfutils.h"
using namespace std;
uint8_t LoadImage(std::ifstream &File, BfHeader_t *Header, uint16_t *MemoryPtr){
uint8_t status = 0;
File.read(reinterpret_cast<char *>(Header), sizeof(BfHeader_t));
BfSection_t Code;
Code.Position.Byte.high = Header->Code.Position.Byte.high;
Code.Position.Byte.low = Header->Code.Position.Byte.low;
Code.Length.Byte.high = Header->Code.Length.Byte.high;
Code.Length.Byte.low = Header->Code.Length.Byte.low;
BfSection_t Data;
Data.Position.Byte.high = Header->Data.Position.Byte.high;
Data.Position.Byte.low = Header->Data.Position.Byte.low;
Data.Length.Byte.high = Header->Data.Length.Byte.high;
Data.Length.Byte.low = Header->Data.Length.Byte.low;
File.read(reinterpret_cast<char *>(MemoryPtr+Code.Position.Word), sizeof(uint16_t)*Code.Length.Word);
if (Data.Length.Word != 0){
File.read(reinterpret_cast<char *>(MemoryPtr+Data.Position.Word), sizeof(uint16_t)*Data.Length.Word);
}
return status;
}
uint8_t LoadBF(char *fName, BfHeader_t *Header, uint16_t *MemoryPtr){
uint8_t status = 0;
std::ifstream File(fName, std::ifstream::binary);
if (!File.good()){
return -1;
}
LoadImage(File, Header, MemoryPtr);
return status;
}
bool SegFault(const BfSection_t §ion, uint16_t Ptr){
bool result = false;
if ((Ptr < section.Position.Word) ||(Ptr > section.Position.Word + section.Length.Word)){
result = true;
}
return result;
}
uint8_t ExecCmd(BfHeader_t *Header, uint16_t *MemoryPtr, uint16_t &IP, uint16_t &AP){
uint8_t status = SUCCESS;
uint16_t cmd = MemoryPtr[IP];
uint16_t cmd_bin = ((cmd>>13) & 0x0007);
bool sign = ((cmd >> 12)&0x01)? true: false;
uint16_t bias = (cmd&0x0FFF);
switch (cmd_bin){
case 0:
MemoryPtr[AP] = sign? MemoryPtr[AP] - bias: MemoryPtr[AP] + bias;
break;
case 1:
AP = sign? AP - bias: AP + bias;
if (SegFault(Header->Data, AP)){
return -1;
}
break;
case 2:
MemoryPtr[AP] = In();
break;
case 3:
Out(MemoryPtr[AP]);
break;
case 4:
IP = MemoryPtr[AP]? IP : (sign? IP - bias: IP + bias);
if (SegFault(Header->Data, IP)){
return -1;
}
break;
case 5:
IP = MemoryPtr[AP]? (sign? IP - bias: IP + bias) : IP;
if (SegFault(Header->Data, IP)){
return -1;
}
break;
case 6:
IP = bias;
if (SegFault(Header->Data, IP)){
return -1;
}
break;
case 7:
AP = Header->Data.Position.Word + bias;
if (SegFault(Header->Data, AP)){
return -1;
}
break;
}
return status;
}
uint8_t ExecCode(BfHeader_t *Header, uint16_t *MemoryPtr){
uint8_t status = 0;
uint16_t IP = Header->Code.Position.Word;
uint16_t AP = Header->Data.Position.Word;
do {
status = ExecCmd(Header,MemoryPtr, IP, AP);
if (status){
return -1;
}
IP++;
}while (IP < Header->Code.Position.Word + Header->Code.Length.Word);
return status;
}
int main(int argc, char *argv[]) {
int status = -1;
int c = 0;
char filePath[4096] = {0x00};
while((c = getopt(argc, argv, "f:c:di")) != -1){
switch(c)
{
case 'f':
strcpy(filePath,optarg);
break;
}
}
if (*filePath == 0){
cout << "Fatal error: add input file"<< endl;
return -1;
}
BfHeader_t *Header = new BfHeader_t;
uint16_t Memory[65536];
memset(&Memory,0,sizeof(Memory));
status = LoadBF(filePath,Header,Memory);
if (status){
return -1;
}
ExecCode(Header, Memory);
return 0;
}
<commit_msg>FIX: BFRUN perform helloworld correctly<commit_after>//============================================================================
// Name : brainfuck_rpc_emulator.cpp
// Author : Artem Kashkanov
// Version :
// Copyright :
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <cstring>
#include "Console.h"
#include <fstream>
#include <vector>
#include "bfutils.h"
using namespace std;
bool ProtectedModeEnabled = false;
void SetProtectedMode(bool mode){
ProtectedModeEnabled = mode;
}
bool GetProtectedMode(void){
return ProtectedModeEnabled;
}
//Set 16-bit word mode:
bool WordModeEnabled = false;
void SetWordMode(bool mode){
WordModeEnabled = mode;
}
bool GetWordMode(void){
return WordModeEnabled;
}
void swapLEtoBE(WordToBigEndian_t *array, size_t size){
uint8_t tmp = 0;
for (size_t i = 0; i < size/sizeof(uint16_t); ++i){
tmp = array[i].Byte.low;
array[i].Byte.low = array[i].Byte.high;
array[i].Byte.high = tmp;
}
}
uint8_t LoadImage(std::ifstream &File, BfHeader_t *Header, uint16_t *MemoryPtr){
uint8_t status = 0;
File.read(reinterpret_cast<char *>(Header), sizeof(BfHeader_t));
swapLEtoBE((WordToBigEndian_t*)(Header), sizeof(BfHeader_t));
BfSection_t Code;
Code.Position.Byte.high = Header->Code.Position.Byte.high;
Code.Position.Byte.low = Header->Code.Position.Byte.low;
Code.Length.Byte.high = Header->Code.Length.Byte.high;
Code.Length.Byte.low = Header->Code.Length.Byte.low;
BfSection_t Data;
Data.Position.Byte.high = Header->Data.Position.Byte.high;
Data.Position.Byte.low = Header->Data.Position.Byte.low;
Data.Length.Byte.high = Header->Data.Length.Byte.high;
Data.Length.Byte.low = Header->Data.Length.Byte.low;
File.read(reinterpret_cast<char *>(MemoryPtr+Code.Position.Word), sizeof(uint16_t)*Code.Length.Word);
swapLEtoBE((WordToBigEndian_t*)(MemoryPtr+Code.Position.Word),sizeof(uint16_t)*Code.Length.Word);
if (Data.Length.Word != 0){
File.read(reinterpret_cast<char *>(MemoryPtr+Data.Position.Word), sizeof(uint16_t)*Data.Length.Word);
swapLEtoBE((WordToBigEndian_t*)(MemoryPtr+Data.Position.Word), sizeof(uint16_t)*Data.Length.Word);
}
return status;
}
uint8_t LoadBF(char *fName, BfHeader_t *Header, uint16_t *MemoryPtr){
uint8_t status = 0;
std::ifstream File(fName, std::ifstream::binary);
if (!File.good()){
return -1;
}
LoadImage(File, Header, MemoryPtr);
return status;
}
bool SegFault(const BfSection_t §ion, uint16_t Ptr){
bool result = false;
if ((Ptr < section.Position.Word) ||(Ptr > section.Position.Word + section.Length.Word)){
result = true;
}
return (GetProtectedMode()? result : false);
}
uint8_t ExecCmd(BfHeader_t *Header, uint16_t *MemoryPtr, uint16_t &IP, uint16_t &AP){
uint8_t status = SUCCESS;
uint16_t cmd = MemoryPtr[IP];
uint16_t cmd_bin = ((cmd>>13) & 0x0007);
bool sign = ((cmd >> 12)&0x01)? true: false;
uint16_t bias = (cmd&0x0FFF);
switch (cmd_bin){
case 0:// '<' and '>' commands
MemoryPtr[AP] = sign? MemoryPtr[AP] - bias: MemoryPtr[AP] + bias;
break;
case 1:// '+' and '-' commands
AP = sign? AP - bias: AP + bias;
if (SegFault(Header->Data, AP)){
return -1;
}
break;
case 2://Console input cmd
if (GetWordMode()){
MemoryPtr[AP] = In();
}
else{
MemoryPtr[AP] = In() & 0xFF;
}
break;
case 3://console output cmd
if (GetWordMode()){
Out(MemoryPtr[AP]);
}
else{
Out(MemoryPtr[AP] & 0xFF);
}
break;
case 4://Jump If Zero
if (GetWordMode()){
IP = MemoryPtr[AP]? IP : (sign? IP - bias: IP + bias);
}
else{
IP = (MemoryPtr[AP] & 0xFF)? IP : (sign? IP - bias: IP + bias);
}
if (SegFault(Header->Data, IP)){
return -2;
}
break;
case 5://Jump If not zero
if (GetWordMode()){
IP = MemoryPtr[AP]? (sign? IP - bias: IP + bias) : IP;
}
else{
IP = (MemoryPtr[AP] & 0xFF)? (sign? IP - bias: IP + bias) : IP;
}
if (SegFault(Header->Data, IP)){
return -3;
}
break;
case 6://Set IP
IP = bias;
if (SegFault(Header->Data, IP)){
return -4;
}
break;
case 7://Set AP
AP = Header->Data.Position.Word + bias;
if (SegFault(Header->Data, AP)){
return -5;
}
break;
}
return status;
}
uint8_t ExecCode(BfHeader_t *Header, uint16_t *MemoryPtr){
uint8_t status = 0;
uint16_t IP = Header->Code.Position.Word;
uint16_t AP = Header->Data.Position.Word;
size_t i = 0;
do {
i++;
status = ExecCmd(Header,MemoryPtr, IP, AP);
if (status){
return -1;
}
IP++;
}while (IP < Header->Code.Position.Word + Header->Code.Length.Word);
cerr << "\r\nIstructions_retired:" << i << "\r\n";
return status;
}
int main(int argc, char *argv[]) {
int status = -1;
int c = 0;
char filePath[4096] = {0x00};
while((c = getopt(argc, argv, "f:px")) != -1){
switch(c)
{
case 'f':
strcpy(filePath,optarg);
break;
case 'p':
SetProtectedMode(true);
break;
case 'x':
SetWordMode(true);
break;
}
}
if (*filePath == 0){
cout << "Fatal error: add input file"<< endl;
return -1;
}
BfHeader_t *Header = new BfHeader_t;
uint16_t Memory[65536];
memset(&Memory,0,sizeof(Memory));
status = LoadBF(filePath,Header,Memory);
if (status){
cerr << "Load BF buffer Error, Status =" << status << endl;
return -1;
}
status = ExecCode(Header, Memory);
if (status){
cerr << "Code Execution Error, Status =" << status << endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_unicode.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2005-11-17 20:30:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _I18N_BREAKITERATOR_UNICODE_HXX_
#define _I18N_BREAKITERATOR_UNICODE_HXX_
#include <breakiteratorImpl.hxx>
#include <unicode/brkiter.h>
namespace com { namespace sun { namespace star { namespace i18n {
#define LOAD_CHARACTER_BREAKITERATOR 0
#define LOAD_WORD_BREAKITERATOR 1
#define LOAD_SENTENCE_BREAKITERATOR 2
#define LOAD_LINE_BREAKITERATOR 3
// ----------------------------------------------------
// class BreakIterator_Unicode
// ----------------------------------------------------
class BreakIterator_Unicode : public BreakIteratorImpl
{
public:
BreakIterator_Unicode();
~BreakIterator_Unicode();
virtual sal_Int32 SAL_CALL previousCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL nextCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL previousWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL nextWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL getWordBoundary( const rtl::OUString& Text, sal_Int32 nPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType, sal_Bool bDirection )
throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL beginOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL endOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual LineBreakResults SAL_CALL getLineBreak( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int32 nMinBreakPos,
const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions )
throw(com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
throw( com::sun::star::uno::RuntimeException );
protected:
const sal_Char *cBreakIterator, *wordRule, *lineRule;
Boundary result; // for word break iterator
struct {
rtl::OUString aText;
icu::BreakIterator *aBreakIterator;
} character, word, sentence, line, *icuBI;
com::sun::star::lang::Locale aLocale;
sal_Int16 aBreakType, aWordType;
void SAL_CALL loadICUBreakIterator(const com::sun::star::lang::Locale& rLocale,
sal_Int16 rBreakType, sal_Int16 rWordType, const sal_Char* name, const rtl::OUString& rText) throw(com::sun::star::uno::RuntimeException);
};
} } } }
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.12.16); FILE MERGED 2006/03/08 13:19:07 nn 1.12.16.1: #i53898# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_unicode.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2006-06-20 04:40:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _I18N_BREAKITERATOR_UNICODE_HXX_
#define _I18N_BREAKITERATOR_UNICODE_HXX_
#include <breakiteratorImpl.hxx>
// External unicode includes (from icu) cause warning C4668 on Windows.
// We want to minimize the patches to external headers, so the warnings are
// disabled here instead of in the header file itself.
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <unicode/brkiter.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace com { namespace sun { namespace star { namespace i18n {
#define LOAD_CHARACTER_BREAKITERATOR 0
#define LOAD_WORD_BREAKITERATOR 1
#define LOAD_SENTENCE_BREAKITERATOR 2
#define LOAD_LINE_BREAKITERATOR 3
// ----------------------------------------------------
// class BreakIterator_Unicode
// ----------------------------------------------------
class BreakIterator_Unicode : public BreakIteratorImpl
{
public:
BreakIterator_Unicode();
~BreakIterator_Unicode();
virtual sal_Int32 SAL_CALL previousCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL nextCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL previousWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL nextWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL getWordBoundary( const rtl::OUString& Text, sal_Int32 nPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType, sal_Bool bDirection )
throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL beginOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL endOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual LineBreakResults SAL_CALL getLineBreak( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int32 nMinBreakPos,
const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions )
throw(com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
throw( com::sun::star::uno::RuntimeException );
protected:
const sal_Char *cBreakIterator, *wordRule, *lineRule;
Boundary result; // for word break iterator
struct {
rtl::OUString aText;
icu::BreakIterator *aBreakIterator;
} character, word, sentence, line, *icuBI;
com::sun::star::lang::Locale aLocale;
sal_Int16 aBreakType, aWordType;
void SAL_CALL loadICUBreakIterator(const com::sun::star::lang::Locale& rLocale,
sal_Int16 rBreakType, sal_Int16 rWordType, const sal_Char* name, const rtl::OUString& rText) throw(com::sun::star::uno::RuntimeException);
};
} } } }
#endif
<|endoftext|> |
<commit_before><commit_msg>Removed unnecessary dynamic_cast.<commit_after><|endoftext|> |
<commit_before>#include "dataFile.h"
#include "debugUtils.h"
DataFile::DataFile(void)
: file(0)
, fileIsOpen(false)
{
}
DataFile::DataFile(const std::string& in_filename, std::ios_base::openmode mode)
: file(0)
{
open(in_filename, mode);
}
DataFile::~DataFile(void)
{
close();
}
void DataFile::writeScalar(const std::string& name, const double x)
{
require_file_open();
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(0, NULL, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &x);
H5Dclose(dataset);
}
double DataFile::readScalar(const std::string& name)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 0) {
throw DebugException((format(
"DataFile::readScalar: '%s' is not a scalar.") % name).str());
}
double value;
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
H5Dclose(dataset);
return value;
}
void DataFile::writeVector(const std::string& name, const dvector& v)
{
require_file_open();
hsize_t dims = v.size();
if (dims == 0) {
logFile.write(format(
"DataFile::writeVector: Warning: '%s' is empty.") % name);
return;
}
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(1, &dims, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &v[0]);
H5Dclose(dataset);
}
void DataFile::writeVec(const std::string& name, const dvec& v)
{
require_file_open();
hsize_t dims = v.rows();
if (dims == 0) {
logFile.write(format(
"DataFile::writeVector: Warning: '%s' is empty.") % name);
return;
}
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(1, &dims, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, v.data());
H5Dclose(dataset);
}
dvector DataFile::readVector(const std::string& name)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 1) {
throw DebugException((format(
"DataFile::readVector: '%s' is not a 1D array.") % name).str());
}
hssize_t N = H5Sget_simple_extent_npoints(dataspace);
dvector values(static_cast<size_t>(N));
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &values[0]);
H5Dclose(dataset);
return values;
}
dvec DataFile::readVec(const std::string& name)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 1) {
throw DebugException((format(
"DataFile::readVector: '%s' is not a 1D array.") % name).str());
}
hssize_t N = H5Sget_simple_extent_npoints(dataspace);
dvec values(static_cast<size_t>(N));
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, values.data());
H5Dclose(dataset);
return values;
}
void DataFile::writeArray2D(const std::string& name, const dmatrix& y, bool transpose)
{
require_file_open();
dmatrix yt;
if (transpose) {
yt = y.transpose();
} else {
yt = y;
}
hsize_t dims[2];
dims[0] = yt.cols(); // TODO: double check the order of these
dims[1] = yt.rows();
if (dims[0] == 0 || dims[1] == 0) {
logFile.write(format(
"DataFile::writeArray2D: Warning: '%s' is empty.") % name);
return;
}
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(2, dims, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, yt.data());
H5Dclose(dataset);
}
dmatrix DataFile::readArray2D(const std::string& name, bool transpose)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 2) {
throw DebugException((format(
"DataFile::readVector: '%s' is not a 2D array.\n"
"(file: '%s'; ndims: %i") % name % filename %
H5Sget_simple_extent_ndims(dataspace)).str());
}
hsize_t ndim = 2;
vector<hsize_t> dimensions(2);
H5Sget_simple_extent_dims(dataspace, &dimensions[0], &ndim);
dmatrix y(dimensions[1], dimensions[0]);
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL,
H5S_ALL, H5P_DEFAULT, y.data());
H5Dclose(dataset);
if (transpose) {
y = y.transpose().eval();
}
return y;
}
void DataFile::open(const std::string& in_filename, std::ios_base::openmode mode)
{
if (file) {
close();
}
filename = in_filename;
std::ifstream test(filename.c_str());
bool exists = test.good();
test.close();
if (exists && (mode & std::ios_base::app)) {
file = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
} else {
file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC,
H5P_DEFAULT, H5P_DEFAULT);
}
fileIsOpen = true;
}
void DataFile::close()
{
if (file) {
H5Fclose(file);
file = 0;
}
fileIsOpen = false;
}
void DataFile::require_file_open()
{
if (!file) {
throw DebugException(
"Can't access DataFile object: H5File object not initialized.");
} else if (!fileIsOpen) {
throw DebugException(
"Can't access DataFile object: H5File is closed.");
}
}
hid_t DataFile::get_dataset
(const std::string& name, hid_t datatype, hid_t dataspace)
{
if (H5Lexists(file, name.c_str(), H5P_DEFAULT)) {
H5Ldelete(file, name.c_str(), H5P_DEFAULT);
}
return H5Dcreate(file, name.c_str(), datatype, dataspace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}
void dataFileTest()
{
// Test reading from / writing to an HDF5 data file
DataFile f("test.h5");
double x = 9001;
f.writeScalar("x", x);
dvector v(10);
for (size_t i=0; i<v.size(); i++) {
v[i] = static_cast<double>(i*i);
}
f.writeVector("v", v);
dmatrix A(3,7);
for (dmatrix::Index i=0; i<A.rows(); i++) {
for (dmatrix::Index j=0; j<A.cols(); j++) {
A(i,j) = static_cast<double>(10*i + j);
}
}
logFile.write(format("rows: %i") % A.rows());
logFile.write(format("cols: %i") % A.cols());
f.writeArray2D("A", A);
f.close();
DataFile g("test.h5");
dvector w = g.readVector("v");
for (size_t i=0; i<w.size(); i++) {
logFile.write(format("%g") % w[i]);
}
logFile.write(format("%g") % g.readScalar("x"));
logFile.write(g.readArray2D("A"));
g.close();
}
<commit_msg>Fix invalid memory access in DataFile::readArray2D<commit_after>#include "dataFile.h"
#include "debugUtils.h"
DataFile::DataFile(void)
: file(0)
, fileIsOpen(false)
{
}
DataFile::DataFile(const std::string& in_filename, std::ios_base::openmode mode)
: file(0)
{
open(in_filename, mode);
}
DataFile::~DataFile(void)
{
close();
}
void DataFile::writeScalar(const std::string& name, const double x)
{
require_file_open();
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(0, NULL, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &x);
H5Dclose(dataset);
}
double DataFile::readScalar(const std::string& name)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 0) {
throw DebugException((format(
"DataFile::readScalar: '%s' is not a scalar.") % name).str());
}
double value;
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
H5Dclose(dataset);
return value;
}
void DataFile::writeVector(const std::string& name, const dvector& v)
{
require_file_open();
hsize_t dims = v.size();
if (dims == 0) {
logFile.write(format(
"DataFile::writeVector: Warning: '%s' is empty.") % name);
return;
}
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(1, &dims, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &v[0]);
H5Dclose(dataset);
}
void DataFile::writeVec(const std::string& name, const dvec& v)
{
require_file_open();
hsize_t dims = v.rows();
if (dims == 0) {
logFile.write(format(
"DataFile::writeVector: Warning: '%s' is empty.") % name);
return;
}
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(1, &dims, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, v.data());
H5Dclose(dataset);
}
dvector DataFile::readVector(const std::string& name)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 1) {
throw DebugException((format(
"DataFile::readVector: '%s' is not a 1D array.") % name).str());
}
hssize_t N = H5Sget_simple_extent_npoints(dataspace);
dvector values(static_cast<size_t>(N));
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &values[0]);
H5Dclose(dataset);
return values;
}
dvec DataFile::readVec(const std::string& name)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 1) {
throw DebugException((format(
"DataFile::readVector: '%s' is not a 1D array.") % name).str());
}
hssize_t N = H5Sget_simple_extent_npoints(dataspace);
dvec values(static_cast<size_t>(N));
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, values.data());
H5Dclose(dataset);
return values;
}
void DataFile::writeArray2D(const std::string& name, const dmatrix& y, bool transpose)
{
require_file_open();
dmatrix yt;
if (transpose) {
yt = y.transpose();
} else {
yt = y;
}
hsize_t dims[2];
dims[0] = yt.cols(); // TODO: double check the order of these
dims[1] = yt.rows();
if (dims[0] == 0 || dims[1] == 0) {
logFile.write(format(
"DataFile::writeArray2D: Warning: '%s' is empty.") % name);
return;
}
hid_t dataspace, dataset, datatype;
dataspace = H5Screate_simple(2, dims, NULL);
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
H5Tset_order(datatype, H5T_ORDER_LE);
dataset = get_dataset(name, datatype, dataspace);
H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, yt.data());
H5Dclose(dataset);
}
dmatrix DataFile::readArray2D(const std::string& name, bool transpose)
{
require_file_open();
hid_t dataspace, dataset;
dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if (H5Sget_simple_extent_ndims(dataspace) != 2) {
throw DebugException((format(
"DataFile::readVector: '%s' is not a 2D array.\n"
"(file: '%s'; ndims: %i") % name % filename %
H5Sget_simple_extent_ndims(dataspace)).str());
}
hsize_t dimensions[2];
H5Sget_simple_extent_dims(dataspace, dimensions, NULL);
dmatrix y(dimensions[1], dimensions[0]);
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL,
H5S_ALL, H5P_DEFAULT, y.data());
H5Dclose(dataset);
if (transpose) {
y = y.transpose().eval();
}
return y;
}
void DataFile::open(const std::string& in_filename, std::ios_base::openmode mode)
{
if (file) {
close();
}
filename = in_filename;
std::ifstream test(filename.c_str());
bool exists = test.good();
test.close();
if (exists && (mode & std::ios_base::app)) {
file = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
} else {
file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC,
H5P_DEFAULT, H5P_DEFAULT);
}
fileIsOpen = true;
}
void DataFile::close()
{
if (file) {
H5Fclose(file);
file = 0;
}
fileIsOpen = false;
}
void DataFile::require_file_open()
{
if (!file) {
throw DebugException(
"Can't access DataFile object: H5File object not initialized.");
} else if (!fileIsOpen) {
throw DebugException(
"Can't access DataFile object: H5File is closed.");
}
}
hid_t DataFile::get_dataset
(const std::string& name, hid_t datatype, hid_t dataspace)
{
if (H5Lexists(file, name.c_str(), H5P_DEFAULT)) {
H5Ldelete(file, name.c_str(), H5P_DEFAULT);
}
return H5Dcreate(file, name.c_str(), datatype, dataspace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}
void dataFileTest()
{
// Test reading from / writing to an HDF5 data file
DataFile f("test.h5");
double x = 9001;
f.writeScalar("x", x);
dvector v(10);
for (size_t i=0; i<v.size(); i++) {
v[i] = static_cast<double>(i*i);
}
f.writeVector("v", v);
dmatrix A(3,7);
for (dmatrix::Index i=0; i<A.rows(); i++) {
for (dmatrix::Index j=0; j<A.cols(); j++) {
A(i,j) = static_cast<double>(10*i + j);
}
}
logFile.write(format("rows: %i") % A.rows());
logFile.write(format("cols: %i") % A.cols());
f.writeArray2D("A", A);
f.close();
DataFile g("test.h5");
dvector w = g.readVector("v");
for (size_t i=0; i<w.size(); i++) {
logFile.write(format("%g") % w[i]);
}
logFile.write(format("%g") % g.readScalar("x"));
logFile.write(g.readArray2D("A"));
g.close();
}
<|endoftext|> |
<commit_before><commit_msg>Error messages added by PeiYong Zhang.<commit_after><|endoftext|> |
<commit_before>
#include <stdarg.h>
#include <stdio.h>
#include "../imgui/imgui.h"
#if defined _WIN32 || defined __CYGWIN__
#define API __declspec(dllexport)
#else
#define API
#endif
extern "C" API ImGuiIO* ImGui_GetIO()
{
return &ImGui::GetIO();
}
extern "C" API void ImGui_Shutdown()
{
ImGui::Shutdown();
}
extern "C" API void ImGui_NewFrame()
{
ImGui::NewFrame();
}
extern "C" API void ImGui_Render()
{
ImGui::Render();
}
extern "C" API void ImGui_ShowTestWindow(bool* opened)
{
ImGui::ShowTestWindow(opened);
}
extern "C" API bool ImGui_Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
{
return ImGui::Begin(name, p_opened, flags);
}
extern "C" API void ImGui_End()
{
ImGui::End();
}
extern "C" API void ImGui_Text(const char* text, ...)
{
char buffer[256];
va_list args;
va_start (args, text);
vsprintf (buffer, text, args);
va_end (args);
ImGui::Text(buffer);
}
extern "C" API bool ImGui_ColorEdit3(const char* label, float col[3])
{
return ImGui::ColorEdit3(label,col);
}
extern "C" API void ImGui_SetNextWindowPos(const ImVec2 pos, ImGuiSetCond cond)
{
ImGui::SetNextWindowPos(pos,cond);
}
extern "C" API void ImGui_SetNextWindowSize(const ImVec2 size, ImGuiSetCond cond)
{
ImGui::SetNextWindowSize(size, cond);
}
extern "C" API void ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
ImGui::SliderFloat(label,v,v_min,v_max,display_format,power);
}
extern "C" API bool ImGui_Button(const char* label, const ImVec2& size, bool repeat_when_held)
{
return ImGui::Button(label,size,repeat_when_held);
}
extern "C" API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* atlas, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
atlas->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel);
}
extern "C" API void ImFontAtlas_SetTexID(ImFontAtlas* atlas, void* tex)
{
atlas->TexID = tex;
}
extern "C" API int ImDrawList_GetVertexBufferSize(ImDrawList* list)
{
return list->vtx_buffer.size();
}
extern "C" API ImDrawVert* ImDrawList_GetVertexPtr(ImDrawList* list, int n)
{
return &list->vtx_buffer[n];
}
extern "C" API int ImDrawList_GetCmdSize(ImDrawList* list)
{
return list->commands.size();
}
extern "C" API ImDrawCmd* ImDrawList_GetCmdPtr(ImDrawList* list, int n)
{
return &list->commands[n];
}
extern "C" API void ImGuiIO_AddInputCharacter(unsigned short c)
{
ImGui::GetIO().AddInputCharacter(c);
}
<commit_msg>more bindings<commit_after>
#include <stdarg.h>
#include <stdio.h>
#include "../imgui/imgui.h"
#if defined _WIN32 || defined __CYGWIN__
#define API __declspec(dllexport)
#else
#define API
#endif
extern "C" API ImGuiIO* ImGui_GetIO()
{
return &ImGui::GetIO();
}
extern "C" API void ImGui_Shutdown()
{
ImGui::Shutdown();
}
extern "C" API void ImGui_NewFrame()
{
ImGui::NewFrame();
}
extern "C" API void ImGui_Render()
{
ImGui::Render();
}
extern "C" API void ImGui_ShowTestWindow(bool* opened)
{
ImGui::ShowTestWindow(opened);
}
extern "C" API bool ImGui_Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
{
return ImGui::Begin(name, p_opened, flags);
}
extern "C" API void ImGui_End()
{
ImGui::End();
}
extern "C" API void ImGui_Text(const char* text, ...)
{
char buffer[256];
va_list args;
va_start (args, text);
vsprintf (buffer, text, args);
va_end (args);
ImGui::Text(buffer);
}
extern "C" API bool ImGui_ColorEdit3(const char* label, float col[3])
{
return ImGui::ColorEdit3(label,col);
}
extern "C" API void ImGui_SetNextWindowPos(const ImVec2 pos, ImGuiSetCond cond)
{
ImGui::SetNextWindowPos(pos,cond);
}
extern "C" API void ImGui_SetNextWindowSize(const ImVec2 size, ImGuiSetCond cond)
{
ImGui::SetNextWindowSize(size, cond);
}
extern "C" API void ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
ImGui::SliderFloat(label,v,v_min,v_max,display_format,power);
}
extern "C" API bool ImGui_Button(const char* label, const ImVec2& size, bool repeat_when_held)
{
return ImGui::Button(label,size,repeat_when_held);
}
extern "C" API bool ImGui_SmallButton(const char* label)
{
return ImGui::SmallButton(label);
}
extern "C" API bool ImGui_TreeNode(const char* str_label_id)
{
return ImGui::TreeNode(str_label_id);
}
extern "C" API bool ImGui_TreeNode_IdFmt(const void* ptr_id, const char* fmt, ...)
{
char buffer[256];
va_list args;
va_start (args, fmt);
vsprintf (buffer, fmt, args);
va_end (args);
//TODO: use TreeNodeV
return ImGui::TreeNode(ptr_id,"%s",buffer);
}
extern "C" API void ImGui_TreePop()
{
ImGui::TreePop();
}
extern "C" API void ImGui_SameLine(int column_x, int spacing_w)
{
ImGui::SameLine(column_x,spacing_w);
}
extern "C" API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* atlas, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
atlas->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel);
}
extern "C" API void ImFontAtlas_SetTexID(ImFontAtlas* atlas, void* tex)
{
atlas->TexID = tex;
}
extern "C" API int ImDrawList_GetVertexBufferSize(ImDrawList* list)
{
return list->vtx_buffer.size();
}
extern "C" API ImDrawVert* ImDrawList_GetVertexPtr(ImDrawList* list, int n)
{
return &list->vtx_buffer[n];
}
extern "C" API int ImDrawList_GetCmdSize(ImDrawList* list)
{
return list->commands.size();
}
extern "C" API ImDrawCmd* ImDrawList_GetCmdPtr(ImDrawList* list, int n)
{
return &list->commands[n];
}
extern "C" API void ImGuiIO_AddInputCharacter(unsigned short c)
{
ImGui::GetIO().AddInputCharacter(c);
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(k)
class Solution {
public:
/**
* @param nums: A list of integers
* @param k: As described
* @return: The majority number
*/
int majorityNumber(vector<int> nums, int k) {
unordered_map<int, int> hash;
int n = nums.size();
for (auto& i : nums) {
++hash[i];
// Detecting k items in hash, at least one of them must have exactly
// one in it. We will discard those k items by one for each.
// This action keeps the same mojority numbers in the remaining numbers.
// Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
if (hash.size() == k) {
auto it = hash.begin();
while (it != hash.end()) {
if (--(it->second) == 0) {
hash.erase(it++);
} else {
++it;
}
}
}
}
// Resets hash for the following counting.
for (auto& it : hash) {
it.second = 0;
}
// Counts the occurrence of each candidate integer.
for (auto& i : nums) {
auto it = hash.find(i);
if (it != hash.end()) {
++it->second;
}
}
// Selects the integer which occurs > n / k times.
vector<int> ret;
for (const pair<int, int>& it : hash) {
if (it.second > static_cast<double>(n) / k) {
ret.emplace_back(it.first);
}
}
return ret[0];
}
};
<commit_msg>update<commit_after>// Time: O(n)
// Space: O(k)
class Solution {
public:
/**
* @param nums: A list of integers
* @param k: As described
* @return: The majority number
*/
int majorityNumber(vector<int> nums, int k) {
const int n = nums.size();
unordered_map<int, int> hash;
for (const auto& i : nums) {
++hash[i];
// Detecting k items in hash, at least one of them must have exactly
// one in it. We will discard those k items by one for each.
// This action keeps the same mojority numbers in the remaining numbers.
// Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
if (hash.size() == k) {
auto it = hash.begin();
while (it != hash.end()) {
if (--(it->second) == 0) {
hash.erase(it++);
} else {
++it;
}
}
}
}
// Resets hash for the following counting.
for (auto& it : hash) {
it.second = 0;
}
// Counts the occurrence of each candidate integer.
for (const auto& i : nums) {
auto it = hash.find(i);
if (it != hash.end()) {
++it->second;
}
}
// Selects the integer which occurs > n / k times.
vector<int> ret;
for (const pair<int, int>& it : hash) {
if (it.second > static_cast<double>(n) / k) {
ret.emplace_back(it.first);
}
}
return ret[0];
}
};
<|endoftext|> |
<commit_before>// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
An example running of this program:
./lda \
--num_topics 2 \
--alpha 0.1 \
--beta 0.01 \
--training_data_file ./testdata/test_data.txt \
--model_file /tmp/lda_model.txt \
--burn_in_iterations 100 \
--total_iterations 150
*/
#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include <map>
#include "common.h"
#include "document.h"
#include "model.h"
#include "accumulative_model.h"
#include "sampler.h"
#include "cmd_flags.h"
namespace learning_lda {
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::set;
using std::map;
int LoadAndInitTrainingCorpus(std::vector<string> &lines,
int num_topics,
LDACorpus* corpus,
map<string, int>* word_index_map) {
corpus->clear();
word_index_map->clear();
string line;
for (int i=0; i < lines.size(); i++){ // Each line is a training document.
string line = lines[i];
if (line.size() > 0 && // Skip empty lines.
line[0] != '\r' && // Skip empty lines.
line[0] != '\n' && // Skip empty lines.
line[0] != '#') { // Skip comment lines.
istringstream ss(line);
DocumentWordTopicsPB document;
string word;
int count;
while (ss >> word >> count) { // Load and init a document.
vector<int32> topics;
for (int i = 0; i < count; ++i) {
topics.push_back(RandInt(num_topics));
}
int word_index;
map<string, int>::const_iterator iter = word_index_map->find(word);
if (iter == word_index_map->end()) {
word_index = word_index_map->size();
(*word_index_map)[word] = word_index;
} else {
word_index = iter->second;
}
document.add_wordtopics(word, word_index, topics);
}
corpus->push_back(new LDADocument(document, num_topics));
}
}
return corpus->size();
}
int LoadAndInitTrainingCorpus(const string& corpus_file,
int num_topics,
LDACorpus* corpus,
map<string, int>* word_index_map) {
ifstream fin(corpus_file.c_str());
string line;
vector<string> lines;
while (getline(fin, line)) { // Each line is a training document.
if (line.size() > 0 && // Skip empty lines.
line[0] != '\r' && // Skip empty lines.
line[0] != '\n' && // Skip empty lines.
line[0] != '#') { // Skip comment lines.
lines.push_back(line);
}
}
return LoadAndInitTrainingCorpus(lines,num_topics,corpus,word_index_map);
}
void FreeCorpus(LDACorpus* corpus) {
for (list<LDADocument*>::iterator iter = corpus->begin();
iter != corpus->end();
++iter) {
if (*iter != NULL) {
delete *iter;
*iter = NULL;
}
}
}
LDAAccumulativeModel* LearnFromFile(const string& corpus_file,int num_topics,map<string, int>* word_index_map, int total_iterations, int burn_in_iterations, double alpha, double beta)
{
using learning_lda::LDACorpus;
using learning_lda::LDAModel;
using learning_lda::LDAAccumulativeModel;
using learning_lda::LDASampler;
using learning_lda::LDADocument;
using learning_lda::LoadAndInitTrainingCorpus;
using std::list;
LDACorpus corpus;
int ret = LoadAndInitTrainingCorpus(corpus_file,
num_topics,
&corpus, word_index_map);
LDAAccumulativeModel *accum_model = new LDAAccumulativeModel(num_topics, (*word_index_map).size());
LDAModel model(num_topics, *word_index_map);
LDASampler sampler(alpha, beta, &model, accum_model);
sampler.InitModelGivenTopics(corpus);
for (int iter = 0; iter < total_iterations; ++iter) {
std::cout << "Iteration " << iter << " ...\n";
double loglikelihood = 0;
for (list<LDADocument*>::const_iterator iterator = corpus.begin();
iterator != corpus.end();
++iterator) {
loglikelihood += sampler.LogLikelihood(*iterator);
}
std::cout << "Loglikelihood: " << loglikelihood << std::endl;
sampler.DoIteration(&corpus, true, iter < burn_in_iterations);
std::cout << "DONEa" << "\n";
}
std::cout << "DONE1" << "\n";
(*accum_model).AverageModel(total_iterations - burn_in_iterations);
std::cout << "DONE1" << "\n";
FreeCorpus(&corpus);
std::cout << "DONE1" << "\n";
return accum_model;
}
} // namespace learning_lda
int main(int argc, char** argv) {
using learning_lda::LDACmdLineFlags;
using learning_lda::LearnFromFile;
using learning_lda::LDAAccumulativeModel;
map<string, int> word_index_map;
srand(time(NULL));
LDACmdLineFlags flags;
flags.ParseCmdFlags(argc, argv);
if (!flags.CheckTrainingValidity()) {
return -1;
}
LDAAccumulativeModel *accum_model = LearnFromFile(flags.training_data_file_,flags.num_topics_,&word_index_map, flags.total_iterations_, flags.burn_in_iterations_, flags.alpha_, flags.beta_);
std::cout << "OUTPUTTING TO " << flags.model_file_ << "\n";
std::ofstream fout(flags.model_file_.c_str());
(*accum_model).AppendAsString(word_index_map, fout);
return 0;
}
<commit_msg>Can now pass a std::vector rather than file handle<commit_after>// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
An example running of this program:
./lda \
--num_topics 2 \
--alpha 0.1 \
--beta 0.01 \
--training_data_file ./testdata/test_data.txt \
--model_file /tmp/lda_model.txt \
--burn_in_iterations 100 \
--total_iterations 150
*/
#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include <map>
#include "common.h"
#include "document.h"
#include "model.h"
#include "accumulative_model.h"
#include "sampler.h"
#include "cmd_flags.h"
namespace learning_lda {
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::set;
using std::map;
int LoadAndInitTrainingCorpus(std::vector<string> &lines,
int num_topics,
LDACorpus* corpus,
map<string, int>* word_index_map) {
corpus->clear();
word_index_map->clear();
string line;
for (int i=0; i < lines.size(); i++){ // Each line is a training document.
string line = lines[i];
if (line.size() > 0 && // Skip empty lines.
line[0] != '\r' && // Skip empty lines.
line[0] != '\n' && // Skip empty lines.
line[0] != '#') { // Skip comment lines.
istringstream ss(line);
DocumentWordTopicsPB document;
string word;
int count;
while (ss >> word >> count) { // Load and init a document.
vector<int32> topics;
for (int i = 0; i < count; ++i) {
topics.push_back(RandInt(num_topics));
}
int word_index;
map<string, int>::const_iterator iter = word_index_map->find(word);
if (iter == word_index_map->end()) {
word_index = word_index_map->size();
(*word_index_map)[word] = word_index;
} else {
word_index = iter->second;
}
document.add_wordtopics(word, word_index, topics);
}
corpus->push_back(new LDADocument(document, num_topics));
}
}
return corpus->size();
}
std::vector<string>* LoadCorpusFile(const string& corpus_file)
{
ifstream fin(corpus_file.c_str());
string line;
std::vector<string> *lines = new std::vector<string>();
while (getline(fin, line)) { // Each line is a training document.
if (line.size() > 0 && // Skip empty lines.
line[0] != '\r' && // Skip empty lines.
line[0] != '\n' && // Skip empty lines.
line[0] != '#') { // Skip comment lines.
lines->push_back(line);
}
}
return lines;
}
void FreeCorpus(LDACorpus* corpus) {
for (list<LDADocument*>::iterator iter = corpus->begin();
iter != corpus->end();
++iter) {
if (*iter != NULL) {
delete *iter;
*iter = NULL;
}
}
}
LDAAccumulativeModel* LearnFromCorpus(std::vector<string> *lines,int num_topics,map<string, int>* word_index_map, int total_iterations, int burn_in_iterations, double alpha, double beta)
{
using learning_lda::LDACorpus;
using learning_lda::LDAModel;
using learning_lda::LDAAccumulativeModel;
using learning_lda::LDASampler;
using learning_lda::LDADocument;
using learning_lda::LoadAndInitTrainingCorpus;
using std::list;
LDACorpus corpus;
int ret = LoadAndInitTrainingCorpus(*lines,
num_topics,
&corpus, word_index_map);
LDAAccumulativeModel *accum_model = new LDAAccumulativeModel(num_topics, (*word_index_map).size());
LDAModel model(num_topics, *word_index_map);
LDASampler sampler(alpha, beta, &model, accum_model);
sampler.InitModelGivenTopics(corpus);
for (int iter = 0; iter < total_iterations; ++iter) {
std::cout << "Iteration " << iter << " ...\n";
double loglikelihood = 0;
for (list<LDADocument*>::const_iterator iterator = corpus.begin();
iterator != corpus.end();
++iterator) {
loglikelihood += sampler.LogLikelihood(*iterator);
}
std::cout << "Loglikelihood: " << loglikelihood << std::endl;
sampler.DoIteration(&corpus, true, iter < burn_in_iterations);
std::cout << "DONEa" << "\n";
}
std::cout << "DONE1" << "\n";
(*accum_model).AverageModel(total_iterations - burn_in_iterations);
std::cout << "DONE1" << "\n";
FreeCorpus(&corpus);
std::cout << "DONE1" << "\n";
return accum_model;
}
} // namespace learning_lda
int main(int argc, char** argv) {
using learning_lda::LDACmdLineFlags;
using learning_lda::LearnFromCorpus;
using learning_lda::LoadCorpusFile;
using learning_lda::LDAAccumulativeModel;
map<string, int> word_index_map;
srand(time(NULL));
LDACmdLineFlags flags;
flags.ParseCmdFlags(argc, argv);
if (!flags.CheckTrainingValidity()) {
return -1;
}
LDAAccumulativeModel *accum_model = LearnFromCorpus(LoadCorpusFile(flags.training_data_file_),flags.num_topics_,&word_index_map, flags.total_iterations_, flags.burn_in_iterations_, flags.alpha_, flags.beta_);
std::cout << "OUTPUTTING TO " << flags.model_file_ << "\n";
std::ofstream fout(flags.model_file_.c_str());
(*accum_model).AppendAsString(word_index_map, fout);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef DUBINS_TRAFFIC_PROBLEM_H
#define DUBINS_TRAFFIC_PROBLEM_H
#include <iostream>
#include <vector>
#include <string>
#include <Eigen/Dense>
#include "roadnet.hpp"
namespace dubins_traffic {
/** Representation of problem instances.
\ingroup dubins_traffic */
class Problem {
public:
double intersection_radius;
std::vector<size_t> goals;
RoadNetwork rnd;
Problem( const RoadNetwork &rnd_ );
Problem( const Problem &to_be_copied );
static Problem random( const RoadNetwork &rnd_,
const Eigen::Vector2i &number_goals_bounds );
/** Create formula using SPIN LTL syntax <http://spinroot.com/spin/Man/ltl.html>.
Support for other syntax is coming soon. */
void to_formula( std::ostream &out ) const;
/** Output description of problem in JSON to a stream */
friend std::ostream & operator<<( std::ostream &out, const Problem &prob );
/** Get description of problem in JSON. */
std::string dumpJSON() const;
};
Problem::Problem( const RoadNetwork &rnd_ )
: rnd(rnd_)
{
intersection_radius = 0.0;
}
Problem::Problem( const Problem &to_be_copied )
: intersection_radius( to_be_copied.intersection_radius ),
goals( to_be_copied.goals ),
rnd( to_be_copied.rnd )
{
assert( intersection_radius > 0 );
}
Problem Problem::random( const RoadNetwork &rnd_,
const Eigen::Vector2i &number_goals_bounds )
{
assert( number_goals_bounds(0) >= 0
&& number_goals_bounds(0) <= number_goals_bounds(1) );
Problem pinstance( rnd_ );
pinstance.intersection_radius = 1.0;
int number_goals = number_goals_bounds(0);
if (number_goals_bounds(1) != number_goals_bounds(0))
number_goals += (std::rand()
% (1+number_goals_bounds(1)
- number_goals_bounds(0)));
for (size_t goal_idx = 0; goal_idx < number_goals; goal_idx++)
pinstance.goals.push_back( std::rand() % rnd_.number_of_intersections() );
return pinstance;
}
void Problem::to_formula( std::ostream &out ) const
{
if (goals.size() > 0) {
for (size_t i = 0; i < goals.size(); i++) {
if (i > 0)
out << " && ";
out << "([]<> ego_" << rnd.get_intersection_str( goals[i] ) << ")";
}
}
}
std::ostream & operator<<( std::ostream &out, const Problem &prob )
{
out << "{" << std::endl << "\"version\": " << 0 << "," << std::endl;
out << "\"goals\": [" << std::endl;
for (int i = 0; i < prob.goals.size(); i++) {
if (i > 0)
out << ", ";
out << "\"ego_" << prob.rnd.get_intersection_str( prob.goals[i] ) << "\"";
out << std::endl;
}
out << "]";
out << std::endl << "}";
return out;
}
std::string Problem::dumpJSON() const
{
std::ostringstream out;
out << *this;
return out.str();
}
} // namespace dubins_traffic
#endif
<commit_msg>Include road net in dubins_traffic problem instance JSON<commit_after>#ifndef DUBINS_TRAFFIC_PROBLEM_H
#define DUBINS_TRAFFIC_PROBLEM_H
#include <iostream>
#include <vector>
#include <string>
#include <Eigen/Dense>
#include "roadnet.hpp"
namespace dubins_traffic {
/** Representation of problem instances.
\ingroup dubins_traffic */
class Problem {
public:
double intersection_radius;
std::vector<size_t> goals;
RoadNetwork rnd;
Problem( const RoadNetwork &rnd_ );
Problem( const Problem &to_be_copied );
static Problem random( const RoadNetwork &rnd_,
const Eigen::Vector2i &number_goals_bounds );
/** Create formula using SPIN LTL syntax <http://spinroot.com/spin/Man/ltl.html>.
Support for other syntax is coming soon. */
void to_formula( std::ostream &out ) const;
/** Output description of problem in JSON to a stream */
friend std::ostream & operator<<( std::ostream &out, const Problem &prob );
/** Get description of problem in JSON. */
std::string dumpJSON() const;
};
Problem::Problem( const RoadNetwork &rnd_ )
: rnd(rnd_)
{
intersection_radius = 0.0;
}
Problem::Problem( const Problem &to_be_copied )
: intersection_radius( to_be_copied.intersection_radius ),
goals( to_be_copied.goals ),
rnd( to_be_copied.rnd )
{
assert( intersection_radius > 0 );
}
Problem Problem::random( const RoadNetwork &rnd_,
const Eigen::Vector2i &number_goals_bounds )
{
assert( number_goals_bounds(0) >= 0
&& number_goals_bounds(0) <= number_goals_bounds(1) );
Problem pinstance( rnd_ );
pinstance.intersection_radius = 1.0;
int number_goals = number_goals_bounds(0);
if (number_goals_bounds(1) != number_goals_bounds(0))
number_goals += (std::rand()
% (1+number_goals_bounds(1)
- number_goals_bounds(0)));
for (size_t goal_idx = 0; goal_idx < number_goals; goal_idx++)
pinstance.goals.push_back( std::rand() % rnd_.number_of_intersections() );
return pinstance;
}
void Problem::to_formula( std::ostream &out ) const
{
if (goals.size() > 0) {
for (size_t i = 0; i < goals.size(); i++) {
if (i > 0)
out << " && ";
out << "([]<> ego_" << rnd.get_intersection_str( goals[i] ) << ")";
}
}
}
std::ostream & operator<<( std::ostream &out, const Problem &prob )
{
out << "{" << std::endl << "\"version\": " << 0 << "," << std::endl;
out << "\"goals\": [" << std::endl;
for (int i = 0; i < prob.goals.size(); i++) {
if (i > 0)
out << ", ";
out << "\"ego_" << prob.rnd.get_intersection_str( prob.goals[i] ) << "\"";
out << std::endl;
}
out << "]," << std::endl;
out << "\"rnd\": " << prob.rnd << std::endl;
out << std::endl << "}";
return out;
}
std::string Problem::dumpJSON() const
{
std::ostringstream out;
out << *this;
return out.str();
}
} // namespace dubins_traffic
#endif
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCObject.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCObject
//
// -------------------------------------------------------------------------
#include "NFCObject.h"
#include "NFCRecordManager.h"
#include "NFCHeartBeatManager.h"
#include "NFCPropertyManager.h"
#include "NFCComponentManager.h"
NFCObject::NFCObject(const NFIDENTID& self, NFIPluginManager* pLuginManager)
{
mSelf = self;
m_pPluginManager = pLuginManager;
m_pRecordManager = new NFCRecordManager(mSelf);
m_pHeartBeatManager = new NFCHeartBeatManager(mSelf);
m_pPropertyManager = new NFCPropertyManager(mSelf);
m_pComponentManager = new NFCComponentManager(mSelf, m_pPluginManager);
}
NFCObject::~NFCObject()
{
delete m_pComponentManager;
delete m_pPropertyManager;
delete m_pRecordManager;
delete m_pHeartBeatManager;
}
bool NFCObject::Init()
{
return true;
}
bool NFCObject::Shut()
{
return true;
}
bool NFCObject::Execute(const float fLastTime, const float fAllTime)
{
//ѭУɾԼ
GetHeartBeatManager()->Execute(fLastTime, fAllTime);
GetComponentManager()->Execute(fLastTime, fAllTime);
return true;
}
bool NFCObject::AddHeartBeat(const std::string& strHeartBeatName, const HEART_BEAT_FUNCTOR_PTR& cb, const NFIValueList& var, const float fTime, const int nCount)
{
return GetHeartBeatManager()->AddHeartBeat(mSelf , strHeartBeatName, cb, var, fTime, nCount);
}
bool NFCObject::FindHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->Exist(strHeartBeatName);
}
bool NFCObject::RemoveHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->RemoveHeartBeat(strHeartBeatName);
}
bool NFCObject::AddRecordCallBack(const std::string& strRecordName, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
pRecord->AddRecordHook(cb);
return true;
}
return false;
}
bool NFCObject::AddPropertyCallBack(const std::string& strCriticalName, const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strCriticalName);
if (pProperty)
{
pProperty->RegisterCallback(cb, NFCValueList());
return true;
}
return false;
}
bool NFCObject::FindProperty(const std::string& strPropertyName)
{
if (GetPropertyManager()->GetElement(strPropertyName))
{
return true;
}
return false;
}
bool NFCObject::SetPropertyInt(const std::string& strPropertyName, const int nValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetInt(nValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyFloat(const std::string& strPropertyName, const float fValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetFloat(fValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyDouble(const std::string& strPropertyName, const double dwValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetDouble(dwValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyString(const std::string& strPropertyName, const std::string& strValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetString(strValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyObject(const std::string& strPropertyName, const NFIDENTID& obj)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetObject(obj);
return true;
}
return false;
}
int NFCObject::QueryPropertyInt(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryInt();
}
return -1;
}
float NFCObject::QueryPropertyFloat(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryFloat();
}
return 0.0f;
}
double NFCObject::QueryPropertyDouble(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryDouble();
}
return 0.0;
}
const std::string& NFCObject::QueryPropertyString(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryString();
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryPropertyObject(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryObject();
}
return 0;
}
bool NFCObject::FindRecord(const std::string& strRecordName)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return true;
}
return false;
}
bool NFCObject::SetRecordInt(const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordInt(pRecord, strRecordName, nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
if (pRecord)
{
return pRecord->SetInt(nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordFloat(const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordFloat(pRecord, strRecordName, nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordFloat(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
if (pRecord)
{
return pRecord->SetFloat(nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordDouble(const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordDouble(pRecord, strRecordName, nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordDouble(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
if (pRecord)
{
return pRecord->SetDouble(nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordString(const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordString(pRecord, strRecordName, nRow, nCol, strValue);
}
return false;
}
bool NFCObject::SetRecordString(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
if (pRecord)
{
return pRecord->SetString(nRow, nCol, strValue.c_str());
}
return false;
}
bool NFCObject::SetRecordObject(const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordObject(pRecord, strRecordName, nRow, nCol, obj);
}
return false;
}
bool NFCObject::SetRecordObject(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
if (pRecord)
{
return pRecord->SetObject(nRow, nCol, obj);
}
return false;
}
int NFCObject::QueryRecordInt(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordInt(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
int NFCObject::QueryRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryInt(nRow, nCol);
}
return 0;
}
float NFCObject::QueryRecordFloat(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordFloat(pRecord, strRecordName, nRow, nCol);
}
return 0.0f;
}
float NFCObject::QueryRecordFloat(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryFloat(nRow, nCol);
}
return 0.0f;
}
double NFCObject::QueryRecordDouble(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordDouble(pRecord, strRecordName, nRow, nCol);
}
return 0.0;
}
double NFCObject::QueryRecordDouble(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryDouble(nRow, nCol);
}
return 0.0;
}
const std::string& NFCObject::QueryRecordString(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordString(pRecord, strRecordName, nRow, nCol);
}
return NULL_STR;
}
const std::string& NFCObject::QueryRecordString(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryString(nRow, nCol);
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryRecordObject(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordObject(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
NFIDENTID NFCObject::QueryRecordObject(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryObject(nRow, nCol);
}
return 0;
}
NFIRecordManager* NFCObject::GetRecordManager()
{
return m_pRecordManager;
}
NFIHeartBeatManager* NFCObject::GetHeartBeatManager()
{
return m_pHeartBeatManager;
}
NFIPropertyManager* NFCObject::GetPropertyManager()
{
return m_pPropertyManager;
}
NFIDENTID NFCObject::Self()
{
return mSelf;
}
NFIComponentManager* NFCObject::GetComponentManager()
{
return m_pComponentManager;
}
NFIComponent* NFCObject::AddComponent( const std::string& strComponentName )
{
return m_pComponentManager->AddComponent(strComponentName);
}
NFIComponent* NFCObject::FindComponent( const std::string& strComponentName )
{
return m_pComponentManager->Findomponent(strComponentName);
}
<commit_msg>fixed for build error<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCObject.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCObject
//
// -------------------------------------------------------------------------
#include "NFCObject.h"
#include "NFCRecordManager.h"
#include "NFCHeartBeatManager.h"
#include "NFCPropertyManager.h"
#include "NFCComponentManager.h"
NFCObject::NFCObject(const NFIDENTID& self, NFIPluginManager* pLuginManager)
{
mSelf = self;
m_pPluginManager = pLuginManager;
m_pRecordManager = new NFCRecordManager(mSelf);
m_pHeartBeatManager = new NFCHeartBeatManager(mSelf);
m_pPropertyManager = new NFCPropertyManager(mSelf);
m_pComponentManager = new NFCComponentManager(mSelf, m_pPluginManager);
}
NFCObject::~NFCObject()
{
delete m_pComponentManager;
delete m_pPropertyManager;
delete m_pRecordManager;
delete m_pHeartBeatManager;
}
bool NFCObject::Init()
{
return true;
}
bool NFCObject::Shut()
{
return true;
}
bool NFCObject::Execute(const float fLastTime, const float fAllTime)
{
//ѭУɾԼ
GetHeartBeatManager()->Execute(fLastTime, fAllTime);
GetComponentManager()->Execute(fLastTime, fAllTime);
return true;
}
bool NFCObject::AddHeartBeat(const std::string& strHeartBeatName, const HEART_BEAT_FUNCTOR_PTR& cb, const NFIValueList& var, const float fTime, const int nCount)
{
return GetHeartBeatManager()->AddHeartBeat(mSelf , strHeartBeatName, cb, var, fTime, nCount);
}
bool NFCObject::FindHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->Exist(strHeartBeatName);
}
bool NFCObject::RemoveHeartBeat(const std::string& strHeartBeatName)
{
return GetHeartBeatManager()->RemoveHeartBeat(strHeartBeatName);
}
bool NFCObject::AddRecordCallBack(const std::string& strRecordName, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
pRecord->AddRecordHook(cb);
return true;
}
return false;
}
bool NFCObject::AddPropertyCallBack(const std::string& strCriticalName, const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strCriticalName);
if (pProperty)
{
pProperty->RegisterCallback(cb, NFCValueList());
return true;
}
return false;
}
bool NFCObject::FindProperty(const std::string& strPropertyName)
{
if (GetPropertyManager()->GetElement(strPropertyName))
{
return true;
}
return false;
}
bool NFCObject::SetPropertyInt(const std::string& strPropertyName, const int nValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetInt(nValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyFloat(const std::string& strPropertyName, const float fValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetFloat(fValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyDouble(const std::string& strPropertyName, const double dwValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetDouble(dwValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyString(const std::string& strPropertyName, const std::string& strValue)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetString(strValue);
return true;
}
return false;
}
bool NFCObject::SetPropertyObject(const std::string& strPropertyName, const NFIDENTID& obj)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
pProperty->SetObject(obj);
return true;
}
return false;
}
int NFCObject::QueryPropertyInt(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryInt();
}
return -1;
}
float NFCObject::QueryPropertyFloat(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryFloat();
}
return 0.0f;
}
double NFCObject::QueryPropertyDouble(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryDouble();
}
return 0.0;
}
const std::string& NFCObject::QueryPropertyString(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryString();
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryPropertyObject(const std::string& strPropertyName)
{
NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
if (pProperty)
{
return pProperty->QueryObject();
}
return 0;
}
bool NFCObject::FindRecord(const std::string& strRecordName)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return true;
}
return false;
}
bool NFCObject::SetRecordInt(const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordInt(pRecord, strRecordName, nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
if (pRecord)
{
return pRecord->SetInt(nRow, nCol, nValue);
}
return false;
}
bool NFCObject::SetRecordFloat(const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordFloat(pRecord, strRecordName, nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordFloat(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
if (pRecord)
{
return pRecord->SetFloat(nRow, nCol, fValue);
}
return false;
}
bool NFCObject::SetRecordDouble(const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordDouble(pRecord, strRecordName, nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordDouble(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
if (pRecord)
{
return pRecord->SetDouble(nRow, nCol, dwValue);
}
return false;
}
bool NFCObject::SetRecordString(const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordString(pRecord, strRecordName, nRow, nCol, strValue);
}
return false;
}
bool NFCObject::SetRecordString(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
if (pRecord)
{
return pRecord->SetString(nRow, nCol, strValue.c_str());
}
return false;
}
bool NFCObject::SetRecordObject(const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return SetRecordObject(pRecord, strRecordName, nRow, nCol, obj);
}
return false;
}
bool NFCObject::SetRecordObject(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
if (pRecord)
{
return pRecord->SetObject(nRow, nCol, obj);
}
return false;
}
int NFCObject::QueryRecordInt(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordInt(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
int NFCObject::QueryRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryInt(nRow, nCol);
}
return 0;
}
float NFCObject::QueryRecordFloat(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordFloat(pRecord, strRecordName, nRow, nCol);
}
return 0.0f;
}
float NFCObject::QueryRecordFloat(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryFloat(nRow, nCol);
}
return 0.0f;
}
double NFCObject::QueryRecordDouble(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordDouble(pRecord, strRecordName, nRow, nCol);
}
return 0.0;
}
double NFCObject::QueryRecordDouble(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryDouble(nRow, nCol);
}
return 0.0;
}
const std::string& NFCObject::QueryRecordString(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordString(pRecord, strRecordName, nRow, nCol);
}
return NULL_STR;
}
const std::string& NFCObject::QueryRecordString(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryString(nRow, nCol);
}
return NULL_STR;
}
NFIDENTID NFCObject::QueryRecordObject(const std::string& strRecordName, const int nRow, const int nCol)
{
NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
if (pRecord)
{
return QueryRecordObject(pRecord, strRecordName, nRow, nCol);
}
return 0;
}
NFIDENTID NFCObject::QueryRecordObject(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
if (pRecord)
{
return pRecord->QueryObject(nRow, nCol);
}
return 0;
}
NFIRecordManager* NFCObject::GetRecordManager()
{
return m_pRecordManager;
}
NFIHeartBeatManager* NFCObject::GetHeartBeatManager()
{
return m_pHeartBeatManager;
}
NFIPropertyManager* NFCObject::GetPropertyManager()
{
return m_pPropertyManager;
}
NFIDENTID NFCObject::Self()
{
return mSelf;
}
NFIComponentManager* NFCObject::GetComponentManager()
{
return m_pComponentManager;
}
NFIComponent* NFCObject::AddComponent( const std::string& strComponentName )
{
return m_pComponentManager->AddComponent(strComponentName);
}
NFIComponent* NFCObject::FindComponent( const std::string& strComponentName )
{
return m_pComponentManager->FindComponent(strComponentName);
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE libraries
Copyright (C) 2001-2003 Christoph Cullmann <cullmann@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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// $Id$
#include "kateschema.h"
#include "kateschema.moc"
#include "kateconfig.h"
#include "katefactory.h"
#include <klocale.h>
#include <kdialog.h>
#include <kcolorbutton.h>
#include <kcombobox.h>
#include <klineeditdlg.h>
#include <kfontdialog.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qptrcollection.h>
#include <qdialog.h>
#include <qgrid.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qtextcodec.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qlistbox.h>
#include <qhbox.h>
#include <qobjectlist.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qspinbox.h>
#include <qstringlist.h>
#include <qtabwidget.h>
#include <qvbox.h>
#include <qvgroupbox.h>
#include <qwhatsthis.h>
KateSchemaManager::KateSchemaManager ()
: m_config ("kateschemarc", false, false)
{
update ();
}
KateSchemaManager::~KateSchemaManager ()
{
}
//
// read the types from config file and update the internal list
//
void KateSchemaManager::update (bool readfromfile)
{
if (readfromfile)
m_config.reparseConfiguration ();
m_schemas = m_config.groupList();
m_schemas.sort ();
m_schemas.remove ("Kate Printing Schema");
m_schemas.remove ("Kate Normal Schema");
m_schemas.prepend (i18n("Printing"));
m_schemas.prepend (i18n("Normal"));
}
//
// get the right group
// special handling of the default schemas ;)
//
KConfig *KateSchemaManager::schema (uint number)
{
if ((number>1) && (number < m_schemas.count()))
m_config.setGroup (m_schemas[number]);
else if (number == 1)
m_config.setGroup ("Kate Printing Schema");
else
m_config.setGroup ("Kate Normal Schema");
return &m_config;
}
void KateSchemaManager::addSchema (const QString &t)
{
m_config.setGroup (t);
m_config.writeEntry("Color Background", KGlobalSettings::baseColor());
update (false);
}
void KateSchemaManager::removeSchema (uint number)
{
if (number >= m_schemas.count())
return;
if (number < 2)
return;
m_config.deleteGroup (name (number));
update (false);
}
uint KateSchemaManager::number (const QString &name)
{
int i;
if ((i = m_schemas.findIndex(name)) > -1)
return i;
return 0;
}
QString KateSchemaManager::name (uint number)
{
if ((number>1) && (number < m_schemas.count()))
return m_schemas[number];
else if (number == 1)
return "Kate Printing Schema";
return "Kate Normal Schema";
}
//
//
//
// DIALOGS !!!
//
//
//BEGIN KateSchemaConfigColorTab
KateSchemaConfigColorTab::KateSchemaConfigColorTab( QWidget *parent, const char * )
: QWidget (parent)
{
QHBox *b;
QLabel *label;
QVBoxLayout *blay=new QVBoxLayout(this, 0, KDialog::spacingHint());
QVGroupBox *gbTextArea = new QVGroupBox(i18n("Text Area Background"), this);
b = new QHBox (gbTextArea);
label = new QLabel( i18n("Normal text:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_back = new KColorButton(b);
connect( m_back, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbTextArea);
label = new QLabel( i18n("Selected text:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_selected = new KColorButton(b);
connect( m_selected, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbTextArea);
label = new QLabel( i18n("Current line:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_current = new KColorButton(b);
connect( m_current, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
blay->addWidget(gbTextArea);
QVGroupBox *gbBorder = new QVGroupBox(i18n("Additional Elements"), this);
b = new QHBox (gbBorder);
label = new QLabel( i18n("Left border background:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_iconborder = new KColorButton(b);
connect( m_iconborder, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbBorder);
label = new QLabel( i18n("Bracket highlight:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_bracket = new KColorButton(b);
connect( m_bracket, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbBorder);
label = new QLabel( i18n("Word wrap markers:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_wwmarker = new KColorButton(b);
connect( m_wwmarker, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbBorder);
label = new QLabel( i18n("Tab markers:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_tmarker = new KColorButton(b);
connect( m_tmarker, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
blay->addWidget(gbBorder);
blay->addStretch();
// QWhatsThis help
QWhatsThis::add(m_back, i18n("<p>Sets the background color of the editing area.</p>"));
QWhatsThis::add(m_selected, i18n("<p>Sets the background color of the selection.</p>"
"<p>To set the text color for selected text, use the \"<b>Configure "
"Highlighting</b>\" dialog.</p>"));
QWhatsThis::add(m_current, i18n("<p>Sets the background color of the currently "
"active line, which means the line where your cursor is positioned.</p>"));
QWhatsThis::add(m_bracket, i18n("<p>Sets the bracket matching color. This means, "
"if you place the cursor e.g. at a <b>(</b>, the matching <b>)</b> will "
"be highlighted with this color.</p>"));
QWhatsThis::add(m_wwmarker, i18n(
"<p>Sets the color of Word Wrap-related markers:</p>"
"<dl><dt>Static Word Wrap</dt><dd>A vertical line which shows the column where "
"text is going to be wrapped</dd>"
"<dt>Dynamic Word Wrap</dt><dd>An arrow shown to the left of "
"visually-wrapped lines</dd></dl>"));
QWhatsThis::add(m_tmarker, i18n(
"<p>Sets the color of the tabulator marks:</p>"));
}
KateSchemaConfigColorTab::~KateSchemaConfigColorTab()
{
}
void KateSchemaConfigColorTab::readConfig (KConfig *config)
{
QColor tmp0 (KGlobalSettings::baseColor());
QColor tmp1 (KGlobalSettings::highlightColor());
QColor tmp2 (KGlobalSettings::alternateBackgroundColor());
QColor tmp3 ( "#FFFF99" );
QColor tmp4 (tmp2.dark());
QColor tmp5 ( KGlobalSettings::textColor() );
QColor tmp6 ( "#EAE9E8" );
m_back->setColor(config->readColorEntry("Color Background", &tmp0));
m_selected->setColor(config->readColorEntry("Color Selection", &tmp1));
m_current->setColor(config->readColorEntry("Color Highlighted Line", &tmp2));
m_bracket->setColor(config->readColorEntry("Color Highlighted Bracket", &tmp3));
m_wwmarker->setColor(config->readColorEntry("Color Word Wrap Marker", &tmp4));
m_tmarker->setColor(config->readColorEntry("Color Tab Marker", &tmp5));
m_iconborder->setColor(config->readColorEntry("Color Icon Bar", &tmp6));
}
void KateSchemaConfigColorTab::writeConfig (KConfig *config)
{
config->writeEntry("Color Background", m_back->color());
config->writeEntry("Color Selection", m_selected->color());
config->writeEntry("Color Highlighted Line", m_current->color());
config->writeEntry("Color Highlighted Bracket", m_bracket->color());
config->writeEntry("Color Word Wrap Marker", m_wwmarker->color());
config->writeEntry("Color Tab Marker", m_tmarker->color());
config->writeEntry("Color Icon Bar", m_iconborder->color());
}
//END KateSchemaConfigColorTab
//BEGIN FontConfig
KateSchemaConfigFontTab::KateSchemaConfigFontTab( QWidget *parent, const char * )
: QWidget (parent)
{
// sizemanagment
QGridLayout *grid = new QGridLayout( this, 1, 1 );
m_fontchooser = new KFontChooser ( this, 0L, false, QStringList(), false );
m_fontchooser->enableColumn(KFontChooser::StyleList, false);
grid->addWidget( m_fontchooser, 0, 0);
connect (m_fontchooser, SIGNAL (fontSelected( const QFont & )), this, SLOT (slotFontSelected( const QFont & )));
connect (m_fontchooser, SIGNAL (fontSelected( const QFont & )), parent->parentWidget(), SLOT (slotChanged()));
}
KateSchemaConfigFontTab::~KateSchemaConfigFontTab()
{
}
void KateSchemaConfigFontTab::slotFontSelected( const QFont &font )
{
myFont = font;
}
void KateSchemaConfigFontTab::readConfig (KConfig *config)
{
QFont f (KGlobalSettings::fixedFont());
m_fontchooser->setFont (config->readFontEntry("Font", &f));
}
void KateSchemaConfigFontTab::writeConfig (KConfig *config)
{
config->writeEntry("Font", myFont);
}
//END FontConfig
KateSchemaConfigPage::KateSchemaConfigPage( QWidget *parent )
: Kate::ConfigPage( parent ),
m_lastSchema (-1)
{
QVBoxLayout *layout = new QVBoxLayout(this, 0, KDialog::spacingHint() );
// hl chooser
QHBox *hbHl = new QHBox( this );
layout->add (hbHl);
hbHl->setSpacing( KDialog::spacingHint() );
QLabel *lHl = new QLabel( i18n("&Schema:"), hbHl );
schemaCombo = new QComboBox( false, hbHl );
lHl->setBuddy( schemaCombo );
connect( schemaCombo, SIGNAL(activated(int)),
this, SLOT(schemaChanged(int)) );
btndel = new QPushButton( i18n("&Delete"), hbHl );
connect( btndel, SIGNAL(clicked()), this, SLOT(deleteSchema()) );
QPushButton *btnnew = new QPushButton( i18n("&New"), hbHl );
connect( btnnew, SIGNAL(clicked()), this, SLOT(newSchema()) );
m_tabWidget = new QTabWidget ( this );
layout->add (m_tabWidget);
m_colorTab = new KateSchemaConfigColorTab (m_tabWidget);
m_tabWidget->addTab (m_colorTab, i18n("Colors"));
m_fontTab = new KateSchemaConfigFontTab (m_tabWidget);
m_tabWidget->addTab (m_fontTab, i18n("Font"));
reload();
}
KateSchemaConfigPage::~KateSchemaConfigPage ()
{
// just reload config from disc
KateFactory::schemaManager()->update ();
}
void KateSchemaConfigPage::apply()
{
if (m_lastSchema > -1)
{
m_colorTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
m_fontTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
}
// just sync the config
KateFactory::schemaManager()->schema (0)->sync();
KateFactory::schemaManager()->update ();
KateRendererConfig::global()->setSchema (KateRendererConfig::global()->schema());
}
void KateSchemaConfigPage::reload()
{
// just reload the config from disc
KateFactory::schemaManager()->update ();
update ();
}
void KateSchemaConfigPage::reset()
{
reload ();
}
void KateSchemaConfigPage::defaults()
{
reload ();
}
void KateSchemaConfigPage::update ()
{
// soft update, no load from disk
KateFactory::schemaManager()->update (false);
schemaCombo->clear ();
schemaCombo->insertStringList (KateFactory::schemaManager()->list ());
schemaCombo->setCurrentItem (0);
schemaChanged (0);
schemaCombo->setEnabled (schemaCombo->count() > 0);
}
void KateSchemaConfigPage::deleteSchema ()
{
int t = schemaCombo->currentItem ();
KateFactory::schemaManager()->removeSchema (t);
update ();
}
void KateSchemaConfigPage::newSchema ()
{
QString t = KLineEditDlg::getText (i18n("Name for new Schema"), i18n ("Name:"), i18n("New Schema"), 0, this);
KateFactory::schemaManager()->addSchema (t);
// soft update, no load from disk
KateFactory::schemaManager()->update (false);
int i = KateFactory::schemaManager()->list ().findIndex (t);
update ();
if (i > -1)
{
schemaCombo->setCurrentItem (i);
schemaChanged (i);
}
}
void KateSchemaConfigPage::schemaChanged (int schema)
{
if (schema < 2)
{
btndel->setEnabled (false);
}
else
{
btndel->setEnabled (true);
}
if (m_lastSchema > -1)
{
m_colorTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
m_fontTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
}
m_colorTab->readConfig (KateFactory::schemaManager()->schema(schema));
m_fontTab->readConfig (KateFactory::schemaManager()->schema(schema));
m_lastSchema = schema;
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>using margin hint, more compliant to style guide andd even looks good ;)<commit_after>/* This file is part of the KDE libraries
Copyright (C) 2001-2003 Christoph Cullmann <cullmann@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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// $Id$
#include "kateschema.h"
#include "kateschema.moc"
#include "kateconfig.h"
#include "katefactory.h"
#include <klocale.h>
#include <kdialog.h>
#include <kcolorbutton.h>
#include <kcombobox.h>
#include <klineeditdlg.h>
#include <kfontdialog.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qptrcollection.h>
#include <qdialog.h>
#include <qgrid.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qtextcodec.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qlistbox.h>
#include <qhbox.h>
#include <qobjectlist.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qspinbox.h>
#include <qstringlist.h>
#include <qtabwidget.h>
#include <qvbox.h>
#include <qvgroupbox.h>
#include <qwhatsthis.h>
KateSchemaManager::KateSchemaManager ()
: m_config ("kateschemarc", false, false)
{
update ();
}
KateSchemaManager::~KateSchemaManager ()
{
}
//
// read the types from config file and update the internal list
//
void KateSchemaManager::update (bool readfromfile)
{
if (readfromfile)
m_config.reparseConfiguration ();
m_schemas = m_config.groupList();
m_schemas.sort ();
m_schemas.remove ("Kate Printing Schema");
m_schemas.remove ("Kate Normal Schema");
m_schemas.prepend (i18n("Printing"));
m_schemas.prepend (i18n("Normal"));
}
//
// get the right group
// special handling of the default schemas ;)
//
KConfig *KateSchemaManager::schema (uint number)
{
if ((number>1) && (number < m_schemas.count()))
m_config.setGroup (m_schemas[number]);
else if (number == 1)
m_config.setGroup ("Kate Printing Schema");
else
m_config.setGroup ("Kate Normal Schema");
return &m_config;
}
void KateSchemaManager::addSchema (const QString &t)
{
m_config.setGroup (t);
m_config.writeEntry("Color Background", KGlobalSettings::baseColor());
update (false);
}
void KateSchemaManager::removeSchema (uint number)
{
if (number >= m_schemas.count())
return;
if (number < 2)
return;
m_config.deleteGroup (name (number));
update (false);
}
uint KateSchemaManager::number (const QString &name)
{
int i;
if ((i = m_schemas.findIndex(name)) > -1)
return i;
return 0;
}
QString KateSchemaManager::name (uint number)
{
if ((number>1) && (number < m_schemas.count()))
return m_schemas[number];
else if (number == 1)
return "Kate Printing Schema";
return "Kate Normal Schema";
}
//
//
//
// DIALOGS !!!
//
//
//BEGIN KateSchemaConfigColorTab
KateSchemaConfigColorTab::KateSchemaConfigColorTab( QWidget *parent, const char * )
: QWidget (parent)
{
QHBox *b;
QLabel *label;
QVBoxLayout *blay=new QVBoxLayout(this, 0, KDialog::spacingHint());
QVGroupBox *gbTextArea = new QVGroupBox(i18n("Text Area Background"), this);
b = new QHBox (gbTextArea);
label = new QLabel( i18n("Normal text:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_back = new KColorButton(b);
connect( m_back, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbTextArea);
label = new QLabel( i18n("Selected text:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_selected = new KColorButton(b);
connect( m_selected, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbTextArea);
label = new QLabel( i18n("Current line:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_current = new KColorButton(b);
connect( m_current, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
blay->addWidget(gbTextArea);
QVGroupBox *gbBorder = new QVGroupBox(i18n("Additional Elements"), this);
b = new QHBox (gbBorder);
label = new QLabel( i18n("Left border background:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_iconborder = new KColorButton(b);
connect( m_iconborder, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbBorder);
label = new QLabel( i18n("Bracket highlight:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_bracket = new KColorButton(b);
connect( m_bracket, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbBorder);
label = new QLabel( i18n("Word wrap markers:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_wwmarker = new KColorButton(b);
connect( m_wwmarker, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
b = new QHBox (gbBorder);
label = new QLabel( i18n("Tab markers:"), b);
label->setAlignment( AlignLeft|AlignVCenter);
m_tmarker = new KColorButton(b);
connect( m_tmarker, SIGNAL( changed( const QColor & ) ), parent->parentWidget(), SLOT( slotChanged() ) );
blay->addWidget(gbBorder);
blay->addStretch();
// QWhatsThis help
QWhatsThis::add(m_back, i18n("<p>Sets the background color of the editing area.</p>"));
QWhatsThis::add(m_selected, i18n("<p>Sets the background color of the selection.</p>"
"<p>To set the text color for selected text, use the \"<b>Configure "
"Highlighting</b>\" dialog.</p>"));
QWhatsThis::add(m_current, i18n("<p>Sets the background color of the currently "
"active line, which means the line where your cursor is positioned.</p>"));
QWhatsThis::add(m_bracket, i18n("<p>Sets the bracket matching color. This means, "
"if you place the cursor e.g. at a <b>(</b>, the matching <b>)</b> will "
"be highlighted with this color.</p>"));
QWhatsThis::add(m_wwmarker, i18n(
"<p>Sets the color of Word Wrap-related markers:</p>"
"<dl><dt>Static Word Wrap</dt><dd>A vertical line which shows the column where "
"text is going to be wrapped</dd>"
"<dt>Dynamic Word Wrap</dt><dd>An arrow shown to the left of "
"visually-wrapped lines</dd></dl>"));
QWhatsThis::add(m_tmarker, i18n(
"<p>Sets the color of the tabulator marks:</p>"));
}
KateSchemaConfigColorTab::~KateSchemaConfigColorTab()
{
}
void KateSchemaConfigColorTab::readConfig (KConfig *config)
{
QColor tmp0 (KGlobalSettings::baseColor());
QColor tmp1 (KGlobalSettings::highlightColor());
QColor tmp2 (KGlobalSettings::alternateBackgroundColor());
QColor tmp3 ( "#FFFF99" );
QColor tmp4 (tmp2.dark());
QColor tmp5 ( KGlobalSettings::textColor() );
QColor tmp6 ( "#EAE9E8" );
m_back->setColor(config->readColorEntry("Color Background", &tmp0));
m_selected->setColor(config->readColorEntry("Color Selection", &tmp1));
m_current->setColor(config->readColorEntry("Color Highlighted Line", &tmp2));
m_bracket->setColor(config->readColorEntry("Color Highlighted Bracket", &tmp3));
m_wwmarker->setColor(config->readColorEntry("Color Word Wrap Marker", &tmp4));
m_tmarker->setColor(config->readColorEntry("Color Tab Marker", &tmp5));
m_iconborder->setColor(config->readColorEntry("Color Icon Bar", &tmp6));
}
void KateSchemaConfigColorTab::writeConfig (KConfig *config)
{
config->writeEntry("Color Background", m_back->color());
config->writeEntry("Color Selection", m_selected->color());
config->writeEntry("Color Highlighted Line", m_current->color());
config->writeEntry("Color Highlighted Bracket", m_bracket->color());
config->writeEntry("Color Word Wrap Marker", m_wwmarker->color());
config->writeEntry("Color Tab Marker", m_tmarker->color());
config->writeEntry("Color Icon Bar", m_iconborder->color());
}
//END KateSchemaConfigColorTab
//BEGIN FontConfig
KateSchemaConfigFontTab::KateSchemaConfigFontTab( QWidget *parent, const char * )
: QWidget (parent)
{
// sizemanagment
QGridLayout *grid = new QGridLayout( this, 1, 1 );
m_fontchooser = new KFontChooser ( this, 0L, false, QStringList(), false );
m_fontchooser->enableColumn(KFontChooser::StyleList, false);
grid->addWidget( m_fontchooser, 0, 0);
connect (m_fontchooser, SIGNAL (fontSelected( const QFont & )), this, SLOT (slotFontSelected( const QFont & )));
connect (m_fontchooser, SIGNAL (fontSelected( const QFont & )), parent->parentWidget(), SLOT (slotChanged()));
}
KateSchemaConfigFontTab::~KateSchemaConfigFontTab()
{
}
void KateSchemaConfigFontTab::slotFontSelected( const QFont &font )
{
myFont = font;
}
void KateSchemaConfigFontTab::readConfig (KConfig *config)
{
QFont f (KGlobalSettings::fixedFont());
m_fontchooser->setFont (config->readFontEntry("Font", &f));
}
void KateSchemaConfigFontTab::writeConfig (KConfig *config)
{
config->writeEntry("Font", myFont);
}
//END FontConfig
KateSchemaConfigPage::KateSchemaConfigPage( QWidget *parent )
: Kate::ConfigPage( parent ),
m_lastSchema (-1)
{
QVBoxLayout *layout = new QVBoxLayout(this, 0, KDialog::spacingHint() );
// hl chooser
QHBox *hbHl = new QHBox( this );
layout->add (hbHl);
hbHl->setSpacing( KDialog::spacingHint() );
QLabel *lHl = new QLabel( i18n("&Schema:"), hbHl );
schemaCombo = new QComboBox( false, hbHl );
lHl->setBuddy( schemaCombo );
connect( schemaCombo, SIGNAL(activated(int)),
this, SLOT(schemaChanged(int)) );
btndel = new QPushButton( i18n("&Delete"), hbHl );
connect( btndel, SIGNAL(clicked()), this, SLOT(deleteSchema()) );
QPushButton *btnnew = new QPushButton( i18n("&New"), hbHl );
connect( btnnew, SIGNAL(clicked()), this, SLOT(newSchema()) );
m_tabWidget = new QTabWidget ( this );
m_tabWidget->setMargin (KDialog::marginHint());
layout->add (m_tabWidget);
m_colorTab = new KateSchemaConfigColorTab (m_tabWidget);
m_tabWidget->addTab (m_colorTab, i18n("Colors"));
m_fontTab = new KateSchemaConfigFontTab (m_tabWidget);
m_tabWidget->addTab (m_fontTab, i18n("Font"));
reload();
}
KateSchemaConfigPage::~KateSchemaConfigPage ()
{
// just reload config from disc
KateFactory::schemaManager()->update ();
}
void KateSchemaConfigPage::apply()
{
if (m_lastSchema > -1)
{
m_colorTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
m_fontTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
}
// just sync the config
KateFactory::schemaManager()->schema (0)->sync();
KateFactory::schemaManager()->update ();
KateRendererConfig::global()->setSchema (KateRendererConfig::global()->schema());
}
void KateSchemaConfigPage::reload()
{
// just reload the config from disc
KateFactory::schemaManager()->update ();
update ();
}
void KateSchemaConfigPage::reset()
{
reload ();
}
void KateSchemaConfigPage::defaults()
{
reload ();
}
void KateSchemaConfigPage::update ()
{
// soft update, no load from disk
KateFactory::schemaManager()->update (false);
schemaCombo->clear ();
schemaCombo->insertStringList (KateFactory::schemaManager()->list ());
schemaCombo->setCurrentItem (0);
schemaChanged (0);
schemaCombo->setEnabled (schemaCombo->count() > 0);
}
void KateSchemaConfigPage::deleteSchema ()
{
int t = schemaCombo->currentItem ();
KateFactory::schemaManager()->removeSchema (t);
update ();
}
void KateSchemaConfigPage::newSchema ()
{
QString t = KLineEditDlg::getText (i18n("Name for new Schema"), i18n ("Name:"), i18n("New Schema"), 0, this);
KateFactory::schemaManager()->addSchema (t);
// soft update, no load from disk
KateFactory::schemaManager()->update (false);
int i = KateFactory::schemaManager()->list ().findIndex (t);
update ();
if (i > -1)
{
schemaCombo->setCurrentItem (i);
schemaChanged (i);
}
}
void KateSchemaConfigPage::schemaChanged (int schema)
{
if (schema < 2)
{
btndel->setEnabled (false);
}
else
{
btndel->setEnabled (true);
}
if (m_lastSchema > -1)
{
m_colorTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
m_fontTab->writeConfig (KateFactory::schemaManager()->schema(m_lastSchema));
}
m_colorTab->readConfig (KateFactory::schemaManager()->schema(schema));
m_fontTab->readConfig (KateFactory::schemaManager()->schema(schema));
m_lastSchema = schema;
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>/*
Mailbox
Copyright (C) 2015 Will Penington
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <QString>
#include <QtTest>
#include <QSignalSpy>
#include "erlangshell.h"
#include "erlatom.h"
#include "erlvartypes.h"
#include "mailboxqt.h"
#include "client.h"
class MailboxTest : public QObject
{
Q_OBJECT
public:
MailboxTest();
private Q_SLOTS:
void canCommunicateWithErlangShell_data();
void canCommunicateWithErlangShell();
void clientCanConnectToErlang_data();
void clientCanConnectToErlang();
void canSendMessageToErlang_data();
void canSendMessageToErlang();
void canRecieveMessagesFromErlang_data();
void canRecieveMessagesFromErlang();
void canSendMultipleMessagesToErlang();
void canRecieveMultipleMessagesFromErlang();
void unusedNodeDoesNotCrash();
};
QVariantMap simpleValues {
{"int", 5},
{"float", 4.3},
{"round_float", 4.0},
{"large_int", 1000000},
{"atom", QVariant::fromValue(Mailbox::ErlAtom("testatom"))}
};
MailboxTest::MailboxTest()
{
Mailbox::init();
}
void MailboxTest::canCommunicateWithErlangShell_data() {
QTest::addColumn<QByteArray>("statement");
QTest::addColumn<QByteArray>("expected");
QTest::newRow("atom") << QByteArray("sample_atom.") << QByteArray("sample_atom\n");
QTest::newRow("maths") << QByteArray("1 + 1.") << QByteArray("2\n");
QTest::newRow("complex types") << QByteArray("[{foo, bar}, 1 + 3, baz].")
<< QByteArray("[{foo,bar},4,baz]\n");
}
void MailboxTest::canCommunicateWithErlangShell()
{
ErlangShell erl("dummy", "cookie");
QFETCH(QByteArray, statement);
QTEST(erl.execStatement(statement), "expected");
}
void MailboxTest::clientCanConnectToErlang_data()
{
QTest::addColumn<QByteArray>("erlangNodeName");
QTest::addColumn<QByteArray>("cnodeNodeName");
QTest::addColumn<QByteArray>("cnodeConnectTo");
QTest::addColumn<QByteArray>("erlangCookie");
QTest::addColumn<QByteArray>("cnodeCookie");
QTest::addColumn<bool>("expected");
QTest::newRow("normal") << QByteArray("conTest1") << QByteArray("conTest1Lib")
<< QByteArray("conTest1") << QByteArray("cookie")
<< QByteArray("cookie") << true;
QTest::newRow("all_different") << QByteArray("conTest2")
<< QByteArray("conTest2Lib")
<< QByteArray("wrong") << QByteArray("cookie1")
<< QByteArray("cookie2") << false;
QTest::newRow("names_different") << QByteArray("conTest2")
<< QByteArray("conTest2Lib")
<< QByteArray("wrong") << QByteArray("cookie")
<< QByteArray("cookie") << false;
QTest::newRow("cookies_different") << QByteArray("conTest1")
<< QByteArray("conTest1Lib") << QByteArray("conTest1")
<< QByteArray("cookie1") << QByteArray("cookie2")
<< false;
QTest::newRow("all_same") << QByteArray("conTest3") << QByteArray("conTest3")
<< QByteArray("conTest3") << QByteArray("cookie")
<< QByteArray("cookie") << false;
}
void MailboxTest::clientCanConnectToErlang()
{
QFETCH(QByteArray, erlangNodeName);
QFETCH(QByteArray, cnodeNodeName);
QFETCH(QByteArray, cnodeConnectTo);
QFETCH(QByteArray, erlangCookie);
QFETCH(QByteArray, cnodeCookie);
ErlangShell erl(erlangNodeName, erlangCookie);
Mailbox::Client *node = new Mailbox::Client();
QTEST(node->connect(cnodeNodeName, cnodeConnectTo, cnodeCookie), "expected");
delete(node);
}
void MailboxTest::canSendMessageToErlang_data()
{
// QTest::addColumn<QVariant>("value");
// QTest::newRow("int") << QVariant(1);
// Mailbox::ErlAtom atom("testatom");
// QTest::newRow("atom") << QVariant::fromValue(atom);
QTest::addColumn<QVariant>("value");
QVariantMap::const_iterator i = simpleValues.constBegin();
while (i != simpleValues.constEnd()) {
QTest::newRow(i.key().toLocal8Bit().data()) << i.value();
i++;
}
}
QString erl_output(QVariant value)
{
QString raw = Mailbox::formatErlangTerm(value);
QRegularExpression re;
re.setPattern("(\\d+\\.\\d*?[1-9])0+");
QRegularExpressionMatch match = re.match(raw);
if (match.hasMatch()) {
QString result = match.captured(1);
return result;
}
re.setPattern("(\\d+\\.0)0+");
match = re.match(raw);
if (match.hasMatch()) {
QString result = match.captured(1);
return result;
}
return raw;
}
void MailboxTest::canSendMessageToErlang()
{
QFETCH(QVariant, value);
ErlangShell erl("sendmessage", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("sendmessagelib", "sendmessage", "cookie"));
erl.execStatement("register(shell, self()).");
QCOMPARE(erl.execStatement("flush()."), QByteArray("ok\n"));
node->sendMessage("shell", value);
QByteArray full_result = QByteArray("Shell got ") + erl_output(value).toLatin1() + QByteArray("\n");
QCOMPARE(erl.execStatement("flush()."), full_result);
delete(node);
}
void MailboxTest::canRecieveMessagesFromErlang_data()
{
QTest::addColumn<QVariant>("value");
QVariantMap::const_iterator i = simpleValues.constBegin();
while (i != simpleValues.constEnd()) {
QTest::newRow(i.key().toLocal8Bit().data()) << i.value();
i++;
}
}
void MailboxTest::canRecieveMessagesFromErlang()
{
ErlangShell erl("recvmessage", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("recvmessagelib", "recvmessage", "cookie"));
QSignalSpy recvSpy(node, &Mailbox::Client::messageRecieved);
erl.execStatement("register(shell, self()).");
node->sendPid("shell");
QCOMPARE(recvSpy.count(), 0);
QFETCH(QVariant, value);
QByteArray val_str = Mailbox::formatErlangTerm(value).toUtf8();
QString stmt = "receive\n Pid -> Pid ! " + val_str + "\n end.";
erl.execStatement(stmt.toUtf8());
QVERIFY(recvSpy.count() == 1 || recvSpy.wait(1000));
QCOMPARE(recvSpy.takeFirst()[0], value);
delete(node);
}
void MailboxTest::canSendMultipleMessagesToErlang()
{
ErlangShell erl("sendmultimessage", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("sendmultimessagelib", "sendmultimessage", "cookie"));
erl.execStatement("register(shell, self()).");
QCOMPARE(erl.execStatement("flush()."), QByteArray("ok\n"));
node->sendAtom("shell", "test1");
QThread::sleep(1);
QCOMPARE(erl.execStatement("flush()."), QByteArray("Shell got test1\n"));
node->sendAtom("shell", "test2");
QThread::sleep(1);
QCOMPARE(erl.execStatement("flush()."), QByteArray("Shell got test2\n"));
node->sendAtom("shell", "test3");
QThread::sleep(1);
QCOMPARE(erl.execStatement("flush()."), QByteArray("Shell got test3\n"));
delete(node);
}
void MailboxTest::canRecieveMultipleMessagesFromErlang()
{
ErlangShell erl("rmm", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("rmml", "rmm", "cookie"));
QSignalSpy recvSpy(node, &Mailbox::Client::messageRecieved);
erl.execStatement("register(shell, self()).");
node->sendPid("shell");
QCOMPARE(recvSpy.count(), 0);
erl.execStatement("Pid = receive\n Pid -> Pid\n end.");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 1 || recvSpy.wait(1000));
node->sendPid("shell");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 2 || recvSpy.wait(1000));
node->sendPid("shell");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 3 || recvSpy.wait(1000));
node->sendPid("shell");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 4 || recvSpy.wait(1000));
delete(node);
}
void MailboxTest::unusedNodeDoesNotCrash()
{
Mailbox::Client *node = new Mailbox::Client();
delete(node);
}
QTEST_GUILESS_MAIN(MailboxTest)
#include "tst_mailboxtest.moc"
<commit_msg>Roundtrip test added<commit_after>/*
Mailbox
Copyright (C) 2015 Will Penington
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <QString>
#include <QtTest>
#include <QSignalSpy>
#include "erlangshell.h"
#include "erlatom.h"
#include "erlvartypes.h"
#include "mailboxqt.h"
#include "client.h"
class MailboxTest : public QObject
{
Q_OBJECT
public:
MailboxTest();
private Q_SLOTS:
void canCommunicateWithErlangShell_data();
void canCommunicateWithErlangShell();
void clientCanConnectToErlang_data();
void clientCanConnectToErlang();
void canSendMessageToErlang_data();
void canSendMessageToErlang();
void canRecieveMessagesFromErlang_data();
void canRecieveMessagesFromErlang();
void canSendMultipleMessagesToErlang();
void canRecieveMultipleMessagesFromErlang();
void canRoundTripFromCNode_data();
void canRoundTripFromCNode();
void unusedNodeDoesNotCrash();
};
QVariantMap simpleValues {
{"int", 5},
{"float", 4.3},
{"round_float", 4.0},
{"large_int", 1000000},
{"atom", QVariant::fromValue(Mailbox::ErlAtom("testatom"))}
};
MailboxTest::MailboxTest()
{
Mailbox::init();
}
void MailboxTest::canCommunicateWithErlangShell_data() {
QTest::addColumn<QByteArray>("statement");
QTest::addColumn<QByteArray>("expected");
QTest::newRow("atom") << QByteArray("sample_atom.") << QByteArray("sample_atom\n");
QTest::newRow("maths") << QByteArray("1 + 1.") << QByteArray("2\n");
QTest::newRow("complex types") << QByteArray("[{foo, bar}, 1 + 3, baz].")
<< QByteArray("[{foo,bar},4,baz]\n");
}
void MailboxTest::canCommunicateWithErlangShell()
{
ErlangShell erl("dummy", "cookie");
QFETCH(QByteArray, statement);
QTEST(erl.execStatement(statement), "expected");
}
void MailboxTest::clientCanConnectToErlang_data()
{
QTest::addColumn<QByteArray>("erlangNodeName");
QTest::addColumn<QByteArray>("cnodeNodeName");
QTest::addColumn<QByteArray>("cnodeConnectTo");
QTest::addColumn<QByteArray>("erlangCookie");
QTest::addColumn<QByteArray>("cnodeCookie");
QTest::addColumn<bool>("expected");
QTest::newRow("normal") << QByteArray("conTest1") << QByteArray("conTest1Lib")
<< QByteArray("conTest1") << QByteArray("cookie")
<< QByteArray("cookie") << true;
QTest::newRow("all_different") << QByteArray("conTest2")
<< QByteArray("conTest2Lib")
<< QByteArray("wrong") << QByteArray("cookie1")
<< QByteArray("cookie2") << false;
QTest::newRow("names_different") << QByteArray("conTest2")
<< QByteArray("conTest2Lib")
<< QByteArray("wrong") << QByteArray("cookie")
<< QByteArray("cookie") << false;
QTest::newRow("cookies_different") << QByteArray("conTest1")
<< QByteArray("conTest1Lib") << QByteArray("conTest1")
<< QByteArray("cookie1") << QByteArray("cookie2")
<< false;
QTest::newRow("all_same") << QByteArray("conTest3") << QByteArray("conTest3")
<< QByteArray("conTest3") << QByteArray("cookie")
<< QByteArray("cookie") << false;
}
void MailboxTest::clientCanConnectToErlang()
{
QFETCH(QByteArray, erlangNodeName);
QFETCH(QByteArray, cnodeNodeName);
QFETCH(QByteArray, cnodeConnectTo);
QFETCH(QByteArray, erlangCookie);
QFETCH(QByteArray, cnodeCookie);
ErlangShell erl(erlangNodeName, erlangCookie);
Mailbox::Client *node = new Mailbox::Client();
QTEST(node->connect(cnodeNodeName, cnodeConnectTo, cnodeCookie), "expected");
delete(node);
}
void MailboxTest::canSendMessageToErlang_data()
{
// QTest::addColumn<QVariant>("value");
// QTest::newRow("int") << QVariant(1);
// Mailbox::ErlAtom atom("testatom");
// QTest::newRow("atom") << QVariant::fromValue(atom);
QTest::addColumn<QVariant>("value");
QVariantMap::const_iterator i = simpleValues.constBegin();
while (i != simpleValues.constEnd()) {
QTest::newRow(i.key().toLocal8Bit().data()) << i.value();
i++;
}
}
QString erl_output(QVariant value)
{
QString raw = Mailbox::formatErlangTerm(value);
QRegularExpression re;
re.setPattern("(\\d+\\.\\d*?[1-9])0+");
QRegularExpressionMatch match = re.match(raw);
if (match.hasMatch()) {
QString result = match.captured(1);
return result;
}
re.setPattern("(\\d+\\.0)0+");
match = re.match(raw);
if (match.hasMatch()) {
QString result = match.captured(1);
return result;
}
return raw;
}
void MailboxTest::canSendMessageToErlang()
{
QFETCH(QVariant, value);
ErlangShell erl("sendmessage", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("sendmessagelib", "sendmessage", "cookie"));
erl.execStatement("register(shell, self()).");
QCOMPARE(erl.execStatement("flush()."), QByteArray("ok\n"));
node->sendMessage("shell", value);
QByteArray full_result = QByteArray("Shell got ") + erl_output(value).toLatin1() + QByteArray("\n");
QCOMPARE(erl.execStatement("flush()."), full_result);
delete(node);
}
void MailboxTest::canRecieveMessagesFromErlang_data()
{
QTest::addColumn<QVariant>("value");
QVariantMap::const_iterator i = simpleValues.constBegin();
while (i != simpleValues.constEnd()) {
QTest::newRow(i.key().toLocal8Bit().data()) << i.value();
i++;
}
}
void MailboxTest::canRecieveMessagesFromErlang()
{
ErlangShell erl("recvmessage", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("recvmessagelib", "recvmessage", "cookie"));
QSignalSpy recvSpy(node, &Mailbox::Client::messageRecieved);
erl.execStatement("register(shell, self()).");
node->sendPid("shell");
QCOMPARE(recvSpy.count(), 0);
QFETCH(QVariant, value);
QByteArray val_str = Mailbox::formatErlangTerm(value).toUtf8();
QString stmt = "receive\n Pid -> Pid ! " + val_str + "\n end.";
erl.execStatement(stmt.toUtf8());
QVERIFY(recvSpy.count() == 1 || recvSpy.wait(1000));
QCOMPARE(recvSpy.takeFirst()[0], value);
delete(node);
}
void MailboxTest::canSendMultipleMessagesToErlang()
{
ErlangShell erl("sendmultimessage", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("sendmultimessagelib", "sendmultimessage", "cookie"));
erl.execStatement("register(shell, self()).");
QCOMPARE(erl.execStatement("flush()."), QByteArray("ok\n"));
node->sendAtom("shell", "test1");
QThread::sleep(1);
QCOMPARE(erl.execStatement("flush()."), QByteArray("Shell got test1\n"));
node->sendAtom("shell", "test2");
QThread::sleep(1);
QCOMPARE(erl.execStatement("flush()."), QByteArray("Shell got test2\n"));
node->sendAtom("shell", "test3");
QThread::sleep(1);
QCOMPARE(erl.execStatement("flush()."), QByteArray("Shell got test3\n"));
delete(node);
}
void MailboxTest::canRecieveMultipleMessagesFromErlang()
{
ErlangShell erl("rmm", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("rmml", "rmm", "cookie"));
QSignalSpy recvSpy(node, &Mailbox::Client::messageRecieved);
erl.execStatement("register(shell, self()).");
node->sendPid("shell");
QCOMPARE(recvSpy.count(), 0);
erl.execStatement("Pid = receive\n Pid -> Pid\n end.");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 1 || recvSpy.wait(1000));
node->sendPid("shell");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 2 || recvSpy.wait(1000));
node->sendPid("shell");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 3 || recvSpy.wait(1000));
node->sendPid("shell");
erl.execStatement("Pid ! hello.");
QVERIFY(recvSpy.count() == 4 || recvSpy.wait(1000));
delete(node);
}
void MailboxTest::canRoundTripFromCNode_data()
{
QTest::addColumn<QVariant>("value");
QVariantMap::const_iterator i = simpleValues.constBegin();
while (i != simpleValues.constEnd()) {
QTest::newRow(i.key().toLocal8Bit().data()) << i.value();
i++;
}
}
void MailboxTest::canRoundTripFromCNode()
{
QFETCH(QVariant, value);
ErlangShell erl("roundtrip", "cookie");
Mailbox::Client *node = new Mailbox::Client();
QVERIFY(node->connect("roundtriplib", "roundtrip", "cookie"));
QSignalSpy recvSpy(node, &Mailbox::Client::messageRecieved);
erl.execStatement("register(shell, self()).");
node->sendPid("shell");
QCOMPARE(recvSpy.count(), 0);
erl.execStatement("Pid = receive\n Pid -> Pid\n end.");
node->sendMessage("shell", value);
erl.execStatement("receive\n Val -> Pid ! Val\n end.");
QVERIFY(recvSpy.count() == 1 || recvSpy.wait(1000));
QCOMPARE(recvSpy.takeFirst()[0], value);
}
void MailboxTest::unusedNodeDoesNotCrash()
{
Mailbox::Client *node = new Mailbox::Client();
delete(node);
}
QTEST_GUILESS_MAIN(MailboxTest)
#include "tst_mailboxtest.moc"
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/tables.h>
#include <osquery/sql.h>
extern "C" {
#include <libcryptsetup.h>
}
namespace osquery {
namespace tables {
void genFDEStatusForBlockDevice(const std::string &name,
const std::string &uuid,
QueryData &results) {
Row r;
r["name"] = name;
r["uuid"] = uuid;
struct crypt_device *cd = nullptr;
const char *opt_header_device = nullptr;
struct crypt_active_device cad;
crypt_status_info ci;
std::string type;
std::string cipher;
std::string cipher_mode;
ci = crypt_status(cd, name.c_str());
switch (ci) {
case CRYPT_ACTIVE:
case CRYPT_BUSY:
r["encrypted"] = "1";
int crypt_init;
#ifdef CENTOS_CENTOS6
crypt_init = crypt_init_by_name(&cd, name.c_str());
#else
crypt_init =
crypt_init_by_name_and_header(&cd, name.c_str(), opt_header_device);
#endif
if (crypt_init < 0) {
VLOG(1) << "Unable to initialize crypt device for " << name;
crypt_free(cd);
break;
}
type = crypt_get_type(cd);
if (crypt_get_active_device(cd, name.c_str(), &cad) < 0) {
VLOG(1) << "Unable to get active device for " << name;
crypt_free(cd);
break;
}
cipher = crypt_get_cipher(cd);
cipher_mode = crypt_get_cipher_mode(cd);
r["type"] = type + "-" + cipher + "-" + cipher_mode;
break;
default:
r["encrypted"] = "0";
}
results.push_back(r);
}
QueryData genFDEStatus(QueryContext &context) {
QueryData results;
if (getuid() || geteuid()) {
VLOG(1) << "Not running as root, disk encryption status not available.";
return results;
}
auto block_devices = SQL::selectAllFrom("block_devices");
for (const auto &row : block_devices) {
const auto name = (row.count("name") > 0) ? row.at("name") : "";
const auto uuid = (row.count("uuid") > 0) ? row.at("uuid") : "";
genFDEStatusForBlockDevice(name, uuid, results);
}
return results;
}
}
}
<commit_msg>Support RHEL6<commit_after>#include <unistd.h>
#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/tables.h>
#include <osquery/sql.h>
extern "C" {
#include <libcryptsetup.h>
}
namespace osquery {
namespace tables {
void genFDEStatusForBlockDevice(const std::string &name,
const std::string &uuid,
QueryData &results) {
Row r;
r["name"] = name;
r["uuid"] = uuid;
struct crypt_device *cd = nullptr;
struct crypt_active_device cad;
crypt_status_info ci;
std::string type;
std::string cipher;
std::string cipher_mode;
ci = crypt_status(cd, name.c_str());
switch (ci) {
case CRYPT_ACTIVE:
case CRYPT_BUSY:
r["encrypted"] = "1";
int crypt_init;
#if defined(CENTOS_CENTOS6) || defined(RHEL_RHEL6)
crypt_init = crypt_init_by_name(&cd, name.c_str());
#else
crypt_init =
crypt_init_by_name_and_header(&cd, name.c_str(), nullptr);
#endif
if (crypt_init < 0) {
VLOG(1) << "Unable to initialize crypt device for " << name;
crypt_free(cd);
break;
}
type = crypt_get_type(cd);
if (crypt_get_active_device(cd, name.c_str(), &cad) < 0) {
VLOG(1) << "Unable to get active device for " << name;
crypt_free(cd);
break;
}
cipher = crypt_get_cipher(cd);
cipher_mode = crypt_get_cipher_mode(cd);
r["type"] = type + "-" + cipher + "-" + cipher_mode;
break;
default:
r["encrypted"] = "0";
}
results.push_back(r);
}
QueryData genFDEStatus(QueryContext &context) {
QueryData results;
if (getuid() || geteuid()) {
VLOG(1) << "Not running as root, disk encryption status not available.";
return results;
}
auto block_devices = SQL::selectAllFrom("block_devices");
for (const auto &row : block_devices) {
const auto name = (row.count("name") > 0) ? row.at("name") : "";
const auto uuid = (row.count("uuid") > 0) ? row.at("uuid") : "";
genFDEStatusForBlockDevice(name, uuid, results);
}
return results;
}
}
}
<|endoftext|> |
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2018 INRIA.
*
* 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 "Lagrangian2d2DR.hpp"
#include "Interaction.hpp"
#include "BlockVector.hpp"
#include <boost/math/quaternion.hpp>
// #define DEBUG_NOCOLOR
// #define DEBUG_STDOUT
// #define DEBUG_MESSAGES
#include "debug.h"
void Lagrangian2d2DR::initialize(Interaction& inter)
{
LagrangianR::initialize(inter);
//proj_with_q _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));
if((inter.getSizeOfDS() !=3) and (inter.getSizeOfDS() !=6))
{
RuntimeException::selfThrow("Lagrangian2d2DR::initialize(Interaction& inter). The size of ds must of size 3");
}
unsigned int qSize = 3 * (inter.getSizeOfDS() / 3);
_jachq.reset(new SimpleMatrix(2, qSize));
}
void Lagrangian2d2DR::computeJachq(SiconosVector& q, SiconosVector& z)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0 \n");
double Nx = _Nc->getValue(0);
double Ny = _Nc->getValue(1);
double Px = _Pc1->getValue(0);
double Py = _Pc1->getValue(1);
double G1x = q.getValue(0);
double G1y = q.getValue(1);
/* construct tangent vector */
double Tx = Ny;
double Ty = - Nx;
double lever_arm_x = G1x-Px ;
double lever_arm_y = G1y-Py ;
DEBUG_PRINTF("lever_arm_x = %4.2e,\t lever_arm_ y = %4.2e\n", lever_arm_x, lever_arm_y);
_jachq->setValue(0,0,Nx);
_jachq->setValue(0,1,Ny);
_jachq->setValue(0,2,lever_arm_y*Nx - lever_arm_x*Ny);
_jachq->setValue(1,0,Tx);
_jachq->setValue(1,1,Ty);
_jachq->setValue(1,2,lever_arm_y*Tx - lever_arm_x*Ty);
if(q.size() ==6)
{
DEBUG_PRINT("take into account second ds\n");
double G2x = q.getValue(3);
double G2y = q.getValue(4);
_jachq->setValue(0,3,-Nx);
_jachq->setValue(0,4,-Ny);
_jachq->setValue(0,5,- ((G2y-Py)*Nx - (G2x-Px)*Ny));
_jachq->setValue(1,3,-Tx);
_jachq->setValue(1,4,-Ty);
_jachq->setValue(1,5,-(G1y-Py)*Tx + (G1x-Px)*Ty);
}
DEBUG_EXPR(_jachq->display(););
DEBUG_END("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0) \n");
}
double Lagrangian2d2DR::distance() const
{
DEBUG_BEGIN("Lagrangian2d2DR::distance(...)\n")
SiconosVector dpc(*_Pc2 - *_Pc1);
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(dpc.display(););
DEBUG_END("Lagrangian2d2DR::distance(...)\n")
return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);
}
void Lagrangian2d2DR::computeh(SiconosVector& q, SiconosVector& z, SiconosVector& y)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeh(...)\n");
DEBUG_EXPR(q.display());
// Contact points and normal are stored as relative to q1 and q2, if
// no q2 then pc2 and normal are absolute.
// Update pc1 based on q and relPc1
double angle= q(2);
DEBUG_PRINTF("angle (ds1)= %e\n", angle);
(*_Pc1)(0) = q(0) + cos(angle) * (*_relPc1)(0)- sin(angle) * (*_relPc1)(1);
(*_Pc1)(1) = q(1) + sin(angle) * (*_relPc1)(0)+ cos(angle) * (*_relPc1)(1);
if(q.size() == 6)
{
// To be checked
DEBUG_PRINT("take into account second ds\n");
angle = q(5);
DEBUG_PRINTF("angle (ds2) = %e\n", angle);
(*_Pc2)(0) = q(3) + cos(angle) * (*_relPc2)(0)- sin(angle) * (*_relPc2)(1);
(*_Pc2)(1) = q(4) + sin(angle) * (*_relPc2)(0)+ cos(angle) * (*_relPc2)(1);
(*_Nc)(0) = cos(angle) * (*_relNc)(0)- sin(angle) * (*_relNc)(1);
(*_Nc)(1) = sin(angle) * (*_relNc)(0)+ cos(angle) * (*_relNc)(1);
}
else
{
*_Pc2 = *_relPc2;
*_Nc = *_relNc;
}
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(_Nc->display(););
// SP::SiconosVector q1 = (q0.getAllVect())[0];
// ::boost::math::quaternion<double> qq1((*q1)(3), (*q1)(4), (*q1)(5), (*q1)(6));
// ::boost::math::quaternion<double> qpc1(0,(*_relPc1)(0),(*_relPc1)(1),(*_relPc1)(2));
// // apply q1 rotation and add
// qpc1 = qq1 * qpc1 / qq1;
// (*_Pc1)(0) = qpc1.R_component_2() + (*q1)(0);
// (*_Pc1)(1) = qpc1.R_component_3() + (*q1)(1);
// (*_Pc1)(2) = qpc1.R_component_4() + (*q1)(2);
// if (q0.numberOfBlocks() > 1)
// {
// // Update pc2 based on q0 and relPc2
// SP::SiconosVector q2 = (q0.getAllVect())[1];
// ::boost::math::quaternion<double> qq2((*q2)(3), (*q2)(4), (*q2)(5), (*q2)(6));
// ::boost::math::quaternion<double> qpc2(0,(*_relPc2)(0),(*_relPc2)(1),(*_relPc2)(2));
// // apply q2 rotation and add
// qpc2 = qq2 * qpc2 / qq2;
// (*_Pc2)(0) = qpc2.R_component_2() + (*q2)(0);
// (*_Pc2)(1) = qpc2.R_component_3() + (*q2)(1);
// (*_Pc2)(2) = qpc2.R_component_4() + (*q2)(2);
// // same for normal
// ::boost::math::quaternion<double> qnc(0, (*_relNc)(0), (*_relNc)(1), (*_relNc)(2));
// qnc = qq2 * qnc / qq2;
// (*_Nc)(0) = qnc.R_component_2();
// (*_Nc)(1) = qnc.R_component_3();
// (*_Nc)(2) = qnc.R_component_4();
// }
// else
// {
// *_Pc2 = *_relPc2;
// *_Nc = *_relNc;
// }
LagrangianScleronomousR::computeh(q, z, y);
y.setValue(0, distance());
DEBUG_EXPR(y.display(););
DEBUG_EXPR(display(););
DEBUG_END("Lagrangian2d2DR::computeh(...)\n")
}
void Lagrangian2d2DR::display() const
{
LagrangianR::display();
std::cout << " _Pc1 :" << std::endl;
if(_Pc1)
_Pc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Pc2 :" << std::endl;
if(_Pc2)
_Pc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc1 :" << std::endl;
if(_relPc1)
_relPc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc2 :" << std::endl;
if(_relPc2)
_relPc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Nc :" << std::endl;
if(_Nc)
_Nc->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relNc :" << std::endl;
if(_relNc)
_relNc->display();
else
std::cout << " NULL :" << std::endl;
}
<commit_msg>[kernel] correct bug in the 2D computation of the relative velocity<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2018 INRIA.
*
* 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 "Lagrangian2d2DR.hpp"
#include "Interaction.hpp"
#include "BlockVector.hpp"
#include <boost/math/quaternion.hpp>
// #define DEBUG_NOCOLOR
// #define DEBUG_STDOUT
// #define DEBUG_MESSAGES
#include "debug.h"
void Lagrangian2d2DR::initialize(Interaction& inter)
{
LagrangianR::initialize(inter);
//proj_with_q _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));
if((inter.getSizeOfDS() !=3) and (inter.getSizeOfDS() !=6))
{
RuntimeException::selfThrow("Lagrangian2d2DR::initialize(Interaction& inter). The size of ds must of size 3");
}
unsigned int qSize = 3 * (inter.getSizeOfDS() / 3);
_jachq.reset(new SimpleMatrix(2, qSize));
}
void Lagrangian2d2DR::computeJachq(SiconosVector& q, SiconosVector& z)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0 \n");
double Nx = _Nc->getValue(0);
double Ny = _Nc->getValue(1);
double Px = _Pc1->getValue(0);
double Py = _Pc1->getValue(1);
double G1x = q.getValue(0);
double G1y = q.getValue(1);
/* construct tangent vector */
double Tx = Ny;
double Ty = - Nx;
double lever_arm_x = G1x-Px ;
double lever_arm_y = G1y-Py ;
DEBUG_PRINTF("lever_arm_x = %4.2e,\t lever_arm_ y = %4.2e\n", lever_arm_x, lever_arm_y);
_jachq->setValue(0,0,Nx);
_jachq->setValue(0,1,Ny);
_jachq->setValue(0,2,lever_arm_y*Nx - lever_arm_x*Ny);
_jachq->setValue(1,0,Tx);
_jachq->setValue(1,1,Ty);
_jachq->setValue(1,2,lever_arm_y*Tx - lever_arm_x*Ty);
if(q.size() ==6)
{
DEBUG_PRINT("take into account second ds\n");
double G2x = q.getValue(3);
double G2y = q.getValue(4);
_jachq->setValue(0,3,-Nx);
_jachq->setValue(0,4,-Ny);
_jachq->setValue(0,5,- ((G2y-Py)*Nx - (G2x-Px)*Ny));
_jachq->setValue(1,3,-Tx);
_jachq->setValue(1,4,-Ty);
_jachq->setValue(1,5,-((G2y-Py)*Tx - (G2x-Px)*Ty));
}
DEBUG_EXPR(_jachq->display(););
DEBUG_END("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0) \n");
}
double Lagrangian2d2DR::distance() const
{
DEBUG_BEGIN("Lagrangian2d2DR::distance(...)\n")
SiconosVector dpc(*_Pc2 - *_Pc1);
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(dpc.display(););
DEBUG_END("Lagrangian2d2DR::distance(...)\n")
return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);
}
void Lagrangian2d2DR::computeh(SiconosVector& q, SiconosVector& z, SiconosVector& y)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeh(...)\n");
DEBUG_EXPR(q.display());
// Contact points and normal are stored as relative to q1 and q2, if
// no q2 then pc2 and normal are absolute.
// Update pc1 based on q and relPc1
double angle= q(2);
DEBUG_PRINTF("angle (ds1)= %e\n", angle);
(*_Pc1)(0) = q(0) + cos(angle) * (*_relPc1)(0)- sin(angle) * (*_relPc1)(1);
(*_Pc1)(1) = q(1) + sin(angle) * (*_relPc1)(0)+ cos(angle) * (*_relPc1)(1);
if(q.size() == 6)
{
// To be checked
DEBUG_PRINT("take into account second ds\n");
angle = q(5);
DEBUG_PRINTF("angle (ds2) = %e\n", angle);
(*_Pc2)(0) = q(3) + cos(angle) * (*_relPc2)(0)- sin(angle) * (*_relPc2)(1);
(*_Pc2)(1) = q(4) + sin(angle) * (*_relPc2)(0)+ cos(angle) * (*_relPc2)(1);
(*_Nc)(0) = cos(angle) * (*_relNc)(0)- sin(angle) * (*_relNc)(1);
(*_Nc)(1) = sin(angle) * (*_relNc)(0)+ cos(angle) * (*_relNc)(1);
}
else
{
*_Pc2 = *_relPc2;
*_Nc = *_relNc;
}
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(_Nc->display(););
LagrangianScleronomousR::computeh(q, z, y);
y.setValue(0, distance());
DEBUG_EXPR(y.display(););
DEBUG_EXPR(display(););
DEBUG_END("Lagrangian2d2DR::computeh(...)\n")
}
void Lagrangian2d2DR::display() const
{
LagrangianR::display();
std::cout << " _Pc1 :" << std::endl;
if(_Pc1)
_Pc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Pc2 :" << std::endl;
if(_Pc2)
_Pc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc1 :" << std::endl;
if(_relPc1)
_relPc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc2 :" << std::endl;
if(_relPc2)
_relPc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Nc :" << std::endl;
if(_Nc)
_Nc->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relNc :" << std::endl;
if(_relNc)
_relNc->display();
else
std::cout << " NULL :" << std::endl;
}
<|endoftext|> |
<commit_before>/*------------ant.cpp---------------------------------------------------------//
*
* ants -- We have them
*
* Purpose: Figure out ant pathing to food. I want food.
*
*-----------------------------------------------------------------------------*/
#include <array>
#include <iostream>
#include <vector>
#include <random>
#include <fstream>
/*----------------------------------------------------------------------------//
* STRUCTS
*-----------------------------------------------------------------------------*/
// grid size
const int n = 5;
// structs for ant movement
struct coord{
int x, y;
};
// Template for 2d boolean arrays
template <typename T, size_t rows, size_t cols>
using array2d = std::array<std::array<T, cols>, rows>;
// defines operators for definitions above
inline bool operator==(const coord& lhs, const coord& rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const coord& lhs, const coord& rhs) {
return !(lhs == rhs);
}
struct ant{
array2d<bool, n, n> phetus;
coord pos;
std::vector<coord> phepath, antpath;
int stepnum, phenum, pernum;
};
struct grid{
array2d<bool, n, n> wall;
coord prize;
};
// Functions for ant movement
// Chooses step
ant step(ant curr, grid landscape, int gen_flag);
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate);
// Changes template ant
ant plate_toss(ant winner);
// Moves simulation every timestep
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output);
/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/
int main(){
// defining output file
std::ofstream output("out.dat", std::ofstream::out);
// defining initial ant vector and grid
std::vector<ant> ants;
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
// defining spawn point
coord spawn;
spawn.x = n - 1;
spawn.y = 0;
// defining misc characters
int final_time = 100;
int pernum = 10;
move(ants, landscape, spawn, pernum, final_time, output);
//output.close();
}
/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/
// Chooses step
ant step(ant curr, grid landscape, int gen_flag){
coord next_step[4];
coord up, down, left, right, next;
int pcount = 0;
std::cout << curr.pos.x << '\t' << curr.pos.y << '\n' << '\n';
up.x = curr.pos.x; up.y = curr.pos.y + 1;
down.x = curr.pos.x; down.y = curr.pos.y - 1;
left.x = curr.pos.x - 1; left.y = curr.pos.y;
right.x = curr.pos.x + 1; right.y = curr.pos.y;
//std::cout << up.x << '\t' << up.y << '\n';
coord last;
if (curr.stepnum == 0){
last.x = -1;
last.y = -1;
}
else{
last = curr.antpath.back();
}
// determine possible movement
// up case
if (last != up) {
if (up.y < n && landscape.wall[up.x][up.y] == 0){
next_step[pcount] = up;
pcount++;
}
}
// down case
if (last != down) {
if (down.y > 0 && landscape.wall[down.x][down.y] == 0){
next_step[pcount] = down;
pcount++;
}
}
if (last != left) {
if (left.x > 0 && landscape.wall[left.x][left.y] == 0){
next_step[pcount] = left;
pcount++;
}
}
// right case
if (last != right) {
if (right.x < n && landscape.wall[right.x][right.y] == 0){
next_step[pcount] = right;
pcount++;
}
}
static std::random_device rd;
auto seed = rd();
static std::mt19937 gen(seed);
if (gen_flag == 0 && curr.phetus[curr.pos.x][curr.pos.y] == 0){
std::uniform_int_distribution<int> ant_distribution(0,pcount - 1);
next = next_step[ant_distribution(gen)];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
else{
double prob = curr.pernum / curr.phenum, aprob[4], rn, psum = 0;
int choice = -1, cthulu;
std::uniform_real_distribution<double> ant_distribution(0,1);
// search through phepath to find ant's curr location
for (size_t q = 0; q < curr.phepath.size(); q++){
if (curr.pos.x == curr.phepath[q].x &&
curr.pos.y == curr.phepath[q].y){
cthulu = q;
}
}
std::uniform_real_distribution<double> ant_ddist(0,1);
rn = ant_ddist(gen);
for (size_t q = 0; q < pcount; q++){
if (next_step[q].x == curr.phepath[cthulu +1].x &&
next_step[q].y == curr.phepath[cthulu +1].y){
aprob[q] = prob;
}
else{
aprob[q] = (1 - prob) / (pcount - 1);
}
psum += aprob[q];
if (rn < psum && choice < 0){
choice = q;
}
}
next = next_step[choice];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
curr.stepnum++;
return curr;
}
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate){
ant curr;
curr = plate;
ants.push_back(curr);
return ants;
}
// Changes template ant
ant plate_toss(ant winner){
ant plate = winner;
plate.phenum = winner.stepnum;
plate.stepnum = 0;
// generate a new phetus
plate.phetus = {};
for (size_t i = 0; i < winner.antpath.size(); i++){
plate.phetus[winner.antpath[i].x][winner.antpath[i].y] = 1;
}
plate.antpath = {};
return plate;
}
// Moves simulation every timestep
// step 1: create ants
// step 2: move ants
// step 3: profit?
// redefine all paths = to shortest path
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output){
std::vector<int> killlist;
// setting template for first generate
ant plate;
plate.pos.x = spawn.x;
plate.pos.y = spawn.y;
plate.stepnum = 0;
plate.phenum = n*n;
plate.phetus = {};
// to be defined later
plate.pernum = pernum;
/*
// define walls and prize at random spot
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
*/
for (size_t i = 0; i < final_time; i++){
std::cout << i << '\n';
int flag = 0;
// step 1: generate ant
ants = gen_ants(ants, plate);
// step 2: Move ants
for (size_t j = 0; j < ants.size(); j++){
ants[j] = step(ants[j], landscape, flag);
if (ants[j].stepnum > ants[j].phenum){
killlist.push_back(j);
}
if (ants[j].pos.x == landscape.prize.x &&
ants[j].pos.y == landscape.prize.y){
plate = plate_toss(ants[j]);
}
}
for (size_t k = 0; k < killlist.size(); k++){
ants.erase(ants.begin() + killlist[k]);
}
for (size_t l = 0; l < ants[0].phepath.size(); l++){
output << ants[0].phepath[l].x << '\t'
<< ants[0].phepath[l].y << '\n';
}
output << '\n' << '\n';
}
return ants;
}
<commit_msg>need to sort out the killlist.<commit_after>/*------------ant.cpp---------------------------------------------------------//
*
* ants -- We have them
*
* Purpose: Figure out ant pathing to food. I want food.
*
*-----------------------------------------------------------------------------*/
#include <array>
#include <iostream>
#include <vector>
#include <random>
#include <fstream>
#include <algorithm>
/*----------------------------------------------------------------------------//
* STRUCTS
*-----------------------------------------------------------------------------*/
// grid size
const int n = 5;
// structs for ant movement
struct coord{
int x, y;
};
// Template for 2d boolean arrays
template <typename T, size_t rows, size_t cols>
using array2d = std::array<std::array<T, cols>, rows>;
// defines operators for definitions above
inline bool operator==(const coord& lhs, const coord& rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const coord& lhs, const coord& rhs) {
return !(lhs == rhs);
}
struct ant{
array2d<bool, n, n> phetus;
coord pos;
std::vector<coord> phepath, antpath;
int stepnum, phenum, pernum;
};
struct grid{
array2d<bool, n, n> wall;
coord prize;
};
// Functions for ant movement
// Chooses step
ant step(ant curr, grid landscape, int gen_flag);
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate);
// Changes template ant
ant plate_toss(ant winner);
// Moves simulation every timestep
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output);
/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/
int main(){
// defining output file
std::ofstream output("out.dat", std::ofstream::out);
// defining initial ant vector and grid
std::vector<ant> ants;
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
// defining spawn point
coord spawn;
spawn.x = n - 1;
spawn.y = 0;
// defining misc characters
int final_time = 100;
int pernum = 10;
move(ants, landscape, spawn, pernum, final_time, output);
//output.close();
}
/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/
// Chooses step
ant step(ant curr, grid landscape, int gen_flag){
coord next_step[4];
coord up, down, left, right, next;
int pcount = 0;
std::cout << curr.pos.x << '\t' << curr.pos.y << '\n' << '\n';
up.x = curr.pos.x; up.y = curr.pos.y + 1;
down.x = curr.pos.x; down.y = curr.pos.y - 1;
left.x = curr.pos.x - 1; left.y = curr.pos.y;
right.x = curr.pos.x + 1; right.y = curr.pos.y;
//std::cout << up.x << '\t' << up.y << '\n';
coord last;
if (curr.stepnum == 0){
last.x = -1;
last.y = -1;
}
else{
last = curr.antpath.back();
}
// determine possible movement
// up case
if (last != up) {
if (up.y < n && landscape.wall[up.x][up.y] == 0){
next_step[pcount] = up;
pcount++;
}
}
// down case
if (last != down) {
if (down.y > 0 && landscape.wall[down.x][down.y] == 0){
next_step[pcount] = down;
pcount++;
}
}
if (last != left) {
if (left.x > 0 && landscape.wall[left.x][left.y] == 0){
next_step[pcount] = left;
pcount++;
}
}
// right case
if (last != right) {
if (right.x < n && landscape.wall[right.x][right.y] == 0){
next_step[pcount] = right;
pcount++;
}
}
static std::random_device rd;
auto seed = rd();
static std::mt19937 gen(seed);
if (gen_flag == 0 && curr.phetus[curr.pos.x][curr.pos.y] == 0){
std::uniform_int_distribution<int> ant_distribution(0,pcount - 1);
next = next_step[ant_distribution(gen)];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
else{
double prob = curr.pernum / curr.phenum, aprob[4], rn, psum = 0;
int choice = -1, cthulu;
std::uniform_real_distribution<double> ant_distribution(0,1);
// search through phepath to find ant's curr location
for (size_t q = 0; q < curr.phepath.size(); q++){
if (curr.pos.x == curr.phepath[q].x &&
curr.pos.y == curr.phepath[q].y){
cthulu = q;
}
}
std::uniform_real_distribution<double> ant_ddist(0,1);
rn = ant_ddist(gen);
for (size_t q = 0; q < pcount; q++){
if (next_step[q].x == curr.phepath[cthulu +1].x &&
next_step[q].y == curr.phepath[cthulu +1].y){
aprob[q] = prob;
}
else{
aprob[q] = (1 - prob) / (pcount - 1);
}
psum += aprob[q];
if (rn < psum && choice < 0){
choice = q;
}
}
next = next_step[choice];
curr.antpath.push_back(curr.pos);
curr.pos = next;
}
curr.stepnum++;
return curr;
}
// Generates ants
std::vector<ant> gen_ants(std::vector<ant> ants, ant plate){
ant curr;
curr = plate;
ants.push_back(curr);
return ants;
}
// Changes template ant
ant plate_toss(ant winner){
ant plate = winner;
plate.phenum = winner.stepnum;
plate.stepnum = 0;
// generate a new phetus
plate.phetus = {};
for (size_t i = 0; i < winner.antpath.size(); i++){
plate.phetus[winner.antpath[i].x][winner.antpath[i].y] = 1;
}
plate.antpath = {};
return plate;
}
// Moves simulation every timestep
// step 1: create ants
// step 2: move ants
// step 3: profit?
// redefine all paths = to shortest path
std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn,
int pernum, int final_time, std::ofstream &output){
std::vector<int> killlist;
// setting template for first generate
ant plate;
plate.pos.x = spawn.x;
plate.pos.y = spawn.y;
plate.stepnum = 0;
plate.phenum = n*n;
plate.phetus = {};
// to be defined later
plate.pernum = pernum;
/*
// define walls and prize at random spot
grid landscape;
landscape.wall = {};
landscape.prize.x = n; landscape.prize.y = n;
*/
for (size_t i = 0; i < final_time; i++){
std::cout << i << '\n';
int flag = 0;
// step 1: generate ant
ants = gen_ants(ants, plate);
// step 2: Move ants
for (size_t j = 0; j < ants.size(); j++){
ants[j] = step(ants[j], landscape, flag);
if (ants[j].stepnum > ants[j].phenum){
killlist.push_back(j);
}
if (ants[j].pos.x == landscape.prize.x &&
ants[j].pos.y == landscape.prize.y){
plate = plate_toss(ants[j]);
flag = 1;
}
}
std::sort(std::begin(killlist), std::end(killlist),
[](int &dum1, int &dum2)
{return dum1 > dum2;});
/*
std::cout << "size: " << killlist.size() << '\n';
for (size_t k = 0; k < killlist.size(); k++){
ants.erase(ants.begin() + killlist[k]);
}
*/
if (flag == 1){
for (size_t l = 0; l < ants[0].phepath.size(); l++){
output << ants[0].phepath[l].x << '\t'
<< ants[0].phepath[l].y << '\n';
}
}
output << '\n' << '\n';
}
return ants;
}
<|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/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLException.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local, static data
// ---------------------------------------------------------------------------
static XMLMsgLoader* sMsgLoader = 0;
static XMLRegisterCleanup msgLoaderCleanup;
static bool sScannerMutexRegistered = false;
static XMLMutex* sMsgMutex = 0;
static XMLRegisterCleanup msgMutexCleanup;
// ---------------------------------------------------------------------------
// Local, static functions
// ---------------------------------------------------------------------------
//
// We need to fault in this mutex. But, since its used for synchronization
// itself, we have to do this the low level way using a compare and swap.
//
static XMLMutex& gMsgMutex()
{
if (!sScannerMutexRegistered)
{
XMLMutexLock lockInit(XMLPlatformUtils::fgAtomicMutex);
if (!sScannerMutexRegistered)
{
sMsgMutex = new XMLMutex;
msgMutexCleanup.registerCleanup(XMLException::reinitMsgMutex);
sScannerMutexRegistered = true;
}
}
return *sMsgMutex;
}
//
// This method is a lazy evaluator for the message loader for exception
// messages.
//
static XMLMsgLoader& gGetMsgLoader()
{
if (!sMsgLoader)
{
// Lock the message loader mutex and load the text
XMLMutexLock lockInit(&gMsgMutex());
// Fault it in on first request
if (!sMsgLoader)
{
sMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgExceptDomain);
if (!sMsgLoader)
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
//
// Register this XMLMsgLoader for cleanup at Termination.
//
msgLoaderCleanup.registerCleanup(XMLException::reinitMsgLoader);
}
}
// We got it, so return it
return *sMsgLoader;
}
// ---------------------------------------------------------------------------
// XMLException: Virtual destructor
// ---------------------------------------------------------------------------
XMLException::~XMLException()
{
fMemoryManager->deallocate(fMsg);
fMemoryManager->deallocate(fSrcFile);
}
// ---------------------------------------------------------------------------
// XMLException: Setter methods
// ---------------------------------------------------------------------------
void XMLException::setPosition(const char* const file, const unsigned int line)
{
fSrcLine = line;
fMemoryManager->deallocate(fSrcFile);
fSrcFile = XMLString::replicate(file, fMemoryManager);
}
// ---------------------------------------------------------------------------
// XMLException: Hidden constructors and operators
// ---------------------------------------------------------------------------
XMLException::XMLException() :
fCode(XMLExcepts::NoError)
, fSrcFile(0)
, fSrcLine(0)
, fMsg(0)
, fMemoryManager(0)
{
}
XMLException::XMLException( const char* const srcFile
, const unsigned int srcLine
, MemoryManager* const memoryManager) :
fCode(XMLExcepts::NoError)
, fSrcFile(0)
, fSrcLine(srcLine)
, fMsg(0)
, fMemoryManager(memoryManager)
{
if (!memoryManager)
fMemoryManager = XMLPlatformUtils::fgMemoryManager;
fSrcFile = XMLString::replicate(srcFile, fMemoryManager);
}
XMLException::XMLException(const XMLException& toCopy) :
fCode(toCopy.fCode)
, fSrcFile(0)
, fSrcLine(toCopy.fSrcLine)
, fMsg(XMLString::replicate(toCopy.fMsg, toCopy.fMemoryManager))
, fMemoryManager(toCopy.fMemoryManager)
{
if (toCopy.fSrcFile) {
fSrcFile = XMLString::replicate
(
toCopy.fSrcFile
, fMemoryManager
);
}
}
XMLException& XMLException::operator=(const XMLException& toAssign)
{
if (this != &toAssign)
{
//use the original memory manager to deallocate
fMemoryManager->deallocate(fSrcFile);
fSrcFile = 0;
fMemoryManager->deallocate(fMsg);
fMsg = 0;
fMemoryManager = toAssign.fMemoryManager;
fSrcLine = toAssign.fSrcLine;
fCode = toAssign.fCode;
if (toAssign.fMsg) {
fMsg = XMLString::replicate
(
toAssign.fMsg
, fMemoryManager
);
}
if (toAssign.fSrcFile) {
fSrcFile = XMLString::replicate
(
toAssign.fSrcFile
, fMemoryManager
);
}
}
return *this;
}
// ---------------------------------------------------------------------------
// XMLException: Protected methods
// ---------------------------------------------------------------------------
void XMLException::loadExceptText(const XMLExcepts::Codes toLoad)
{
// Store the error code
fCode = toLoad;
// Load up the text into a local buffer
const unsigned int msgSize = 2047;
XMLCh errText[msgSize + 1];
// load the text
if (!gGetMsgLoader().loadMsg(toLoad, errText, msgSize))
{
fMsg = XMLString::replicate
(
XMLUni::fgDefErrMsg
, fMemoryManager
);
return;
}
// We got the text so replicate it into the message member
fMsg = XMLString::replicate(errText, fMemoryManager);
}
void
XMLException::loadExceptText(const XMLExcepts::Codes toLoad
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Store the error code
fCode = toLoad;
// Load up the text into a local buffer
const unsigned int msgSize = 4095;
XMLCh errText[msgSize + 1];
// load the text
if (!gGetMsgLoader().loadMsg(toLoad, errText, msgSize, text1, text2, text3, text4, fMemoryManager))
{
fMsg = XMLString::replicate
(
XMLUni::fgDefErrMsg
, fMemoryManager
);
return;
}
// We got the text so replicate it into the message member
fMsg = XMLString::replicate(errText, fMemoryManager);
}
void
XMLException::loadExceptText(const XMLExcepts::Codes toLoad
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Store the error code
fCode = toLoad;
// Load up the text into a local buffer
const unsigned int msgSize = 4095;
XMLCh errText[msgSize + 1];
// load the text
if (!gGetMsgLoader().loadMsg(toLoad, errText, msgSize, text1, text2, text3, text4, fMemoryManager))
{
fMsg = XMLString::replicate
(
XMLUni::fgDefErrMsg
, fMemoryManager
);
return;
}
// We got the text so replicate it into the message member
fMsg = XMLString::replicate(errText, fMemoryManager);
}
// -----------------------------------------------------------------------
// Reinitialise the message mutex
// -----------------------------------------------------------------------
void XMLException::reinitMsgMutex()
{
delete sMsgMutex;
sMsgMutex = 0;
sScannerMutexRegistered = false;
}
// -----------------------------------------------------------------------
// Reinitialise the message loader
// -----------------------------------------------------------------------
void XMLException::reinitMsgLoader()
{
delete sMsgLoader;
sMsgLoader = 0;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Initialize memory manager to default.<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/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLException.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local, static data
// ---------------------------------------------------------------------------
static XMLMsgLoader* sMsgLoader = 0;
static XMLRegisterCleanup msgLoaderCleanup;
static bool sScannerMutexRegistered = false;
static XMLMutex* sMsgMutex = 0;
static XMLRegisterCleanup msgMutexCleanup;
// ---------------------------------------------------------------------------
// Local, static functions
// ---------------------------------------------------------------------------
//
// We need to fault in this mutex. But, since its used for synchronization
// itself, we have to do this the low level way using a compare and swap.
//
static XMLMutex& gMsgMutex()
{
if (!sScannerMutexRegistered)
{
XMLMutexLock lockInit(XMLPlatformUtils::fgAtomicMutex);
if (!sScannerMutexRegistered)
{
sMsgMutex = new XMLMutex;
msgMutexCleanup.registerCleanup(XMLException::reinitMsgMutex);
sScannerMutexRegistered = true;
}
}
return *sMsgMutex;
}
//
// This method is a lazy evaluator for the message loader for exception
// messages.
//
static XMLMsgLoader& gGetMsgLoader()
{
if (!sMsgLoader)
{
// Lock the message loader mutex and load the text
XMLMutexLock lockInit(&gMsgMutex());
// Fault it in on first request
if (!sMsgLoader)
{
sMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgExceptDomain);
if (!sMsgLoader)
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
//
// Register this XMLMsgLoader for cleanup at Termination.
//
msgLoaderCleanup.registerCleanup(XMLException::reinitMsgLoader);
}
}
// We got it, so return it
return *sMsgLoader;
}
// ---------------------------------------------------------------------------
// XMLException: Virtual destructor
// ---------------------------------------------------------------------------
XMLException::~XMLException()
{
fMemoryManager->deallocate(fMsg);
fMemoryManager->deallocate(fSrcFile);
}
// ---------------------------------------------------------------------------
// XMLException: Setter methods
// ---------------------------------------------------------------------------
void XMLException::setPosition(const char* const file, const unsigned int line)
{
fSrcLine = line;
fMemoryManager->deallocate(fSrcFile);
fSrcFile = XMLString::replicate(file, fMemoryManager);
}
// ---------------------------------------------------------------------------
// XMLException: Hidden constructors and operators
// ---------------------------------------------------------------------------
XMLException::XMLException() :
fCode(XMLExcepts::NoError)
, fSrcFile(0)
, fSrcLine(0)
, fMsg(0)
, fMemoryManager(XMLPlatformUtils::fgMemoryManager)
{
}
XMLException::XMLException( const char* const srcFile
, const unsigned int srcLine
, MemoryManager* const memoryManager) :
fCode(XMLExcepts::NoError)
, fSrcFile(0)
, fSrcLine(srcLine)
, fMsg(0)
, fMemoryManager(memoryManager)
{
if (!memoryManager)
fMemoryManager = XMLPlatformUtils::fgMemoryManager;
fSrcFile = XMLString::replicate(srcFile, fMemoryManager);
}
XMLException::XMLException(const XMLException& toCopy) :
fCode(toCopy.fCode)
, fSrcFile(0)
, fSrcLine(toCopy.fSrcLine)
, fMsg(XMLString::replicate(toCopy.fMsg, toCopy.fMemoryManager))
, fMemoryManager(toCopy.fMemoryManager)
{
if (toCopy.fSrcFile) {
fSrcFile = XMLString::replicate
(
toCopy.fSrcFile
, fMemoryManager
);
}
}
XMLException& XMLException::operator=(const XMLException& toAssign)
{
if (this != &toAssign)
{
//use the original memory manager to deallocate
fMemoryManager->deallocate(fSrcFile);
fSrcFile = 0;
fMemoryManager->deallocate(fMsg);
fMsg = 0;
fMemoryManager = toAssign.fMemoryManager;
fSrcLine = toAssign.fSrcLine;
fCode = toAssign.fCode;
if (toAssign.fMsg) {
fMsg = XMLString::replicate
(
toAssign.fMsg
, fMemoryManager
);
}
if (toAssign.fSrcFile) {
fSrcFile = XMLString::replicate
(
toAssign.fSrcFile
, fMemoryManager
);
}
}
return *this;
}
// ---------------------------------------------------------------------------
// XMLException: Protected methods
// ---------------------------------------------------------------------------
void XMLException::loadExceptText(const XMLExcepts::Codes toLoad)
{
// Store the error code
fCode = toLoad;
// Load up the text into a local buffer
const unsigned int msgSize = 2047;
XMLCh errText[msgSize + 1];
// load the text
if (!gGetMsgLoader().loadMsg(toLoad, errText, msgSize))
{
fMsg = XMLString::replicate
(
XMLUni::fgDefErrMsg
, fMemoryManager
);
return;
}
// We got the text so replicate it into the message member
fMsg = XMLString::replicate(errText, fMemoryManager);
}
void
XMLException::loadExceptText(const XMLExcepts::Codes toLoad
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4)
{
// Store the error code
fCode = toLoad;
// Load up the text into a local buffer
const unsigned int msgSize = 4095;
XMLCh errText[msgSize + 1];
// load the text
if (!gGetMsgLoader().loadMsg(toLoad, errText, msgSize, text1, text2, text3, text4, fMemoryManager))
{
fMsg = XMLString::replicate
(
XMLUni::fgDefErrMsg
, fMemoryManager
);
return;
}
// We got the text so replicate it into the message member
fMsg = XMLString::replicate(errText, fMemoryManager);
}
void
XMLException::loadExceptText(const XMLExcepts::Codes toLoad
, const char* const text1
, const char* const text2
, const char* const text3
, const char* const text4)
{
// Store the error code
fCode = toLoad;
// Load up the text into a local buffer
const unsigned int msgSize = 4095;
XMLCh errText[msgSize + 1];
// load the text
if (!gGetMsgLoader().loadMsg(toLoad, errText, msgSize, text1, text2, text3, text4, fMemoryManager))
{
fMsg = XMLString::replicate
(
XMLUni::fgDefErrMsg
, fMemoryManager
);
return;
}
// We got the text so replicate it into the message member
fMsg = XMLString::replicate(errText, fMemoryManager);
}
// -----------------------------------------------------------------------
// Reinitialise the message mutex
// -----------------------------------------------------------------------
void XMLException::reinitMsgMutex()
{
delete sMsgMutex;
sMsgMutex = 0;
sScannerMutexRegistered = false;
}
// -----------------------------------------------------------------------
// Reinitialise the message loader
// -----------------------------------------------------------------------
void XMLException::reinitMsgLoader()
{
delete sMsgLoader;
sMsgLoader = 0;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "lupdate.h"
#include <translator.h>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QString>
QT_BEGIN_NAMESPACE
#include "parser/javascriptengine_p.h"
#include "parser/javascriptparser_p.h"
#include "parser/javascriptlexer_p.h"
#include "parser/javascriptnodepool_p.h"
#include "parser/javascriptastvisitor_p.h"
#include "parser/javascriptast_p.h"
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QtDebug>
#include <QStringList>
#include <iostream>
#include <cstdlib>
using namespace JavaScript;
class FindTrCalls: protected AST::Visitor
{
public:
void operator()(Translator *translator, const QString &fileName, AST::Node *node)
{
m_translator = translator;
m_fileName = fileName;
m_component = QFileInfo(fileName).baseName(); //matches qsTr usage in QScriptEngine
accept(node);
}
protected:
using AST::Visitor::visit;
using AST::Visitor::endVisit;
void accept(AST::Node *node)
{ AST::Node::acceptChild(node, this); }
virtual void endVisit(AST::CallExpression *node)
{
if (AST::IdentifierExpression *idExpr = AST::cast<AST::IdentifierExpression *>(node->base)) {
if (idExpr->name->asString() == QLatin1String("qsTr")) {
if (node->arguments && AST::cast<AST::StringLiteral *>(node->arguments->expression)) {
AST::StringLiteral *literal = AST::cast<AST::StringLiteral *>(node->arguments->expression);
const QString source = literal->value->asString();
QString comment;
bool plural = false;
AST::ArgumentList *commentNode = node->arguments->next;
if (commentNode) {
literal = AST::cast<AST::StringLiteral *>(commentNode->expression);
comment = literal->value->asString();
AST::ArgumentList *nNode = commentNode->next;
if (nNode) {
AST::NumericLiteral *literal3 = AST::cast<AST::NumericLiteral *>(nNode->expression);
if (literal3) {
plural = true;
}
}
}
TranslatorMessage msg(m_component, source,
comment, QString(), m_fileName,
node->firstSourceLocation().startLine, QStringList(),
TranslatorMessage::Unfinished, plural);
m_translator->extend(msg);
}
}
//### support qsTranslate, QT_TR_NOOP, and QT_TRANSLATE_NOOP
}
}
private:
Translator *m_translator;
QString m_fileName;
QString m_component;
};
QString createErrorString(const QString &filename, const QString &code, Parser &parser)
{
// print out error
QStringList lines = code.split(QLatin1Char('\n'));
lines.append(QLatin1String("\n")); // sentinel.
QString errorString;
foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
if (m.isWarning())
continue;
QString error = filename + QLatin1Char(':') + QString::number(m.loc.startLine)
+ QLatin1Char(':') + QString::number(m.loc.startColumn) + QLatin1String(": error: ")
+ m.message + QLatin1Char('\n');
int line = 0;
if (m.loc.startLine > 0)
line = m.loc.startLine - 1;
const QString textLine = lines.at(line);
error += textLine + QLatin1Char('\n');
int column = m.loc.startColumn - 1;
if (column < 0)
column = 0;
column = qMin(column, textLine.length());
for (int i = 0; i < column; ++i) {
const QChar ch = textLine.at(i);
if (ch.isSpace())
error += ch.unicode();
else
error += QLatin1Char(' ');
}
error += QLatin1String("^\n");
errorString += error;
}
return errorString;
}
bool loadQml(Translator &translator, const QString &filename, ConversionData &cd)
{
cd.m_sourceFileName = filename;
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
cd.appendError(QString::fromLatin1("Cannot open %1: %2")
.arg(filename, file.errorString()));
return false;
}
const QString code = QTextStream(&file).readAll();
Engine driver;
Parser parser(&driver);
NodePool nodePool(filename, &driver);
driver.setNodePool(&nodePool);
Lexer lexer(&driver);
lexer.setCode(code, /*line = */ 1);
driver.setLexer(&lexer);
if (parser.parse()) {
FindTrCalls trCalls;
trCalls(&translator, filename, parser.ast());
} else {
QString error = createErrorString(filename, code, parser);
cd.appendError(error);
return false;
}
return true;
}
QT_END_NAMESPACE
<commit_msg>Add support for qsTranslate, QT_TR_NOOP, and QT_TRANSLATE_NOOP.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "lupdate.h"
#include <translator.h>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QString>
QT_BEGIN_NAMESPACE
#include "parser/javascriptengine_p.h"
#include "parser/javascriptparser_p.h"
#include "parser/javascriptlexer_p.h"
#include "parser/javascriptnodepool_p.h"
#include "parser/javascriptastvisitor_p.h"
#include "parser/javascriptast_p.h"
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QtDebug>
#include <QStringList>
#include <iostream>
#include <cstdlib>
using namespace JavaScript;
class FindTrCalls: protected AST::Visitor
{
public:
void operator()(Translator *translator, const QString &fileName, AST::Node *node)
{
m_translator = translator;
m_fileName = fileName;
m_component = QFileInfo(fileName).baseName(); //matches qsTr usage in QScriptEngine
accept(node);
}
protected:
using AST::Visitor::visit;
using AST::Visitor::endVisit;
void accept(AST::Node *node)
{ AST::Node::acceptChild(node, this); }
virtual void endVisit(AST::CallExpression *node)
{
if (AST::IdentifierExpression *idExpr = AST::cast<AST::IdentifierExpression *>(node->base)) {
if (idExpr->name->asString() == QLatin1String("qsTr") ||
idExpr->name->asString() == QLatin1String("QT_TR_NOOP")) {
if (node->arguments && AST::cast<AST::StringLiteral *>(node->arguments->expression)) {
AST::StringLiteral *literal = AST::cast<AST::StringLiteral *>(node->arguments->expression);
const QString source = literal->value->asString();
QString comment;
bool plural = false;
AST::ArgumentList *commentNode = node->arguments->next;
if (commentNode) {
literal = AST::cast<AST::StringLiteral *>(commentNode->expression);
comment = literal->value->asString();
AST::ArgumentList *nNode = commentNode->next;
if (nNode) {
AST::NumericLiteral *numLiteral = AST::cast<AST::NumericLiteral *>(nNode->expression);
if (numLiteral) {
plural = true;
}
}
}
TranslatorMessage msg(m_component, source,
comment, QString(), m_fileName,
node->firstSourceLocation().startLine, QStringList(),
TranslatorMessage::Unfinished, plural);
m_translator->extend(msg);
}
} else if (idExpr->name->asString() == QLatin1String("qsTranslate") ||
idExpr->name->asString() == QLatin1String("QT_TRANSLATE_NOOP")) {
if (node->arguments && AST::cast<AST::StringLiteral *>(node->arguments->expression)) {
AST::StringLiteral *literal = AST::cast<AST::StringLiteral *>(node->arguments->expression);
const QString context = literal->value->asString();
QString source;
QString comment;
bool plural = false;
AST::ArgumentList *sourceNode = node->arguments->next;
if (sourceNode) {
literal = AST::cast<AST::StringLiteral *>(sourceNode->expression);
source = literal->value->asString();
AST::ArgumentList *commentNode = sourceNode->next;
if (commentNode) {
literal = AST::cast<AST::StringLiteral *>(commentNode->expression);
comment = literal->value->asString();
AST::ArgumentList *nNode = commentNode->next;
if (nNode) {
AST::NumericLiteral *numLiteral = AST::cast<AST::NumericLiteral *>(nNode->expression);
if (numLiteral) {
plural = true;
}
}
}
}
TranslatorMessage msg(context, source,
comment, QString(), m_fileName,
node->firstSourceLocation().startLine, QStringList(),
TranslatorMessage::Unfinished, plural);
m_translator->extend(msg);
}
}
}
}
private:
Translator *m_translator;
QString m_fileName;
QString m_component;
};
QString createErrorString(const QString &filename, const QString &code, Parser &parser)
{
// print out error
QStringList lines = code.split(QLatin1Char('\n'));
lines.append(QLatin1String("\n")); // sentinel.
QString errorString;
foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
if (m.isWarning())
continue;
QString error = filename + QLatin1Char(':') + QString::number(m.loc.startLine)
+ QLatin1Char(':') + QString::number(m.loc.startColumn) + QLatin1String(": error: ")
+ m.message + QLatin1Char('\n');
int line = 0;
if (m.loc.startLine > 0)
line = m.loc.startLine - 1;
const QString textLine = lines.at(line);
error += textLine + QLatin1Char('\n');
int column = m.loc.startColumn - 1;
if (column < 0)
column = 0;
column = qMin(column, textLine.length());
for (int i = 0; i < column; ++i) {
const QChar ch = textLine.at(i);
if (ch.isSpace())
error += ch.unicode();
else
error += QLatin1Char(' ');
}
error += QLatin1String("^\n");
errorString += error;
}
return errorString;
}
bool loadQml(Translator &translator, const QString &filename, ConversionData &cd)
{
cd.m_sourceFileName = filename;
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
cd.appendError(QString::fromLatin1("Cannot open %1: %2")
.arg(filename, file.errorString()));
return false;
}
const QString code = QTextStream(&file).readAll();
Engine driver;
Parser parser(&driver);
NodePool nodePool(filename, &driver);
driver.setNodePool(&nodePool);
Lexer lexer(&driver);
lexer.setCode(code, /*line = */ 1);
driver.setLexer(&lexer);
if (parser.parse()) {
FindTrCalls trCalls;
trCalls(&translator, filename, parser.ast());
} else {
QString error = createErrorString(filename, code, parser);
cd.appendError(error);
return false;
}
return true;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <Nazara/Utility/Debug.hpp>
namespace Nz
{
inline PixelFormatInfo::PixelFormatInfo() :
content(PixelFormatContent_Undefined),
bitsPerPixel(0)
{
}
inline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
bitsPerPixel(bpp)
{
}
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
name(formatName),
bitsPerPixel(bpp)
{
}
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
redMask(rMask),
greenMask(gMask),
blueMask(bMask),
alphaMask(aMask),
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
name(formatName)
{
RecomputeBitsPerPixel();
}
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :
redMask(rMask),
greenMask(gMask),
blueMask(bMask),
alphaMask(aMask),
content(formatContent),
redType(rType),
greenType(gType),
blueType(bType),
alphaType(aType),
name(formatName)
{
if (bpp == 0)
RecomputeBitsPerPixel();
}
inline void PixelFormatInfo::Clear()
{
bitsPerPixel = 0;
alphaMask.Clear();
blueMask.Clear();
greenMask.Clear();
redMask.Clear();
name.Clear();
}
inline bool PixelFormatInfo::IsCompressed() const
{
return redType == PixelFormatSubType_Compressed ||
greenType == PixelFormatSubType_Compressed ||
blueType == PixelFormatSubType_Compressed ||
alphaType == PixelFormatSubType_Compressed;
}
inline bool PixelFormatInfo::IsValid() const
{
return bitsPerPixel != 0;
}
inline void PixelFormatInfo::RecomputeBitsPerPixel()
{
Bitset<> counter;
counter |= redMask;
counter |= greenMask;
counter |= blueMask;
counter |= alphaMask;
bitsPerPixel = static_cast<UInt8>(counter.Count());
}
inline bool PixelFormatInfo::Validate() const
{
if (!IsValid())
return false;
if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)
return false;
std::array<const Nz::Bitset<>*, 4> masks = { {&redMask, &greenMask, &blueMask, &alphaMask} };
std::array<PixelFormatSubType, 4> types = { {redType, greenType, blueType, alphaType} };
for (unsigned int i = 0; i < 4; ++i)
{
UInt8 usedBits = static_cast<UInt8>(masks[i]->Count());
if (usedBits == 0)
continue;
if (usedBits > bitsPerPixel)
return false;
switch (types[i])
{
case PixelFormatSubType_Half:
if (usedBits != 16)
return false;
break;
case PixelFormatSubType_Float:
if (usedBits != 32)
return false;
break;
default:
break;
}
}
return true;
}
inline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)
{
if (IsCompressed(format))
{
switch (format)
{
case PixelFormatType_DXT1:
case PixelFormatType_DXT3:
case PixelFormatType_DXT5:
return (((width + 3) / 4) * ((height + 3) / 4) * ((format == PixelFormatType_DXT1) ? 8 : 16)) * depth;
default:
NazaraError("Unsupported format");
return 0;
}
}
else
return width * height * depth * GetBytesPerPixel(format);
}
inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)
{
if (srcFormat == dstFormat)
{
std::memcpy(dst, src, GetBytesPerPixel(srcFormat));
return true;
}
#if NAZARA_UTILITY_SAFE
if (IsCompressed(srcFormat))
{
NazaraError("Cannot convert single pixel from compressed format");
return false;
}
if (IsCompressed(dstFormat))
{
NazaraError("Cannot convert single pixel to compressed format");
return false;
}
#endif
ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
if (!func)
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
return false;
}
if (!func(reinterpret_cast<const UInt8*>(src), reinterpret_cast<const UInt8*>(src) + GetBytesPerPixel(srcFormat), reinterpret_cast<UInt8*>(dst)))
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
return false;
}
return true;
}
inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)
{
if (srcFormat == dstFormat)
{
std::memcpy(dst, start, reinterpret_cast<const UInt8*>(end)-reinterpret_cast<const UInt8*>(start));
return true;
}
ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
if (!func)
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
return false;
}
if (!func(reinterpret_cast<const UInt8*>(start), reinterpret_cast<const UInt8*>(end), reinterpret_cast<UInt8*>(dst)))
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
return false;
}
return true;
}
inline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)
{
#if NAZARA_UTILITY_SAFE
if (!IsValid(format))
{
NazaraError("Invalid pixel format");
return false;
}
#endif
auto it = s_flipFunctions[flipping].find(format);
if (it != s_flipFunctions[flipping].end())
it->second(width, height, depth, reinterpret_cast<const UInt8*>(src), reinterpret_cast<UInt8*>(dst));
else
{
// Flipping générique
#if NAZARA_UTILITY_SAFE
if (IsCompressed(format))
{
NazaraError("No function to flip compressed format");
return false;
}
#endif
UInt8 bpp = GetBytesPerPixel(format);
unsigned int lineStride = width*bpp;
switch (flipping)
{
case PixelFlipping_Horizontally:
{
if (src == dst)
{
for (unsigned int z = 0; z < depth; ++z)
{
UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
for (unsigned int y = 0; y < height/2; ++y)
std::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);
}
}
else
{
for (unsigned int z = 0; z < depth; ++z)
{
const UInt8* srcPtr = reinterpret_cast<const UInt8*>(src);
UInt8* dstPtr = reinterpret_cast<UInt8*>(dst) + (width-1)*height*depth*bpp;
for (unsigned int y = 0; y < height; ++y)
{
std::memcpy(dstPtr, srcPtr, lineStride);
srcPtr += lineStride;
dstPtr -= lineStride;
}
}
}
break;
}
case PixelFlipping_Vertically:
{
if (src == dst)
{
for (unsigned int z = 0; z < depth; ++z)
{
UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width/2; ++x)
std::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);
ptr += lineStride;
}
}
}
else
{
for (unsigned int z = 0; z < depth; ++z)
{
UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width; ++x)
std::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);
ptr += lineStride;
}
}
}
break;
}
}
}
return true;
}
inline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)
{
return s_pixelFormatInfos[format].bitsPerPixel;
}
inline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)
{
return GetBitsPerPixel(format)/8;
}
inline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)
{
return s_pixelFormatInfos[format].content;
}
inline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)
{
return s_pixelFormatInfos[format];
}
inline const String& PixelFormat::GetName(PixelFormatType format)
{
return s_pixelFormatInfos[format].name;
}
inline bool PixelFormat::HasAlpha(PixelFormatType format)
{
return s_pixelFormatInfos[format].alphaMask.TestAny();
}
inline bool PixelFormat::IsCompressed(PixelFormatType format)
{
return s_pixelFormatInfos[format].IsCompressed();
}
inline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)
{
if (srcFormat == dstFormat)
return true;
return s_convertFunctions[srcFormat][dstFormat] != nullptr;
}
inline bool PixelFormat::IsValid(PixelFormatType format)
{
return format != PixelFormatType_Undefined;
}
inline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)
{
s_convertFunctions[srcFormat][dstFormat] = func;
}
inline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)
{
s_flipFunctions[flipping][format] = func;
}
}
#include <Nazara/Utility/DebugOff.hpp>
<commit_msg>Utility/PixelFormat: Reject formats with over 64 bpp per component<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <Nazara/Utility/Debug.hpp>
namespace Nz
{
inline PixelFormatInfo::PixelFormatInfo() :
content(PixelFormatContent_Undefined),
bitsPerPixel(0)
{
}
inline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
bitsPerPixel(bpp)
{
}
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
name(formatName),
bitsPerPixel(bpp)
{
}
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
redMask(rMask),
greenMask(gMask),
blueMask(bMask),
alphaMask(aMask),
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
name(formatName)
{
RecomputeBitsPerPixel();
}
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :
redMask(rMask),
greenMask(gMask),
blueMask(bMask),
alphaMask(aMask),
content(formatContent),
redType(rType),
greenType(gType),
blueType(bType),
alphaType(aType),
name(formatName)
{
if (bpp == 0)
RecomputeBitsPerPixel();
}
inline void PixelFormatInfo::Clear()
{
bitsPerPixel = 0;
alphaMask.Clear();
blueMask.Clear();
greenMask.Clear();
redMask.Clear();
name.Clear();
}
inline bool PixelFormatInfo::IsCompressed() const
{
return redType == PixelFormatSubType_Compressed ||
greenType == PixelFormatSubType_Compressed ||
blueType == PixelFormatSubType_Compressed ||
alphaType == PixelFormatSubType_Compressed;
}
inline bool PixelFormatInfo::IsValid() const
{
return bitsPerPixel != 0;
}
inline void PixelFormatInfo::RecomputeBitsPerPixel()
{
Bitset<> counter;
counter |= redMask;
counter |= greenMask;
counter |= blueMask;
counter |= alphaMask;
bitsPerPixel = static_cast<UInt8>(counter.Count());
}
inline bool PixelFormatInfo::Validate() const
{
if (!IsValid())
return false;
if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)
return false;
std::array<const Nz::Bitset<>*, 4> masks = { {&redMask, &greenMask, &blueMask, &alphaMask} };
std::array<PixelFormatSubType, 4> types = { {redType, greenType, blueType, alphaType} };
for (unsigned int i = 0; i < 4; ++i)
{
UInt8 usedBits = static_cast<UInt8>(masks[i]->Count());
if (usedBits == 0)
continue;
if (usedBits > bitsPerPixel)
return false;
if (usedBits > 64) //< Currently, formats with over 64 bits per component are not supported
return false;
switch (types[i])
{
case PixelFormatSubType_Half:
if (usedBits != 16)
return false;
break;
case PixelFormatSubType_Float:
if (usedBits != 32)
return false;
break;
default:
break;
}
}
return true;
}
inline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)
{
if (IsCompressed(format))
{
switch (format)
{
case PixelFormatType_DXT1:
case PixelFormatType_DXT3:
case PixelFormatType_DXT5:
return (((width + 3) / 4) * ((height + 3) / 4) * ((format == PixelFormatType_DXT1) ? 8 : 16)) * depth;
default:
NazaraError("Unsupported format");
return 0;
}
}
else
return width * height * depth * GetBytesPerPixel(format);
}
inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)
{
if (srcFormat == dstFormat)
{
std::memcpy(dst, src, GetBytesPerPixel(srcFormat));
return true;
}
#if NAZARA_UTILITY_SAFE
if (IsCompressed(srcFormat))
{
NazaraError("Cannot convert single pixel from compressed format");
return false;
}
if (IsCompressed(dstFormat))
{
NazaraError("Cannot convert single pixel to compressed format");
return false;
}
#endif
ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
if (!func)
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
return false;
}
if (!func(reinterpret_cast<const UInt8*>(src), reinterpret_cast<const UInt8*>(src) + GetBytesPerPixel(srcFormat), reinterpret_cast<UInt8*>(dst)))
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
return false;
}
return true;
}
inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)
{
if (srcFormat == dstFormat)
{
std::memcpy(dst, start, reinterpret_cast<const UInt8*>(end)-reinterpret_cast<const UInt8*>(start));
return true;
}
ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
if (!func)
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
return false;
}
if (!func(reinterpret_cast<const UInt8*>(start), reinterpret_cast<const UInt8*>(end), reinterpret_cast<UInt8*>(dst)))
{
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
return false;
}
return true;
}
inline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)
{
#if NAZARA_UTILITY_SAFE
if (!IsValid(format))
{
NazaraError("Invalid pixel format");
return false;
}
#endif
auto it = s_flipFunctions[flipping].find(format);
if (it != s_flipFunctions[flipping].end())
it->second(width, height, depth, reinterpret_cast<const UInt8*>(src), reinterpret_cast<UInt8*>(dst));
else
{
// Flipping générique
#if NAZARA_UTILITY_SAFE
if (IsCompressed(format))
{
NazaraError("No function to flip compressed format");
return false;
}
#endif
UInt8 bpp = GetBytesPerPixel(format);
unsigned int lineStride = width*bpp;
switch (flipping)
{
case PixelFlipping_Horizontally:
{
if (src == dst)
{
for (unsigned int z = 0; z < depth; ++z)
{
UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
for (unsigned int y = 0; y < height/2; ++y)
std::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);
}
}
else
{
for (unsigned int z = 0; z < depth; ++z)
{
const UInt8* srcPtr = reinterpret_cast<const UInt8*>(src);
UInt8* dstPtr = reinterpret_cast<UInt8*>(dst) + (width-1)*height*depth*bpp;
for (unsigned int y = 0; y < height; ++y)
{
std::memcpy(dstPtr, srcPtr, lineStride);
srcPtr += lineStride;
dstPtr -= lineStride;
}
}
}
break;
}
case PixelFlipping_Vertically:
{
if (src == dst)
{
for (unsigned int z = 0; z < depth; ++z)
{
UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width/2; ++x)
std::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);
ptr += lineStride;
}
}
}
else
{
for (unsigned int z = 0; z < depth; ++z)
{
UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width; ++x)
std::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);
ptr += lineStride;
}
}
}
break;
}
}
}
return true;
}
inline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)
{
return s_pixelFormatInfos[format].bitsPerPixel;
}
inline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)
{
return GetBitsPerPixel(format)/8;
}
inline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)
{
return s_pixelFormatInfos[format].content;
}
inline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)
{
return s_pixelFormatInfos[format];
}
inline const String& PixelFormat::GetName(PixelFormatType format)
{
return s_pixelFormatInfos[format].name;
}
inline bool PixelFormat::HasAlpha(PixelFormatType format)
{
return s_pixelFormatInfos[format].alphaMask.TestAny();
}
inline bool PixelFormat::IsCompressed(PixelFormatType format)
{
return s_pixelFormatInfos[format].IsCompressed();
}
inline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)
{
if (srcFormat == dstFormat)
return true;
return s_convertFunctions[srcFormat][dstFormat] != nullptr;
}
inline bool PixelFormat::IsValid(PixelFormatType format)
{
return format != PixelFormatType_Undefined;
}
inline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)
{
s_convertFunctions[srcFormat][dstFormat] = func;
}
inline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)
{
s_flipFunctions[flipping][format] = func;
}
}
#include <Nazara/Utility/DebugOff.hpp>
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Sacha Refshauge
*
*/
// Qt 4.7+ / 5.0+ implementation of the framework.
// Currently supports: Symbian, Blackberry, Meego, Linux, Windows
#include <QApplication>
#include <QUrl>
#include <QDir>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QLocale>
#include <QThread>
#ifdef __SYMBIAN32__
#include <e32std.h>
#include <QSystemScreenSaver>
#include <QFeedbackHapticsEffect>
#include "SymbianMediaKeys.h"
#endif
#include "QtMain.h"
InputState* input_state;
std::string System_GetProperty(SystemProperty prop) {
switch (prop) {
case SYSPROP_NAME:
#ifdef __SYMBIAN32__
return "Qt:Symbian";
#elif defined(BLACKBERRY)
return "Qt:Blackberry10";
#elif defined(MEEGO_EDITION_HARMATTAN)
return "Qt:Meego";
#elif defined(Q_OS_LINUX)
return "Qt:Linux";
#elif defined(_WIN32)
return "Qt:Windows";
#else
return "Qt";
#endif
case SYSPROP_LANGREGION:
return QLocale::system().name().toStdString();
default:
return "";
}
}
void Vibrate(int length_ms) {
if (length_ms == -1 || length_ms == -3)
length_ms = 50;
else if (length_ms == -2)
length_ms = 25;
// Symbian only for now
#if defined(__SYMBIAN32__)
QFeedbackHapticsEffect effect;
effect.setIntensity(0.8);
effect.setDuration(length_ms);
effect.start();
#endif
}
void LaunchBrowser(const char *url)
{
QDesktopServices::openUrl(QUrl(url));
}
float CalculateDPIScale()
{
// Sane default rather than check DPI
#ifdef __SYMBIAN32__
return 1.4f;
#elif defined(ARM)
return 1.2f;
#else
return 1.0f;
#endif
}
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_LINUX
QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
QApplication a(argc, argv);
QSize res = QApplication::desktop()->screenGeometry().size();
if (res.width() < res.height())
res.transpose();
pixel_xres = res.width();
pixel_yres = res.height();
g_dpi_scale = CalculateDPIScale();
dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale);
net::Init();
#ifdef __SYMBIAN32__
const char *savegame_dir = "E:/PPSSPP/";
const char *assets_dir = "E:/PPSSPP/";
#elif defined(BLACKBERRY)
const char *savegame_dir = "/accounts/1000/shared/misc/";
const char *assets_dir = "app/native/assets/";
#elif defined(MEEGO_EDITION_HARMATTAN)
const char *savegame_dir = "/home/user/MyDocs/PPSSPP/";
QDir myDocs("/home/user/MyDocs/");
if (!myDocs.exists("PPSSPP"))
myDocs.mkdir("PPSSPP");
const char *assets_dir = "/opt/PPSSPP/";
#else
const char *savegame_dir = "./";
const char *assets_dir = "./";
#endif
NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE");
#if !defined(Q_OS_LINUX) || defined(ARM)
MainUI w;
w.resize(pixel_xres, pixel_yres);
#ifdef ARM
w.showFullScreen();
#else
w.show();
#endif
#endif
#ifdef __SYMBIAN32__
// Set RunFast hardware mode for VFPv2.
User::SetFloatingPointMode(EFpModeRunFast);
// Disable screensaver
QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w);
ssObject->setScreenSaverInhibit();
SymbianMediaKeys* mediakeys = new SymbianMediaKeys();
#endif
QThread* thread = new QThread;
MainAudio *audio = new MainAudio();
audio->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), audio, SLOT(run()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
int ret = a.exec();
delete audio;
thread->quit();
NativeShutdown();
net::Shutdown();
return ret;
}
<commit_msg>disable non-menu Main Window for all non ARM Qt platforms including Linux, Windows and OSX.<commit_after>/*
* Copyright (c) 2012 Sacha Refshauge
*
*/
// Qt 4.7+ / 5.0+ implementation of the framework.
// Currently supports: Symbian, Blackberry, Meego, Linux, Windows
#include <QApplication>
#include <QUrl>
#include <QDir>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QLocale>
#include <QThread>
#ifdef __SYMBIAN32__
#include <e32std.h>
#include <QSystemScreenSaver>
#include <QFeedbackHapticsEffect>
#include "SymbianMediaKeys.h"
#endif
#include "QtMain.h"
InputState* input_state;
std::string System_GetProperty(SystemProperty prop) {
switch (prop) {
case SYSPROP_NAME:
#ifdef __SYMBIAN32__
return "Qt:Symbian";
#elif defined(BLACKBERRY)
return "Qt:Blackberry10";
#elif defined(MEEGO_EDITION_HARMATTAN)
return "Qt:Meego";
#elif defined(Q_OS_LINUX)
return "Qt:Linux";
#elif defined(_WIN32)
return "Qt:Windows";
#else
return "Qt";
#endif
case SYSPROP_LANGREGION:
return QLocale::system().name().toStdString();
default:
return "";
}
}
void Vibrate(int length_ms) {
if (length_ms == -1 || length_ms == -3)
length_ms = 50;
else if (length_ms == -2)
length_ms = 25;
// Symbian only for now
#if defined(__SYMBIAN32__)
QFeedbackHapticsEffect effect;
effect.setIntensity(0.8);
effect.setDuration(length_ms);
effect.start();
#endif
}
void LaunchBrowser(const char *url)
{
QDesktopServices::openUrl(QUrl(url));
}
float CalculateDPIScale()
{
// Sane default rather than check DPI
#ifdef __SYMBIAN32__
return 1.4f;
#elif defined(ARM)
return 1.2f;
#else
return 1.0f;
#endif
}
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_LINUX
QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
QApplication a(argc, argv);
QSize res = QApplication::desktop()->screenGeometry().size();
if (res.width() < res.height())
res.transpose();
pixel_xres = res.width();
pixel_yres = res.height();
g_dpi_scale = CalculateDPIScale();
dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale);
net::Init();
#ifdef __SYMBIAN32__
const char *savegame_dir = "E:/PPSSPP/";
const char *assets_dir = "E:/PPSSPP/";
#elif defined(BLACKBERRY)
const char *savegame_dir = "/accounts/1000/shared/misc/";
const char *assets_dir = "app/native/assets/";
#elif defined(MEEGO_EDITION_HARMATTAN)
const char *savegame_dir = "/home/user/MyDocs/PPSSPP/";
QDir myDocs("/home/user/MyDocs/");
if (!myDocs.exists("PPSSPP"))
myDocs.mkdir("PPSSPP");
const char *assets_dir = "/opt/PPSSPP/";
#else
const char *savegame_dir = "./";
const char *assets_dir = "./";
#endif
NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE");
#if defined(ARM)
MainUI w;
w.resize(pixel_xres, pixel_yres);
#ifdef ARM
w.showFullScreen();
#else
w.show();
#endif
#endif
#ifdef __SYMBIAN32__
// Set RunFast hardware mode for VFPv2.
User::SetFloatingPointMode(EFpModeRunFast);
// Disable screensaver
QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w);
ssObject->setScreenSaverInhibit();
SymbianMediaKeys* mediakeys = new SymbianMediaKeys();
#endif
QThread* thread = new QThread;
MainAudio *audio = new MainAudio();
audio->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), audio, SLOT(run()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
int ret = a.exec();
delete audio;
thread->quit();
NativeShutdown();
net::Shutdown();
return ret;
}
<|endoftext|> |
<commit_before>/*
This file is part of:
NoahFrame
https://github.com/ketoo/NoahGameFrame
Copyright 2009 - 2018 NoahFrame(NoahGameFrame)
File creator: lvsheng.huang
NoahFrame is open-source software and you can redistribute it and/or modify
it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.
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 "NFCLevelModule.h"
bool NFCLevelModule::Init()
{
mbExpForHero = true;
return true;
}
bool NFCLevelModule::Shut()
{
return true;
}
bool NFCLevelModule::Execute()
{
return true;
}
bool NFCLevelModule::AfterInit()
{
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pPropertyConfigModule = pPluginManager->FindModule<NFIPropertyConfigModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
//m_pHeroModule = pPluginManager->FindModule<NFIHeroModule>();
return true;
}
int NFCLevelModule::AddExp(const NFGUID& self, const int64_t nExp)
{
if (mbExpForHero)
{
//m_pHeroModule->AddHeroExp(self, nExp);
return 0;
}
int eJobType = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Job());
int64_t nCurExp = m_pKernelModule->GetPropertyInt(self, NFrame::Player::EXP());
int nLevel = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Level());
int64_t nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());
nCurExp += nExp;
int64_t nRemainExp = nCurExp - nMaxExp;
while (nRemainExp >= 0)
{
nLevel++;
m_pKernelModule->SetPropertyInt(self, NFrame::Player::Level(), nLevel);
nCurExp = nRemainExp;
nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());
if (nMaxExp <= 0)
{
break;
}
nRemainExp -= nMaxExp;
}
m_pKernelModule->SetPropertyInt(self, NFrame::Player::EXP(), nCurExp);
return 0;
}<commit_msg>add hero module for game server<commit_after>/*
This file is part of:
NoahFrame
https://github.com/ketoo/NoahGameFrame
Copyright 2009 - 2018 NoahFrame(NoahGameFrame)
File creator: lvsheng.huang
NoahFrame is open-source software and you can redistribute it and/or modify
it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.
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 "NFCLevelModule.h"
bool NFCLevelModule::Init()
{
mbExpForHero = true;
return true;
}
bool NFCLevelModule::Shut()
{
return true;
}
bool NFCLevelModule::Execute()
{
return true;
}
bool NFCLevelModule::AfterInit()
{
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pPropertyConfigModule = pPluginManager->FindModule<NFIPropertyConfigModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pHeroModule = pPluginManager->FindModule<NFIHeroModule>();
return true;
}
int NFCLevelModule::AddExp(const NFGUID& self, const int64_t nExp)
{
if (mbExpForHero)
{
m_pHeroModule->AddHeroExp(self, nExp);
return 0;
}
int eJobType = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Job());
int64_t nCurExp = m_pKernelModule->GetPropertyInt(self, NFrame::Player::EXP());
int nLevel = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Level());
int64_t nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());
nCurExp += nExp;
int64_t nRemainExp = nCurExp - nMaxExp;
while (nRemainExp >= 0)
{
nLevel++;
m_pKernelModule->SetPropertyInt(self, NFrame::Player::Level(), nLevel);
nCurExp = nRemainExp;
nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());
if (nMaxExp <= 0)
{
break;
}
nRemainExp -= nMaxExp;
}
m_pKernelModule->SetPropertyInt(self, NFrame::Player::EXP(), nCurExp);
return 0;
}<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
auto dummy = ListNode(0);
while (head) {
auto tmp = head->next;
head->next = dummy.next;
dummy.next = head;
head = tmp;
}
return dummy.next;
}
};
<commit_msg>Update reverse-linked-list.cpp<commit_after>// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
auto dummy = ListNode{0};
while (head) {
auto tmp = head->next;
head->next = dummy.next;
dummy.next = head;
head = tmp;
}
return dummy.next;
}
};
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2011 by Benedict Paten (benedictpaten@gmail.com)
*
* Released under the MIT license, see LICENSE.txt
*/
/*
* sonLibKVDatabase_KyotoTycoon.cpp
*
* Created on: 5-1-11
* Author: epaull
*
* Note: all the KT methods seem to have a C and a CPP version (in terms of the arguments) ,
* and for this implementation we're using the plain C versions as much as we can.
*/
//Database functions
#ifdef HAVE_KYOTO_TYCOON
#include <ktremotedb.h>
#include "sonLibGlobalsInternal.h"
#include "sonLibKVDatabasePrivate.h"
using namespace std;
using namespace kyototycoon;
/*
* construct in the Tokyo Tyrant case means connect to the remote DB
*/
static RemoteDB *constructDB(stKVDatabaseConf *conf, bool create) {
// we actually do need a local DB dir for Kyoto Tycoon to store the sequences file
const char *dbDir = stKVDatabaseConf_getDir(conf);
mkdir(dbDir, S_IRWXU); // just let open of database generate error (FIXME: would be better to make this report errors)
char *databaseName = stString_print("%s/%s", dbDir, "data");
const char *dbRemote_Host = stKVDatabaseConf_getHost(conf);
unsigned dbRemote_Port = stKVDatabaseConf_getPort(conf);
int timeout = stKVDatabaseConf_getTimeout(conf);
// create the database object
RemoteDB db;
RemoteDB *rdb = &db;
// tcrdb open sets the host and port for the rdb object
if (!rdb->open(dbRemote_Host, dbRemote_Port, timeout)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Opening connection to host: %s with error: %s", dbRemote_Host, rdb->error().name());
}
free(databaseName);
return rdb;
}
/* closes the remote DB connection and deletes the rdb object, but does not destroy the
remote database */
static void destructDB(stKVDatabase *database) {
RemoteDB *rdb = (RemoteDB*)database->dbImpl;
if (rdb != NULL) {
// close the connection: first try a graceful close, then a forced close
if (!rdb->close(true)) {
if (!rdb->close(false)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Closing database error: %s",rdb->error().name());
}
}
// delete the local in-memory object
delete rdb;
database->dbImpl = NULL;
}
}
/* WARNING: removes all records from the remote database */
static void deleteDB(stKVDatabase *database) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
if (rdb != NULL) {
rdb->clear();
}
destructDB(database);
// this removes all records from the remove database object
}
/* check if a record already exists */
static bool recordExists(RemoteDB *rdb, int64_t key) {
size_t sp;
if (rdb->get((char *)&key, (size_t)sizeof(key), &sp, NULL) == NULL) {
return false;
} else {
return true;
}
}
static bool containsRecord(stKVDatabase *database, int64_t key) {
return recordExists((RemoteDB *)database->dbImpl, key);
}
static void insertRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
// add method: If the key already exists the record will not be modified and it'll return false
if (!rdb->add((char *)&key, (size_t)sizeof(int64_t), (const char *)value, sizeOfRecord)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Inserting key/value to database error: %s", rdb->error().name());
}
}
static void updateRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
// replace method: If the key doesn't already exist it won't be created, and we'll get an error
if (!rdb->replace((char *)&key, (size_t)sizeof(int64_t), (const char *)value, sizeOfRecord)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Updating key/value to database error: %s", rdb->error().name());
}
}
static int64_t numberOfRecords(stKVDatabase *database) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
return rdb->count();
}
static void *getRecord2(stKVDatabase *database, int64_t key, int64_t *recordSize) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
//Return value must be freed.
size_t i;
void *record = (void *)rdb->get((char *)&key, (size_t)sizeof(int64_t), &i, NULL);
*recordSize = (int64_t)i;
return record;
}
/* get a single non-string record */
static void *getRecord(stKVDatabase *database, int64_t key) {
int64_t i;
return getRecord2(database, key, &i);
}
/* get part of a string record */
static void *getPartialRecord(stKVDatabase *database, int64_t key, int64_t zeroBasedByteOffset, int64_t sizeInBytes, int64_t recordSize) {
int64_t recordSize2;
char *record = (char *)getRecord2(database, key, &recordSize2);
if(recordSize2 != recordSize) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The given record size is incorrect: %lld, should be %lld", (long long)recordSize, recordSize2);
}
if(record == NULL) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The record does not exist: %lld for partial retrieval", (long long)key);
}
if(zeroBasedByteOffset < 0 || sizeInBytes < 0 || zeroBasedByteOffset + sizeInBytes > recordSize) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Partial record retrieval to out of bounds memory, record size: %lld, requested start: %lld, requested size: %lld", (long long)recordSize, (long long)zeroBasedByteOffset, (long long)sizeInBytes);
}
void *partialRecord = memcpy(st_malloc(sizeInBytes), record + zeroBasedByteOffset, sizeInBytes);
free(record);
return partialRecord;
}
static void removeRecord(stKVDatabase *database, int64_t key) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
if (!rdb->remove((char *)&key, (size_t)sizeof(int64_t))) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Removing key/value to database error: %s", rdb->error().name());
}
}
static void startTransaction(stKVDatabase *database) {
// transactions supported through bulk_... methods
return;
}
static void commitTransaction(stKVDatabase *database) {
// transactions supported through bulk_... methods
return;
}
static void abortTransaction(stKVDatabase *database) {
// transactions supported through bulk_... methods
return;
}
void stKVDatabase_initialise_kyotoTycoon(stKVDatabase *database, stKVDatabaseConf *conf, bool create) {
database->dbImpl = constructDB(stKVDatabase_getConf(database), create);
database->destruct = destructDB;
database->deleteDatabase = deleteDB;
database->containsRecord = containsRecord;
database->insertRecord = insertRecord;
database->updateRecord = updateRecord;
database->numberOfRecords = numberOfRecords;
database->getRecord = getRecord;
database->getRecord2 = getRecord2;
database->getPartialRecord = getPartialRecord;
database->removeRecord = removeRecord;
database->startTransaction = startTransaction;
database->commitTransaction = commitTransaction;
database->abortTransaction = abortTransaction;
}
#endif
<commit_msg>-- oops, need to create remoteDB object on the heap<commit_after>/*
* Copyright (C) 2006-2011 by Benedict Paten (benedictpaten@gmail.com)
*
* Released under the MIT license, see LICENSE.txt
*/
/*
* sonLibKVDatabase_KyotoTycoon.cpp
*
* Created on: 5-1-11
* Author: epaull
*
* Note: all the KT methods seem to have a C and a CPP version (in terms of the arguments) ,
* and for this implementation we're using the plain C versions as much as we can.
*/
//Database functions
#ifdef HAVE_KYOTO_TYCOON
#include <ktremotedb.h>
#include "sonLibGlobalsInternal.h"
#include "sonLibKVDatabasePrivate.h"
using namespace std;
using namespace kyototycoon;
/*
* construct in the Tokyo Tyrant case means connect to the remote DB
*/
static RemoteDB *constructDB(stKVDatabaseConf *conf, bool create) {
// we actually do need a local DB dir for Kyoto Tycoon to store the sequences file
const char *dbDir = stKVDatabaseConf_getDir(conf);
mkdir(dbDir, S_IRWXU); // just let open of database generate error (FIXME: would be better to make this report errors)
char *databaseName = stString_print("%s/%s", dbDir, "data");
const char *dbRemote_Host = stKVDatabaseConf_getHost(conf);
unsigned dbRemote_Port = stKVDatabaseConf_getPort(conf);
int timeout = stKVDatabaseConf_getTimeout(conf);
// create the database object
RemoteDB *rdb = new RemoteDB();
// tcrdb open sets the host and port for the rdb object
if (!rdb->open(dbRemote_Host, dbRemote_Port, timeout)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Opening connection to host: %s with error: %s", dbRemote_Host, rdb->error().name());
}
free(databaseName);
return rdb;
}
/* closes the remote DB connection and deletes the rdb object, but does not destroy the
remote database */
static void destructDB(stKVDatabase *database) {
RemoteDB *rdb = (RemoteDB*)database->dbImpl;
if (rdb != NULL) {
// close the connection: first try a graceful close, then a forced close
if (!rdb->close(true)) {
if (!rdb->close(false)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Closing database error: %s",rdb->error().name());
}
}
// delete the local in-memory object
delete rdb;
database->dbImpl = NULL;
}
}
/* WARNING: removes all records from the remote database */
static void deleteDB(stKVDatabase *database) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
if (rdb != NULL) {
rdb->clear();
}
destructDB(database);
// this removes all records from the remove database object
}
/* check if a record already exists */
static bool recordExists(RemoteDB *rdb, int64_t key) {
size_t sp;
if (rdb->get((char *)&key, (size_t)sizeof(key), &sp, NULL) == NULL) {
return false;
} else {
return true;
}
}
static bool containsRecord(stKVDatabase *database, int64_t key) {
return recordExists((RemoteDB *)database->dbImpl, key);
}
static void insertRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
// add method: If the key already exists the record will not be modified and it'll return false
if (!rdb->add((char *)&key, (size_t)sizeof(int64_t), (const char *)value, sizeOfRecord)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Inserting key/value to database error: %s", rdb->error().name());
}
}
static void updateRecord(stKVDatabase *database, int64_t key, const void *value, int64_t sizeOfRecord) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
// replace method: If the key doesn't already exist it won't be created, and we'll get an error
if (!rdb->replace((char *)&key, (size_t)sizeof(int64_t), (const char *)value, sizeOfRecord)) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Updating key/value to database error: %s", rdb->error().name());
}
}
static int64_t numberOfRecords(stKVDatabase *database) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
return rdb->count();
}
static void *getRecord2(stKVDatabase *database, int64_t key, int64_t *recordSize) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
//Return value must be freed.
size_t i;
void *record = (void *)rdb->get((char *)&key, (size_t)sizeof(int64_t), &i, NULL);
*recordSize = (int64_t)i;
return record;
}
/* get a single non-string record */
static void *getRecord(stKVDatabase *database, int64_t key) {
int64_t i;
return getRecord2(database, key, &i);
}
/* get part of a string record */
static void *getPartialRecord(stKVDatabase *database, int64_t key, int64_t zeroBasedByteOffset, int64_t sizeInBytes, int64_t recordSize) {
int64_t recordSize2;
char *record = (char *)getRecord2(database, key, &recordSize2);
if(recordSize2 != recordSize) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The given record size is incorrect: %lld, should be %lld", (long long)recordSize, recordSize2);
}
if(record == NULL) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "The record does not exist: %lld for partial retrieval", (long long)key);
}
if(zeroBasedByteOffset < 0 || sizeInBytes < 0 || zeroBasedByteOffset + sizeInBytes > recordSize) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Partial record retrieval to out of bounds memory, record size: %lld, requested start: %lld, requested size: %lld", (long long)recordSize, (long long)zeroBasedByteOffset, (long long)sizeInBytes);
}
void *partialRecord = memcpy(st_malloc(sizeInBytes), record + zeroBasedByteOffset, sizeInBytes);
free(record);
return partialRecord;
}
static void removeRecord(stKVDatabase *database, int64_t key) {
RemoteDB *rdb = (RemoteDB *)database->dbImpl;
if (!rdb->remove((char *)&key, (size_t)sizeof(int64_t))) {
stThrowNew(ST_KV_DATABASE_EXCEPTION_ID, "Removing key/value to database error: %s", rdb->error().name());
}
}
static void startTransaction(stKVDatabase *database) {
// transactions supported through bulk_... methods
return;
}
static void commitTransaction(stKVDatabase *database) {
// transactions supported through bulk_... methods
return;
}
static void abortTransaction(stKVDatabase *database) {
// transactions supported through bulk_... methods
return;
}
void stKVDatabase_initialise_kyotoTycoon(stKVDatabase *database, stKVDatabaseConf *conf, bool create) {
database->dbImpl = constructDB(stKVDatabase_getConf(database), create);
database->destruct = destructDB;
database->deleteDatabase = deleteDB;
database->containsRecord = containsRecord;
database->insertRecord = insertRecord;
database->updateRecord = updateRecord;
database->numberOfRecords = numberOfRecords;
database->getRecord = getRecord;
database->getRecord2 = getRecord2;
database->getPartialRecord = getPartialRecord;
database->removeRecord = removeRecord;
database->startTransaction = startTransaction;
database->commitTransaction = commitTransaction;
database->abortTransaction = abortTransaction;
}
#endif
<|endoftext|> |
<commit_before>/*
* File: PPSequenceTypes.cpp
* Copyright (C) 2006 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "sedna.h"
#include "PPSequenceTypes.h"
#include "PPUtils.h"
#include "casting_operations.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPCast
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPCast::PPCast(variable_context *_cxt_,
PPOpIn _child_,
xmlscm_type _target_type_,
bool _can_be_empty_seq_) : PPIterator(_cxt_),
child(_child_),
target_type(_target_type_),
can_be_empty_seq(_can_be_empty_seq_)
{
}
PPCast::~PPCast()
{
delete child.op;
child.op = NULL;
}
void PPCast::open ()
{
child.op->open();
first_time = true;
}
void PPCast::reopen()
{
child.op->reopen();
first_time = true;
}
void PPCast::close ()
{
child.op->close();
}
void PPCast::next (tuple &t)
{
if (first_time)
{
first_time = false;
child.op->next(t);
if (t.is_eos())
if (can_be_empty_seq)
{
first_time = true;
t.set_eos();
return;
}
else throw USER_EXCEPTION2(XP0006, "cast expression ('?' is not specified in target type but empty sequence is given)");
tuple_cell tc = atomize(child.get(t));
child.op->next(t);
if (!t.is_eos()) throw USER_EXCEPTION2(XP0006, "cast expression (the result of atomization is a sequence of more than one atomic value)");
t.copy(cast(tc, target_type));
}
else
{
first_time = true;
t.set_eos();
}
}
PPIterator* PPCast::copy(variable_context *_cxt_)
{
PPCast *res = new PPCast(_cxt_, child, target_type, can_be_empty_seq);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPCast::result(PPIterator* cur, variable_context *cxt, void*& r)
{
PPOpIn child;
((PPCast*)cur)->children(child);
void *child_r;
bool child_s = (child.op->res_fun())(child.op, cxt, child_r);
if (!child_s) // if expression is not strict
{ // create PPCast and transmit state
child.op = (PPIterator*)child_r;
PPCast *res_op = new PPCast(cxt, child,
((PPCast*)cur)->target_type,
((PPCast*)cur)->can_be_empty_seq);
r = res_op;
return false;
}
sequence *child_seq = (sequence*)child_r;
if (child_seq->size() == 0)
if (((PPCast*)cur)->can_be_empty_seq)
{
r = child_seq;
return true;
}
else throw USER_EXCEPTION2(XP0006, "cast expression ('?' is not specified in target type but empty sequence is given)");
if (child_seq->size() != 1) throw USER_EXCEPTION2(XP0006, "cast expression (the result of atomization is a sequence of more than one atomic value)");
tuple t(1);
child_seq->get(t, child_seq->begin());
t.cells[0] = cast(atomize(t.cells[0]), ((PPCast*)cur)->target_type);
child_seq->clear();
child_seq->add(t);
r = child_seq;
return true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPCastable
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPCastable::PPCastable(variable_context *_cxt_,
PPOpIn _child_,
xmlscm_type _target_type_,
bool _can_be_empty_seq_) : PPIterator(_cxt_),
child(_child_),
target_type(_target_type_),
can_be_empty_seq(_can_be_empty_seq_)
{
}
PPCastable::~PPCastable()
{
delete child.op;
child.op = NULL;
}
void PPCastable::open ()
{
child.op->open();
first_time = true;
}
void PPCastable::reopen()
{
child.op->reopen();
first_time = true;
}
void PPCastable::close ()
{
child.op->close();
}
void PPCastable::next (tuple &t)
{
bool res;
if (first_time)
{
first_time = false;
child.op->next(t);
if (t.is_eos())
{
if (can_be_empty_seq)
{
first_time = true;
res = true;
}
else res = false; //cast expression ('?' is not specified in target type but empty sequence is given)
}
else
{
tuple_cell tc = atomize(child.get(t));
child.op->next(t);
if (!t.is_eos()) res = false; //cast expression (the result of atomization is a sequence of more than one atomic value)
else res = is_castable(tc, target_type);
}
t.copy(tuple_cell::atomic(res));
}
else
{
first_time = true;
t.set_eos();
}
}
PPIterator* PPCastable::copy(variable_context *_cxt_)
{
PPCastable *res = new PPCastable(_cxt_, child, target_type, can_be_empty_seq);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPCastable::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPCastable::result");
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPInstanceOf
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPInstanceOf::PPInstanceOf(variable_context *_cxt_,
PPOpIn _child_,
const sequence_type& _st_) : PPIterator(_cxt_),
child(_child_),
st(_st_)
{
}
PPInstanceOf::~PPInstanceOf()
{
delete child.op;
child.op = NULL;
}
void PPInstanceOf::open ()
{
child.op->open();
first_time = true;
eos_reached = true;
}
void PPInstanceOf::reopen()
{
child.op->reopen();
first_time = true;
eos_reached = true;
}
void PPInstanceOf::close ()
{
child.op->close();
}
bool type_matches(const PPOpIn &child, tuple &t, bool &eos_reached, const sequence_type& st);
void PPInstanceOf::next (tuple &t)
{
if (first_time)
{
first_time = false;
if (!eos_reached) child.op->reopen();
bool res = type_matches(child, t, eos_reached, st);
t.copy(tuple_cell::atomic(res));
}
else
{
first_time = true;
t.set_eos();
}
}
PPIterator* PPInstanceOf::copy(variable_context *_cxt_)
{
PPInstanceOf *res = new PPInstanceOf(_cxt_, child, st);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPInstanceOf::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPInstanceOf::result");
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPTreat
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPTreat::PPTreat(variable_context *_cxt_,
PPOpIn _child_,
const sequence_type& _st_) : PPIterator(_cxt_),
child(_child_),
st(_st_)
{
}
PPTreat::~PPTreat()
{
delete child.op;
child.op = NULL;
}
void PPTreat::open ()
{
child.op->open();
first_time = true;
eos_reached = true;
s = new sequence(child.ts);
pos = 0;
}
void PPTreat::reopen()
{
child.op->reopen();
first_time = true;
eos_reached = true;
pos = 0;
s->clear();
}
void PPTreat::close ()
{
child.op->close();
}
void PPTreat::next(tuple &t)
{
if (first_time)
{
first_time = false;
if (!eos_reached) child.op->reopen();
bool res = type_matches(child, s, t, eos_reached, st);
//!!! FIXME: error code must be XPDY0050 there
if(res == false) throw USER_EXCEPTION(XP0050);
}
if(pos < s->size())
{
s->get(t, pos++);
return;
}
else if(!eos_reached)
{
child.op->next(t);
if(t.is_eos()) eos_reached = true;
else return;
}
t.set_eos();
first_time = true;
s->clear();
pos=0;
}
PPIterator* PPTreat::copy(variable_context *_cxt_)
{
PPTreat *res = new PPTreat(_cxt_, child, st);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPTreat::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPTreat::result");
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPTypeswitch
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPTypeswitch::PPTypeswitch(variable_context *_cxt_,
arr_of_var_dsc _var_dscs_,
PPOpIn _source_child_,
const arr_of_sequence_type& _types_,
arr_of_PPOpIn _cases_,
PPOpIn _default_child_): PPVarIterator(_cxt_),
var_dscs(_var_dscs_),
source_child(_source_child_),
types(_types_),
cases(_cases_),
default_child(_default_child_)
{
if(cases.size() != types.size())
throw USER_EXCEPTION2(SE1003, "PPTypeswitch: number of cases must be equal to number of types");
}
PPTypeswitch::~PPTypeswitch()
{
delete source_child.op;
source_child.op = NULL;
for( int i = 0; i < cases.size(); i++)
{
delete (cases[i].op);
cases[i].op = NULL;
}
delete default_child.op;
default_child.op = NULL;
}
void PPTypeswitch::open ()
{
s = new sequence_tmp(source_child.ts);
source_child.op->open();
first_time = true;
eos_reached = false;
need_reopen = false;
effective_case = NULL;
for (int i = 0; i < var_dscs.size(); i++)
{
producer &p = cxt->producers[var_dscs[i]];
p.type = pt_lazy_simple;
p.op = this;
p.cvc = new complex_var_consumption;
p.tuple_pos = i;
}
for(int i = 0; i < cases.size(); i++)
(cases[i].op) -> open();
default_child.op->open();
}
void PPTypeswitch::reopen()
{
if(!eos_reached) source_child.op->reopen();
if(effective_case != NULL)
{
(effective_case->op) -> reopen();
effective_case = NULL;
}
eos_reached = false;
first_time = true;
need_reopen = false;
s->clear();
reinit_consumer_table();
}
void PPTypeswitch::close ()
{
source_child.op->close();
for( int i = 0; i < cases.size(); i++)
(cases[i].op) -> close();
default_child.op->close();
delete s;
}
void PPTypeswitch::next(tuple &t)
{
if (first_time)
{
if(need_reopen)
{
if(!eos_reached) source_child.op->reopen();
s->clear();
reinit_consumer_table();
need_reopen = false;
}
first_time = false;
eos_reached = false;
effective_case = &default_child;
for(int i = 0; i < cases.size(); i++)
{
if(type_matches(source_child, s, t, eos_reached, types[i]))
{
effective_case = &cases[i];
break;
}
}
}
(effective_case->op) -> next(t);
if(t.is_eos())
{
first_time = true;
need_reopen = true;
}
}
PPIterator* PPTypeswitch::copy(variable_context *_cxt_)
{
PPTypeswitch *res = new PPTypeswitch(_cxt_,
var_dscs,
source_child,
types,
cases,
default_child);
for (int i = 0; i < cases.size(); i++)
res->cases[i].op = cases[i].op->copy(_cxt_);
res->source_child.op = source_child.op->copy(_cxt_);
res->default_child.op = default_child.op->copy(_cxt_);
return res;
}
var_c_id PPTypeswitch::register_consumer(var_dsc dsc)
{
complex_var_consumption &cvc = *(cxt->producers[dsc].cvc);
cvc.push_back(0);
return cvc.size() - 1;
}
void PPTypeswitch::next(tuple &t, var_dsc dsc, var_c_id id)
{
producer &p = cxt->producers[dsc];
complex_var_consumption &cvc = *(p.cvc);
if (cvc[id] < s->size())
{
s->get(source, cvc[id]);
t.copy(source.cells[p.tuple_pos]);
cvc[id]++;
}
else
{
if (eos_reached)
{
t.set_eos();
cvc[id] = 0;
}
else
{
source_child.op->next(source);
if (source.is_eos())
{
eos_reached = true;
t.set_eos();
cvc[id] = 0;
}
else
{
s->add(source);
t.copy(source.cells[p.tuple_pos]);
cvc[id]++;
}
}
}
}
void PPTypeswitch::reopen(var_dsc dsc, var_c_id id)
{
cxt->producers[dsc].svc->at(id) = 0;
}
inline void PPTypeswitch::reinit_consumer_table()
{
for (int i = 0; i < var_dscs.size(); i++)
{
producer &p = cxt->producers[var_dscs[i]];
for (int j = 0; j < p.cvc->size(); j++) p.cvc->at(j) = 0;
}
}
bool PPTypeswitch::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPTypeswitch::result");
}
<commit_msg>castable empty bug fix<commit_after>/*
* File: PPSequenceTypes.cpp
* Copyright (C) 2006 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "sedna.h"
#include "PPSequenceTypes.h"
#include "PPUtils.h"
#include "casting_operations.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPCast
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPCast::PPCast(variable_context *_cxt_,
PPOpIn _child_,
xmlscm_type _target_type_,
bool _can_be_empty_seq_) : PPIterator(_cxt_),
child(_child_),
target_type(_target_type_),
can_be_empty_seq(_can_be_empty_seq_)
{
}
PPCast::~PPCast()
{
delete child.op;
child.op = NULL;
}
void PPCast::open ()
{
child.op->open();
first_time = true;
}
void PPCast::reopen()
{
child.op->reopen();
first_time = true;
}
void PPCast::close ()
{
child.op->close();
}
void PPCast::next (tuple &t)
{
if (first_time)
{
first_time = false;
child.op->next(t);
if (t.is_eos())
if (can_be_empty_seq)
{
first_time = true;
t.set_eos();
return;
}
else throw USER_EXCEPTION2(XP0006, "cast expression ('?' is not specified in target type but empty sequence is given)");
tuple_cell tc = atomize(child.get(t));
child.op->next(t);
if (!t.is_eos()) throw USER_EXCEPTION2(XP0006, "cast expression (the result of atomization is a sequence of more than one atomic value)");
t.copy(cast(tc, target_type));
}
else
{
first_time = true;
t.set_eos();
}
}
PPIterator* PPCast::copy(variable_context *_cxt_)
{
PPCast *res = new PPCast(_cxt_, child, target_type, can_be_empty_seq);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPCast::result(PPIterator* cur, variable_context *cxt, void*& r)
{
PPOpIn child;
((PPCast*)cur)->children(child);
void *child_r;
bool child_s = (child.op->res_fun())(child.op, cxt, child_r);
if (!child_s) // if expression is not strict
{ // create PPCast and transmit state
child.op = (PPIterator*)child_r;
PPCast *res_op = new PPCast(cxt, child,
((PPCast*)cur)->target_type,
((PPCast*)cur)->can_be_empty_seq);
r = res_op;
return false;
}
sequence *child_seq = (sequence*)child_r;
if (child_seq->size() == 0)
if (((PPCast*)cur)->can_be_empty_seq)
{
r = child_seq;
return true;
}
else throw USER_EXCEPTION2(XP0006, "cast expression ('?' is not specified in target type but empty sequence is given)");
if (child_seq->size() != 1) throw USER_EXCEPTION2(XP0006, "cast expression (the result of atomization is a sequence of more than one atomic value)");
tuple t(1);
child_seq->get(t, child_seq->begin());
t.cells[0] = cast(atomize(t.cells[0]), ((PPCast*)cur)->target_type);
child_seq->clear();
child_seq->add(t);
r = child_seq;
return true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPCastable
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPCastable::PPCastable(variable_context *_cxt_,
PPOpIn _child_,
xmlscm_type _target_type_,
bool _can_be_empty_seq_) : PPIterator(_cxt_),
child(_child_),
target_type(_target_type_),
can_be_empty_seq(_can_be_empty_seq_)
{
}
PPCastable::~PPCastable()
{
delete child.op;
child.op = NULL;
}
void PPCastable::open ()
{
child.op->open();
first_time = true;
}
void PPCastable::reopen()
{
child.op->reopen();
first_time = true;
}
void PPCastable::close ()
{
child.op->close();
}
void PPCastable::next (tuple &t)
{
bool res;
if (first_time)
{
first_time = false;
child.op->next(t);
if (t.is_eos())
{
if (can_be_empty_seq) res = true;
else res = false; //cast expression ('?' is not specified in target type but empty sequence is given)
}
else
{
tuple_cell tc = atomize(child.get(t));
child.op->next(t);
if (!t.is_eos()) res = false; //cast expression (the result of atomization is a sequence of more than one atomic value)
else res = is_castable(tc, target_type);
}
t.copy(tuple_cell::atomic(res));
}
else
{
first_time = true;
t.set_eos();
}
}
PPIterator* PPCastable::copy(variable_context *_cxt_)
{
PPCastable *res = new PPCastable(_cxt_, child, target_type, can_be_empty_seq);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPCastable::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPCastable::result");
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPInstanceOf
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPInstanceOf::PPInstanceOf(variable_context *_cxt_,
PPOpIn _child_,
const sequence_type& _st_) : PPIterator(_cxt_),
child(_child_),
st(_st_)
{
}
PPInstanceOf::~PPInstanceOf()
{
delete child.op;
child.op = NULL;
}
void PPInstanceOf::open ()
{
child.op->open();
first_time = true;
eos_reached = true;
}
void PPInstanceOf::reopen()
{
child.op->reopen();
first_time = true;
eos_reached = true;
}
void PPInstanceOf::close ()
{
child.op->close();
}
bool type_matches(const PPOpIn &child, tuple &t, bool &eos_reached, const sequence_type& st);
void PPInstanceOf::next (tuple &t)
{
if (first_time)
{
first_time = false;
if (!eos_reached) child.op->reopen();
bool res = type_matches(child, t, eos_reached, st);
t.copy(tuple_cell::atomic(res));
}
else
{
first_time = true;
t.set_eos();
}
}
PPIterator* PPInstanceOf::copy(variable_context *_cxt_)
{
PPInstanceOf *res = new PPInstanceOf(_cxt_, child, st);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPInstanceOf::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPInstanceOf::result");
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPTreat
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPTreat::PPTreat(variable_context *_cxt_,
PPOpIn _child_,
const sequence_type& _st_) : PPIterator(_cxt_),
child(_child_),
st(_st_)
{
}
PPTreat::~PPTreat()
{
delete child.op;
child.op = NULL;
}
void PPTreat::open ()
{
child.op->open();
first_time = true;
eos_reached = true;
s = new sequence(child.ts);
pos = 0;
}
void PPTreat::reopen()
{
child.op->reopen();
first_time = true;
eos_reached = true;
pos = 0;
s->clear();
}
void PPTreat::close ()
{
child.op->close();
}
void PPTreat::next(tuple &t)
{
if (first_time)
{
first_time = false;
if (!eos_reached) child.op->reopen();
bool res = type_matches(child, s, t, eos_reached, st);
//!!! FIXME: error code must be XPDY0050 there
if(res == false) throw USER_EXCEPTION(XP0050);
}
if(pos < s->size())
{
s->get(t, pos++);
return;
}
else if(!eos_reached)
{
child.op->next(t);
if(t.is_eos()) eos_reached = true;
else return;
}
t.set_eos();
first_time = true;
s->clear();
pos=0;
}
PPIterator* PPTreat::copy(variable_context *_cxt_)
{
PPTreat *res = new PPTreat(_cxt_, child, st);
res->child.op = child.op->copy(_cxt_);
return res;
}
bool PPTreat::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPTreat::result");
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// PPTypeswitch
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
PPTypeswitch::PPTypeswitch(variable_context *_cxt_,
arr_of_var_dsc _var_dscs_,
PPOpIn _source_child_,
const arr_of_sequence_type& _types_,
arr_of_PPOpIn _cases_,
PPOpIn _default_child_): PPVarIterator(_cxt_),
var_dscs(_var_dscs_),
source_child(_source_child_),
types(_types_),
cases(_cases_),
default_child(_default_child_)
{
if(cases.size() != types.size())
throw USER_EXCEPTION2(SE1003, "PPTypeswitch: number of cases must be equal to number of types");
}
PPTypeswitch::~PPTypeswitch()
{
delete source_child.op;
source_child.op = NULL;
for( int i = 0; i < cases.size(); i++)
{
delete (cases[i].op);
cases[i].op = NULL;
}
delete default_child.op;
default_child.op = NULL;
}
void PPTypeswitch::open ()
{
s = new sequence_tmp(source_child.ts);
source_child.op->open();
first_time = true;
eos_reached = false;
need_reopen = false;
effective_case = NULL;
for (int i = 0; i < var_dscs.size(); i++)
{
producer &p = cxt->producers[var_dscs[i]];
p.type = pt_lazy_simple;
p.op = this;
p.cvc = new complex_var_consumption;
p.tuple_pos = i;
}
for(int i = 0; i < cases.size(); i++)
(cases[i].op) -> open();
default_child.op->open();
}
void PPTypeswitch::reopen()
{
if(!eos_reached) source_child.op->reopen();
if(effective_case != NULL)
{
(effective_case->op) -> reopen();
effective_case = NULL;
}
eos_reached = false;
first_time = true;
need_reopen = false;
s->clear();
reinit_consumer_table();
}
void PPTypeswitch::close ()
{
source_child.op->close();
for( int i = 0; i < cases.size(); i++)
(cases[i].op) -> close();
default_child.op->close();
delete s;
}
void PPTypeswitch::next(tuple &t)
{
if (first_time)
{
if(need_reopen)
{
if(!eos_reached) source_child.op->reopen();
s->clear();
reinit_consumer_table();
need_reopen = false;
}
first_time = false;
eos_reached = false;
effective_case = &default_child;
for(int i = 0; i < cases.size(); i++)
{
if(type_matches(source_child, s, t, eos_reached, types[i]))
{
effective_case = &cases[i];
break;
}
}
}
(effective_case->op) -> next(t);
if(t.is_eos())
{
first_time = true;
need_reopen = true;
}
}
PPIterator* PPTypeswitch::copy(variable_context *_cxt_)
{
PPTypeswitch *res = new PPTypeswitch(_cxt_,
var_dscs,
source_child,
types,
cases,
default_child);
for (int i = 0; i < cases.size(); i++)
res->cases[i].op = cases[i].op->copy(_cxt_);
res->source_child.op = source_child.op->copy(_cxt_);
res->default_child.op = default_child.op->copy(_cxt_);
return res;
}
var_c_id PPTypeswitch::register_consumer(var_dsc dsc)
{
complex_var_consumption &cvc = *(cxt->producers[dsc].cvc);
cvc.push_back(0);
return cvc.size() - 1;
}
void PPTypeswitch::next(tuple &t, var_dsc dsc, var_c_id id)
{
producer &p = cxt->producers[dsc];
complex_var_consumption &cvc = *(p.cvc);
if (cvc[id] < s->size())
{
s->get(source, cvc[id]);
t.copy(source.cells[p.tuple_pos]);
cvc[id]++;
}
else
{
if (eos_reached)
{
t.set_eos();
cvc[id] = 0;
}
else
{
source_child.op->next(source);
if (source.is_eos())
{
eos_reached = true;
t.set_eos();
cvc[id] = 0;
}
else
{
s->add(source);
t.copy(source.cells[p.tuple_pos]);
cvc[id]++;
}
}
}
}
void PPTypeswitch::reopen(var_dsc dsc, var_c_id id)
{
cxt->producers[dsc].svc->at(id) = 0;
}
inline void PPTypeswitch::reinit_consumer_table()
{
for (int i = 0; i < var_dscs.size(); i++)
{
producer &p = cxt->producers[var_dscs[i]];
for (int j = 0; j < p.cvc->size(); j++) p.cvc->at(j) = 0;
}
}
bool PPTypeswitch::result(PPIterator* cur, variable_context *cxt, void*& r)
{
throw USER_EXCEPTION2(SE1002, "PPTypeswitch::result");
}
<|endoftext|> |
<commit_before>//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Link Time Optimization library. This library is
// intended to be used by linker to optimize code at link time.
//
//===----------------------------------------------------------------------===//
#include "LTOCodeGenerator.h"
#include "LTOModule.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Linker.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Config/config.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/system_error.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;
static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
cl::desc("Do not run the inliner pass"));
static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
cl::desc("Do not run the GVN load PRE pass"));
const char* LTOCodeGenerator::getVersionString() {
#ifdef LLVM_VERSION_INFO
return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
#else
return PACKAGE_NAME " version " PACKAGE_VERSION;
#endif
}
LTOCodeGenerator::LTOCodeGenerator()
: _context(getGlobalContext()),
_linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
_emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
_codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
_nativeObjectFile(NULL) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
}
LTOCodeGenerator::~LTOCodeGenerator() {
delete _target;
delete _nativeObjectFile;
for (std::vector<char*>::iterator I = _codegenOptions.begin(),
E = _codegenOptions.end(); I != E; ++I)
free(*I);
}
bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
for (int i = 0, e = undefs.size(); i != e; ++i)
_asmUndefinedRefs[undefs[i]] = 1;
return ret;
}
bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
std::string& errMsg) {
switch (debug) {
case LTO_DEBUG_MODEL_NONE:
_emitDwarfDebugInfo = false;
return false;
case LTO_DEBUG_MODEL_DWARF:
_emitDwarfDebugInfo = true;
return false;
}
llvm_unreachable("Unknown debug format!");
}
bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
std::string& errMsg) {
switch (model) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
_codeModel = model;
return false;
}
llvm_unreachable("Unknown PIC model!");
}
bool LTOCodeGenerator::writeMergedModules(const char *path,
std::string &errMsg) {
if (determineTarget(errMsg))
return true;
// mark which symbols can not be internalized
applyScopeRestrictions();
// create output file
std::string ErrInfo;
tool_output_file Out(path, ErrInfo,
raw_fd_ostream::F_Binary);
if (!ErrInfo.empty()) {
errMsg = "could not open bitcode file for writing: ";
errMsg += path;
return true;
}
// write bitcode to it
WriteBitcodeToFile(_linker.getModule(), Out.os());
Out.os().close();
if (Out.os().has_error()) {
errMsg = "could not write bitcode file: ";
errMsg += path;
Out.os().clear_error();
return true;
}
Out.keep();
return false;
}
bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
// make unique temp .o file to put generated object file
sys::PathWithStatus uniqueObjPath("lto-llvm.o");
if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
uniqueObjPath.eraseFromDisk();
return true;
}
sys::RemoveFileOnSignal(uniqueObjPath);
// generate object file
bool genResult = false;
tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
if (!errMsg.empty())
return true;
genResult = this->generateObjectFile(objFile.os(), errMsg);
objFile.os().close();
if (objFile.os().has_error()) {
objFile.os().clear_error();
return true;
}
objFile.keep();
if ( genResult ) {
uniqueObjPath.eraseFromDisk();
return true;
}
_nativeObjectPath = uniqueObjPath.str();
*name = _nativeObjectPath.c_str();
return false;
}
const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
const char *name;
if (compile_to_file(&name, errMsg))
return NULL;
// remove old buffer if compile() called twice
delete _nativeObjectFile;
// read .o file into memory buffer
OwningPtr<MemoryBuffer> BuffPtr;
if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
errMsg = ec.message();
return NULL;
}
_nativeObjectFile = BuffPtr.take();
// remove temp files
sys::Path(_nativeObjectPath).eraseFromDisk();
// return buffer, unless error
if ( _nativeObjectFile == NULL )
return NULL;
*length = _nativeObjectFile->getBufferSize();
return _nativeObjectFile->getBufferStart();
}
bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
if ( _target == NULL ) {
std::string Triple = _linker.getModule()->getTargetTriple();
if (Triple.empty())
Triple = sys::getDefaultTargetTriple();
// create target machine from info for merged modules
const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
if ( march == NULL )
return true;
// The relocation model is actually a static member of TargetMachine and
// needs to be set before the TargetMachine is instantiated.
Reloc::Model RelocModel = Reloc::Default;
switch( _codeModel ) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
RelocModel = Reloc::Static;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
RelocModel = Reloc::PIC_;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
RelocModel = Reloc::DynamicNoPIC;
break;
}
// construct LTOModule, hand over ownership of module and target
SubtargetFeatures Features;
Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
std::string FeatureStr = Features.getString();
TargetOptions Options;
_target = march->createTargetMachine(Triple, _mCpu, FeatureStr, Options,
RelocModel);
}
return false;
}
void LTOCodeGenerator::
applyRestriction(GlobalValue &GV,
std::vector<const char*> &mustPreserveList,
SmallPtrSet<GlobalValue*, 8> &asmUsed,
Mangler &mangler) {
SmallString<64> Buffer;
mangler.getNameWithPrefix(Buffer, &GV, false);
if (GV.isDeclaration())
return;
if (_mustPreserveSymbols.count(Buffer))
mustPreserveList.push_back(GV.getName().data());
if (_asmUndefinedRefs.count(Buffer))
asmUsed.insert(&GV);
}
static void findUsedValues(GlobalVariable *LLVMUsed,
SmallPtrSet<GlobalValue*, 8> &UsedValues) {
if (LLVMUsed == 0) return;
ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
if (Inits == 0) return;
for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
if (GlobalValue *GV =
dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
UsedValues.insert(GV);
}
void LTOCodeGenerator::applyScopeRestrictions() {
if (_scopeRestrictionsDone) return;
Module *mergedModule = _linker.getModule();
// Start off with a verification pass.
PassManager passes;
passes.add(createVerifierPass());
// mark which symbols can not be internalized
MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
Mangler mangler(Context, *_target->getTargetData());
std::vector<const char*> mustPreserveList;
SmallPtrSet<GlobalValue*, 8> asmUsed;
for (Module::iterator f = mergedModule->begin(),
e = mergedModule->end(); f != e; ++f)
applyRestriction(*f, mustPreserveList, asmUsed, mangler);
for (Module::global_iterator v = mergedModule->global_begin(),
e = mergedModule->global_end(); v != e; ++v)
applyRestriction(*v, mustPreserveList, asmUsed, mangler);
for (Module::alias_iterator a = mergedModule->alias_begin(),
e = mergedModule->alias_end(); a != e; ++a)
applyRestriction(*a, mustPreserveList, asmUsed, mangler);
GlobalVariable *LLVMCompilerUsed =
mergedModule->getGlobalVariable("llvm.compiler.used");
findUsedValues(LLVMCompilerUsed, asmUsed);
if (LLVMCompilerUsed)
LLVMCompilerUsed->eraseFromParent();
llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
std::vector<Constant*> asmUsed2;
for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
e = asmUsed.end(); i !=e; ++i) {
GlobalValue *GV = *i;
Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
asmUsed2.push_back(c);
}
llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
LLVMCompilerUsed =
new llvm::GlobalVariable(*mergedModule, ATy, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, asmUsed2),
"llvm.compiler.used");
LLVMCompilerUsed->setSection("llvm.metadata");
passes.add(createInternalizePass(mustPreserveList));
// apply scope restrictions
passes.run(*mergedModule);
_scopeRestrictionsDone = true;
}
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
std::string &errMsg) {
if ( this->determineTarget(errMsg) )
return true;
Module* mergedModule = _linker.getModule();
// if options were requested, set them
if ( !_codegenOptions.empty() )
cl::ParseCommandLineOptions(_codegenOptions.size(),
const_cast<char **>(&_codegenOptions[0]));
// mark which symbols can not be internalized
this->applyScopeRestrictions();
// Instantiate the pass manager to organize the passes.
PassManager passes;
// Start off with a verification pass.
passes.add(createVerifierPass());
// Add an appropriate TargetData instance for this module...
passes.add(new TargetData(*_target->getTargetData()));
// Enabling internalize here would use its AllButMain variant. It
// keeps only main if it exists and does nothing for libraries. Instead
// we create the pass ourselves with the symbol list provided by the linker.
PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/false,
!DisableInline,
DisableGVNLoadPRE);
// Make sure everything is still good.
passes.add(createVerifierPass());
FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
codeGenPasses->add(new TargetData(*_target->getTargetData()));
formatted_raw_ostream Out(out);
if (_target->addPassesToEmitFile(*codeGenPasses, Out,
TargetMachine::CGFT_ObjectFile,
CodeGenOpt::Aggressive)) {
errMsg = "target file type not supported";
return true;
}
// Run our queue of passes all at once now, efficiently.
passes.run(*mergedModule);
// Run the code generator, and write assembly file
codeGenPasses->doInitialization();
for (Module::iterator
it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
if (!it->isDeclaration())
codeGenPasses->run(*it);
codeGenPasses->doFinalization();
delete codeGenPasses;
return false; // success
}
/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
/// LTO problems.
void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
for (std::pair<StringRef, StringRef> o = getToken(options);
!o.first.empty(); o = getToken(o.second)) {
// ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
// that.
if ( _codegenOptions.empty() )
_codegenOptions.push_back(strdup("libLTO"));
_codegenOptions.push_back(strdup(o.first.str().c_str()));
}
}
<commit_msg>Reinstate -O3 for LTO.<commit_after>//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Link Time Optimization library. This library is
// intended to be used by linker to optimize code at link time.
//
//===----------------------------------------------------------------------===//
#include "LTOCodeGenerator.h"
#include "LTOModule.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Linker.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Config/config.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/system_error.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;
static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
cl::desc("Do not run the inliner pass"));
static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
cl::desc("Do not run the GVN load PRE pass"));
const char* LTOCodeGenerator::getVersionString() {
#ifdef LLVM_VERSION_INFO
return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
#else
return PACKAGE_NAME " version " PACKAGE_VERSION;
#endif
}
LTOCodeGenerator::LTOCodeGenerator()
: _context(getGlobalContext()),
_linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
_emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
_codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
_nativeObjectFile(NULL) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
}
LTOCodeGenerator::~LTOCodeGenerator() {
delete _target;
delete _nativeObjectFile;
for (std::vector<char*>::iterator I = _codegenOptions.begin(),
E = _codegenOptions.end(); I != E; ++I)
free(*I);
}
bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
for (int i = 0, e = undefs.size(); i != e; ++i)
_asmUndefinedRefs[undefs[i]] = 1;
return ret;
}
bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
std::string& errMsg) {
switch (debug) {
case LTO_DEBUG_MODEL_NONE:
_emitDwarfDebugInfo = false;
return false;
case LTO_DEBUG_MODEL_DWARF:
_emitDwarfDebugInfo = true;
return false;
}
llvm_unreachable("Unknown debug format!");
}
bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
std::string& errMsg) {
switch (model) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
_codeModel = model;
return false;
}
llvm_unreachable("Unknown PIC model!");
}
bool LTOCodeGenerator::writeMergedModules(const char *path,
std::string &errMsg) {
if (determineTarget(errMsg))
return true;
// mark which symbols can not be internalized
applyScopeRestrictions();
// create output file
std::string ErrInfo;
tool_output_file Out(path, ErrInfo,
raw_fd_ostream::F_Binary);
if (!ErrInfo.empty()) {
errMsg = "could not open bitcode file for writing: ";
errMsg += path;
return true;
}
// write bitcode to it
WriteBitcodeToFile(_linker.getModule(), Out.os());
Out.os().close();
if (Out.os().has_error()) {
errMsg = "could not write bitcode file: ";
errMsg += path;
Out.os().clear_error();
return true;
}
Out.keep();
return false;
}
bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
// make unique temp .o file to put generated object file
sys::PathWithStatus uniqueObjPath("lto-llvm.o");
if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
uniqueObjPath.eraseFromDisk();
return true;
}
sys::RemoveFileOnSignal(uniqueObjPath);
// generate object file
bool genResult = false;
tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
if (!errMsg.empty())
return true;
genResult = this->generateObjectFile(objFile.os(), errMsg);
objFile.os().close();
if (objFile.os().has_error()) {
objFile.os().clear_error();
return true;
}
objFile.keep();
if ( genResult ) {
uniqueObjPath.eraseFromDisk();
return true;
}
_nativeObjectPath = uniqueObjPath.str();
*name = _nativeObjectPath.c_str();
return false;
}
const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
const char *name;
if (compile_to_file(&name, errMsg))
return NULL;
// remove old buffer if compile() called twice
delete _nativeObjectFile;
// read .o file into memory buffer
OwningPtr<MemoryBuffer> BuffPtr;
if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
errMsg = ec.message();
return NULL;
}
_nativeObjectFile = BuffPtr.take();
// remove temp files
sys::Path(_nativeObjectPath).eraseFromDisk();
// return buffer, unless error
if ( _nativeObjectFile == NULL )
return NULL;
*length = _nativeObjectFile->getBufferSize();
return _nativeObjectFile->getBufferStart();
}
bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
if ( _target == NULL ) {
std::string Triple = _linker.getModule()->getTargetTriple();
if (Triple.empty())
Triple = sys::getDefaultTargetTriple();
// create target machine from info for merged modules
const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
if ( march == NULL )
return true;
// The relocation model is actually a static member of TargetMachine and
// needs to be set before the TargetMachine is instantiated.
Reloc::Model RelocModel = Reloc::Default;
switch( _codeModel ) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
RelocModel = Reloc::Static;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
RelocModel = Reloc::PIC_;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
RelocModel = Reloc::DynamicNoPIC;
break;
}
// construct LTOModule, hand over ownership of module and target
SubtargetFeatures Features;
Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
std::string FeatureStr = Features.getString();
TargetOptions Options;
_target = march->createTargetMachine(Triple, _mCpu, FeatureStr, Options,
RelocModel, CodeModel::Default,
CodeGenOpt::Aggressive);
}
return false;
}
void LTOCodeGenerator::
applyRestriction(GlobalValue &GV,
std::vector<const char*> &mustPreserveList,
SmallPtrSet<GlobalValue*, 8> &asmUsed,
Mangler &mangler) {
SmallString<64> Buffer;
mangler.getNameWithPrefix(Buffer, &GV, false);
if (GV.isDeclaration())
return;
if (_mustPreserveSymbols.count(Buffer))
mustPreserveList.push_back(GV.getName().data());
if (_asmUndefinedRefs.count(Buffer))
asmUsed.insert(&GV);
}
static void findUsedValues(GlobalVariable *LLVMUsed,
SmallPtrSet<GlobalValue*, 8> &UsedValues) {
if (LLVMUsed == 0) return;
ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
if (Inits == 0) return;
for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
if (GlobalValue *GV =
dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
UsedValues.insert(GV);
}
void LTOCodeGenerator::applyScopeRestrictions() {
if (_scopeRestrictionsDone) return;
Module *mergedModule = _linker.getModule();
// Start off with a verification pass.
PassManager passes;
passes.add(createVerifierPass());
// mark which symbols can not be internalized
MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
Mangler mangler(Context, *_target->getTargetData());
std::vector<const char*> mustPreserveList;
SmallPtrSet<GlobalValue*, 8> asmUsed;
for (Module::iterator f = mergedModule->begin(),
e = mergedModule->end(); f != e; ++f)
applyRestriction(*f, mustPreserveList, asmUsed, mangler);
for (Module::global_iterator v = mergedModule->global_begin(),
e = mergedModule->global_end(); v != e; ++v)
applyRestriction(*v, mustPreserveList, asmUsed, mangler);
for (Module::alias_iterator a = mergedModule->alias_begin(),
e = mergedModule->alias_end(); a != e; ++a)
applyRestriction(*a, mustPreserveList, asmUsed, mangler);
GlobalVariable *LLVMCompilerUsed =
mergedModule->getGlobalVariable("llvm.compiler.used");
findUsedValues(LLVMCompilerUsed, asmUsed);
if (LLVMCompilerUsed)
LLVMCompilerUsed->eraseFromParent();
llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
std::vector<Constant*> asmUsed2;
for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
e = asmUsed.end(); i !=e; ++i) {
GlobalValue *GV = *i;
Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
asmUsed2.push_back(c);
}
llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
LLVMCompilerUsed =
new llvm::GlobalVariable(*mergedModule, ATy, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, asmUsed2),
"llvm.compiler.used");
LLVMCompilerUsed->setSection("llvm.metadata");
passes.add(createInternalizePass(mustPreserveList));
// apply scope restrictions
passes.run(*mergedModule);
_scopeRestrictionsDone = true;
}
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
std::string &errMsg) {
if ( this->determineTarget(errMsg) )
return true;
Module* mergedModule = _linker.getModule();
// if options were requested, set them
if ( !_codegenOptions.empty() )
cl::ParseCommandLineOptions(_codegenOptions.size(),
const_cast<char **>(&_codegenOptions[0]));
// mark which symbols can not be internalized
this->applyScopeRestrictions();
// Instantiate the pass manager to organize the passes.
PassManager passes;
// Start off with a verification pass.
passes.add(createVerifierPass());
// Add an appropriate TargetData instance for this module...
passes.add(new TargetData(*_target->getTargetData()));
// Enabling internalize here would use its AllButMain variant. It
// keeps only main if it exists and does nothing for libraries. Instead
// we create the pass ourselves with the symbol list provided by the linker.
PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/false,
!DisableInline,
DisableGVNLoadPRE);
// Make sure everything is still good.
passes.add(createVerifierPass());
FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
codeGenPasses->add(new TargetData(*_target->getTargetData()));
formatted_raw_ostream Out(out);
if (_target->addPassesToEmitFile(*codeGenPasses, Out,
TargetMachine::CGFT_ObjectFile)) {
errMsg = "target file type not supported";
return true;
}
// Run our queue of passes all at once now, efficiently.
passes.run(*mergedModule);
// Run the code generator, and write assembly file
codeGenPasses->doInitialization();
for (Module::iterator
it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
if (!it->isDeclaration())
codeGenPasses->run(*it);
codeGenPasses->doFinalization();
delete codeGenPasses;
return false; // success
}
/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
/// LTO problems.
void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
for (std::pair<StringRef, StringRef> o = getToken(options);
!o.first.empty(); o = getToken(o.second)) {
// ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
// that.
if ( _codegenOptions.empty() )
_codegenOptions.push_back(strdup("libLTO"));
_codegenOptions.push_back(strdup(o.first.str().c_str()));
}
}
<|endoftext|> |
<commit_before>// Copyright 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <iomanip>
#include "base/safe_strerror_posix.h"
#if defined(OS_MACOSX)
#include <mach/mach.h>
#include "base/mac/scoped_mach_port.h"
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#endif
namespace logging {
namespace {
const char* const log_severity_names[] = {
"INFO",
"WARNING",
"ERROR",
"ERROR_REPORT",
"FATAL"
};
} // namespace
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity)
: severity_(severity) {
Init(function, file_path, line);
}
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
std::string* result)
: severity_(LOG_FATAL) {
Init(function, file_path, line);
stream_ << "Check failed: " << *result << ". ";
delete result;
}
LogMessage::~LogMessage() {
stream_ << std::endl;
std::string str_newline(stream_.str());
fprintf(stderr, "%s", str_newline.c_str());
fflush(stderr);
if (severity_ == LOG_FATAL) {
#ifndef NDEBUG
abort();
#else
__asm__("int3");
#endif
}
}
void LogMessage::Init(const char* function,
const std::string& file_path,
int line) {
std::string file_name;
size_t last_slash = file_path.find_last_of('/');
if (last_slash != std::string::npos) {
file_name.assign(file_path.substr(last_slash + 1));
} else {
file_name.assign(file_path);
}
pid_t pid = getpid();
#if defined(OS_MACOSX)
base::mac::ScopedMachPort thread(mach_thread_self());
#elif defined(OS_LINUX)
pid_t thread = syscall(__NR_gettid);
#endif
struct timeval tv;
gettimeofday(&tv, NULL);
struct tm local_time;
localtime_r(&tv.tv_sec, &local_time);
stream_ << '['
<< pid
<< ':'
<< thread
<< ':'
<< std::setfill('0')
<< std::setw(4) << local_time.tm_year + 1900
<< std::setw(2) << local_time.tm_mon + 1
<< std::setw(2) << local_time.tm_mday
<< ','
<< std::setw(2) << local_time.tm_hour
<< std::setw(2) << local_time.tm_min
<< std::setw(2) << local_time.tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec
<< ':';
if (severity_ >= 0) {
stream_ << log_severity_names[severity_];
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ' '
<< file_name
<< ':'
<< line
<< "] ";
}
ErrnoLogMessage::ErrnoLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
int err)
: LogMessage(function, file_path, line, severity),
err_(err) {
}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": "
<< safe_strerror(err_)
<< " ("
<< err_
<< ")";
}
} // namespace logging
<commit_msg>Change mac logging.cc from mach_thread_self() to pthread_mach_thread_np(pthread_self()) to avoid needing to manage the Mach port reference.<commit_after>// Copyright 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <iomanip>
#include "base/safe_strerror_posix.h"
#if defined(OS_MACOSX)
#include <mach/mach.h>
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#endif
namespace logging {
namespace {
const char* const log_severity_names[] = {
"INFO",
"WARNING",
"ERROR",
"ERROR_REPORT",
"FATAL"
};
} // namespace
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity)
: severity_(severity) {
Init(function, file_path, line);
}
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
std::string* result)
: severity_(LOG_FATAL) {
Init(function, file_path, line);
stream_ << "Check failed: " << *result << ". ";
delete result;
}
LogMessage::~LogMessage() {
stream_ << std::endl;
std::string str_newline(stream_.str());
fprintf(stderr, "%s", str_newline.c_str());
fflush(stderr);
if (severity_ == LOG_FATAL) {
#ifndef NDEBUG
abort();
#else
__asm__("int3");
#endif
}
}
void LogMessage::Init(const char* function,
const std::string& file_path,
int line) {
std::string file_name;
size_t last_slash = file_path.find_last_of('/');
if (last_slash != std::string::npos) {
file_name.assign(file_path.substr(last_slash + 1));
} else {
file_name.assign(file_path);
}
pid_t pid = getpid();
#if defined(OS_MACOSX)
mach_port_t thread = pthread_mach_thread_np(pthread_self());
#elif defined(OS_LINUX)
pid_t thread = syscall(__NR_gettid);
#endif
struct timeval tv;
gettimeofday(&tv, NULL);
struct tm local_time;
localtime_r(&tv.tv_sec, &local_time);
stream_ << '['
<< pid
<< ':'
<< thread
<< ':'
<< std::setfill('0')
<< std::setw(4) << local_time.tm_year + 1900
<< std::setw(2) << local_time.tm_mon + 1
<< std::setw(2) << local_time.tm_mday
<< ','
<< std::setw(2) << local_time.tm_hour
<< std::setw(2) << local_time.tm_min
<< std::setw(2) << local_time.tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec
<< ':';
if (severity_ >= 0) {
stream_ << log_severity_names[severity_];
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ' '
<< file_name
<< ':'
<< line
<< "] ";
}
ErrnoLogMessage::ErrnoLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
int err)
: LogMessage(function, file_path, line, severity),
err_(err) {
}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": "
<< safe_strerror(err_)
<< " ("
<< err_
<< ")";
}
} // namespace logging
<|endoftext|> |
<commit_before>// Time: O(nlogn)
// Space: O(n)
// Divide and Conquer.
class Solution {
public:
enum {start, end, height};
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size()));
vector<pair<int, int>> res;
int last_end = -1;
for (const auto& interval : intervals) {
if (last_end != -1 && last_end < interval[start]) {
res.emplace_back(last_end, 0);
}
res.emplace_back(interval[start], interval[height]);
last_end = interval[end];
}
if (last_end != -1) {
res.emplace_back(last_end, 0);
}
return res;
}
// Divide and Conquer.
vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings,
int left_endpoint, int right_endpoint) {
if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it.
return {buildings.cbegin() + left_endpoint,
buildings.cbegin() + right_endpoint};
}
int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2);
auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid));
auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint));
return MergeSkylines(left_skyline, right_skyline);
}
// Merge Sort
vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) {
int i = 0, j = 0;
vector<vector<int>> merged;
while (i < left_skyline.size() && j < right_skyline.size()) {
if (left_skyline[i][end] < right_skyline[j][start]) {
merged.emplace_back(move(left_skyline[i++]));
} else if (right_skyline[j][end] < left_skyline[i][start]) {
merged.emplace_back(move(right_skyline[j++]));
} else if (left_skyline[i][start] <= right_skyline[j][start]) {
MergeIntersectSkylines(merged, left_skyline[i], i,
right_skyline[j], j);
} else { // left_skyline[i][start] > right_skyline[j][start].
MergeIntersectSkylines(merged, right_skyline[j], j,
left_skyline[i], i);
}
}
// Insert the remaining skylines.
merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end());
merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end());
return merged;
}
// a[start] <= b[start]
void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx,
vector<int>& b, int& b_idx) {
if (a[end] <= b[end]) {
if (a[height] > b[height]) { // |aaa|
if (b[end] != a[end]) { // |abb|b
b[start] = a[end];
merged.emplace_back(move(a)), ++a_idx;
} else { // aaa
++b_idx; // abb
}
} else if (a[height] == b[height]) { // abb
b[start] = a[start], ++a_idx; // abb
} else { // a[height] < b[height].
if (a[start] != b[start]) { // bb
merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); // |a|bb
}
++a_idx;
}
} else { // a[end] > b[end].
if (a[height] >= b[height]) { // aaaa
++b_idx; // abba
} else {
// |bb|
// |a||bb|a
if (a[start] != b[start]) {
merged.emplace_back(move(vector<int>{a[start], b[start], a[height]}));
}
a[start] = b[end];
merged.emplace_back(move(b)), ++b_idx;
}
}
}
};
// Time: O(nlogn)
// Space: O(n)
// BST Solution.
class Solution2 {
public:
vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) {
unordered_map<int, vector<int>> start_point_to_heights;
unordered_map<int, vector<int>> end_point_to_heights;
set<int> points;
for (int i = 0; i < buildings.size(); ++i) {
start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]);
end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]);
points.emplace(buildings[i][0]);
points.emplace(buildings[i][1]);
}
vector<pair<int, int>> res;
map<int, int> height_to_count;
int curr_max = 0;
// Enumerate each point in increasing order.
for (auto it = points.begin(); it != points.end(); ++it) {
vector<int> start_point_heights = start_point_to_heights[*it];
vector<int> end_point_heights = end_point_to_heights[*it];
for (int i = 0; i < start_point_heights.size(); ++i) {
++height_to_count[start_point_heights[i]];
}
for (int i = 0; i < end_point_heights.size(); ++i) {
--height_to_count[end_point_heights[i]];
if (height_to_count[end_point_heights[i]] == 0) {
height_to_count.erase(end_point_heights[i]);
}
}
if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) {
curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first;
res.emplace_back(*it, curr_max);
}
}
return res;
}
};
<commit_msg>Update the-skyline-problem.cpp<commit_after>// Time: O(nlogn)
// Space: O(n)
// BST solution.
class Solution {
public:
vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) {
unordered_map<int, vector<int>> start_point_to_heights;
unordered_map<int, vector<int>> end_point_to_heights;
set<int> points;
for (int i = 0; i < buildings.size(); ++i) {
start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]);
end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]);
points.emplace(buildings[i][0]);
points.emplace(buildings[i][1]);
}
vector<pair<int, int>> res;
map<int, int> height_to_count;
int curr_max = 0;
// Enumerate each point in increasing order.
for (auto it = points.begin(); it != points.end(); ++it) {
vector<int> start_point_heights = start_point_to_heights[*it];
vector<int> end_point_heights = end_point_to_heights[*it];
for (int i = 0; i < start_point_heights.size(); ++i) {
++height_to_count[start_point_heights[i]];
}
for (int i = 0; i < end_point_heights.size(); ++i) {
--height_to_count[end_point_heights[i]];
if (height_to_count[end_point_heights[i]] == 0) {
height_to_count.erase(end_point_heights[i]);
}
}
if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) {
curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first;
res.emplace_back(*it, curr_max);
}
}
return res;
}
};
// Time: O(nlogn)
// Space: O(n)
// Divide and conquer solution.
class Solution {
public:
enum {start, end, height};
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
const auto intervals = move(ComputeSkylineInInterval(buildings, 0, buildings.size()));
vector<pair<int, int>> res;
int last_end = -1;
for (const auto& interval : intervals) {
if (last_end != -1 && last_end < interval[start]) {
res.emplace_back(last_end, 0);
}
res.emplace_back(interval[start], interval[height]);
last_end = interval[end];
}
if (last_end != -1) {
res.emplace_back(last_end, 0);
}
return res;
}
// Divide and Conquer.
vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings,
int left_endpoint, int right_endpoint) {
if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it.
return {buildings.cbegin() + left_endpoint,
buildings.cbegin() + right_endpoint};
}
int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2);
auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid));
auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint));
return MergeSkylines(left_skyline, right_skyline);
}
// Merge Sort
vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) {
int i = 0, j = 0;
vector<vector<int>> merged;
while (i < left_skyline.size() && j < right_skyline.size()) {
if (left_skyline[i][end] < right_skyline[j][start]) {
merged.emplace_back(move(left_skyline[i++]));
} else if (right_skyline[j][end] < left_skyline[i][start]) {
merged.emplace_back(move(right_skyline[j++]));
} else if (left_skyline[i][start] <= right_skyline[j][start]) {
MergeIntersectSkylines(merged, left_skyline[i], i,
right_skyline[j], j);
} else { // left_skyline[i][start] > right_skyline[j][start].
MergeIntersectSkylines(merged, right_skyline[j], j,
left_skyline[i], i);
}
}
// Insert the remaining skylines.
merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end());
merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end());
return merged;
}
// a[start] <= b[start]
void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx,
vector<int>& b, int& b_idx) {
if (a[end] <= b[end]) {
if (a[height] > b[height]) { // |aaa|
if (b[end] != a[end]) { // |abb|b
b[start] = a[end];
merged.emplace_back(move(a)), ++a_idx;
} else { // aaa
++b_idx; // abb
}
} else if (a[height] == b[height]) { // abb
b[start] = a[start], ++a_idx; // abb
} else { // a[height] < b[height].
if (a[start] != b[start]) { // bb
merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); // |a|bb
}
++a_idx;
}
} else { // a[end] > b[end].
if (a[height] >= b[height]) { // aaaa
++b_idx; // abba
} else {
// |bb|
// |a||bb|a
if (a[start] != b[start]) {
merged.emplace_back(move(vector<int>{a[start], b[start], a[height]}));
}
a[start] = b[end];
merged.emplace_back(move(b)), ++b_idx;
}
}
}
};
<|endoftext|> |
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qeventloop.h>
#include <qhbox.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <dcopclient.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kurllabel.h>
#include <kcharsets.h>
#include "summarywidget.h"
SummaryWidget::SummaryWidget( QWidget *parent, const char *name )
: Kontact::Summary( parent, name ),
DCOPObject( "NewsTickerPlugin" ), mLayout( 0 )
{
QVBoxLayout *vlay = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_news",
KIcon::Desktop, KIcon::SizeMedium );
QWidget *header = createHeader( this, icon, i18n( "News Feeds" ) );
vlay->addWidget( header );
QString error;
QCString appID;
bool dcopAvailable = true;
if ( !kapp->dcopClient()->isApplicationRegistered( "rssservice" ) ) {
if ( KApplication::startServiceByDesktopName( "rssservice", QStringList(), &error, &appID ) ) {
QLabel *label = new QLabel( i18n( "No rss dcop service available.\nYou need rssservice to use this plugin." ), this );
vlay->addWidget( label, Qt::AlignHCenter );
dcopAvailable = false;
}
}
mBaseWidget = new QWidget( this, "baseWidget" );
vlay->addWidget( mBaseWidget );
connect( &mTimer, SIGNAL( timeout() ), this, SLOT( updateDocuments() ) );
readConfig();
if ( dcopAvailable )
initDocuments();
connectDCOPSignal( 0, 0, "added(QString)", "documentAdded(QString)", false );
connectDCOPSignal( 0, 0, "removed(QString)", "documentRemoved(QString)", false );
}
int SummaryWidget::summaryHight() const
{
return ( mFeeds.count() == 0 ? 1 : mFeeds.count() );
}
void SummaryWidget::documentAdded( QString )
{
initDocuments();
}
void SummaryWidget::documentRemoved( QString )
{
initDocuments();
}
void SummaryWidget::configChanged()
{
readConfig();
updateView();
}
void SummaryWidget::readConfig()
{
KConfig config( "kcmkontactkntrc" );
config.setGroup( "General" );
mUpdateInterval = config.readNumEntry( "UpdateInterval", 600 );
mArticleCount = config.readNumEntry( "ArticleCount", 4 );
}
void SummaryWidget::initDocuments()
{
mFeeds.clear();
DCOPRef dcopCall( "rssservice", "RSSService" );
QStringList urls;
dcopCall.call( "list()" ).get( urls );
if ( urls.isEmpty() ) { // add default
urls.append( "http://www.kde.org/dotkdeorg.rdf" );
dcopCall.send( "add(QString)", urls[ 0 ] );
}
QStringList::Iterator it;
for ( it = urls.begin(); it != urls.end(); ++it ) {
DCOPRef feedRef = dcopCall.call( "document(QString)", *it );
Feed feed;
feed.ref = feedRef;
feedRef.call( "title()" ).get( feed.title );
feedRef.call( "link()" ).get( feed.url );
feedRef.call( "pixmap()" ).get( feed.logo );
mFeeds.append( feed );
connectDCOPSignal( "rssservice", feedRef.obj(), "documentUpdated(DCOPRef)",
"documentUpdated(DCOPRef)", false );
qApp->processEvents( QEventLoop::ExcludeUserInput |
QEventLoop::ExcludeSocketNotifiers );
}
updateDocuments();
}
void SummaryWidget::updateDocuments()
{
mTimer.stop();
FeedList::Iterator it;
for ( it = mFeeds.begin(); it != mFeeds.end(); ++it )
(*it).ref.send( "refresh()" );
mTimer.start( 1000 * mUpdateInterval );
}
void SummaryWidget::documentUpdated( DCOPRef feedRef )
{
static uint feedCounter = 0;
ArticleMap map;
int numArticles = feedRef.call( "count()" );
for ( int i = 0; i < numArticles; ++i ) {
DCOPRef artRef = feedRef.call( "article(int)", i );
QString title, url;
qApp->processEvents( QEventLoop::ExcludeUserInput |
QEventLoop::ExcludeSocketNotifiers );
artRef.call( "title()" ).get( title );
artRef.call( "link()" ).get( url );
QPair<QString, KURL> article(title, KURL( url ));
map.append( article );
}
FeedList::Iterator it;
for ( it = mFeeds.begin(); it != mFeeds.end(); ++it )
if ( (*it).ref.obj() == feedRef.obj() ) {
(*it).map = map;
if ( (*it).title.isEmpty() )
feedRef.call( "title()" ).get( (*it).title );
if ( (*it).url.isEmpty() )
feedRef.call( "link()" ).get( (*it).url );
if ( (*it).logo.isNull() )
feedRef.call( "pixmap()" ).get( (*it).logo );
}
feedCounter++;
if ( feedCounter == mFeeds.count() ) {
feedCounter = 0;
updateView();
}
}
void SummaryWidget::updateView()
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
delete mLayout;
mLayout = new QVBoxLayout( mBaseWidget, 3 );
QFont boldFont;
boldFont.setBold( true );
boldFont.setPointSize( boldFont.pointSize() + 2 );
FeedList::Iterator it;
for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) {
QHBox *hbox = new QHBox( mBaseWidget );
mLayout->addWidget( hbox );
// icon
KURLLabel *urlLabel = new KURLLabel( hbox );
urlLabel->setURL( (*it).url );
urlLabel->setPixmap( (*it).logo );
urlLabel->setMaximumSize( urlLabel->minimumSizeHint() );
mLabels.append( urlLabel );
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
kapp, SLOT( invokeBrowser( const QString& ) ) );
// header
QLabel *label = new QLabel( hbox );
label->setText( KCharsets::resolveEntities( (*it).title ) );
label->setAlignment( AlignLeft|AlignVCenter );
label->setFont( boldFont );
label->setIndent( 6 );
label->setMaximumSize( label->minimumSizeHint() );
mLabels.append( label );
hbox->setMaximumWidth( hbox->minimumSizeHint().width() );
hbox->show();
// articles
ArticleMap articles = (*it).map;
ArticleMap::Iterator artIt;
int numArticles = 0;
for ( artIt = articles.begin(); artIt != articles.end() && numArticles < mArticleCount; ++artIt ) {
urlLabel = new KURLLabel( (*artIt).second.url(), (*artIt).first, mBaseWidget );
urlLabel->setMaximumSize( urlLabel->minimumSizeHint() );
mLabels.append( urlLabel );
mLayout->addWidget( urlLabel );
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
kapp, SLOT( invokeBrowser( const QString& ) ) );
numArticles++;
}
}
for ( QLabel *label = mLabels.first(); label; label = mLabels.next() )
label->show();
}
QStringList SummaryWidget::configModules() const
{
return "kcmkontactknt.desktop";
}
#include "summarywidget.moc"
<commit_msg>Make the newsticker wrap and make it possible to avoid horizontal scrollbars. Approved by: danimo<commit_after>/*
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qeventloop.h>
#include <qhbox.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <dcopclient.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kurllabel.h>
#include <kcharsets.h>
#include "summarywidget.h"
SummaryWidget::SummaryWidget( QWidget *parent, const char *name )
: Kontact::Summary( parent, name ),
DCOPObject( "NewsTickerPlugin" ), mLayout( 0 )
{
QVBoxLayout *vlay = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_news",
KIcon::Desktop, KIcon::SizeMedium );
QWidget *header = createHeader( this, icon, i18n( "News Feeds" ) );
vlay->addWidget( header );
QString error;
QCString appID;
bool dcopAvailable = true;
if ( !kapp->dcopClient()->isApplicationRegistered( "rssservice" ) ) {
if ( KApplication::startServiceByDesktopName( "rssservice", QStringList(), &error, &appID ) ) {
QLabel *label = new QLabel( i18n( "No rss dcop service available.\nYou need rssservice to use this plugin." ), this );
vlay->addWidget( label, Qt::AlignHCenter );
dcopAvailable = false;
}
}
mBaseWidget = new QWidget( this, "baseWidget" );
vlay->addWidget( mBaseWidget );
connect( &mTimer, SIGNAL( timeout() ), this, SLOT( updateDocuments() ) );
readConfig();
if ( dcopAvailable )
initDocuments();
connectDCOPSignal( 0, 0, "added(QString)", "documentAdded(QString)", false );
connectDCOPSignal( 0, 0, "removed(QString)", "documentRemoved(QString)", false );
}
int SummaryWidget::summaryHight() const
{
return ( mFeeds.count() == 0 ? 1 : mFeeds.count() );
}
void SummaryWidget::documentAdded( QString )
{
initDocuments();
}
void SummaryWidget::documentRemoved( QString )
{
initDocuments();
}
void SummaryWidget::configChanged()
{
readConfig();
updateView();
}
void SummaryWidget::readConfig()
{
KConfig config( "kcmkontactkntrc" );
config.setGroup( "General" );
mUpdateInterval = config.readNumEntry( "UpdateInterval", 600 );
mArticleCount = config.readNumEntry( "ArticleCount", 4 );
}
void SummaryWidget::initDocuments()
{
mFeeds.clear();
DCOPRef dcopCall( "rssservice", "RSSService" );
QStringList urls;
dcopCall.call( "list()" ).get( urls );
if ( urls.isEmpty() ) { // add default
urls.append( "http://www.kde.org/dotkdeorg.rdf" );
dcopCall.send( "add(QString)", urls[ 0 ] );
}
QStringList::Iterator it;
for ( it = urls.begin(); it != urls.end(); ++it ) {
DCOPRef feedRef = dcopCall.call( "document(QString)", *it );
Feed feed;
feed.ref = feedRef;
feedRef.call( "title()" ).get( feed.title );
feedRef.call( "link()" ).get( feed.url );
feedRef.call( "pixmap()" ).get( feed.logo );
mFeeds.append( feed );
connectDCOPSignal( "rssservice", feedRef.obj(), "documentUpdated(DCOPRef)",
"documentUpdated(DCOPRef)", false );
qApp->processEvents( QEventLoop::ExcludeUserInput |
QEventLoop::ExcludeSocketNotifiers );
}
updateDocuments();
}
void SummaryWidget::updateDocuments()
{
mTimer.stop();
FeedList::Iterator it;
for ( it = mFeeds.begin(); it != mFeeds.end(); ++it )
(*it).ref.send( "refresh()" );
mTimer.start( 1000 * mUpdateInterval );
}
void SummaryWidget::documentUpdated( DCOPRef feedRef )
{
static uint feedCounter = 0;
ArticleMap map;
int numArticles = feedRef.call( "count()" );
for ( int i = 0; i < numArticles; ++i ) {
DCOPRef artRef = feedRef.call( "article(int)", i );
QString title, url;
qApp->processEvents( QEventLoop::ExcludeUserInput |
QEventLoop::ExcludeSocketNotifiers );
artRef.call( "title()" ).get( title );
artRef.call( "link()" ).get( url );
QPair<QString, KURL> article(title, KURL( url ));
map.append( article );
}
FeedList::Iterator it;
for ( it = mFeeds.begin(); it != mFeeds.end(); ++it )
if ( (*it).ref.obj() == feedRef.obj() ) {
(*it).map = map;
if ( (*it).title.isEmpty() )
feedRef.call( "title()" ).get( (*it).title );
if ( (*it).url.isEmpty() )
feedRef.call( "link()" ).get( (*it).url );
if ( (*it).logo.isNull() )
feedRef.call( "pixmap()" ).get( (*it).logo );
}
feedCounter++;
if ( feedCounter == mFeeds.count() ) {
feedCounter = 0;
updateView();
}
}
void SummaryWidget::updateView()
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
delete mLayout;
mLayout = new QVBoxLayout( mBaseWidget, 3 );
QFont boldFont;
boldFont.setBold( true );
boldFont.setPointSize( boldFont.pointSize() + 2 );
FeedList::Iterator it;
for ( it = mFeeds.begin(); it != mFeeds.end(); ++it ) {
QHBox *hbox = new QHBox( mBaseWidget );
mLayout->addWidget( hbox );
// icon
KURLLabel *urlLabel = new KURLLabel( hbox );
urlLabel->setURL( (*it).url );
urlLabel->setPixmap( (*it).logo );
urlLabel->setMaximumSize( urlLabel->minimumSizeHint() );
mLabels.append( urlLabel );
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
kapp, SLOT( invokeBrowser( const QString& ) ) );
// header
QLabel *label = new QLabel( hbox );
label->setText( KCharsets::resolveEntities( (*it).title ) );
label->setAlignment( AlignLeft|AlignVCenter );
label->setFont( boldFont );
label->setIndent( 6 );
label->setMaximumSize( label->minimumSizeHint() );
mLabels.append( label );
hbox->setMaximumWidth( hbox->minimumSizeHint().width() );
hbox->show();
// articles
ArticleMap articles = (*it).map;
ArticleMap::Iterator artIt;
int numArticles = 0;
for ( artIt = articles.begin(); artIt != articles.end() && numArticles < mArticleCount; ++artIt ) {
urlLabel = new KURLLabel( (*artIt).second.url(), (*artIt).first, mBaseWidget );
urlLabel->setTextFormat( RichText );
mLabels.append( urlLabel );
mLayout->addWidget( urlLabel );
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
kapp, SLOT( invokeBrowser( const QString& ) ) );
numArticles++;
}
}
for ( QLabel *label = mLabels.first(); label; label = mLabels.next() )
label->show();
}
QStringList SummaryWidget::configModules() const
{
return "kcmkontactknt.desktop";
}
#include "summarywidget.moc"
<|endoftext|> |
<commit_before>// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"
#include <assert.h>
#include <float.h>
#include <string.h>
// This work is based on:
// Nicolas Capens. Advanced Rasterization. 2004
namespace meshopt
{
const int kViewport = 256;
struct OverdrawBuffer
{
float z[kViewport][kViewport][2];
unsigned int overdraw[kViewport][kViewport][2];
};
template <typename T>
static T min(T a, T b)
{
return a < b ? a : b;
}
template <typename T>
static T max(T a, T b)
{
return a > b ? a : b;
}
static float det2x2(float a, float b, float c, float d)
{
// (a b)
// (c d)
return a * d - b * c;
}
static float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3)
{
// z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1)
// z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1)
// (x2-x1 y2-y1)(dzdx) = (z2-z1)
// (x3-x1 y3-y1)(dzdy) (z3-z1)
// we'll solve it with Cramer's rule
float det = det2x2(x2 - x1, y2 - y1, x3 - x1, y3 - y1);
float invdet = (det == 0) ? 0 : 1 / det;
dzdx = det2x2(z2 - z1, y2 - y1, z3 - z1, y3 - y1) * invdet;
dzdy = det2x2(x2 - x1, z2 - z1, x3 - x1, z3 - z1) * invdet;
return det;
}
// half-space fixed point triangle rasterizer
static void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z)
{
// compute depth gradients
float DZx, DZy;
float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z);
int sign = det > 0;
// flip backfacing triangles to simplify rasterization logic
if (sign)
{
// flipping v2 & v3 preserves depth gradients since they're based on v1
float t;
t = v2x, v2x = v3x, v3x = t;
t = v2y, v2y = v3y, v3y = t;
t = v2z, v2z = v3z, v3z = t;
// flip depth since we rasterize backfacing triangles to second buffer with reverse Z; only v1z is used below
v1z = kViewport - v1z;
DZx = -DZx;
DZy = -DZy;
}
// coordinates, 28.4 fixed point
int X1 = int(16.0f * v1x + 0.5f);
int X2 = int(16.0f * v2x + 0.5f);
int X3 = int(16.0f * v3x + 0.5f);
int Y1 = int(16.0f * v1y + 0.5f);
int Y2 = int(16.0f * v2y + 0.5f);
int Y3 = int(16.0f * v3y + 0.5f);
// bounding rectangle, clipped against viewport
// since we rasterize pixels with covered centers, min >0.5 should round up
// as for max, due to top-left filling convention we will never rasterize right/bottom edges
// so max >= 0.5 should round down
int minx = max((min(X1, min(X2, X3)) + 7) >> 4, 0);
int maxx = min((max(X1, max(X2, X3)) + 7) >> 4, kViewport);
int miny = max((min(Y1, min(Y2, Y3)) + 7) >> 4, 0);
int maxy = min((max(Y1, max(Y2, Y3)) + 7) >> 4, kViewport);
// deltas, 28.4 fixed point
int DX12 = X1 - X2;
int DX23 = X2 - X3;
int DX31 = X3 - X1;
int DY12 = Y1 - Y2;
int DY23 = Y2 - Y3;
int DY31 = Y3 - Y1;
// fill convention correction
int TL1 = DY12 < 0 || (DY12 == 0 && DX12 > 0);
int TL2 = DY23 < 0 || (DY23 == 0 && DX23 > 0);
int TL3 = DY31 < 0 || (DY31 == 0 && DX31 > 0);
// half edge equations, 24.8 fixed point
// note that we offset minx/miny by half pixel since we want to rasterize pixels with covered centers
int FX = (minx << 4) + 8;
int FY = (miny << 4) + 8;
int CY1 = DX12 * (FY - Y1) - DY12 * (FX - X1) + TL1 - 1;
int CY2 = DX23 * (FY - Y2) - DY23 * (FX - X2) + TL2 - 1;
int CY3 = DX31 * (FY - Y3) - DY31 * (FX - X3) + TL3 - 1;
float ZY = v1z + (DZx * float(FX - X1) + DZy * float(FY - Y1)) * (1 / 16.f);
for (int y = miny; y < maxy; y++)
{
int CX1 = CY1;
int CX2 = CY2;
int CX3 = CY3;
float ZX = ZY;
for (int x = minx; x < maxx; x++)
{
// check if all CXn are non-negative
if ((CX1 | CX2 | CX3) >= 0)
{
if (ZX >= buffer->z[y][x][sign])
{
buffer->z[y][x][sign] = ZX;
buffer->overdraw[y][x][sign]++;
}
}
// signed left shift is UB for negative numbers so use unsigned-signed casts
CX1 -= int(unsigned(DY12) << 4);
CX2 -= int(unsigned(DY23) << 4);
CX3 -= int(unsigned(DY31) << 4);
ZX += DZx;
}
// signed left shift is UB for negative numbers so use unsigned-signed casts
CY1 += int(unsigned(DX12) << 4);
CY2 += int(unsigned(DX23) << 4);
CY3 += int(unsigned(DX31) << 4);
ZY += DZy;
}
}
} // namespace meshopt
meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
{
using namespace meshopt;
assert(index_count % 3 == 0);
assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
assert(vertex_positions_stride % sizeof(float) == 0);
meshopt_Allocator allocator;
size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
meshopt_OverdrawStatistics result = {};
float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};
float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
for (size_t i = 0; i < vertex_count; ++i)
{
const float* v = vertex_positions + i * vertex_stride_float;
for (int j = 0; j < 3; ++j)
{
minv[j] = min(minv[j], v[j]);
maxv[j] = max(maxv[j], v[j]);
}
}
float extent = max(maxv[0] - minv[0], max(maxv[1] - minv[1], maxv[2] - minv[2]));
float scale = kViewport / extent;
float* triangles = allocator.allocate<float>(index_count * 3);
for (size_t i = 0; i < index_count; ++i)
{
unsigned int index = indices[i];
assert(index < vertex_count);
const float* v = vertex_positions + index * vertex_stride_float;
triangles[i * 3 + 0] = (v[0] - minv[0]) * scale;
triangles[i * 3 + 1] = (v[1] - minv[1]) * scale;
triangles[i * 3 + 2] = (v[2] - minv[2]) * scale;
}
OverdrawBuffer* buffer = allocator.allocate<OverdrawBuffer>(1);
for (int axis = 0; axis < 3; ++axis)
{
memset(buffer, 0, sizeof(OverdrawBuffer));
for (size_t i = 0; i < index_count; i += 3)
{
const float* vn0 = &triangles[3 * (i + 0)];
const float* vn1 = &triangles[3 * (i + 1)];
const float* vn2 = &triangles[3 * (i + 2)];
switch (axis)
{
case 0:
rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]);
break;
case 1:
rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]);
break;
case 2:
rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]);
break;
}
}
for (int y = 0; y < kViewport; ++y)
for (int x = 0; x < kViewport; ++x)
for (int s = 0; s < 2; ++s)
{
unsigned int overdraw = buffer->overdraw[y][x][s];
result.pixels_covered += overdraw > 0;
result.pixels_shaded += overdraw;
}
}
result.overdraw = result.pixels_covered ? float(result.pixels_shaded) / float(result.pixels_covered) : 0.f;
return result;
}
<commit_msg>overdraw: Optimize rasterizer in Debug<commit_after>// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"
#include <assert.h>
#include <float.h>
#include <string.h>
// This work is based on:
// Nicolas Capens. Advanced Rasterization. 2004
namespace meshopt
{
const int kViewport = 256;
struct OverdrawBuffer
{
float z[kViewport][kViewport][2];
unsigned int overdraw[kViewport][kViewport][2];
};
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef max
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif
static float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3)
{
// z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1)
// z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1)
// (x2-x1 y2-y1)(dzdx) = (z2-z1)
// (x3-x1 y3-y1)(dzdy) (z3-z1)
// we'll solve it with Cramer's rule
float det = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1);
float invdet = (det == 0) ? 0 : 1 / det;
dzdx = (z2 - z1) * (y3 - y1) - (y2 - y1) * (z3 - z1) * invdet;
dzdy = (x2 - x1) * (z3 - z1) - (z2 - z1) * (x3 - x1) * invdet;
return det;
}
// half-space fixed point triangle rasterizer
static void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z)
{
// compute depth gradients
float DZx, DZy;
float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z);
int sign = det > 0;
// flip backfacing triangles to simplify rasterization logic
if (sign)
{
// flipping v2 & v3 preserves depth gradients since they're based on v1
float t;
t = v2x, v2x = v3x, v3x = t;
t = v2y, v2y = v3y, v3y = t;
t = v2z, v2z = v3z, v3z = t;
// flip depth since we rasterize backfacing triangles to second buffer with reverse Z; only v1z is used below
v1z = kViewport - v1z;
DZx = -DZx;
DZy = -DZy;
}
// coordinates, 28.4 fixed point
int X1 = int(16.0f * v1x + 0.5f);
int X2 = int(16.0f * v2x + 0.5f);
int X3 = int(16.0f * v3x + 0.5f);
int Y1 = int(16.0f * v1y + 0.5f);
int Y2 = int(16.0f * v2y + 0.5f);
int Y3 = int(16.0f * v3y + 0.5f);
// bounding rectangle, clipped against viewport
// since we rasterize pixels with covered centers, min >0.5 should round up
// as for max, due to top-left filling convention we will never rasterize right/bottom edges
// so max >= 0.5 should round down
int minx = max((min(X1, min(X2, X3)) + 7) >> 4, 0);
int maxx = min((max(X1, max(X2, X3)) + 7) >> 4, kViewport);
int miny = max((min(Y1, min(Y2, Y3)) + 7) >> 4, 0);
int maxy = min((max(Y1, max(Y2, Y3)) + 7) >> 4, kViewport);
// deltas, 28.4 fixed point
int DX12 = X1 - X2;
int DX23 = X2 - X3;
int DX31 = X3 - X1;
int DY12 = Y1 - Y2;
int DY23 = Y2 - Y3;
int DY31 = Y3 - Y1;
// fill convention correction
int TL1 = DY12 < 0 || (DY12 == 0 && DX12 > 0);
int TL2 = DY23 < 0 || (DY23 == 0 && DX23 > 0);
int TL3 = DY31 < 0 || (DY31 == 0 && DX31 > 0);
// half edge equations, 24.8 fixed point
// note that we offset minx/miny by half pixel since we want to rasterize pixels with covered centers
int FX = (minx << 4) + 8;
int FY = (miny << 4) + 8;
int CY1 = DX12 * (FY - Y1) - DY12 * (FX - X1) + TL1 - 1;
int CY2 = DX23 * (FY - Y2) - DY23 * (FX - X2) + TL2 - 1;
int CY3 = DX31 * (FY - Y3) - DY31 * (FX - X3) + TL3 - 1;
float ZY = v1z + (DZx * float(FX - X1) + DZy * float(FY - Y1)) * (1 / 16.f);
for (int y = miny; y < maxy; y++)
{
int CX1 = CY1;
int CX2 = CY2;
int CX3 = CY3;
float ZX = ZY;
for (int x = minx; x < maxx; x++)
{
// check if all CXn are non-negative
if ((CX1 | CX2 | CX3) >= 0)
{
if (ZX >= buffer->z[y][x][sign])
{
buffer->z[y][x][sign] = ZX;
buffer->overdraw[y][x][sign]++;
}
}
// signed left shift is UB for negative numbers so use unsigned-signed casts
CX1 -= int(unsigned(DY12) << 4);
CX2 -= int(unsigned(DY23) << 4);
CX3 -= int(unsigned(DY31) << 4);
ZX += DZx;
}
// signed left shift is UB for negative numbers so use unsigned-signed casts
CY1 += int(unsigned(DX12) << 4);
CY2 += int(unsigned(DX23) << 4);
CY3 += int(unsigned(DX31) << 4);
ZY += DZy;
}
}
} // namespace meshopt
meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
{
using namespace meshopt;
assert(index_count % 3 == 0);
assert(vertex_positions_stride > 0 && vertex_positions_stride <= 256);
assert(vertex_positions_stride % sizeof(float) == 0);
meshopt_Allocator allocator;
size_t vertex_stride_float = vertex_positions_stride / sizeof(float);
meshopt_OverdrawStatistics result = {};
float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};
float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
for (size_t i = 0; i < vertex_count; ++i)
{
const float* v = vertex_positions + i * vertex_stride_float;
for (int j = 0; j < 3; ++j)
{
minv[j] = min(minv[j], v[j]);
maxv[j] = max(maxv[j], v[j]);
}
}
float extent = max(maxv[0] - minv[0], max(maxv[1] - minv[1], maxv[2] - minv[2]));
float scale = kViewport / extent;
float* triangles = allocator.allocate<float>(index_count * 3);
for (size_t i = 0; i < index_count; ++i)
{
unsigned int index = indices[i];
assert(index < vertex_count);
const float* v = vertex_positions + index * vertex_stride_float;
triangles[i * 3 + 0] = (v[0] - minv[0]) * scale;
triangles[i * 3 + 1] = (v[1] - minv[1]) * scale;
triangles[i * 3 + 2] = (v[2] - minv[2]) * scale;
}
OverdrawBuffer* buffer = allocator.allocate<OverdrawBuffer>(1);
for (int axis = 0; axis < 3; ++axis)
{
memset(buffer, 0, sizeof(OverdrawBuffer));
for (size_t i = 0; i < index_count; i += 3)
{
const float* vn0 = &triangles[3 * (i + 0)];
const float* vn1 = &triangles[3 * (i + 1)];
const float* vn2 = &triangles[3 * (i + 2)];
switch (axis)
{
case 0:
rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]);
break;
case 1:
rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]);
break;
case 2:
rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]);
break;
}
}
for (int y = 0; y < kViewport; ++y)
for (int x = 0; x < kViewport; ++x)
for (int s = 0; s < 2; ++s)
{
unsigned int overdraw = buffer->overdraw[y][x][s];
result.pixels_covered += overdraw > 0;
result.pixels_shaded += overdraw;
}
}
result.overdraw = result.pixels_covered ? float(result.pixels_shaded) / float(result.pixels_covered) : 0.f;
return result;
}
<|endoftext|> |
<commit_before><commit_msg>Eliminate precarious use of const_cast<wchar*>(wstring.get()) Review URL: http://codereview.chromium.org/42617<commit_after><|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wifipropconnection.h"
#define CALIBRATE_DELAY 10
#define HTTP_PORT 80
#define TELNET_PORT 23
#define DISCOVER_PORT 2000
int resetPin = 12;
extern int verbose;
WiFiPropConnection::WiFiPropConnection()
: m_ipaddr(NULL),
m_socket(INVALID_SOCKET)
{
m_loaderBaudRate = WIFI_LOADER_BAUD_RATE;
m_fastLoaderBaudRate = WIFI_FAST_LOADER_BAUD_RATE;
m_programBaudRate = WIFI_PROGRAM_BAUD_RATE;
}
WiFiPropConnection::~WiFiPropConnection()
{
if (m_ipaddr)
free(m_ipaddr);
disconnect();
}
int WiFiPropConnection::setAddress(const char *ipaddr)
{
if (m_ipaddr)
free(m_ipaddr);
if (!(m_ipaddr = (char *)malloc(strlen(ipaddr) + 1)))
return -1;
strcpy(m_ipaddr, ipaddr);
if (GetInternetAddress(m_ipaddr, HTTP_PORT, &m_httpAddr) != 0)
return -1;
if (GetInternetAddress(m_ipaddr, TELNET_PORT, &m_telnetAddr) != 0)
return -1;
return 0;
}
int WiFiPropConnection::close()
{
if (!isOpen())
return -1;
return 0;
}
int WiFiPropConnection::connect()
{
if (!m_ipaddr)
return -1;
if (m_socket != INVALID_SOCKET)
return -1;
if (ConnectSocketTimeout(&m_telnetAddr, CONNECT_TIMEOUT, &m_socket) != 0)
return -1;
return 0;
}
int WiFiPropConnection::disconnect()
{
if (m_socket == INVALID_SOCKET)
return -1;
CloseSocket(m_socket);
m_socket = INVALID_SOCKET;
return 0;
}
int WiFiPropConnection::identify(int *pVersion)
{
return 0;
}
int WiFiPropConnection::loadImage(const uint8_t *image, int imageSize, LoadType loadType)
{
uint8_t buffer[1024], *packet;
int hdrCnt, result;
/* use the initial loader baud rate */
if (setBaudRate(loaderBaudRate()) != 0)
return -1;
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /propeller/load?reset-pin=%d&baud-rate=%d HTTP/1.1\r\n\
Content-Length: %d\r\n\
\r\n", resetPin, loaderBaudRate(), imageSize);
if (!(packet = (uint8_t *)malloc(hdrCnt + imageSize)))
return -1;
memcpy(packet, buffer, hdrCnt);
memcpy(&packet[hdrCnt], image, imageSize);
if (sendRequest(packet, hdrCnt + imageSize, buffer, sizeof(buffer), &result) == -1) {
printf("error: load request failed\n");
return -1;
}
else if (result != 200) {
printf("error: load returned %d\n", result);
return -1;
}
return 0;
}
#define MAX_IF_ADDRS 20
#define NAME_TAG "\"name\": \""
int WiFiPropConnection::findModules(bool check, WiFiInfoList &list, int count)
{
uint8_t txBuf[1024]; // BUG: get rid of this magic number!
uint8_t rxBuf[1024]; // BUG: get rid of this magic number!
IFADDR ifaddrs[MAX_IF_ADDRS];
uint32_t *txNext;
int ifCnt, tries, txCnt, cnt, i;
SOCKADDR_IN addr;
SOCKET sock;
/* get all of the network interface addresses */
if ((ifCnt = GetInterfaceAddresses(ifaddrs, MAX_IF_ADDRS)) < 0) {
printf("error: GetInterfaceAddresses failed\n");
return -1;
}
/* create a broadcast socket */
if (OpenBroadcastSocket(DISCOVER_PORT, &sock) != 0) {
printf("error: OpenBroadcastSocket failed\n");
return -1;
}
/* initialize the broadcast message to indicate no modules found yet */
txNext = (uint32_t *)txBuf;
*txNext++ = 0; // indicates that this is a request not a response
txCnt = sizeof(uint32_t);
/* keep trying until we have this many attempts that return no new modules */
tries = DISCOVER_ATTEMPTS;
/* make a number of attempts at discovering modules */
while (tries > 0) {
int numberFound = 0;
/* send the broadcast packet to all interfaces */
for (i = 0; i < ifCnt; ++i) {
SOCKADDR_IN bcastaddr;
/* build a broadcast address */
bcastaddr = ifaddrs[i].bcast;
bcastaddr.sin_port = htons(DISCOVER_PORT);
/* send the broadcast packet */
if (SendSocketDataTo(sock, txBuf, txCnt, &bcastaddr) != txCnt) {
perror("error: SendSocketDataTo failed");
CloseSocket(sock);
return -1;
}
}
/* receive wifi module responses */
while (SocketDataAvailableP(sock, DISCOVER_REPLY_TIMEOUT)) {
/* get the next response */
if ((cnt = ReceiveSocketDataAndAddress(sock, rxBuf, sizeof(rxBuf) - 1, &addr)) < 0) {
printf("error: ReceiveSocketData failed\n");
CloseSocket(sock);
return -3;
}
rxBuf[cnt] = '\0';
/* only process replies */
if (cnt >= sizeof(uint32_t) && *(uint32_t *)rxBuf != 0) {
std::string addressStr(AddressToString(&addr));
const char *name, *p, *p2;
char nameBuffer[128];
printf("Address: %08x\n", addr.sin_addr.s_addr);
/* make sure we don't already have a response from this module */
WiFiInfoList::iterator i = list.begin();
bool skip = false;
while (i != list.end()) {
if (i->address() == addressStr) {
printf("Skipping duplicate\n");
skip = true;
break;
}
++i;
}
if (skip)
continue;
/* count this as a module found on this attempt */
++numberFound;
/* add the module's ip address to the next broadcast message */
if (txCnt < sizeof(txBuf)) {
*txNext++ = addr.sin_addr.s_addr;
txCnt += sizeof(uint32_t);
}
if (verbose)
printf("from %s got: %s", AddressToString(&addr), rxBuf);
if (!(p = strstr((char *)rxBuf, NAME_TAG)))
name = "";
else {
p += strlen(NAME_TAG);
if (!(p2 = strchr(p, '"'))) {
CloseSocket(sock);
return -1;
}
else if (p2 - p >= (int)sizeof(nameBuffer)) {
CloseSocket(sock);
return -1;
}
strncpy(nameBuffer, p, p2 - p);
nameBuffer[p2 - p] = '\0';
name = nameBuffer;
}
WiFiInfo info(name, addressStr);
list.push_back(info);
if (count > 0 && --count == 0) {
CloseSocket(sock);
return 0;
}
}
}
/* if we found at least one module, reset the retry counter */
if (numberFound > 0)
tries = DISCOVER_ATTEMPTS;
/* otherwise, decrement the number of attempts remaining */
else
--tries;
}
/* close the socket */
CloseSocket(sock);
/* return successfully */
return 0;
}
bool WiFiPropConnection::isOpen()
{
return m_socket != INVALID_SOCKET;
}
int WiFiPropConnection::setName(const char *name)
{
uint8_t buffer[1024];
int hdrCnt, result;
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /system/update?name=%s HTTP/1.1\r\n\
\r\n", name);
if (sendRequest(buffer, hdrCnt, buffer, sizeof(buffer), &result) == -1) {
printf("error: name update request failed\n");
return -1;
}
else if (result != 204) {
printf("error: name update returned %d\n", result);
return -1;
}
return 0;
}
int WiFiPropConnection::generateResetSignal()
{
uint8_t buffer[1024];
int hdrCnt, result;
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /propeller/reset?reset-pin=%d HTTP/1.1\r\n\
\r\n", resetPin);
if (sendRequest(buffer, hdrCnt, buffer, sizeof(buffer), &result) == -1) {
printf("error: reset request failed\n");
return -1;
}
else if (result != 200) {
printf("error: reset returned %d\n", result);
return -1;
}
return 0;
}
int WiFiPropConnection::sendData(const uint8_t *buf, int len)
{
if (!isOpen())
return -1;
return SendSocketData(m_socket, buf, len);
}
int WiFiPropConnection::receiveDataTimeout(uint8_t *buf, int len, int timeout)
{
if (!isOpen())
return -1;
return ReceiveSocketDataTimeout(m_socket, buf, len, timeout);
}
int WiFiPropConnection::receiveDataExactTimeout(uint8_t *buf, int len, int timeout)
{
if (!isOpen())
return -1;
return ReceiveSocketDataExactTimeout(m_socket, buf, len, timeout);
}
int WiFiPropConnection::setBaudRate(int baudRate)
{
uint8_t buffer[1024];
int hdrCnt, result;
if (baudRate != m_baudRate) {
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /propeller/set-baud-rate?baud-rate=%d HTTP/1.1\r\n\
\r\n", baudRate);
if (sendRequest(buffer, hdrCnt, buffer, sizeof(buffer), &result) == -1) {
printf("error: set-baud-rate request failed\n");
return -1;
}
else if (result != 200) {
printf("error: set-baud-rate returned %d\n", result);
return -1;
}
m_baudRate = baudRate;
}
return 0;
}
int WiFiPropConnection::terminal(bool checkForExit, bool pstMode)
{
if (!connect())
return -1;
SocketTerminal(m_socket, checkForExit, pstMode);
disconnect();
return 0;
}
int WiFiPropConnection::sendRequest(uint8_t *req, int reqSize, uint8_t *res, int resMax, int *pResult)
{
SOCKET sock;
char buf[80];
int cnt;
if (ConnectSocketTimeout(&m_httpAddr, CONNECT_TIMEOUT, &sock) != 0) {
printf("error: connect failed\n");
return -1;
}
if (verbose) {
printf("REQ: %d\n", reqSize);
dumpHdr(req, reqSize);
}
if (SendSocketData(sock, req, reqSize) != reqSize) {
printf("error: send request failed\n");
CloseSocket(sock);
return -1;
}
cnt = ReceiveSocketDataTimeout(sock, res, resMax, 10000);
CloseSocket(sock);
if (cnt == -1) {
printf("error: receive response failed\n");
return -1;
}
if (verbose) {
printf("RES: %d\n", cnt);
dumpResponse(res, cnt);
}
if (sscanf((char *)res, "%s %d", buf, pResult) != 2)
return -1;
return cnt;
}
void WiFiPropConnection::dumpHdr(const uint8_t *buf, int size)
{
int startOfLine = true;
const uint8_t *p = buf;
while (p < buf + size) {
if (*p == '\r') {
if (startOfLine)
break;
startOfLine = true;
putchar('\n');
}
else if (*p != '\n') {
startOfLine = false;
putchar(*p);
}
++p;
}
putchar('\n');
}
void WiFiPropConnection::dumpResponse(const uint8_t *buf, int size)
{
int startOfLine = true;
const uint8_t *p = buf;
const uint8_t *save;
int cnt;
while (p < buf + size) {
if (*p == '\r') {
if (startOfLine) {
++p;
if (*p == '\n')
++p;
break;
}
startOfLine = true;
putchar('\n');
}
else if (*p != '\n') {
startOfLine = false;
putchar(*p);
}
++p;
}
putchar('\n');
save = p;
while (p < buf + size) {
if (*p == '\r')
putchar('\n');
else if (*p != '\n')
putchar(*p);
++p;
}
p = save;
cnt = 0;
while (p < buf + size) {
printf("%02x ", *p++);
if ((++cnt % 16) == 0)
putchar('\n');
}
if ((cnt % 16) != 0)
putchar('\n');
}
<commit_msg>Suppress all of the discovery status messages when -v is not specied.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wifipropconnection.h"
#define CALIBRATE_DELAY 10
#define HTTP_PORT 80
#define TELNET_PORT 23
#define DISCOVER_PORT 2000
int resetPin = 12;
extern int verbose;
WiFiPropConnection::WiFiPropConnection()
: m_ipaddr(NULL),
m_socket(INVALID_SOCKET)
{
m_loaderBaudRate = WIFI_LOADER_BAUD_RATE;
m_fastLoaderBaudRate = WIFI_FAST_LOADER_BAUD_RATE;
m_programBaudRate = WIFI_PROGRAM_BAUD_RATE;
}
WiFiPropConnection::~WiFiPropConnection()
{
if (m_ipaddr)
free(m_ipaddr);
disconnect();
}
int WiFiPropConnection::setAddress(const char *ipaddr)
{
if (m_ipaddr)
free(m_ipaddr);
if (!(m_ipaddr = (char *)malloc(strlen(ipaddr) + 1)))
return -1;
strcpy(m_ipaddr, ipaddr);
if (GetInternetAddress(m_ipaddr, HTTP_PORT, &m_httpAddr) != 0)
return -1;
if (GetInternetAddress(m_ipaddr, TELNET_PORT, &m_telnetAddr) != 0)
return -1;
return 0;
}
int WiFiPropConnection::close()
{
if (!isOpen())
return -1;
return 0;
}
int WiFiPropConnection::connect()
{
if (!m_ipaddr)
return -1;
if (m_socket != INVALID_SOCKET)
return -1;
if (ConnectSocketTimeout(&m_telnetAddr, CONNECT_TIMEOUT, &m_socket) != 0)
return -1;
return 0;
}
int WiFiPropConnection::disconnect()
{
if (m_socket == INVALID_SOCKET)
return -1;
CloseSocket(m_socket);
m_socket = INVALID_SOCKET;
return 0;
}
int WiFiPropConnection::identify(int *pVersion)
{
return 0;
}
int WiFiPropConnection::loadImage(const uint8_t *image, int imageSize, LoadType loadType)
{
uint8_t buffer[1024], *packet;
int hdrCnt, result;
/* use the initial loader baud rate */
if (setBaudRate(loaderBaudRate()) != 0)
return -1;
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /propeller/load?reset-pin=%d&baud-rate=%d HTTP/1.1\r\n\
Content-Length: %d\r\n\
\r\n", resetPin, loaderBaudRate(), imageSize);
if (!(packet = (uint8_t *)malloc(hdrCnt + imageSize)))
return -1;
memcpy(packet, buffer, hdrCnt);
memcpy(&packet[hdrCnt], image, imageSize);
if (sendRequest(packet, hdrCnt + imageSize, buffer, sizeof(buffer), &result) == -1) {
printf("error: load request failed\n");
return -1;
}
else if (result != 200) {
printf("error: load returned %d\n", result);
return -1;
}
return 0;
}
#define MAX_IF_ADDRS 20
#define NAME_TAG "\"name\": \""
int WiFiPropConnection::findModules(bool check, WiFiInfoList &list, int count)
{
uint8_t txBuf[1024]; // BUG: get rid of this magic number!
uint8_t rxBuf[1024]; // BUG: get rid of this magic number!
IFADDR ifaddrs[MAX_IF_ADDRS];
uint32_t *txNext;
int ifCnt, tries, txCnt, cnt, i;
SOCKADDR_IN addr;
SOCKET sock;
/* get all of the network interface addresses */
if ((ifCnt = GetInterfaceAddresses(ifaddrs, MAX_IF_ADDRS)) < 0) {
printf("error: GetInterfaceAddresses failed\n");
return -1;
}
/* create a broadcast socket */
if (OpenBroadcastSocket(DISCOVER_PORT, &sock) != 0) {
printf("error: OpenBroadcastSocket failed\n");
return -1;
}
/* initialize the broadcast message to indicate no modules found yet */
txNext = (uint32_t *)txBuf;
*txNext++ = 0; // indicates that this is a request not a response
txCnt = sizeof(uint32_t);
/* keep trying until we have this many attempts that return no new modules */
tries = DISCOVER_ATTEMPTS;
/* make a number of attempts at discovering modules */
while (tries > 0) {
int numberFound = 0;
/* send the broadcast packet to all interfaces */
for (i = 0; i < ifCnt; ++i) {
SOCKADDR_IN bcastaddr;
/* build a broadcast address */
bcastaddr = ifaddrs[i].bcast;
bcastaddr.sin_port = htons(DISCOVER_PORT);
/* send the broadcast packet */
if (SendSocketDataTo(sock, txBuf, txCnt, &bcastaddr) != txCnt) {
perror("error: SendSocketDataTo failed");
CloseSocket(sock);
return -1;
}
}
/* receive wifi module responses */
while (SocketDataAvailableP(sock, DISCOVER_REPLY_TIMEOUT)) {
/* get the next response */
if ((cnt = ReceiveSocketDataAndAddress(sock, rxBuf, sizeof(rxBuf) - 1, &addr)) < 0) {
printf("error: ReceiveSocketData failed\n");
CloseSocket(sock);
return -3;
}
rxBuf[cnt] = '\0';
/* only process replies */
if (cnt >= sizeof(uint32_t) && *(uint32_t *)rxBuf != 0) {
std::string addressStr(AddressToString(&addr));
const char *name, *p, *p2;
char nameBuffer[128];
/* make sure we don't already have a response from this module */
WiFiInfoList::iterator i = list.begin();
bool skip = false;
while (i != list.end()) {
if (i->address() == addressStr) {
if (verbose)
printf("Skipping duplicate: %s\n", AddressToString(&addr));
skip = true;
break;
}
++i;
}
if (skip)
continue;
/* count this as a module found on this attempt */
++numberFound;
/* add the module's ip address to the next broadcast message */
if (txCnt < sizeof(txBuf)) {
*txNext++ = addr.sin_addr.s_addr;
txCnt += sizeof(uint32_t);
}
if (verbose)
printf("from %s got: %s", AddressToString(&addr), rxBuf);
if (!(p = strstr((char *)rxBuf, NAME_TAG)))
name = "";
else {
p += strlen(NAME_TAG);
if (!(p2 = strchr(p, '"'))) {
CloseSocket(sock);
return -1;
}
else if (p2 - p >= (int)sizeof(nameBuffer)) {
CloseSocket(sock);
return -1;
}
strncpy(nameBuffer, p, p2 - p);
nameBuffer[p2 - p] = '\0';
name = nameBuffer;
}
WiFiInfo info(name, addressStr);
list.push_back(info);
if (count > 0 && --count == 0) {
CloseSocket(sock);
return 0;
}
}
}
/* if we found at least one module, reset the retry counter */
if (numberFound > 0)
tries = DISCOVER_ATTEMPTS;
/* otherwise, decrement the number of attempts remaining */
else
--tries;
}
/* close the socket */
CloseSocket(sock);
/* return successfully */
return 0;
}
bool WiFiPropConnection::isOpen()
{
return m_socket != INVALID_SOCKET;
}
int WiFiPropConnection::setName(const char *name)
{
uint8_t buffer[1024];
int hdrCnt, result;
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /system/update?name=%s HTTP/1.1\r\n\
\r\n", name);
if (sendRequest(buffer, hdrCnt, buffer, sizeof(buffer), &result) == -1) {
printf("error: name update request failed\n");
return -1;
}
else if (result != 204) {
printf("error: name update returned %d\n", result);
return -1;
}
return 0;
}
int WiFiPropConnection::generateResetSignal()
{
uint8_t buffer[1024];
int hdrCnt, result;
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /propeller/reset?reset-pin=%d HTTP/1.1\r\n\
\r\n", resetPin);
if (sendRequest(buffer, hdrCnt, buffer, sizeof(buffer), &result) == -1) {
printf("error: reset request failed\n");
return -1;
}
else if (result != 200) {
printf("error: reset returned %d\n", result);
return -1;
}
return 0;
}
int WiFiPropConnection::sendData(const uint8_t *buf, int len)
{
if (!isOpen())
return -1;
return SendSocketData(m_socket, buf, len);
}
int WiFiPropConnection::receiveDataTimeout(uint8_t *buf, int len, int timeout)
{
if (!isOpen())
return -1;
return ReceiveSocketDataTimeout(m_socket, buf, len, timeout);
}
int WiFiPropConnection::receiveDataExactTimeout(uint8_t *buf, int len, int timeout)
{
if (!isOpen())
return -1;
return ReceiveSocketDataExactTimeout(m_socket, buf, len, timeout);
}
int WiFiPropConnection::setBaudRate(int baudRate)
{
uint8_t buffer[1024];
int hdrCnt, result;
if (baudRate != m_baudRate) {
hdrCnt = snprintf((char *)buffer, sizeof(buffer), "\
POST /propeller/set-baud-rate?baud-rate=%d HTTP/1.1\r\n\
\r\n", baudRate);
if (sendRequest(buffer, hdrCnt, buffer, sizeof(buffer), &result) == -1) {
printf("error: set-baud-rate request failed\n");
return -1;
}
else if (result != 200) {
printf("error: set-baud-rate returned %d\n", result);
return -1;
}
m_baudRate = baudRate;
}
return 0;
}
int WiFiPropConnection::terminal(bool checkForExit, bool pstMode)
{
if (!connect())
return -1;
SocketTerminal(m_socket, checkForExit, pstMode);
disconnect();
return 0;
}
int WiFiPropConnection::sendRequest(uint8_t *req, int reqSize, uint8_t *res, int resMax, int *pResult)
{
SOCKET sock;
char buf[80];
int cnt;
if (ConnectSocketTimeout(&m_httpAddr, CONNECT_TIMEOUT, &sock) != 0) {
printf("error: connect failed\n");
return -1;
}
if (verbose) {
printf("REQ: %d\n", reqSize);
dumpHdr(req, reqSize);
}
if (SendSocketData(sock, req, reqSize) != reqSize) {
printf("error: send request failed\n");
CloseSocket(sock);
return -1;
}
cnt = ReceiveSocketDataTimeout(sock, res, resMax, 10000);
CloseSocket(sock);
if (cnt == -1) {
printf("error: receive response failed\n");
return -1;
}
if (verbose) {
printf("RES: %d\n", cnt);
dumpResponse(res, cnt);
}
if (sscanf((char *)res, "%s %d", buf, pResult) != 2)
return -1;
return cnt;
}
void WiFiPropConnection::dumpHdr(const uint8_t *buf, int size)
{
int startOfLine = true;
const uint8_t *p = buf;
while (p < buf + size) {
if (*p == '\r') {
if (startOfLine)
break;
startOfLine = true;
putchar('\n');
}
else if (*p != '\n') {
startOfLine = false;
putchar(*p);
}
++p;
}
putchar('\n');
}
void WiFiPropConnection::dumpResponse(const uint8_t *buf, int size)
{
int startOfLine = true;
const uint8_t *p = buf;
const uint8_t *save;
int cnt;
while (p < buf + size) {
if (*p == '\r') {
if (startOfLine) {
++p;
if (*p == '\n')
++p;
break;
}
startOfLine = true;
putchar('\n');
}
else if (*p != '\n') {
startOfLine = false;
putchar(*p);
}
++p;
}
putchar('\n');
save = p;
while (p < buf + size) {
if (*p == '\r')
putchar('\n');
else if (*p != '\n')
putchar(*p);
++p;
}
p = save;
cnt = 0;
while (p < buf + size) {
printf("%02x ", *p++);
if ((++cnt % 16) == 0)
putchar('\n');
}
if ((cnt % 16) != 0)
putchar('\n');
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010-2012 Linaro Limited
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the MIT License which accompanies
// this distribution, and is available at
// http://www.opensource.org/licenses/mit-license.php
//
// Contributors:
// Alexandros Frantzis <alexandros.frantzis@linaro.org>
// Jesse Barker <jesse.barker@linaro.org>
//
#include <cstdio>
#include <cstdarg>
#include <string>
#include <sstream>
#include <iostream>
#include "log.h"
#ifdef ANDROID
#include <android/log.h>
#endif
using std::string;
const string Log::continuation_prefix("\x10");
string Log::appname;
bool Log::do_debug_(false);
#ifndef ANDROID
static const string terminal_color_normal("\033[0m");
static const string terminal_color_red("\033[1;31m");
static const string terminal_color_cyan("\033[36m");
static const string terminal_color_yellow("\033[33m");
static const string empty;
static void
print_prefixed_message(std::ostream& stream, const string& color, const string& prefix,
const string& fmt, va_list ap)
{
va_list aq;
/* Estimate message size */
va_copy(aq, ap);
int msg_size = vsnprintf(NULL, 0, fmt.c_str(), aq);
va_end(aq);
/* Create the buffer to hold the message */
char *buf = new char[msg_size + 1];
/* Store the message in the buffer */
va_copy(aq, ap);
vsnprintf(buf, msg_size + 1, fmt.c_str(), aq);
va_end(aq);
/*
* Print the message lines prefixed with the supplied prefix.
* If the target stream is a terminal make the prefix colored.
*/
string linePrefix;
if (!prefix.empty())
{
static const string colon(": ");
string start_color;
string end_color;
if (!color.empty())
{
start_color = color;
if (color[0] != 0)
{
end_color = terminal_color_normal;
}
}
linePrefix = start_color + prefix + end_color + colon;
}
std::string line;
std::stringstream ss(buf);
while(std::getline(ss, line)) {
/*
* If this line is a continuation of a previous log message
* just print the line plainly.
*/
if (line[0] == Log::continuation_prefix[0]) {
stream << line.c_str() + 1;
}
else {
/* Normal line, emit the prefix. */
stream << linePrefix << line;
}
/* Only emit a newline if the original message has it. */
if (!(ss.rdstate() & std::stringstream::eofbit))
stream << std::endl;
}
delete[] buf;
}
void
Log::info(const char *fmt, ...)
{
static const string infoprefix("Info");
static const string& infocolor(isatty(fileno(stdout)) ? terminal_color_cyan : empty);
va_list ap;
va_start(ap, fmt);
if (do_debug_)
print_prefixed_message(std::cout, infocolor, infoprefix, fmt, ap);
else
print_prefixed_message(std::cout, empty, empty, fmt, ap);
va_end(ap);
}
void
Log::debug(const char *fmt, ...)
{
static const string dbgprefix("Debug");
static const string& dbgcolor(isatty(fileno(stdout)) ? terminal_color_yellow : empty);
if (!do_debug_)
return;
va_list ap;
va_start(ap, fmt);
print_prefixed_message(std::cout, dbgcolor, dbgprefix, fmt, ap);
va_end(ap);
}
void
Log::error(const char *fmt, ...)
{
static const string errprefix("Error");
static const string& errcolor(isatty(fileno(stderr)) ? terminal_color_red : empty);
va_list ap;
va_start(ap, fmt);
print_prefixed_message(std::cerr, errcolor, errprefix, fmt, ap);
va_end(ap);
}
void
Log::flush()
{
std::cout.flush();
std::cerr.flush();
}
#else
void
Log::info(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
__android_log_vprint(ANDROID_LOG_INFO, appname.c_str(), fmt, ap);
va_end(ap);
}q
void
Log::debug(const char *fmt, ...)
{
if (!Options::show_debug)
return;
va_list ap;
va_start(ap, fmt);
__android_log_vprint(ANDROID_LOG_DEBUG, appname.c_str(), fmt, ap);
va_end(ap);
}
void
Log::error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
__android_log_vprint(ANDROID_LOG_ERROR, appname.c_str(), fmt, ap);
va_end(ap);
}
void
Log::flush()
{
}
#endif
<commit_msg>log: Remove stray character<commit_after>//
// Copyright (c) 2010-2012 Linaro Limited
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the MIT License which accompanies
// this distribution, and is available at
// http://www.opensource.org/licenses/mit-license.php
//
// Contributors:
// Alexandros Frantzis <alexandros.frantzis@linaro.org>
// Jesse Barker <jesse.barker@linaro.org>
//
#include <cstdio>
#include <cstdarg>
#include <string>
#include <sstream>
#include <iostream>
#include "log.h"
#ifdef ANDROID
#include <android/log.h>
#endif
using std::string;
const string Log::continuation_prefix("\x10");
string Log::appname;
bool Log::do_debug_(false);
#ifndef ANDROID
static const string terminal_color_normal("\033[0m");
static const string terminal_color_red("\033[1;31m");
static const string terminal_color_cyan("\033[36m");
static const string terminal_color_yellow("\033[33m");
static const string empty;
static void
print_prefixed_message(std::ostream& stream, const string& color, const string& prefix,
const string& fmt, va_list ap)
{
va_list aq;
/* Estimate message size */
va_copy(aq, ap);
int msg_size = vsnprintf(NULL, 0, fmt.c_str(), aq);
va_end(aq);
/* Create the buffer to hold the message */
char *buf = new char[msg_size + 1];
/* Store the message in the buffer */
va_copy(aq, ap);
vsnprintf(buf, msg_size + 1, fmt.c_str(), aq);
va_end(aq);
/*
* Print the message lines prefixed with the supplied prefix.
* If the target stream is a terminal make the prefix colored.
*/
string linePrefix;
if (!prefix.empty())
{
static const string colon(": ");
string start_color;
string end_color;
if (!color.empty())
{
start_color = color;
if (color[0] != 0)
{
end_color = terminal_color_normal;
}
}
linePrefix = start_color + prefix + end_color + colon;
}
std::string line;
std::stringstream ss(buf);
while(std::getline(ss, line)) {
/*
* If this line is a continuation of a previous log message
* just print the line plainly.
*/
if (line[0] == Log::continuation_prefix[0]) {
stream << line.c_str() + 1;
}
else {
/* Normal line, emit the prefix. */
stream << linePrefix << line;
}
/* Only emit a newline if the original message has it. */
if (!(ss.rdstate() & std::stringstream::eofbit))
stream << std::endl;
}
delete[] buf;
}
void
Log::info(const char *fmt, ...)
{
static const string infoprefix("Info");
static const string& infocolor(isatty(fileno(stdout)) ? terminal_color_cyan : empty);
va_list ap;
va_start(ap, fmt);
if (do_debug_)
print_prefixed_message(std::cout, infocolor, infoprefix, fmt, ap);
else
print_prefixed_message(std::cout, empty, empty, fmt, ap);
va_end(ap);
}
void
Log::debug(const char *fmt, ...)
{
static const string dbgprefix("Debug");
static const string& dbgcolor(isatty(fileno(stdout)) ? terminal_color_yellow : empty);
if (!do_debug_)
return;
va_list ap;
va_start(ap, fmt);
print_prefixed_message(std::cout, dbgcolor, dbgprefix, fmt, ap);
va_end(ap);
}
void
Log::error(const char *fmt, ...)
{
static const string errprefix("Error");
static const string& errcolor(isatty(fileno(stderr)) ? terminal_color_red : empty);
va_list ap;
va_start(ap, fmt);
print_prefixed_message(std::cerr, errcolor, errprefix, fmt, ap);
va_end(ap);
}
void
Log::flush()
{
std::cout.flush();
std::cerr.flush();
}
#else
void
Log::info(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
__android_log_vprint(ANDROID_LOG_INFO, appname.c_str(), fmt, ap);
va_end(ap);
}
void
Log::debug(const char *fmt, ...)
{
if (!Options::show_debug)
return;
va_list ap;
va_start(ap, fmt);
__android_log_vprint(ANDROID_LOG_DEBUG, appname.c_str(), fmt, ap);
va_end(ap);
}
void
Log::error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
__android_log_vprint(ANDROID_LOG_ERROR, appname.c_str(), fmt, ap);
va_end(ap);
}
void
Log::flush()
{
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Include trivial definition of method in release mode (where we don't do tracking)<commit_after><|endoftext|> |
<commit_before><commit_msg>introduced Date::IsValidDate() and Date::Normalize()<commit_after><|endoftext|> |
<commit_before>#ifndef BLOCK_MASKS_HPP__
#define BLOCK_MASKS_HPP__
#include <cassert>
namespace clotho {
namespace utility {
template < class Block >
class block_masks {
public:
static const unsigned int bits_per_block = sizeof( Block ) * 8;
typedef Block block_type;
typedef Block mask_type;
static const mask_type (&lookupLowBitMask())[bits_per_block] {
static bool i = init_low_order(low_order_bit_masks);
assert( i );
return low_order_bit_masks;
}
static const mask_type (&lookupPositionMask())[bits_per_block] {
static bool i = init_positions(bit_position_masks);
assert( i );
return bit_position_masks;
}
static mask_type low_order_mask( unsigned int idx ) {
assert( idx < bits_per_block );
return ((idx == bits_per_block - 1) ? (mask_type)-1 : (( (mask_type)1 << (idx + 1) ) - 1));
}
static mask_type position_mask( unsigned int idx ) {
assert( idx < bits_per_block );
return ((mask_type)1 << idx);
}
private:
/// LOW_BIT_MASK => bits_{[0, n]} = 1
static mask_type low_order_bit_masks[ bits_per_block ];
/// OFFSET_BIT_MASK => bit_[n] = 1
static mask_type bit_position_masks[ bits_per_block ];
static bool init_low_order( mask_type * masks ) {
for( unsigned int i = 0; i < bits_per_block; ++i ) {
(*masks++) = low_order_mask( i );
}
return true;
}
static bool init_positions( mask_type * masks ) {
for( unsigned int i = 0; i < bits_per_block; ++i ) {
(*masks++) = position_mask( i );
}
return true;
}
};
template < class Block >
typename block_masks< Block >::mask_type block_masks< Block >::low_order_bit_masks[ block_masks< Block >::bits_per_block ];
template < class Block >
typename block_masks< Block >::mask_type block_masks< Block >::bit_position_masks[ block_masks< Block >::bits_per_block ];
} // namespace utility {
} // namespace clotho {
#endif // BLOCK_MASKS_HPP__
<commit_msg>Formatting<commit_after>#ifndef BLOCK_MASKS_HPP__
#define BLOCK_MASKS_HPP__
#include <cassert>
namespace clotho {
namespace utility {
template < class Block >
class block_masks {
public:
static const unsigned int bits_per_block = sizeof( Block ) * 8;
typedef Block block_type;
typedef Block mask_type;
static const mask_type (&lookupLowBitMask())[bits_per_block] {
static bool i = init_low_order(low_order_bit_masks);
assert( i );
return low_order_bit_masks;
}
static const mask_type (&lookupPositionMask())[bits_per_block] {
static bool i = init_positions(bit_position_masks);
assert( i );
return bit_position_masks;
}
static mask_type low_order_mask( unsigned int idx ) {
assert( idx < bits_per_block );
return ((idx == bits_per_block - 1) ? (mask_type)-1 : (( (mask_type)1 << (idx + 1) ) - 1));
}
static mask_type position_mask( unsigned int idx ) {
assert( idx < bits_per_block );
return ((mask_type)1 << idx);
}
private:
/// LOW_BIT_MASK => bits_{[0, n]} = 1
static mask_type low_order_bit_masks[ bits_per_block ];
/// OFFSET_BIT_MASK => bit_[n] = 1
static mask_type bit_position_masks[ bits_per_block ];
static bool init_low_order( mask_type * masks ) {
for( unsigned int i = 0; i < bits_per_block; ++i ) {
(*masks++) = low_order_mask( i );
}
return true;
}
static bool init_positions( mask_type * masks ) {
for( unsigned int i = 0; i < bits_per_block; ++i ) {
(*masks++) = position_mask( i );
}
return true;
}
};
template < class Block >
typename block_masks< Block >::mask_type block_masks< Block >::low_order_bit_masks[ block_masks< Block >::bits_per_block ];
template < class Block >
typename block_masks< Block >::mask_type block_masks< Block >::bit_position_masks[ block_masks< Block >::bits_per_block ];
} // namespace utility {
} // namespace clotho {
#endif // BLOCK_MASKS_HPP__
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreFileSystem.h"
#include "OgreLogManager.h"
#include "OgreException.h"
#include "OgreStringVector.h"
#include "OgreRoot.h"
#include <sys/types.h>
#include <sys/stat.h>
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
# include "OgreSearchOps.h"
# include <sys/param.h>
# define MAX_PATH MAXPATHLEN
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# include <windows.h>
# include <direct.h>
# include <io.h>
#endif
namespace Ogre {
bool FileSystemArchive::ms_IgnoreHidden = true;
//-----------------------------------------------------------------------
FileSystemArchive::FileSystemArchive(const String& name, const String& archType )
: Archive(name, archType)
{
}
//-----------------------------------------------------------------------
bool FileSystemArchive::isCaseSensitive(void) const
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
return false;
#else
return true;
#endif
}
//-----------------------------------------------------------------------
static bool is_reserved_dir (const char *fn)
{
return (fn [0] == '.' && (fn [1] == 0 || (fn [1] == '.' && fn [2] == 0)));
}
//-----------------------------------------------------------------------
static bool is_absolute_path(const char* path)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
if (isalpha(uchar(path[0])) && path[1] == ':')
return true;
#endif
return path[0] == '/' || path[0] == '\\';
}
//-----------------------------------------------------------------------
static String concatenate_path(const String& base, const String& name)
{
if (base.empty() || is_absolute_path(name.c_str()))
return name;
else
return base + '/' + name;
}
//-----------------------------------------------------------------------
void FileSystemArchive::findFiles(const String& pattern, bool recursive,
bool dirs, StringVector* simpleList, FileInfoList* detailList)
{
long lHandle, res;
struct _finddata_t tagData;
// pattern can contain a directory name, separate it from mask
size_t pos1 = pattern.rfind ('/');
size_t pos2 = pattern.rfind ('\\');
if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2)))
pos1 = pos2;
String directory;
if (pos1 != pattern.npos)
directory = pattern.substr (0, pos1 + 1);
String full_pattern = concatenate_path(mName, pattern);
lHandle = _findfirst(full_pattern.c_str(), &tagData);
res = 0;
while (lHandle != -1 && res != -1)
{
if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) &&
( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
(!dirs || !is_reserved_dir (tagData.name)))
{
if (simpleList)
{
simpleList->push_back(directory + tagData.name);
}
else if (detailList)
{
FileInfo fi;
fi.archive = this;
fi.filename = directory + tagData.name;
fi.basename = tagData.name;
fi.path = directory;
fi.compressedSize = tagData.size;
fi.uncompressedSize = tagData.size;
detailList->push_back(fi);
}
}
res = _findnext( lHandle, &tagData );
}
// Close if we found any files
if(lHandle != -1)
_findclose(lHandle);
// Now find directories
if (recursive)
{
String base_dir = mName;
if (!directory.empty ())
{
base_dir = concatenate_path(mName, directory);
// Remove the last '/'
base_dir.erase (base_dir.length () - 1);
}
base_dir.append ("/*");
// Remove directory name from pattern
String mask ("/");
if (pos1 != pattern.npos)
mask.append (pattern.substr (pos1 + 1));
else
mask.append (pattern);
lHandle = _findfirst(base_dir.c_str (), &tagData);
res = 0;
while (lHandle != -1 && res != -1)
{
if ((tagData.attrib & _A_SUBDIR) &&
( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
!is_reserved_dir (tagData.name))
{
// recurse
base_dir = directory;
base_dir.append (tagData.name).append (mask);
findFiles(base_dir, recursive, dirs, simpleList, detailList);
}
res = _findnext( lHandle, &tagData );
}
// Close if we found any files
if(lHandle != -1)
_findclose(lHandle);
}
}
//-----------------------------------------------------------------------
FileSystemArchive::~FileSystemArchive()
{
unload();
}
//-----------------------------------------------------------------------
void FileSystemArchive::load()
{
// do nothing here, what has to be said will be said later
}
//-----------------------------------------------------------------------
void FileSystemArchive::unload()
{
// nothing to see here, move along
}
//-----------------------------------------------------------------------
DataStreamPtr FileSystemArchive::open(const String& filename) const
{
String full_path = concatenate_path(mName, filename);
// Use filesystem to determine size
// (quicker than streaming to the end and back)
struct stat tagStat;
int ret = stat(full_path.c_str(), &tagStat);
assert(ret == 0 && "Problem getting file size" );
// Always open in binary mode
std::ifstream *origStream = new std::ifstream();
origStream->open(full_path.c_str(), std::ios::in | std::ios::binary);
// Should check ensure open succeeded, in case fail for some reason.
if (origStream->fail())
{
delete origStream;
OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
"Cannot open file: " + filename,
"FileSystemArchive::open");
}
/// Construct return stream, tell it to delete on destroy
FileStreamDataStream* stream = new FileStreamDataStream(filename,
origStream, tagStat.st_size, true);
return DataStreamPtr(stream);
}
//-----------------------------------------------------------------------
StringVectorPtr FileSystemArchive::list(bool recursive, bool dirs)
{
// directory change requires locking due to saved returns
StringVectorPtr ret(new StringVector());
findFiles("*", recursive, dirs, ret.getPointer(), 0);
return ret;
}
//-----------------------------------------------------------------------
FileInfoListPtr FileSystemArchive::listFileInfo(bool recursive, bool dirs)
{
FileInfoListPtr ret(new FileInfoList());
findFiles("*", recursive, dirs, 0, ret.getPointer());
return ret;
}
//-----------------------------------------------------------------------
StringVectorPtr FileSystemArchive::find(const String& pattern,
bool recursive, bool dirs)
{
StringVectorPtr ret(new StringVector());
findFiles(pattern, recursive, dirs, ret.getPointer(), 0);
return ret;
}
//-----------------------------------------------------------------------
FileInfoListPtr FileSystemArchive::findFileInfo(const String& pattern,
bool recursive, bool dirs)
{
FileInfoListPtr ret(new FileInfoList());
findFiles(pattern, recursive, dirs, 0, ret.getPointer());
return ret;
}
//-----------------------------------------------------------------------
bool FileSystemArchive::exists(const String& filename)
{
String full_path = concatenate_path(mName, filename);
struct stat tagStat;
bool ret = (stat(full_path.c_str(), &tagStat) == 0);
// stat will return true if the filename is absolute, but we need to check
// the file is actually in this archive
if (ret && is_absolute_path(filename.c_str()))
{
// only valid if full path starts with our base
ret = Ogre::StringUtil::startsWith(full_path, mName);
}
return ret;
}
//-----------------------------------------------------------------------
const String& FileSystemArchiveFactory::getType(void) const
{
static String name = "FileSystem";
return name;
}
}
<commit_msg>Directory comparisons should be case insensitive on non-Windows platforms<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreFileSystem.h"
#include "OgreLogManager.h"
#include "OgreException.h"
#include "OgreStringVector.h"
#include "OgreRoot.h"
#include <sys/types.h>
#include <sys/stat.h>
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
# include "OgreSearchOps.h"
# include <sys/param.h>
# define MAX_PATH MAXPATHLEN
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# include <windows.h>
# include <direct.h>
# include <io.h>
#endif
namespace Ogre {
bool FileSystemArchive::ms_IgnoreHidden = true;
//-----------------------------------------------------------------------
FileSystemArchive::FileSystemArchive(const String& name, const String& archType )
: Archive(name, archType)
{
}
//-----------------------------------------------------------------------
bool FileSystemArchive::isCaseSensitive(void) const
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
return false;
#else
return true;
#endif
}
//-----------------------------------------------------------------------
static bool is_reserved_dir (const char *fn)
{
return (fn [0] == '.' && (fn [1] == 0 || (fn [1] == '.' && fn [2] == 0)));
}
//-----------------------------------------------------------------------
static bool is_absolute_path(const char* path)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
if (isalpha(uchar(path[0])) && path[1] == ':')
return true;
#endif
return path[0] == '/' || path[0] == '\\';
}
//-----------------------------------------------------------------------
static String concatenate_path(const String& base, const String& name)
{
if (base.empty() || is_absolute_path(name.c_str()))
return name;
else
return base + '/' + name;
}
//-----------------------------------------------------------------------
void FileSystemArchive::findFiles(const String& pattern, bool recursive,
bool dirs, StringVector* simpleList, FileInfoList* detailList)
{
long lHandle, res;
struct _finddata_t tagData;
// pattern can contain a directory name, separate it from mask
size_t pos1 = pattern.rfind ('/');
size_t pos2 = pattern.rfind ('\\');
if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2)))
pos1 = pos2;
String directory;
if (pos1 != pattern.npos)
directory = pattern.substr (0, pos1 + 1);
String full_pattern = concatenate_path(mName, pattern);
lHandle = _findfirst(full_pattern.c_str(), &tagData);
res = 0;
while (lHandle != -1 && res != -1)
{
if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) &&
( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
(!dirs || !is_reserved_dir (tagData.name)))
{
if (simpleList)
{
simpleList->push_back(directory + tagData.name);
}
else if (detailList)
{
FileInfo fi;
fi.archive = this;
fi.filename = directory + tagData.name;
fi.basename = tagData.name;
fi.path = directory;
fi.compressedSize = tagData.size;
fi.uncompressedSize = tagData.size;
detailList->push_back(fi);
}
}
res = _findnext( lHandle, &tagData );
}
// Close if we found any files
if(lHandle != -1)
_findclose(lHandle);
// Now find directories
if (recursive)
{
String base_dir = mName;
if (!directory.empty ())
{
base_dir = concatenate_path(mName, directory);
// Remove the last '/'
base_dir.erase (base_dir.length () - 1);
}
base_dir.append ("/*");
// Remove directory name from pattern
String mask ("/");
if (pos1 != pattern.npos)
mask.append (pattern.substr (pos1 + 1));
else
mask.append (pattern);
lHandle = _findfirst(base_dir.c_str (), &tagData);
res = 0;
while (lHandle != -1 && res != -1)
{
if ((tagData.attrib & _A_SUBDIR) &&
( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
!is_reserved_dir (tagData.name))
{
// recurse
base_dir = directory;
base_dir.append (tagData.name).append (mask);
findFiles(base_dir, recursive, dirs, simpleList, detailList);
}
res = _findnext( lHandle, &tagData );
}
// Close if we found any files
if(lHandle != -1)
_findclose(lHandle);
}
}
//-----------------------------------------------------------------------
FileSystemArchive::~FileSystemArchive()
{
unload();
}
//-----------------------------------------------------------------------
void FileSystemArchive::load()
{
// do nothing here, what has to be said will be said later
}
//-----------------------------------------------------------------------
void FileSystemArchive::unload()
{
// nothing to see here, move along
}
//-----------------------------------------------------------------------
DataStreamPtr FileSystemArchive::open(const String& filename) const
{
String full_path = concatenate_path(mName, filename);
// Use filesystem to determine size
// (quicker than streaming to the end and back)
struct stat tagStat;
int ret = stat(full_path.c_str(), &tagStat);
assert(ret == 0 && "Problem getting file size" );
// Always open in binary mode
std::ifstream *origStream = new std::ifstream();
origStream->open(full_path.c_str(), std::ios::in | std::ios::binary);
// Should check ensure open succeeded, in case fail for some reason.
if (origStream->fail())
{
delete origStream;
OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
"Cannot open file: " + filename,
"FileSystemArchive::open");
}
/// Construct return stream, tell it to delete on destroy
FileStreamDataStream* stream = new FileStreamDataStream(filename,
origStream, tagStat.st_size, true);
return DataStreamPtr(stream);
}
//-----------------------------------------------------------------------
StringVectorPtr FileSystemArchive::list(bool recursive, bool dirs)
{
// directory change requires locking due to saved returns
StringVectorPtr ret(new StringVector());
findFiles("*", recursive, dirs, ret.getPointer(), 0);
return ret;
}
//-----------------------------------------------------------------------
FileInfoListPtr FileSystemArchive::listFileInfo(bool recursive, bool dirs)
{
FileInfoListPtr ret(new FileInfoList());
findFiles("*", recursive, dirs, 0, ret.getPointer());
return ret;
}
//-----------------------------------------------------------------------
StringVectorPtr FileSystemArchive::find(const String& pattern,
bool recursive, bool dirs)
{
StringVectorPtr ret(new StringVector());
findFiles(pattern, recursive, dirs, ret.getPointer(), 0);
return ret;
}
//-----------------------------------------------------------------------
FileInfoListPtr FileSystemArchive::findFileInfo(const String& pattern,
bool recursive, bool dirs)
{
FileInfoListPtr ret(new FileInfoList());
findFiles(pattern, recursive, dirs, 0, ret.getPointer());
return ret;
}
//-----------------------------------------------------------------------
bool FileSystemArchive::exists(const String& filename)
{
String full_path = concatenate_path(mName, filename);
struct stat tagStat;
bool ret = (stat(full_path.c_str(), &tagStat) == 0);
// stat will return true if the filename is absolute, but we need to check
// the file is actually in this archive
if (ret && is_absolute_path(filename.c_str()))
{
// only valid if full path starts with our base
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
bool caseInsensitive = true;
#else
bool caseInsensitive = false;
#endif
ret = Ogre::StringUtil::startsWith(full_path, mName, caseInsensitive);
}
return ret;
}
//-----------------------------------------------------------------------
const String& FileSystemArchiveFactory::getType(void) const
{
static String name = "FileSystem";
return name;
}
}
<|endoftext|> |
<commit_before>// 01TextView.cpp : implementation of the CMy01TextView class
//
#include "stdafx.h"
#include "01Text.h"
#include "01TextDoc.h"
#include "01TextView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView
IMPLEMENT_DYNCREATE(CMy01TextView, CView)
BEGIN_MESSAGE_MAP(CMy01TextView, CView)
//{{AFX_MSG_MAP(CMy01TextView)
ON_WM_CREATE()
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView construction/destruction
CMy01TextView::CMy01TextView()
{
// TODO: add construction code here
}
CMy01TextView::~CMy01TextView()
{
}
BOOL CMy01TextView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView drawing
void CMy01TextView::OnDraw(CDC* pDC)
{
CMy01TextDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str("VC++ ");
pDC->TextOut(50, 50, str);
// ַԴַ
str.LoadString(IDS_STRINGVC);
pDC->TextOut(100, 100, str);
// ·㣬ַΧ
CSize sz = pDC->GetTextExtent(str);
pDC->BeginPath();
pDC->Rectangle(CRect(100, 100, 100 + sz.cx, 100 + sz.cy));
pDC->EndPath();
}
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView printing
BOOL CMy01TextView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CMy01TextView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CMy01TextView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView diagnostics
#ifdef _DEBUG
void CMy01TextView::AssertValid() const
{
CView::AssertValid();
}
void CMy01TextView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMy01TextDoc* CMy01TextView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy01TextDoc)));
return (CMy01TextDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView message handlers
int CMy01TextView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
// ֲܶʲôʾ
// CBitmap bitmap;
m_bitmap.LoadBitmap(IDB_BITMAP1);
CreateCaret(&m_bitmap);
ShowCaret();
return 0;
}
<commit_msg><需求实现>使视类中的绘图操作对路径层所在的区域无效 需求: 使视类中的绘图操作对路径层所在的区域无效 实现: 以RGN_DIFF模式选择路径层为裁剪区<commit_after>// 01TextView.cpp : implementation of the CMy01TextView class
//
#include "stdafx.h"
#include "01Text.h"
#include "01TextDoc.h"
#include "01TextView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView
IMPLEMENT_DYNCREATE(CMy01TextView, CView)
BEGIN_MESSAGE_MAP(CMy01TextView, CView)
//{{AFX_MSG_MAP(CMy01TextView)
ON_WM_CREATE()
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView construction/destruction
CMy01TextView::CMy01TextView()
{
// TODO: add construction code here
}
CMy01TextView::~CMy01TextView()
{
}
BOOL CMy01TextView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView drawing
void CMy01TextView::OnDraw(CDC* pDC)
{
CMy01TextDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str("VC++ ");
pDC->TextOut(50, 50, str);
// ַԴַ
str.LoadString(IDS_STRINGVC);
pDC->TextOut(100, 100, str);
// ·㣬ַΧ
CSize sz = pDC->GetTextExtent(str);
pDC->BeginPath();
pDC->Rectangle(CRect(100, 100, 100 + sz.cx, 100 + sz.cy));
pDC->EndPath();
pDC->SelectClipPath(RGN_DIFF);
// еĻͼӰ쵽·ˡ
for(int i = 0; i < 300; i += 10)
{
pDC->MoveTo(0, i);
pDC->LineTo(300, i);
pDC->MoveTo(i, 0);
pDC->LineTo(i, 300);
}
}
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView printing
BOOL CMy01TextView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CMy01TextView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CMy01TextView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView diagnostics
#ifdef _DEBUG
void CMy01TextView::AssertValid() const
{
CView::AssertValid();
}
void CMy01TextView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMy01TextDoc* CMy01TextView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy01TextDoc)));
return (CMy01TextDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMy01TextView message handlers
int CMy01TextView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
// ֲܶʲôʾ
// CBitmap bitmap;
m_bitmap.LoadBitmap(IDB_BITMAP1);
CreateCaret(&m_bitmap);
ShowCaret();
return 0;
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "bit_index_storage.hpp"
using std::pair;
using std::stringstream;
using std::string;
using std::vector;
namespace jubatus {
namespace core {
namespace storage {
bit_vector make_vector(const string& b) {
bit_vector v;
v.resize_and_clear(b.size());
for (size_t i = 0; i < b.size(); ++i) {
if (b[i] == '1') {
v.set_bit(i);
}
}
return v;
}
TEST(bit_index_storage, trivial) {
bit_index_storage s;
EXPECT_EQ("bit_index_storage", s.name());
s.set_row("r1", make_vector("0101"));
s.set_row("r2", make_vector("1010"));
s.set_row("r3", make_vector("1110"));
s.set_row("r4", make_vector("1100"));
vector<pair<string, float> > ids;
s.similar_row(make_vector("1100"), ids, 2);
ASSERT_EQ(2u, ids.size());
EXPECT_EQ("r4", ids[0].first);
EXPECT_FLOAT_EQ(1.0, ids[0].second);
EXPECT_EQ("r3", ids[1].first);
EXPECT_FLOAT_EQ(0.75, ids[1].second);
msgpack::sbuffer buf;
msgpack::packer<msgpack::sbuffer> packer(buf);
s.pack(packer);
bit_index_storage t;
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, buf.data(), buf.size());
t.unpack(unpacked.get());
ids.clear();
t.similar_row(make_vector("1100"), ids, 2);
ASSERT_EQ(2u, ids.size());
EXPECT_EQ("r4", ids[0].first);
s.remove_row("r4");
ids.clear();
s.similar_row(make_vector("1100"), ids, 2);
EXPECT_NE("r4", ids[0].first);
s.clear();
ids.clear();
s.similar_row(make_vector("1100"), ids, 2);
EXPECT_TRUE(ids.empty());
}
TEST(bit_index_storage, diff) {
bit_index_storage s1, s2;
s1.set_row("r1", make_vector("0101"));
s1.set_row("r2", make_vector("1010"));
bit_table_t d1;
s1.get_diff(d1);
s2.set_mixed_and_clear_diff(d1);
bit_vector v;
s2.get_row("r1", v);
EXPECT_TRUE(make_vector("0101") == v);
v.resize_and_clear(4);
s2.get_row("r2", v);
EXPECT_TRUE(make_vector("1010") == v);
}
TEST(bit_index_storage, mix) {
bit_index_storage s1, s2, s3;
s1.set_row("r1", make_vector("0101"));
s1.set_row("r2", make_vector("1010"));
bit_table_t d1;
s1.get_diff(d1);
s2.set_row("r1", make_vector("1110"));
s2.set_row("r3", make_vector("1100"));
bit_table_t d2;
s2.get_diff(d2);
s1.mix(d1, d2);
// d2 is
// r1: 0101 (s1)
// r2: 1010 (s1)
// r3: 1100 (s2)
s3.set_row("r1", make_vector("1111"));
s3.set_row("r2", make_vector("1111"));
s3.set_row("r3", make_vector("1111"));
s3.set_row("r4", make_vector("1111"));
s3.set_mixed_and_clear_diff(d2);
// r1, r2 and r3 are overwritten by d2
// r4 is no longer retained
bit_vector v;
s3.get_row("r1", v);
EXPECT_TRUE(v == make_vector("0101"));
s3.get_row("r2", v);
EXPECT_TRUE(v == make_vector("1010"));
s3.get_row("r3", v);
EXPECT_TRUE(v == make_vector("1100"));
s3.get_row("r4", v);
EXPECT_TRUE(v == bit_vector());
std::vector<std::string> ids;
s3.get_all_row_ids(ids);
EXPECT_EQ(3u, ids.size());
s3.remove_row("r3");
// Once MIXed, remove_row does not take affect until next MIX.
s3.get_all_row_ids(ids);
EXPECT_EQ(3u, ids.size());
// do MIX
bit_table_t d3;
s3.get_diff(d3);
s3.set_mixed_and_clear_diff(d3);
s3.get_all_row_ids(ids);
EXPECT_EQ(2u, ids.size());
}
} // namespace storage
} // namespace core
} // namespace jubatus
<commit_msg>remove unnecessary namespace prefix<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "bit_index_storage.hpp"
using std::pair;
using std::stringstream;
using std::string;
using std::vector;
namespace jubatus {
namespace core {
namespace storage {
bit_vector make_vector(const string& b) {
bit_vector v;
v.resize_and_clear(b.size());
for (size_t i = 0; i < b.size(); ++i) {
if (b[i] == '1') {
v.set_bit(i);
}
}
return v;
}
TEST(bit_index_storage, trivial) {
bit_index_storage s;
EXPECT_EQ("bit_index_storage", s.name());
s.set_row("r1", make_vector("0101"));
s.set_row("r2", make_vector("1010"));
s.set_row("r3", make_vector("1110"));
s.set_row("r4", make_vector("1100"));
vector<pair<string, float> > ids;
s.similar_row(make_vector("1100"), ids, 2);
ASSERT_EQ(2u, ids.size());
EXPECT_EQ("r4", ids[0].first);
EXPECT_FLOAT_EQ(1.0, ids[0].second);
EXPECT_EQ("r3", ids[1].first);
EXPECT_FLOAT_EQ(0.75, ids[1].second);
msgpack::sbuffer buf;
msgpack::packer<msgpack::sbuffer> packer(buf);
s.pack(packer);
bit_index_storage t;
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, buf.data(), buf.size());
t.unpack(unpacked.get());
ids.clear();
t.similar_row(make_vector("1100"), ids, 2);
ASSERT_EQ(2u, ids.size());
EXPECT_EQ("r4", ids[0].first);
s.remove_row("r4");
ids.clear();
s.similar_row(make_vector("1100"), ids, 2);
EXPECT_NE("r4", ids[0].first);
s.clear();
ids.clear();
s.similar_row(make_vector("1100"), ids, 2);
EXPECT_TRUE(ids.empty());
}
TEST(bit_index_storage, diff) {
bit_index_storage s1, s2;
s1.set_row("r1", make_vector("0101"));
s1.set_row("r2", make_vector("1010"));
bit_table_t d1;
s1.get_diff(d1);
s2.set_mixed_and_clear_diff(d1);
bit_vector v;
s2.get_row("r1", v);
EXPECT_TRUE(make_vector("0101") == v);
v.resize_and_clear(4);
s2.get_row("r2", v);
EXPECT_TRUE(make_vector("1010") == v);
}
TEST(bit_index_storage, mix) {
bit_index_storage s1, s2, s3;
s1.set_row("r1", make_vector("0101"));
s1.set_row("r2", make_vector("1010"));
bit_table_t d1;
s1.get_diff(d1);
s2.set_row("r1", make_vector("1110"));
s2.set_row("r3", make_vector("1100"));
bit_table_t d2;
s2.get_diff(d2);
s1.mix(d1, d2);
// d2 is
// r1: 0101 (s1)
// r2: 1010 (s1)
// r3: 1100 (s2)
s3.set_row("r1", make_vector("1111"));
s3.set_row("r2", make_vector("1111"));
s3.set_row("r3", make_vector("1111"));
s3.set_row("r4", make_vector("1111"));
s3.set_mixed_and_clear_diff(d2);
// r1, r2 and r3 are overwritten by d2
// r4 is no longer retained
bit_vector v;
s3.get_row("r1", v);
EXPECT_TRUE(v == make_vector("0101"));
s3.get_row("r2", v);
EXPECT_TRUE(v == make_vector("1010"));
s3.get_row("r3", v);
EXPECT_TRUE(v == make_vector("1100"));
s3.get_row("r4", v);
EXPECT_TRUE(v == bit_vector());
vector<string> ids;
s3.get_all_row_ids(ids);
EXPECT_EQ(3u, ids.size());
s3.remove_row("r3");
// Once MIXed, remove_row does not take affect until next MIX.
s3.get_all_row_ids(ids);
EXPECT_EQ(3u, ids.size());
// do MIX
bit_table_t d3;
s3.get_diff(d3);
s3.set_mixed_and_clear_diff(d3);
s3.get_all_row_ids(ids);
EXPECT_EQ(2u, ids.size());
}
} // namespace storage
} // namespace core
} // namespace jubatus
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QtCore>
#include <QtTest/QtTest>
#ifdef QT_NAMESPACE
#define STRINGIFY_HELPER(s) #s
#define STRINGIFY(s) STRINGIFY_HELPER(s)
QString ns = STRINGIFY(QT_NAMESPACE) + QString("::");
#else
QString ns;
#endif
class tst_Symbols: public QObject
{
Q_OBJECT
private slots:
void prefix();
void globalObjects();
};
/* Computes the line number from a symbol */
static QString symbolToLine(const QString &symbol, const QString &lib)
{
// nm outputs the symbol name, the type, the address and the size
QRegExp re("global constructors keyed to ([a-zA-Z_0-9.]*) (.) ([0-f]*) ([0-f]*)");
if (re.indexIn(symbol) == -1)
return QString();
// address and symbolSize are in hex. Convert to integers
bool ok;
int symbolAddress = re.cap(3).toInt(&ok, 16);
if (!ok)
return QString();
int symbolSize = re.cap(4).toInt(&ok, 16);
if (!ok)
return QString();
// now, find the start address, which is the address - size
QString startAddress = QString::number(symbolAddress - symbolSize, 16);
QProcess proc;
proc.start("addr2line", QStringList() << "-e" << lib << startAddress);
if (!proc.waitForFinished())
return QString();
QString result = QString::fromLocal8Bit(proc.readLine());
result.chop(1); // chop tailing newline
return result;
}
/* This test searches through all Qt libraries and searches for symbols
starting with "global constructors keyed to "
These indicate static global objects, which should not be used in shared
libraries - use Q_GLOBAL_STATIC instead.
*/
void tst_Symbols::globalObjects()
{
#ifndef Q_OS_LINUX
QSKIP("Linux-specific test", SkipAll);
#endif
// these are regexps for global objects that are allowed in Qt
QStringList whitelist = QStringList()
// ignore qInitResources - they are safe to use
<< "^_Z[0-9]*qInitResources_"
<< "qrc_.*\\.cpp"
// ignore qRegisterGuiVariant - it's a safe fallback to register GUI Variants
<< "qRegisterGuiVariant";
bool isFailed = false;
QDir dir(qgetenv("QTDIR") + "/lib", "*.so");
QStringList files = dir.entryList();
QVERIFY(!files.isEmpty());
foreach (QString lib, files) {
QProcess proc;
proc.start("nm",
QStringList() << "-C" << "--format=posix"
<< dir.absolutePath() + "/" + lib);
QVERIFY(proc.waitForFinished());
QCOMPARE(proc.exitCode(), 0);
QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()), QString());
QStringList symbols = QString::fromLocal8Bit(proc.readAll()).split("\n");
QVERIFY(!symbols.isEmpty());
foreach (QString symbol, symbols) {
if (symbol.isEmpty())
continue;
if (!symbol.startsWith("global constructors keyed to "))
continue;
QRegExp re("global constructors keyed to ([a-zA-Z_0-9.]*)");
QVERIFY(re.indexIn(symbol) != -1);
QString cap = re.cap(1);
bool whitelisted = false;
foreach (QString white, whitelist) {
if (cap.indexOf(QRegExp(white)) != -1) {
whitelisted = true;
break;
}
}
if (whitelisted)
continue;
QString line = symbolToLine(symbol, dir.absolutePath() + "/" + lib);
if (cap.contains('.'))
QWARN(qPrintable("Static global object(s) found in " + lib + " in file " + cap + " (" + line + ")"));
else
QWARN(qPrintable("Static global object found in " + lib + " near symbol " + cap + " (" + line + ")"));
isFailed = true;
}
}
if (isFailed) {
#if QT_VERSION >= 0x040600
QVERIFY2(!isFailed, "Libraries contain static global objects. See Debug output above.");
#else
QSKIP("Libraries contains static global objects. See Debug output above. [These errors cannot be fixed in 4.5 in time]", SkipSingle);
#endif
}
}
void tst_Symbols::prefix()
{
#if defined(QT_CROSS_COMPILED)
QSKIP("Probably no compiler on the target", SkipAll);
#elif defined(Q_OS_LINUX)
QStringList qtTypes;
qtTypes << "QString" << "QChar" << "QWidget" << "QObject" << "QVariant" << "QList"
<< "QMap" << "QHash" << "QVector" << "QRect" << "QSize" << "QPoint"
<< "QTextFormat" << "QTextLength" << "QPen" << "QFont" << "QIcon"
<< "QPixmap" << "QImage" << "QRegion" << "QPolygon";
QStringList qAlgorithmFunctions;
qAlgorithmFunctions << "qBinaryFind" << "qLowerBound" << "qUpperBound"
<< "qAbs" << "qMin" << "qMax" << "qBound" << "qSwap"
<< "qHash" << "qDeleteAll" << "qCopy" << "qSort";
QStringList exceptionalSymbols;
exceptionalSymbols << "XRectangle::~XRectangle()"
<< "XChar2b::~XChar2b()"
<< "XPoint::~XPoint()"
<< "glyph_metrics_t::"; // #### Qt 4.2
QStringList stupidCSymbols;
stupidCSymbols << "Add_Glyph_Property"
<< "Check_Property"
<< "Coverage_Index"
<< "Get_Class"
<< "Get_Device"
<< "rcsid3"
<< "sfnt_module_class"
<< "t1cid_driver_class"
<< "t42_driver_class"
<< "winfnt_driver_class"
<< "pshinter_module_class"
<< "psnames_module_class"
;
QHash<QString,QStringList> excusedPrefixes;
excusedPrefixes[QString()] =
QStringList() << "Ui_Q"; // uic generated, like Ui_QPrintDialog
excusedPrefixes["QtCore"] =
QStringList() << "hb_"
<< "HB_"
// zlib symbols, for -qt-zlib ;(
<< "deflate"
<< "compress"
<< "uncompress"
<< "adler32"
<< "gz"
<< "inflate"
<< "zlib"
<< "zError"
<< "get_crc_table"
<< "crc32";
excusedPrefixes["QtGui"] =
QStringList() << "ftglue_"
<< "Load_"
<< "otl_"
<< "TT_"
<< "tt_"
<< "t1_"
<< "Free_"
<< "FT_"
<< "FTC_"
<< "ft_"
<< "ftc_"
<< "af_autofitter"
<< "af_dummy"
<< "af_latin"
<< "autofit_"
<< "XPanorami"
<< "Xinerama"
<< "bdf_"
<< "ccf_"
<< "gray_raster"
<< "pcf_"
<< "cff_"
<< "otv_"
<< "pfr_"
<< "ps_"
<< "psaux"
<< "png_";
excusedPrefixes["QtSql"] =
QStringList() << "sqlite3";
excusedPrefixes["QtWebKit"] =
QStringList() << "WebCore::"
<< "KJS::"
<< "kjs"
<< "kJS"
<< "JS"
// << "OpaqueJS"
<< "WTF"
<< "wtf_"
<< "SVG::"
<< "NPN_"
<< "cti" // ctiTrampoline and ctiVMThrowTrampoline from the JIT
#ifdef QT_NAMESPACE
<< "QWeb" // Webkit is only 'namespace aware'
#endif
;
excusedPrefixes["phonon"] =
QStringList() << ns + "Phonon";
QDir dir(qgetenv("QTDIR") + "/lib", "*.so");
QStringList files = dir.entryList();
QVERIFY(!files.isEmpty());
bool isFailed = false;
foreach (QString lib, files) {
if (lib.contains("Designer") || lib.contains("QtCLucene") || lib.contains("XmlPatternsSDK"))
continue;
bool isPhonon = lib.contains("phonon");
QProcess proc;
proc.start("nm",
QStringList() << "-g" << "-C" << "-D" << "--format=posix"
<< "--defined-only" << dir.absolutePath() + "/" + lib);
QVERIFY(proc.waitForFinished());
QCOMPARE(proc.exitCode(), 0);
QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()), QString());
QStringList symbols = QString::fromLocal8Bit(proc.readAll()).split("\n");
QVERIFY(!symbols.isEmpty());
foreach (QString symbol, symbols) {
if (symbol.isEmpty())
continue;
if (symbol.startsWith("unsigned "))
// strip modifiers
symbol = symbol.mid(symbol.indexOf(' ') + 1);
if (symbol.startsWith("long long ")) {
symbol = symbol.mid(10);
} else if (symbol.startsWith("bool ") || symbol.startsWith("bool* ")
|| symbol.startsWith("char ") || symbol.startsWith("char* ")
|| symbol.startsWith("int ") || symbol.startsWith("int* ") || symbol.startsWith("int*&")
|| symbol.startsWith("short") || symbol.startsWith("long ")
|| symbol.startsWith("void ") || symbol.startsWith("void* ")
|| symbol.startsWith("double ") || symbol.startsWith("double* ")
|| symbol.startsWith("float ") || symbol.startsWith("float* ")) {
// partial templates have the return type in their demangled name, strip it
symbol = symbol.mid(symbol.indexOf(' ') + 1);
}
if (symbol.startsWith("const ") || symbol.startsWith("const* ") ||
symbol.startsWith("const& ")) {
// strip modifiers
symbol = symbol.mid(symbol.indexOf(' ') + 1);
}
if (symbol.startsWith("_") || symbol.startsWith("std::"))
continue;
if (symbol.startsWith("vtable ") || symbol.startsWith("VTT for ") ||
symbol.startsWith("construction vtable for"))
continue;
if (symbol.startsWith("typeinfo "))
continue;
if (symbol.startsWith("non-virtual thunk ") || symbol.startsWith("virtual thunk"))
continue;
if (symbol.startsWith(ns + "operator"))
continue;
if (symbol.startsWith("guard variable for "))
continue;
if (symbol.contains("(" + ns + "QTextStream"))
// QTextStream is excused.
continue;
if (symbol.contains("(" + ns + "Q3TextStream"))
// Q3TextStream is excused.
continue;
if (symbol.startsWith(ns + "bitBlt") || symbol.startsWith(ns + "copyBlt"))
// you're excused, too
continue;
bool symbolOk = false;
QHash<QString,QStringList>::ConstIterator it = excusedPrefixes.constBegin();
for ( ; it != excusedPrefixes.constEnd(); ++it) {
if (!lib.contains(it.key()))
continue;
foreach (QString prefix, it.value())
if (symbol.startsWith(prefix)) {
symbolOk = true;
break;
}
}
if (symbolOk)
continue;
foreach (QString cSymbolPattern, stupidCSymbols)
if (symbol.contains(cSymbolPattern)) {
symbolOk = true;
break;
}
if (symbolOk)
continue;
QStringList fields = symbol.split(' ');
// the last two fields are address and size and the third last field is the symbol type
QVERIFY(fields.count() > 3);
QString type = fields.at(fields.count() - 3);
// weak symbol
if (type == QLatin1String("W")) {
if (symbol.contains("qAtomic"))
continue;
if (symbol.contains("fstat")
|| symbol.contains("lstat")
|| symbol.contains("stat64")
)
continue;
foreach (QString acceptedPattern, qAlgorithmFunctions + exceptionalSymbols)
if (symbol.contains(acceptedPattern)) {
symbolOk = true;
break;
}
if (symbolOk)
continue;
QString plainSymbol;
for (int i = 0; i < fields.count() - 3; ++i) {
if (i > 0)
plainSymbol += QLatin1Char(' ');
plainSymbol += fields.at(i);
}
foreach (QString qtType, qtTypes)
if (plainSymbol.contains(qtType)) {
symbolOk = true;
break;
}
if (symbolOk)
continue;
}
QString prefix = ns + "q";
if (!symbol.startsWith(prefix, Qt::CaseInsensitive)
&& !(isPhonon && symbol.startsWith("Phonon"))) {
qDebug("symbol in '%s' does not start with prefix '%s': '%s'",
qPrintable(lib), qPrintable(prefix), qPrintable(symbol));
isFailed = true;
}
}
}
# if defined(Q_OS_LINUX) && defined(Q_CC_INTEL)
QEXPECT_FAIL("", "linux-icc* incorrectly exports some QtWebkit symbols, waiting for a fix from Intel.", Continue);
# endif
QVERIFY2(!isFailed, "Libraries contain non-prefixed symbols. See Debug output :)");
#else
QSKIP("Linux-specific test", SkipAll);
#endif
}
QTEST_MAIN(tst_Symbols)
#include "tst_symbols.moc"
<commit_msg>Autotest: disable the globalObjects test.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QtCore>
#include <QtTest/QtTest>
#ifdef QT_NAMESPACE
#define STRINGIFY_HELPER(s) #s
#define STRINGIFY(s) STRINGIFY_HELPER(s)
QString ns = STRINGIFY(QT_NAMESPACE) + QString("::");
#else
QString ns;
#endif
class tst_Symbols: public QObject
{
Q_OBJECT
private slots:
void prefix();
void globalObjects();
};
/* Computes the line number from a symbol */
static QString symbolToLine(const QString &symbol, const QString &lib)
{
// nm outputs the symbol name, the type, the address and the size
QRegExp re("global constructors keyed to ([a-zA-Z_0-9.]*) (.) ([0-f]*) ([0-f]*)");
if (re.indexIn(symbol) == -1)
return QString();
// address and symbolSize are in hex. Convert to integers
bool ok;
int symbolAddress = re.cap(3).toInt(&ok, 16);
if (!ok)
return QString();
int symbolSize = re.cap(4).toInt(&ok, 16);
if (!ok)
return QString();
// now, find the start address, which is the address - size
QString startAddress = QString::number(symbolAddress - symbolSize, 16);
QProcess proc;
proc.start("addr2line", QStringList() << "-e" << lib << startAddress);
if (!proc.waitForFinished())
return QString();
QString result = QString::fromLocal8Bit(proc.readLine());
result.chop(1); // chop tailing newline
return result;
}
/* This test searches through all Qt libraries and searches for symbols
starting with "global constructors keyed to "
These indicate static global objects, which should not be used in shared
libraries - use Q_GLOBAL_STATIC instead.
*/
void tst_Symbols::globalObjects()
{
#ifndef Q_OS_LINUX
QSKIP("Linux-specific test", SkipAll);
#endif
QSKIP("Test disabled, we're not fixing these issues in this Qt version", SkipAll);
// these are regexps for global objects that are allowed in Qt
QStringList whitelist = QStringList()
// ignore qInitResources - they are safe to use
<< "^_Z[0-9]*qInitResources_"
<< "qrc_.*\\.cpp"
// ignore qRegisterGuiVariant - it's a safe fallback to register GUI Variants
<< "qRegisterGuiVariant";
bool isFailed = false;
QDir dir(qgetenv("QTDIR") + "/lib", "*.so");
QStringList files = dir.entryList();
QVERIFY(!files.isEmpty());
foreach (QString lib, files) {
QProcess proc;
proc.start("nm",
QStringList() << "-C" << "--format=posix"
<< dir.absolutePath() + "/" + lib);
QVERIFY(proc.waitForFinished());
QCOMPARE(proc.exitCode(), 0);
QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()), QString());
QStringList symbols = QString::fromLocal8Bit(proc.readAll()).split("\n");
QVERIFY(!symbols.isEmpty());
foreach (QString symbol, symbols) {
if (symbol.isEmpty())
continue;
if (!symbol.startsWith("global constructors keyed to "))
continue;
QRegExp re("global constructors keyed to ([a-zA-Z_0-9.]*)");
QVERIFY(re.indexIn(symbol) != -1);
QString cap = re.cap(1);
bool whitelisted = false;
foreach (QString white, whitelist) {
if (cap.indexOf(QRegExp(white)) != -1) {
whitelisted = true;
break;
}
}
if (whitelisted)
continue;
QString line = symbolToLine(symbol, dir.absolutePath() + "/" + lib);
if (cap.contains('.'))
QWARN(qPrintable("Static global object(s) found in " + lib + " in file " + cap + " (" + line + ")"));
else
QWARN(qPrintable("Static global object found in " + lib + " near symbol " + cap + " (" + line + ")"));
isFailed = true;
}
}
if (isFailed) {
#if QT_VERSION >= 0x040600
QVERIFY2(!isFailed, "Libraries contain static global objects. See Debug output above.");
#else
QSKIP("Libraries contains static global objects. See Debug output above. [These errors cannot be fixed in 4.5 in time]", SkipSingle);
#endif
}
}
void tst_Symbols::prefix()
{
#if defined(QT_CROSS_COMPILED)
QSKIP("Probably no compiler on the target", SkipAll);
#elif defined(Q_OS_LINUX)
QStringList qtTypes;
qtTypes << "QString" << "QChar" << "QWidget" << "QObject" << "QVariant" << "QList"
<< "QMap" << "QHash" << "QVector" << "QRect" << "QSize" << "QPoint"
<< "QTextFormat" << "QTextLength" << "QPen" << "QFont" << "QIcon"
<< "QPixmap" << "QImage" << "QRegion" << "QPolygon";
QStringList qAlgorithmFunctions;
qAlgorithmFunctions << "qBinaryFind" << "qLowerBound" << "qUpperBound"
<< "qAbs" << "qMin" << "qMax" << "qBound" << "qSwap"
<< "qHash" << "qDeleteAll" << "qCopy" << "qSort";
QStringList exceptionalSymbols;
exceptionalSymbols << "XRectangle::~XRectangle()"
<< "XChar2b::~XChar2b()"
<< "XPoint::~XPoint()"
<< "glyph_metrics_t::"; // #### Qt 4.2
QStringList stupidCSymbols;
stupidCSymbols << "Add_Glyph_Property"
<< "Check_Property"
<< "Coverage_Index"
<< "Get_Class"
<< "Get_Device"
<< "rcsid3"
<< "sfnt_module_class"
<< "t1cid_driver_class"
<< "t42_driver_class"
<< "winfnt_driver_class"
<< "pshinter_module_class"
<< "psnames_module_class"
;
QHash<QString,QStringList> excusedPrefixes;
excusedPrefixes[QString()] =
QStringList() << "Ui_Q"; // uic generated, like Ui_QPrintDialog
excusedPrefixes["QtCore"] =
QStringList() << "hb_"
<< "HB_"
// zlib symbols, for -qt-zlib ;(
<< "deflate"
<< "compress"
<< "uncompress"
<< "adler32"
<< "gz"
<< "inflate"
<< "zlib"
<< "zError"
<< "get_crc_table"
<< "crc32";
excusedPrefixes["QtGui"] =
QStringList() << "ftglue_"
<< "Load_"
<< "otl_"
<< "TT_"
<< "tt_"
<< "t1_"
<< "Free_"
<< "FT_"
<< "FTC_"
<< "ft_"
<< "ftc_"
<< "af_autofitter"
<< "af_dummy"
<< "af_latin"
<< "autofit_"
<< "XPanorami"
<< "Xinerama"
<< "bdf_"
<< "ccf_"
<< "gray_raster"
<< "pcf_"
<< "cff_"
<< "otv_"
<< "pfr_"
<< "ps_"
<< "psaux"
<< "png_";
excusedPrefixes["QtSql"] =
QStringList() << "sqlite3";
excusedPrefixes["QtWebKit"] =
QStringList() << "WebCore::"
<< "KJS::"
<< "kjs"
<< "kJS"
<< "JS"
// << "OpaqueJS"
<< "WTF"
<< "wtf_"
<< "SVG::"
<< "NPN_"
<< "cti" // ctiTrampoline and ctiVMThrowTrampoline from the JIT
#ifdef QT_NAMESPACE
<< "QWeb" // Webkit is only 'namespace aware'
#endif
;
excusedPrefixes["phonon"] =
QStringList() << ns + "Phonon";
QDir dir(qgetenv("QTDIR") + "/lib", "*.so");
QStringList files = dir.entryList();
QVERIFY(!files.isEmpty());
bool isFailed = false;
foreach (QString lib, files) {
if (lib.contains("Designer") || lib.contains("QtCLucene") || lib.contains("XmlPatternsSDK"))
continue;
bool isPhonon = lib.contains("phonon");
QProcess proc;
proc.start("nm",
QStringList() << "-g" << "-C" << "-D" << "--format=posix"
<< "--defined-only" << dir.absolutePath() + "/" + lib);
QVERIFY(proc.waitForFinished());
QCOMPARE(proc.exitCode(), 0);
QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()), QString());
QStringList symbols = QString::fromLocal8Bit(proc.readAll()).split("\n");
QVERIFY(!symbols.isEmpty());
foreach (QString symbol, symbols) {
if (symbol.isEmpty())
continue;
if (symbol.startsWith("unsigned "))
// strip modifiers
symbol = symbol.mid(symbol.indexOf(' ') + 1);
if (symbol.startsWith("long long ")) {
symbol = symbol.mid(10);
} else if (symbol.startsWith("bool ") || symbol.startsWith("bool* ")
|| symbol.startsWith("char ") || symbol.startsWith("char* ")
|| symbol.startsWith("int ") || symbol.startsWith("int* ") || symbol.startsWith("int*&")
|| symbol.startsWith("short") || symbol.startsWith("long ")
|| symbol.startsWith("void ") || symbol.startsWith("void* ")
|| symbol.startsWith("double ") || symbol.startsWith("double* ")
|| symbol.startsWith("float ") || symbol.startsWith("float* ")) {
// partial templates have the return type in their demangled name, strip it
symbol = symbol.mid(symbol.indexOf(' ') + 1);
}
if (symbol.startsWith("const ") || symbol.startsWith("const* ") ||
symbol.startsWith("const& ")) {
// strip modifiers
symbol = symbol.mid(symbol.indexOf(' ') + 1);
}
if (symbol.startsWith("_") || symbol.startsWith("std::"))
continue;
if (symbol.startsWith("vtable ") || symbol.startsWith("VTT for ") ||
symbol.startsWith("construction vtable for"))
continue;
if (symbol.startsWith("typeinfo "))
continue;
if (symbol.startsWith("non-virtual thunk ") || symbol.startsWith("virtual thunk"))
continue;
if (symbol.startsWith(ns + "operator"))
continue;
if (symbol.startsWith("guard variable for "))
continue;
if (symbol.contains("(" + ns + "QTextStream"))
// QTextStream is excused.
continue;
if (symbol.contains("(" + ns + "Q3TextStream"))
// Q3TextStream is excused.
continue;
if (symbol.startsWith(ns + "bitBlt") || symbol.startsWith(ns + "copyBlt"))
// you're excused, too
continue;
bool symbolOk = false;
QHash<QString,QStringList>::ConstIterator it = excusedPrefixes.constBegin();
for ( ; it != excusedPrefixes.constEnd(); ++it) {
if (!lib.contains(it.key()))
continue;
foreach (QString prefix, it.value())
if (symbol.startsWith(prefix)) {
symbolOk = true;
break;
}
}
if (symbolOk)
continue;
foreach (QString cSymbolPattern, stupidCSymbols)
if (symbol.contains(cSymbolPattern)) {
symbolOk = true;
break;
}
if (symbolOk)
continue;
QStringList fields = symbol.split(' ');
// the last two fields are address and size and the third last field is the symbol type
QVERIFY(fields.count() > 3);
QString type = fields.at(fields.count() - 3);
// weak symbol
if (type == QLatin1String("W")) {
if (symbol.contains("qAtomic"))
continue;
if (symbol.contains("fstat")
|| symbol.contains("lstat")
|| symbol.contains("stat64")
)
continue;
foreach (QString acceptedPattern, qAlgorithmFunctions + exceptionalSymbols)
if (symbol.contains(acceptedPattern)) {
symbolOk = true;
break;
}
if (symbolOk)
continue;
QString plainSymbol;
for (int i = 0; i < fields.count() - 3; ++i) {
if (i > 0)
plainSymbol += QLatin1Char(' ');
plainSymbol += fields.at(i);
}
foreach (QString qtType, qtTypes)
if (plainSymbol.contains(qtType)) {
symbolOk = true;
break;
}
if (symbolOk)
continue;
}
QString prefix = ns + "q";
if (!symbol.startsWith(prefix, Qt::CaseInsensitive)
&& !(isPhonon && symbol.startsWith("Phonon"))) {
qDebug("symbol in '%s' does not start with prefix '%s': '%s'",
qPrintable(lib), qPrintable(prefix), qPrintable(symbol));
isFailed = true;
}
}
}
# if defined(Q_OS_LINUX) && defined(Q_CC_INTEL)
QEXPECT_FAIL("", "linux-icc* incorrectly exports some QtWebkit symbols, waiting for a fix from Intel.", Continue);
# endif
QVERIFY2(!isFailed, "Libraries contain non-prefixed symbols. See Debug output :)");
#else
QSKIP("Linux-specific test", SkipAll);
#endif
}
QTEST_MAIN(tst_Symbols)
#include "tst_symbols.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright (c) 2010-2014 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef __MDDS_FLAT_SEGMENT_TREE_ITR_HPP__
#define __MDDS_FLAT_SEGMENT_TREE_ITR_HPP__
namespace mdds { namespace __fst {
/**
* Handler for forward iterator
*/
template<typename _FstType>
struct itr_forward_handler
{
typedef _FstType fst_type;
static const typename fst_type::node* init_pos(const fst_type* _db, bool _end)
{
return _end ? _db->m_right_leaf.get() : _db->m_left_leaf.get();
}
static void inc(const fst_type* _db, const typename fst_type::node*& p, bool& end)
{
if (p == _db->m_right_leaf.get())
end = true;
else
p = p->next.get();
}
static void dec(const typename fst_type::node*& p, bool& end)
{
if (end)
end = false;
else
p = p->prev.get();
}
};
/**
* Handler for reverse iterator
*/
template<typename _FstType>
struct itr_reverse_handler
{
typedef _FstType fst_type;
static const typename fst_type::node* init_pos(const fst_type* _db, bool _end)
{
return _end ? _db->m_left_leaf.get() : _db->m_right_leaf.get();
}
static void inc(const fst_type* _db, const typename fst_type::node*& p, bool& end)
{
if (p == _db->m_left_leaf.get())
end = true;
else
p = p->prev.get();
}
static void dec(const typename fst_type::node*& p, bool& end)
{
if (end)
end = false;
else
p = p->next.get();
}
};
template<typename _FstType, typename _Hdl>
class const_iterator_base
{
typedef _Hdl handler_type;
public:
typedef _FstType fst_type;
// iterator traits
typedef ::std::pair<typename fst_type::key_type, typename fst_type::value_type> value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef ::std::bidirectional_iterator_tag iterator_category;
explicit const_iterator_base(const fst_type* _db, bool _end) :
m_db(_db), m_pos(nullptr), m_end_pos(_end)
{
if (!_db)
return;
m_pos = handler_type::init_pos(_db, _end);
}
explicit const_iterator_base(const fst_type* _db, const typename fst_type::node* pos) :
m_db(_db), m_pos(pos), m_end_pos(false) {}
const_iterator_base(const const_iterator_base& r) :
m_db(r.m_db), m_pos(r.m_pos), m_end_pos(r.m_end_pos) {}
const_iterator_base& operator=(const const_iterator_base& r)
{
m_db = r.m_db;
m_pos = r.m_pos;
m_end_pos = r.m_end_pos;
return *this;
}
const value_type* operator++()
{
assert(m_pos);
handler_type::inc(m_db, m_pos, m_end_pos);
return operator->();
}
const value_type* operator--()
{
assert(m_pos);
handler_type::dec(m_pos, m_end_pos);
return operator->();
}
bool operator==(const const_iterator_base& r) const
{
if (m_db != r.m_db)
return false;
return (m_pos == r.m_pos) && (m_end_pos == r.m_end_pos);
}
bool operator!=(const const_iterator_base& r) const
{
return !operator==(r);
}
const value_type& operator*()
{
return get_current_node_pair();
}
const value_type* operator->()
{
return &get_current_node_pair();
}
protected:
const typename fst_type::node* get_pos() const { return m_pos; }
const fst_type* get_parent() const { return m_db; }
private:
const value_type& get_current_node_pair()
{
m_current_pair = value_type(m_pos->value_leaf.key, m_pos->value_leaf.value);
return m_current_pair;
}
const fst_type* m_db;
const typename fst_type::node* m_pos;
value_type m_current_pair;
bool m_end_pos;
};
}}
#endif
<commit_msg>fix return values for the operator++/-- in the flat_segement_tree iterators<commit_after>/*************************************************************************
*
* Copyright (c) 2010-2014 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef __MDDS_FLAT_SEGMENT_TREE_ITR_HPP__
#define __MDDS_FLAT_SEGMENT_TREE_ITR_HPP__
namespace mdds { namespace __fst {
/**
* Handler for forward iterator
*/
template<typename _FstType>
struct itr_forward_handler
{
typedef _FstType fst_type;
static const typename fst_type::node* init_pos(const fst_type* _db, bool _end)
{
return _end ? _db->m_right_leaf.get() : _db->m_left_leaf.get();
}
static void inc(const fst_type* _db, const typename fst_type::node*& p, bool& end)
{
if (p == _db->m_right_leaf.get())
end = true;
else
p = p->next.get();
}
static void dec(const typename fst_type::node*& p, bool& end)
{
if (end)
end = false;
else
p = p->prev.get();
}
};
/**
* Handler for reverse iterator
*/
template<typename _FstType>
struct itr_reverse_handler
{
typedef _FstType fst_type;
static const typename fst_type::node* init_pos(const fst_type* _db, bool _end)
{
return _end ? _db->m_left_leaf.get() : _db->m_right_leaf.get();
}
static void inc(const fst_type* _db, const typename fst_type::node*& p, bool& end)
{
if (p == _db->m_left_leaf.get())
end = true;
else
p = p->prev.get();
}
static void dec(const typename fst_type::node*& p, bool& end)
{
if (end)
end = false;
else
p = p->next.get();
}
};
template<typename _FstType, typename _Hdl>
class const_iterator_base
{
typedef _Hdl handler_type;
public:
typedef _FstType fst_type;
// iterator traits
typedef ::std::pair<typename fst_type::key_type, typename fst_type::value_type> value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef ::std::bidirectional_iterator_tag iterator_category;
explicit const_iterator_base(const fst_type* _db, bool _end) :
m_db(_db), m_pos(nullptr), m_end_pos(_end)
{
if (!_db)
return;
m_pos = handler_type::init_pos(_db, _end);
}
explicit const_iterator_base(const fst_type* _db, const typename fst_type::node* pos) :
m_db(_db), m_pos(pos), m_end_pos(false) {}
const_iterator_base(const const_iterator_base& r) :
m_db(r.m_db), m_pos(r.m_pos), m_end_pos(r.m_end_pos) {}
const_iterator_base& operator=(const const_iterator_base& r)
{
m_db = r.m_db;
m_pos = r.m_pos;
m_end_pos = r.m_end_pos;
return *this;
}
const_iterator_base& operator++()
{
assert(m_pos);
handler_type::inc(m_db, m_pos, m_end_pos);
return *this;
}
const_iterator_base operator--()
{
assert(m_pos);
handler_type::dec(m_pos, m_end_pos);
return *this;
}
bool operator==(const const_iterator_base& r) const
{
if (m_db != r.m_db)
return false;
return (m_pos == r.m_pos) && (m_end_pos == r.m_end_pos);
}
bool operator!=(const const_iterator_base& r) const
{
return !operator==(r);
}
const value_type& operator*()
{
return get_current_node_pair();
}
const value_type* operator->()
{
return &get_current_node_pair();
}
protected:
const typename fst_type::node* get_pos() const { return m_pos; }
const fst_type* get_parent() const { return m_db; }
private:
const value_type& get_current_node_pair()
{
m_current_pair = value_type(m_pos->value_leaf.key, m_pos->value_leaf.value);
return m_current_pair;
}
const fst_type* m_db;
const typename fst_type::node* m_pos;
value_type m_current_pair;
bool m_end_pos;
};
}}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright (c) 2012-2013 Kohei Yoshida
*
* 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.
*
************************************************************************/
namespace mdds { namespace __mtv {
/**
* Node that represents the content of each iterator. The private data part
* is an implementation detail that should never be accessed externally.
* What the end position stores in its private data is totally &
* intentionally undefined.
*/
template<typename _SizeT, typename _ElemBlkT>
struct iterator_value_node
{
typedef _SizeT size_type;
typedef _ElemBlkT element_block_type;
mdds::mtv::element_t type;
size_type size;
element_block_type* data;
iterator_value_node(size_type start_pos, size_type block_index) :
type(mdds::mtv::element_type_empty), size(0), data(NULL), __private_data(start_pos, block_index) {}
iterator_value_node(const iterator_value_node& other) :
type(other.type), size(other.size), data(other.data), __private_data(other.__private_data) {}
void swap(iterator_value_node& other)
{
std::swap(type, other.type);
std::swap(size, other.size);
std::swap(data, other.data);
__private_data.swap(other.__private_data);
}
struct private_data
{
size_type start_pos;
size_type block_index;
private_data() : start_pos(0), block_index(0) {}
private_data(size_type _start_pos, size_type _block_index) :
start_pos(_start_pos), block_index(_block_index) {}
private_data(const private_data& other) :
start_pos(other.start_pos), block_index(other.block_index) {}
void swap(private_data& other)
{
std::swap(start_pos, other.start_pos);
std::swap(block_index, other.block_index);
}
};
private_data __private_data;
bool operator== (const iterator_value_node& other) const
{
return type == other.type && size == other.size && data == other.data &&
__private_data.start_pos == other.__private_data.start_pos &&
__private_data.block_index == other.__private_data.block_index;
}
bool operator!= (const iterator_value_node& other) const
{
return !operator== (other);
}
};
template<typename _NodeT>
struct private_data_no_update
{
typedef _NodeT node_type;
static void inc(node_type&) {}
static void dec(node_type&) {}
};
template<typename _NodeT>
struct private_data_forward_update
{
typedef _NodeT node_type;
static void inc(node_type& nd)
{
++nd.__private_data.block_index;
nd.__private_data.start_pos += nd.size;
}
static void dec(node_type& nd)
{
--nd.__private_data.block_index;
nd.__private_data.start_pos -= nd.size;
}
};
/**
* Common base for both const and non-const iterators. Its protected inc()
* and dec() methods have non-const return type, and the derived classes
* wrap them and return values with their respective const modifiers.
*/
template<typename _Trait>
class iterator_common_base
{
protected:
typedef typename _Trait::parent parent_type;
typedef typename _Trait::blocks blocks_type;
typedef typename _Trait::base_iterator base_iterator_type;
typedef typename parent_type::size_type size_type;
typedef iterator_value_node<size_type, typename parent_type::element_block_type> node;
iterator_common_base() : m_cur_node(0, 0) {}
iterator_common_base(
const base_iterator_type& pos, const base_iterator_type& end,
size_type start_pos, size_type block_index) :
m_cur_node(start_pos, block_index),
m_pos(pos),
m_end(end)
{
if (m_pos != m_end)
update_node();
}
iterator_common_base(const iterator_common_base& other) :
m_cur_node(other.m_cur_node),
m_pos(other.m_pos),
m_end(other.m_end)
{
}
void update_node()
{
#ifdef MDDS_MULTI_TYPE_VECTOR_DEBUG
if (m_pos == m_end)
throw general_error("Current node position should never equal the end position during node update.");
#endif
// blocks_type::value_type is a pointer to multi_type_vector::block.
typename blocks_type::value_type blk = *m_pos;
if (blk->mp_data)
m_cur_node.type = mdds::mtv::get_block_type(*blk->mp_data);
else
m_cur_node.type = mdds::mtv::element_type_empty;
m_cur_node.size = blk->m_size;
m_cur_node.data = blk->mp_data;
}
node* inc()
{
++m_pos;
if (m_pos == m_end)
return NULL;
update_node();
return &m_cur_node;
}
node* dec()
{
--m_pos;
update_node();
return &m_cur_node;
}
node m_cur_node;
base_iterator_type m_pos;
base_iterator_type m_end;
public:
bool operator== (const iterator_common_base& other) const
{
if (m_pos != m_end && other.m_pos != other.m_end)
{
// TODO: Set hard-coded values to the current node for the end
// position nodes to remove this if block.
if (m_cur_node != other.m_cur_node)
return false;
}
return m_pos == other.m_pos && m_end == other.m_end;
}
bool operator!= (const iterator_common_base& other) const
{
return !operator==(other);
}
iterator_common_base& operator= (const iterator_common_base& other)
{
iterator_common_base assigned(other);
swap(assigned);
return *this;
}
void swap(iterator_common_base& other)
{
m_cur_node.swap(other.m_cur_node);
std::swap(m_pos, other.m_pos);
std::swap(m_end, other.m_end);
}
};
template<typename _Trait, typename _NodeUpdateFunc>
class iterator_base : public iterator_common_base<_Trait>
{
typedef _Trait trait;
typedef _NodeUpdateFunc node_update_func;
typedef iterator_common_base<trait> common_base;
typedef typename trait::base_iterator base_iterator_type;
typedef typename common_base::size_type size_type;
using common_base::inc;
using common_base::dec;
using common_base::m_cur_node;
using common_base::m_pos;
using common_base::m_end;
public:
// iterator traits
typedef typename common_base::node value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
public:
iterator_base() {}
iterator_base(
const base_iterator_type& pos, const base_iterator_type& end,
size_type start_pos, size_type block_index) :
common_base(pos, end, start_pos, block_index) {}
iterator_base(const iterator_base& other) :
common_base(other) {}
value_type& operator*()
{
return m_cur_node;
}
const value_type& operator*() const
{
return m_cur_node;
}
value_type* operator->()
{
return &m_cur_node;
}
const value_type* operator->() const
{
return &m_cur_node;
}
value_type* operator++()
{
node_update_func::inc(m_cur_node);
return inc();
}
value_type* operator--()
{
value_type* ret = dec();
node_update_func::dec(m_cur_node);
return ret;
}
/**
* These method are public only to allow const_iterator_base to
* instantiate from iterator_base.
*/
const base_iterator_type& get_pos() const { return m_pos; }
const base_iterator_type& get_end() const { return m_end; }
};
template<typename _Trait, typename _NonConstItrBase>
class const_iterator_base : public iterator_common_base<_Trait>
{
typedef _Trait trait;
typedef iterator_common_base<trait> common_base;
typedef typename trait::base_iterator base_iterator_type;
typedef typename common_base::size_type size_type;
using common_base::inc;
using common_base::dec;
using common_base::m_cur_node;
public:
typedef _NonConstItrBase iterator_base;
// iterator traits
typedef typename common_base::node value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
public:
const_iterator_base() : common_base() {}
const_iterator_base(
const base_iterator_type& pos, const base_iterator_type& end,
size_type start_pos, size_type block_index) :
common_base(pos, end, start_pos, block_index) {}
const_iterator_base(const const_iterator_base& other) :
common_base(other) {}
/**
* Take the non-const iterator counterpart to create a const iterator.
*/
const_iterator_base(const iterator_base& other) :
common_base(other.get_pos(), other.get_end(), 0, 0) {}
const value_type& operator*() const
{
return m_cur_node;
}
const value_type* operator->() const
{
return &m_cur_node;
}
const value_type* operator++()
{
return inc();
}
const value_type* operator--()
{
return dec();
}
bool operator== (const const_iterator_base& other) const
{
return iterator_common_base<_Trait>::operator==(other);
}
bool operator!= (const const_iterator_base& other) const
{
return iterator_common_base<_Trait>::operator!=(other);
}
};
}}
<commit_msg>I forgot to guard this header.<commit_after>/*************************************************************************
*
* Copyright (c) 2012-2013 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef MDDS_MULTI_TYPE_VECTOR_ITR_HPP
#define MDDS_MULTI_TYPE_VECTOR_ITR_HPP
#include "multi_type_vector_types.hpp"
namespace mdds { namespace __mtv {
/**
* Node that represents the content of each iterator. The private data part
* is an implementation detail that should never be accessed externally.
* What the end position stores in its private data is totally &
* intentionally undefined.
*/
template<typename _SizeT, typename _ElemBlkT>
struct iterator_value_node
{
typedef _SizeT size_type;
typedef _ElemBlkT element_block_type;
mdds::mtv::element_t type;
size_type size;
element_block_type* data;
iterator_value_node(size_type start_pos, size_type block_index) :
type(mdds::mtv::element_type_empty), size(0), data(NULL), __private_data(start_pos, block_index) {}
iterator_value_node(const iterator_value_node& other) :
type(other.type), size(other.size), data(other.data), __private_data(other.__private_data) {}
void swap(iterator_value_node& other)
{
std::swap(type, other.type);
std::swap(size, other.size);
std::swap(data, other.data);
__private_data.swap(other.__private_data);
}
struct private_data
{
size_type start_pos;
size_type block_index;
private_data() : start_pos(0), block_index(0) {}
private_data(size_type _start_pos, size_type _block_index) :
start_pos(_start_pos), block_index(_block_index) {}
private_data(const private_data& other) :
start_pos(other.start_pos), block_index(other.block_index) {}
void swap(private_data& other)
{
std::swap(start_pos, other.start_pos);
std::swap(block_index, other.block_index);
}
};
private_data __private_data;
bool operator== (const iterator_value_node& other) const
{
return type == other.type && size == other.size && data == other.data &&
__private_data.start_pos == other.__private_data.start_pos &&
__private_data.block_index == other.__private_data.block_index;
}
bool operator!= (const iterator_value_node& other) const
{
return !operator== (other);
}
};
template<typename _NodeT>
struct private_data_no_update
{
typedef _NodeT node_type;
static void inc(node_type&) {}
static void dec(node_type&) {}
};
template<typename _NodeT>
struct private_data_forward_update
{
typedef _NodeT node_type;
static void inc(node_type& nd)
{
++nd.__private_data.block_index;
nd.__private_data.start_pos += nd.size;
}
static void dec(node_type& nd)
{
--nd.__private_data.block_index;
nd.__private_data.start_pos -= nd.size;
}
};
/**
* Common base for both const and non-const iterators. Its protected inc()
* and dec() methods have non-const return type, and the derived classes
* wrap them and return values with their respective const modifiers.
*/
template<typename _Trait>
class iterator_common_base
{
protected:
typedef typename _Trait::parent parent_type;
typedef typename _Trait::blocks blocks_type;
typedef typename _Trait::base_iterator base_iterator_type;
typedef typename parent_type::size_type size_type;
typedef iterator_value_node<size_type, typename parent_type::element_block_type> node;
iterator_common_base() : m_cur_node(0, 0) {}
iterator_common_base(
const base_iterator_type& pos, const base_iterator_type& end,
size_type start_pos, size_type block_index) :
m_cur_node(start_pos, block_index),
m_pos(pos),
m_end(end)
{
if (m_pos != m_end)
update_node();
}
iterator_common_base(const iterator_common_base& other) :
m_cur_node(other.m_cur_node),
m_pos(other.m_pos),
m_end(other.m_end)
{
}
void update_node()
{
#ifdef MDDS_MULTI_TYPE_VECTOR_DEBUG
if (m_pos == m_end)
throw general_error("Current node position should never equal the end position during node update.");
#endif
// blocks_type::value_type is a pointer to multi_type_vector::block.
typename blocks_type::value_type blk = *m_pos;
if (blk->mp_data)
m_cur_node.type = mdds::mtv::get_block_type(*blk->mp_data);
else
m_cur_node.type = mdds::mtv::element_type_empty;
m_cur_node.size = blk->m_size;
m_cur_node.data = blk->mp_data;
}
node* inc()
{
++m_pos;
if (m_pos == m_end)
return NULL;
update_node();
return &m_cur_node;
}
node* dec()
{
--m_pos;
update_node();
return &m_cur_node;
}
node m_cur_node;
base_iterator_type m_pos;
base_iterator_type m_end;
public:
bool operator== (const iterator_common_base& other) const
{
if (m_pos != m_end && other.m_pos != other.m_end)
{
// TODO: Set hard-coded values to the current node for the end
// position nodes to remove this if block.
if (m_cur_node != other.m_cur_node)
return false;
}
return m_pos == other.m_pos && m_end == other.m_end;
}
bool operator!= (const iterator_common_base& other) const
{
return !operator==(other);
}
iterator_common_base& operator= (const iterator_common_base& other)
{
iterator_common_base assigned(other);
swap(assigned);
return *this;
}
void swap(iterator_common_base& other)
{
m_cur_node.swap(other.m_cur_node);
std::swap(m_pos, other.m_pos);
std::swap(m_end, other.m_end);
}
};
template<typename _Trait, typename _NodeUpdateFunc>
class iterator_base : public iterator_common_base<_Trait>
{
typedef _Trait trait;
typedef _NodeUpdateFunc node_update_func;
typedef iterator_common_base<trait> common_base;
typedef typename trait::base_iterator base_iterator_type;
typedef typename common_base::size_type size_type;
using common_base::inc;
using common_base::dec;
using common_base::m_cur_node;
using common_base::m_pos;
using common_base::m_end;
public:
// iterator traits
typedef typename common_base::node value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
public:
iterator_base() {}
iterator_base(
const base_iterator_type& pos, const base_iterator_type& end,
size_type start_pos, size_type block_index) :
common_base(pos, end, start_pos, block_index) {}
iterator_base(const iterator_base& other) :
common_base(other) {}
value_type& operator*()
{
return m_cur_node;
}
const value_type& operator*() const
{
return m_cur_node;
}
value_type* operator->()
{
return &m_cur_node;
}
const value_type* operator->() const
{
return &m_cur_node;
}
value_type* operator++()
{
node_update_func::inc(m_cur_node);
return inc();
}
value_type* operator--()
{
value_type* ret = dec();
node_update_func::dec(m_cur_node);
return ret;
}
/**
* These method are public only to allow const_iterator_base to
* instantiate from iterator_base.
*/
const base_iterator_type& get_pos() const { return m_pos; }
const base_iterator_type& get_end() const { return m_end; }
};
template<typename _Trait, typename _NonConstItrBase>
class const_iterator_base : public iterator_common_base<_Trait>
{
typedef _Trait trait;
typedef iterator_common_base<trait> common_base;
typedef typename trait::base_iterator base_iterator_type;
typedef typename common_base::size_type size_type;
using common_base::inc;
using common_base::dec;
using common_base::m_cur_node;
public:
typedef _NonConstItrBase iterator_base;
// iterator traits
typedef typename common_base::node value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
public:
const_iterator_base() : common_base() {}
const_iterator_base(
const base_iterator_type& pos, const base_iterator_type& end,
size_type start_pos, size_type block_index) :
common_base(pos, end, start_pos, block_index) {}
const_iterator_base(const const_iterator_base& other) :
common_base(other) {}
/**
* Take the non-const iterator counterpart to create a const iterator.
*/
const_iterator_base(const iterator_base& other) :
common_base(other.get_pos(), other.get_end(), 0, 0) {}
const value_type& operator*() const
{
return m_cur_node;
}
const value_type* operator->() const
{
return &m_cur_node;
}
const value_type* operator++()
{
return inc();
}
const value_type* operator--()
{
return dec();
}
bool operator== (const const_iterator_base& other) const
{
return iterator_common_base<_Trait>::operator==(other);
}
bool operator!= (const const_iterator_base& other) const
{
return iterator_common_base<_Trait>::operator!=(other);
}
};
}}
#endif
<|endoftext|> |
<commit_before>/**
* \file
* \brief Basic UDP receiver
*
* \copyright 2012 Omnibius, LLC
* \author Dmitriy Kargapolov
* \version 1.0
* \since 27 May 2012
*
*/
/*
* Copyright (c) 2012 Omnibius, LLC
* Author: Dmitriy Kargapolov <dmitriy.kargapolov@gmail.com>
* Use, modification and distribution are subject to the Boost Software
* License, Version 1.0 (See accompanying file LICENSE_1_0.txt or copy
* at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef _UTIL_IO_BASIC_UDP_RECEIVER_HPP_
#define _UTIL_IO_BASIC_UDP_RECEIVER_HPP_
#include <boost/asio.hpp>
#include <util/buffer.hpp>
namespace util {
namespace io {
template <typename Derived, size_t BufSize = 16*1024>
class basic_udp_receiver : private boost::noncopyable {
public:
typedef basic_io_buffer<BufSize> buffer_type;
/// Constructor
basic_udp_receiver(boost::asio::io_service& a_io_service)
: m_io_service(a_io_service)
, m_socket(a_io_service)
{}
void init(int a_port, size_t a_buf_sz = 0) {
init(boost::asio::ip::udp::endpoint(
boost::asio::ip::udp::v4(), a_port),
a_buf_sz);
}
void init(const std::string& a_host, const std::string& a_service, size_t a_buf_sz = 0) {
boost::asio::ip::udp::resolver l_resolver(m_io_service);
boost::asio::ip::udp::resolver::query l_query(a_host, a_service);
boost::asio::ip::udp::endpoint l_ep = *l_resolver.resolve(l_query);
init(l_ep, a_buf_sz);
}
void init(boost::asio::ip::udp::endpoint a_endpoint, size_t a_buf_sz = 0) {
m_socket.open(a_endpoint.protocol());
boost::asio::socket_base::reuse_address l_opt(true);
m_socket.set_option(l_opt);
if (a_buf_sz) {
boost::asio::socket_base::send_buffer_size l_opt(a_buf_sz);
m_socket.set_option(l_opt);
}
m_socket.bind(a_endpoint);
}
/// Begin reading from socket
void start() { m_rx_bytes = 0; async_read(); }
/// Request to stop
void stop() { m_socket.close(); }
/// Accessor to internal socket
boost::asio::ip::udp::socket& socket() { return m_socket; }
/// Total number of bytes received
size_t rx_bytes() const { return m_rx_bytes; }
private:
/// Start asynchronous socket read.
void async_read() {
m_socket.async_receive_from(m_in_buffer.space(), m_sender_endpoint,
boost::bind(&basic_udp_receiver::handle_read,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/// Handle completion of a read operation.
void handle_read(const boost::system::error_code& e, std::size_t n) {
if (!e && n > 0) {
m_rx_bytes += n;
m_in_buffer.commit(n);
static_cast<Derived*>(this)->on_data(m_in_buffer);
m_in_buffer.crunch();
async_read();
}
}
/// The io_service used to perform asynchronous operations.
boost::asio::io_service& m_io_service;
/// Socket for basic_udp_receiver
boost::asio::ip::udp::socket m_socket;
/// Sender address
boost::asio::ip::udp::endpoint m_sender_endpoint;
/// Buffer for incoming data.
buffer_type m_in_buffer;
/// Total number of bytes read from socket
size_t m_rx_bytes;
};
} // namespace io
} // namespace util
#endif // _UTIL_IO_BASIC_UDP_RECEIVER_HPP_
<commit_msg>socket option typo fix<commit_after>/**
* \file
* \brief Basic UDP receiver
*
* \copyright 2012 Omnibius, LLC
* \author Dmitriy Kargapolov
* \version 1.0
* \since 27 May 2012
*
*/
/*
* Copyright (c) 2012 Omnibius, LLC
* Author: Dmitriy Kargapolov <dmitriy.kargapolov@gmail.com>
* Use, modification and distribution are subject to the Boost Software
* License, Version 1.0 (See accompanying file LICENSE_1_0.txt or copy
* at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef _UTIL_IO_BASIC_UDP_RECEIVER_HPP_
#define _UTIL_IO_BASIC_UDP_RECEIVER_HPP_
#include <boost/asio.hpp>
#include <util/buffer.hpp>
namespace util {
namespace io {
template <typename Derived, size_t BufSize = 16*1024>
class basic_udp_receiver : private boost::noncopyable {
public:
typedef basic_io_buffer<BufSize> buffer_type;
/// Constructor
basic_udp_receiver(boost::asio::io_service& a_io_service)
: m_io_service(a_io_service)
, m_socket(a_io_service)
{}
void init(int a_port, size_t a_buf_sz = 0) {
init(boost::asio::ip::udp::endpoint(
boost::asio::ip::udp::v4(), a_port),
a_buf_sz);
}
void init(const std::string& a_host, const std::string& a_service, size_t a_buf_sz = 0) {
boost::asio::ip::udp::resolver l_resolver(m_io_service);
boost::asio::ip::udp::resolver::query l_query(a_host, a_service);
boost::asio::ip::udp::endpoint l_ep = *l_resolver.resolve(l_query);
init(l_ep, a_buf_sz);
}
void init(boost::asio::ip::udp::endpoint a_endpoint, size_t a_buf_sz = 0) {
m_socket.open(a_endpoint.protocol());
boost::asio::socket_base::reuse_address l_opt(true);
m_socket.set_option(l_opt);
if (a_buf_sz) {
boost::asio::socket_base::receive_buffer_size l_opt(a_buf_sz);
m_socket.set_option(l_opt);
}
m_socket.bind(a_endpoint);
}
/// Begin reading from socket
void start() { m_rx_bytes = 0; async_read(); }
/// Request to stop
void stop() { m_socket.close(); }
/// Accessor to internal socket
boost::asio::ip::udp::socket& socket() { return m_socket; }
/// Total number of bytes received
size_t rx_bytes() const { return m_rx_bytes; }
private:
/// Start asynchronous socket read.
void async_read() {
m_socket.async_receive_from(m_in_buffer.space(), m_sender_endpoint,
boost::bind(&basic_udp_receiver::handle_read,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/// Handle completion of a read operation.
void handle_read(const boost::system::error_code& e, std::size_t n) {
if (!e && n > 0) {
m_rx_bytes += n;
m_in_buffer.commit(n);
static_cast<Derived*>(this)->on_data(m_in_buffer);
m_in_buffer.crunch();
async_read();
}
}
/// The io_service used to perform asynchronous operations.
boost::asio::io_service& m_io_service;
/// Socket for basic_udp_receiver
boost::asio::ip::udp::socket m_socket;
/// Sender address
boost::asio::ip::udp::endpoint m_sender_endpoint;
/// Buffer for incoming data.
buffer_type m_in_buffer;
/// Total number of bytes read from socket
size_t m_rx_bytes;
};
} // namespace io
} // namespace util
#endif // _UTIL_IO_BASIC_UDP_RECEIVER_HPP_
<|endoftext|> |
<commit_before>/**
* @file lllocaltextureobject.cpp
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "lllocaltextureobject.h"
#include "lltexlayer.h"
#include "llviewertexture.h"
#include "lltextureentry.h"
#include "lluuid.h"
#include "llwearable.h"
LLLocalTextureObject::LLLocalTextureObject() :
mIsBakedReady(FALSE),
mDiscard(MAX_DISCARD_LEVEL+1)
{
mImage = NULL;
}
LLLocalTextureObject::LLLocalTextureObject(LLViewerFetchedTexture* image, const LLUUID& id)
{
mImage = image;
gGL.getTexUnit(0)->bind(mImage);
mID = id;
}
LLLocalTextureObject::LLLocalTextureObject(const LLLocalTextureObject& lto) :
mImage(lto.mImage),
mID(lto.mID),
mIsBakedReady(lto.mIsBakedReady),
mDiscard(lto.mDiscard)
{
U32 num_layers = lto.getNumTexLayers();
mTexLayers.reserve(num_layers);
for (U32 index = 0; index < num_layers; index++)
{
LLTexLayer* original_layer = lto.getTexLayer(index);
if (!original_layer)
{
llerrs << "could not clone Local Texture Object: unable to extract texlayer!" << llendl;
}
LLTexLayer* new_layer = new LLTexLayer(*original_layer);
new_layer->setLTO(this);
mTexLayers.push_back(new_layer);
}
}
LLLocalTextureObject::~LLLocalTextureObject()
{
}
LLViewerFetchedTexture* LLLocalTextureObject::getImage() const
{
return mImage;
}
LLTexLayer* LLLocalTextureObject::getTexLayer(U32 index) const
{
if (index >= getNumTexLayers())
{
return NULL;
}
return mTexLayers[index];
}
LLTexLayer* LLLocalTextureObject::getTexLayer(const std::string &name)
{
for( tex_layer_vec_t::iterator iter = mTexLayers.begin(); iter != mTexLayers.end(); iter++)
{
LLTexLayer *layer = *iter;
if (layer->getName().compare(name) == 0)
{
return layer;
}
}
return NULL;
}
U32 LLLocalTextureObject::getNumTexLayers() const
{
return mTexLayers.size();
}
LLUUID LLLocalTextureObject::getID() const
{
return mID;
}
S32 LLLocalTextureObject::getDiscard() const
{
return mDiscard;
}
BOOL LLLocalTextureObject::getBakedReady() const
{
return mIsBakedReady;
}
void LLLocalTextureObject::setImage(LLViewerFetchedTexture* new_image)
{
mImage = new_image;
}
BOOL LLLocalTextureObject::setTexLayer(LLTexLayer *new_tex_layer, U32 index)
{
if (index >= getNumTexLayers() )
{
return FALSE;
}
if (new_tex_layer == NULL)
{
return removeTexLayer(index);
}
LLTexLayer *layer = new LLTexLayer(*new_tex_layer);
layer->setLTO(this);
if (mTexLayers[index])
{
delete mTexLayers[index];
}
mTexLayers[index] = layer;
return TRUE;
}
BOOL LLLocalTextureObject::addTexLayer(LLTexLayer *new_tex_layer, LLWearable *wearable)
{
if (new_tex_layer == NULL)
{
return FALSE;
}
LLTexLayer *layer = new LLTexLayer(*new_tex_layer, wearable);
layer->setLTO(this);
mTexLayers.push_back(layer);
return TRUE;
}
BOOL LLLocalTextureObject::addTexLayer(LLTexLayerTemplate *new_tex_layer, LLWearable *wearable)
{
if (new_tex_layer == NULL)
{
return FALSE;
}
LLTexLayer *layer = new LLTexLayer(*new_tex_layer, this, wearable);
layer->setLTO(this);
mTexLayers.push_back(layer);
return TRUE;
}
BOOL LLLocalTextureObject::removeTexLayer(U32 index)
{
if (index >= getNumTexLayers())
{
return FALSE;
}
tex_layer_vec_t::iterator iter = mTexLayers.begin();
iter += index;
delete *iter;
mTexLayers.erase(iter);
return TRUE;
}
void LLLocalTextureObject::setID(LLUUID new_id)
{
mID = new_id;
}
void LLLocalTextureObject::setDiscard(S32 new_discard)
{
mDiscard = new_discard;
}
void LLLocalTextureObject::setBakedReady(BOOL ready)
{
mIsBakedReady = ready;
}
<commit_msg>CID-359<commit_after>/**
* @file lllocaltextureobject.cpp
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "lllocaltextureobject.h"
#include "lltexlayer.h"
#include "llviewertexture.h"
#include "lltextureentry.h"
#include "lluuid.h"
#include "llwearable.h"
LLLocalTextureObject::LLLocalTextureObject() :
mIsBakedReady(FALSE),
mDiscard(MAX_DISCARD_LEVEL+1)
{
mImage = NULL;
}
LLLocalTextureObject::LLLocalTextureObject(LLViewerFetchedTexture* image, const LLUUID& id) :
mIsBakedReady(FALSE),
mDiscard(MAX_DISCARD_LEVEL+1)
{
mImage = image;
gGL.getTexUnit(0)->bind(mImage);
mID = id;
}
LLLocalTextureObject::LLLocalTextureObject(const LLLocalTextureObject& lto) :
mImage(lto.mImage),
mID(lto.mID),
mIsBakedReady(lto.mIsBakedReady),
mDiscard(lto.mDiscard)
{
U32 num_layers = lto.getNumTexLayers();
mTexLayers.reserve(num_layers);
for (U32 index = 0; index < num_layers; index++)
{
LLTexLayer* original_layer = lto.getTexLayer(index);
if (!original_layer)
{
llerrs << "could not clone Local Texture Object: unable to extract texlayer!" << llendl;
}
LLTexLayer* new_layer = new LLTexLayer(*original_layer);
new_layer->setLTO(this);
mTexLayers.push_back(new_layer);
}
}
LLLocalTextureObject::~LLLocalTextureObject()
{
}
LLViewerFetchedTexture* LLLocalTextureObject::getImage() const
{
return mImage;
}
LLTexLayer* LLLocalTextureObject::getTexLayer(U32 index) const
{
if (index >= getNumTexLayers())
{
return NULL;
}
return mTexLayers[index];
}
LLTexLayer* LLLocalTextureObject::getTexLayer(const std::string &name)
{
for( tex_layer_vec_t::iterator iter = mTexLayers.begin(); iter != mTexLayers.end(); iter++)
{
LLTexLayer *layer = *iter;
if (layer->getName().compare(name) == 0)
{
return layer;
}
}
return NULL;
}
U32 LLLocalTextureObject::getNumTexLayers() const
{
return mTexLayers.size();
}
LLUUID LLLocalTextureObject::getID() const
{
return mID;
}
S32 LLLocalTextureObject::getDiscard() const
{
return mDiscard;
}
BOOL LLLocalTextureObject::getBakedReady() const
{
return mIsBakedReady;
}
void LLLocalTextureObject::setImage(LLViewerFetchedTexture* new_image)
{
mImage = new_image;
}
BOOL LLLocalTextureObject::setTexLayer(LLTexLayer *new_tex_layer, U32 index)
{
if (index >= getNumTexLayers() )
{
return FALSE;
}
if (new_tex_layer == NULL)
{
return removeTexLayer(index);
}
LLTexLayer *layer = new LLTexLayer(*new_tex_layer);
layer->setLTO(this);
if (mTexLayers[index])
{
delete mTexLayers[index];
}
mTexLayers[index] = layer;
return TRUE;
}
BOOL LLLocalTextureObject::addTexLayer(LLTexLayer *new_tex_layer, LLWearable *wearable)
{
if (new_tex_layer == NULL)
{
return FALSE;
}
LLTexLayer *layer = new LLTexLayer(*new_tex_layer, wearable);
layer->setLTO(this);
mTexLayers.push_back(layer);
return TRUE;
}
BOOL LLLocalTextureObject::addTexLayer(LLTexLayerTemplate *new_tex_layer, LLWearable *wearable)
{
if (new_tex_layer == NULL)
{
return FALSE;
}
LLTexLayer *layer = new LLTexLayer(*new_tex_layer, this, wearable);
layer->setLTO(this);
mTexLayers.push_back(layer);
return TRUE;
}
BOOL LLLocalTextureObject::removeTexLayer(U32 index)
{
if (index >= getNumTexLayers())
{
return FALSE;
}
tex_layer_vec_t::iterator iter = mTexLayers.begin();
iter += index;
delete *iter;
mTexLayers.erase(iter);
return TRUE;
}
void LLLocalTextureObject::setID(LLUUID new_id)
{
mID = new_id;
}
void LLLocalTextureObject::setDiscard(S32 new_discard)
{
mDiscard = new_discard;
}
void LLLocalTextureObject::setBakedReady(BOOL ready)
{
mIsBakedReady = ready;
}
<|endoftext|> |
<commit_before><commit_msg>Planning: add more debug more in iterative smoother<commit_after><|endoftext|> |
<commit_before>#include <papyrus/parser/PapyrusLexer.h>
#include <cctype>
#include <map>
namespace caprica { namespace papyrus { namespace parser {
void PapyrusLexer::setTok(TokenType tp, int consumeChars) {
cur = Token(tp);
cur.line = lineNum;
for (int i = 0; i < consumeChars; i++)
strm.get();
}
void PapyrusLexer::setTok(Token& tok) {
cur = tok;
cur.line = lineNum;
}
static std::map<std::string, TokenType, CaselessStringComparer> keywordMap {
{ "as", TokenType::kAs },
{ "auto", TokenType::kAuto },
{ "autoreadonly", TokenType::kAutoReadOnly },
{ "bool", TokenType::kBool },
{ "else", TokenType::kElse },
{ "elseif", TokenType::kElseIf },
{ "endevent", TokenType::kEndEvent },
{ "endfunction", TokenType::kEndFunction },
{ "endif", TokenType::kEndIf },
{ "endproperty", TokenType::kEndProperty },
{ "endstate", TokenType::kEndState },
{ "endwhile", TokenType::kEndWhile },
{ "event", TokenType::kEvent },
{ "extends", TokenType::kExtends },
{ "false", TokenType::kFalse },
{ "float", TokenType::kFloat },
{ "function", TokenType::kFunction },
{ "global", TokenType::kGlobal },
{ "if", TokenType::kIf },
{ "import", TokenType::kImport },
{ "int", TokenType::kInt },
{ "length", TokenType::kLength },
{ "native", TokenType::kNative },
{ "new", TokenType::kNew },
{ "none", TokenType::kNone },
{ "parent", TokenType::kParent },
{ "property", TokenType::kProperty },
{ "return", TokenType::kReturn },
{ "scriptname", TokenType::kScriptName },
{ "self", TokenType::kSelf },
{ "state", TokenType::kState },
{ "string", TokenType::kString },
{ "true", TokenType::kTrue },
{ "while", TokenType::kWhile },
// Additional speculative keywords for FO4
{ "const", TokenType::kConst },
{ "endpropertygroup", TokenType::kEndPropertyGroup },
{ "endstruct", TokenType::kEndStruct },
{ "propertygroup", TokenType::kPropertyGroup },
{ "struct", TokenType::kStruct },
{ "var", TokenType::kVar },
};
void PapyrusLexer::consume() {
StartOver:
auto c = strm.get();
switch (c) {
case -1:
return setTok(TokenType::END);
case '(':
return setTok(TokenType::LParen);
case ')':
return setTok(TokenType::RParen);
case '[':
return setTok(TokenType::LSquare);
case ']':
return setTok(TokenType::RSqaure);
case '.':
return setTok(TokenType::Dot);
case ',':
return setTok(TokenType::Comma);
case '=':
if (strm.peek() == '=')
return setTok(TokenType::CmpEq, 1);
return setTok(TokenType::Equal);
case '!':
if (strm.peek() == '=')
return setTok(TokenType::CmpNeq, 1);
return setTok(TokenType::Exclaim);
case '+':
if (strm.peek() == '=')
return setTok(TokenType::PlusEqual, 1);
return setTok(TokenType::Plus);
case '-':
if (strm.peek() == '=')
return setTok(TokenType::MinusEqual, 1);
if (isdigit(strm.peek()))
goto Number;
return setTok(TokenType::Minus);
case '*':
if (strm.peek() == '=')
return setTok(TokenType::MulEqual, 1);
return setTok(TokenType::Mul);
case '/':
if (strm.peek() == '=')
return setTok(TokenType::DivEqual, 1);
return setTok(TokenType::Div);
case '%':
if (strm.peek() == '=')
return setTok(TokenType::ModEqual, 1);
return setTok(TokenType::Mod);
case '<':
if (strm.peek() == '=')
return setTok(TokenType::CmpLte, 1);
return setTok(TokenType::CmpLt);
case '>':
if (strm.peek() == '=')
return setTok(TokenType::CmpGte, 1);
return setTok(TokenType::CmpGt);
case '|':
if (strm.peek() != '|')
fatalError("Bitwise OR is unsupported. Did you intend to use a logical or (\"||\") instead?");
return setTok(TokenType::LogicalOr);
case '&':
if (strm.peek() != '|')
fatalError("Bitwise AND is unsupported. Did you intend to use a logical and (\"&&\") instead?");
return setTok(TokenType::LogicalAnd);
Number:
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
std::ostringstream str;
str.put(c);
// It's hex.
if (c == '0' && strm.peek() == 'x') {
str.put(strm.get());
while (isxdigit(strm.peek()))
str.put(strm.get());
auto i = std::stoul(str.str(), nullptr, 16);
auto tok = Token(TokenType::Integer);
tok.iValue = (int32_t)i;
return setTok(tok);
}
// Either normal int or float.
while (isdigit(strm.peek()))
str.put(strm.get());
// It's a float.
if (strm.peek() == '.') {
str.put(strm.get());
while (isdigit(strm.peek()))
str.put(strm.get());
auto f = std::stof(str.str());
auto tok = Token(TokenType::Float);
tok.fValue = f;
return setTok(tok);
}
// It's an integer.
auto i = std::stoul(str.str());
auto tok = Token(TokenType::Integer);
tok.iValue = (int32_t)i;
return setTok(tok);
}
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
{
std::ostringstream str;
str.put(c);
while (isalnum(strm.peek()) || strm.peek() == '_')
str.put(strm.get());
auto ident = str.str();
auto f = keywordMap.find(ident);
if (f != keywordMap.end())
return setTok(f->second);
auto tok = Token(TokenType::Identifier);
tok.sValue = ident;
return setTok(tok);
}
case '"':
{
std::ostringstream str;
while (strm.peek() != '"' && strm.peek() != '\r' && strm.peek() != '\n' && strm.peek() != -1) {
if (strm.peek() == '\\') {
strm.get();
auto escapeChar = strm.get();
switch (escapeChar) {
case 'n':
str.put('\n');
break;
case 't':
str.put('\t');
break;
case '\\':
str.put('\\');
break;
case '"':
str.put('"');
break;
case -1:
fatalError("Unexpected EOF before the end of the string.");
default:
fatalError((std::string)"Unrecognized escape sequence: '\\" + (char)escapeChar + "'");
}
}
}
if (strm.peek() != '"')
fatalError("Unclosed string!");
strm.get();
auto tok = Token(TokenType::String);
tok.sValue = str.str();
return setTok(tok);
}
case ';':
{
if (strm.peek() == '/') {
// Multiline comment.
strm.get();
while (strm.peek() != -1) {
if (strm.peek() == '\r' || strm.peek() == '\n') {
auto c2 = strm.get();
if (c2 == '\r' && strm.peek() == '\n')
strm.get();
lineNum++;
}
if (strm.get() == '/' && strm.peek() == ';') {
strm.get();
goto StartOver;
}
}
fatalError("Unexpected EOF before the end of a multiline comment!");
}
// Single line comment.
while (strm.peek() != '\r' && strm.peek() != '\n' && strm.peek() != -1)
strm.get();
goto StartOver;
}
case '{':
{
std::ostringstream str;
while (strm.peek() != '}' && strm.peek() != -1)
str.put(strm.get());
if (strm.peek() == -1)
fatalError("Unexpected EOF before the end of a documentation comment!");
strm.get();
auto tok = Token(TokenType::DocComment);
tok.sValue = str.str();
return setTok(tok);
}
case '\\':
{
consume();
if (cur.type != TokenType::EOL)
fatalError("Unexpected '\'! Division is done with a forward slash '/'.");
goto StartOver;
}
case '\r':
case '\n':
{
if (c == '\r' && strm.peek() == '\n')
strm.get();
lineNum++;
return setTok(TokenType::EOL);
}
case ' ':
case '\t':
{
while (strm.peek() == ' ' || strm.peek() == '\t')
strm.get();
goto StartOver;
}
default:
fatalError((std::string)"Unexpected character '" + (char)c + "'!");
}
}
}}}
<commit_msg>Trim the leading and trailing whitespace from documentation comments, and only emit unix newlines inside of them, even if a windows newline was provided.<commit_after>#include <papyrus/parser/PapyrusLexer.h>
#include <cctype>
#include <map>
namespace caprica { namespace papyrus { namespace parser {
void PapyrusLexer::setTok(TokenType tp, int consumeChars) {
cur = Token(tp);
cur.line = lineNum;
for (int i = 0; i < consumeChars; i++)
strm.get();
}
void PapyrusLexer::setTok(Token& tok) {
cur = tok;
cur.line = lineNum;
}
static std::map<std::string, TokenType, CaselessStringComparer> keywordMap {
{ "as", TokenType::kAs },
{ "auto", TokenType::kAuto },
{ "autoreadonly", TokenType::kAutoReadOnly },
{ "bool", TokenType::kBool },
{ "else", TokenType::kElse },
{ "elseif", TokenType::kElseIf },
{ "endevent", TokenType::kEndEvent },
{ "endfunction", TokenType::kEndFunction },
{ "endif", TokenType::kEndIf },
{ "endproperty", TokenType::kEndProperty },
{ "endstate", TokenType::kEndState },
{ "endwhile", TokenType::kEndWhile },
{ "event", TokenType::kEvent },
{ "extends", TokenType::kExtends },
{ "false", TokenType::kFalse },
{ "float", TokenType::kFloat },
{ "function", TokenType::kFunction },
{ "global", TokenType::kGlobal },
{ "if", TokenType::kIf },
{ "import", TokenType::kImport },
{ "int", TokenType::kInt },
{ "length", TokenType::kLength },
{ "native", TokenType::kNative },
{ "new", TokenType::kNew },
{ "none", TokenType::kNone },
{ "parent", TokenType::kParent },
{ "property", TokenType::kProperty },
{ "return", TokenType::kReturn },
{ "scriptname", TokenType::kScriptName },
{ "self", TokenType::kSelf },
{ "state", TokenType::kState },
{ "string", TokenType::kString },
{ "true", TokenType::kTrue },
{ "while", TokenType::kWhile },
// Additional speculative keywords for FO4
{ "const", TokenType::kConst },
{ "endpropertygroup", TokenType::kEndPropertyGroup },
{ "endstruct", TokenType::kEndStruct },
{ "propertygroup", TokenType::kPropertyGroup },
{ "struct", TokenType::kStruct },
{ "var", TokenType::kVar },
};
void PapyrusLexer::consume() {
StartOver:
auto c = strm.get();
switch (c) {
case -1:
return setTok(TokenType::END);
case '(':
return setTok(TokenType::LParen);
case ')':
return setTok(TokenType::RParen);
case '[':
return setTok(TokenType::LSquare);
case ']':
return setTok(TokenType::RSqaure);
case '.':
return setTok(TokenType::Dot);
case ',':
return setTok(TokenType::Comma);
case '=':
if (strm.peek() == '=')
return setTok(TokenType::CmpEq, 1);
return setTok(TokenType::Equal);
case '!':
if (strm.peek() == '=')
return setTok(TokenType::CmpNeq, 1);
return setTok(TokenType::Exclaim);
case '+':
if (strm.peek() == '=')
return setTok(TokenType::PlusEqual, 1);
return setTok(TokenType::Plus);
case '-':
if (strm.peek() == '=')
return setTok(TokenType::MinusEqual, 1);
if (isdigit(strm.peek()))
goto Number;
return setTok(TokenType::Minus);
case '*':
if (strm.peek() == '=')
return setTok(TokenType::MulEqual, 1);
return setTok(TokenType::Mul);
case '/':
if (strm.peek() == '=')
return setTok(TokenType::DivEqual, 1);
return setTok(TokenType::Div);
case '%':
if (strm.peek() == '=')
return setTok(TokenType::ModEqual, 1);
return setTok(TokenType::Mod);
case '<':
if (strm.peek() == '=')
return setTok(TokenType::CmpLte, 1);
return setTok(TokenType::CmpLt);
case '>':
if (strm.peek() == '=')
return setTok(TokenType::CmpGte, 1);
return setTok(TokenType::CmpGt);
case '|':
if (strm.peek() != '|')
fatalError("Bitwise OR is unsupported. Did you intend to use a logical or (\"||\") instead?");
return setTok(TokenType::LogicalOr);
case '&':
if (strm.peek() != '|')
fatalError("Bitwise AND is unsupported. Did you intend to use a logical and (\"&&\") instead?");
return setTok(TokenType::LogicalAnd);
Number:
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
std::ostringstream str;
str.put(c);
// It's hex.
if (c == '0' && strm.peek() == 'x') {
str.put(strm.get());
while (isxdigit(strm.peek()))
str.put(strm.get());
auto i = std::stoul(str.str(), nullptr, 16);
auto tok = Token(TokenType::Integer);
tok.iValue = (int32_t)i;
return setTok(tok);
}
// Either normal int or float.
while (isdigit(strm.peek()))
str.put(strm.get());
// It's a float.
if (strm.peek() == '.') {
str.put(strm.get());
while (isdigit(strm.peek()))
str.put(strm.get());
auto f = std::stof(str.str());
auto tok = Token(TokenType::Float);
tok.fValue = f;
return setTok(tok);
}
// It's an integer.
auto i = std::stoul(str.str());
auto tok = Token(TokenType::Integer);
tok.iValue = (int32_t)i;
return setTok(tok);
}
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
{
std::ostringstream str;
str.put(c);
while (isalnum(strm.peek()) || strm.peek() == '_')
str.put(strm.get());
auto ident = str.str();
auto f = keywordMap.find(ident);
if (f != keywordMap.end())
return setTok(f->second);
auto tok = Token(TokenType::Identifier);
tok.sValue = ident;
return setTok(tok);
}
case '"':
{
std::ostringstream str;
while (strm.peek() != '"' && strm.peek() != '\r' && strm.peek() != '\n' && strm.peek() != -1) {
if (strm.peek() == '\\') {
strm.get();
auto escapeChar = strm.get();
switch (escapeChar) {
case 'n':
str.put('\n');
break;
case 't':
str.put('\t');
break;
case '\\':
str.put('\\');
break;
case '"':
str.put('"');
break;
case -1:
fatalError("Unexpected EOF before the end of the string.");
default:
fatalError((std::string)"Unrecognized escape sequence: '\\" + (char)escapeChar + "'");
}
}
}
if (strm.peek() != '"')
fatalError("Unclosed string!");
strm.get();
auto tok = Token(TokenType::String);
tok.sValue = str.str();
return setTok(tok);
}
case ';':
{
if (strm.peek() == '/') {
// Multiline comment.
strm.get();
while (strm.peek() != -1) {
if (strm.peek() == '\r' || strm.peek() == '\n') {
auto c2 = strm.get();
if (c2 == '\r' && strm.peek() == '\n')
strm.get();
lineNum++;
}
if (strm.get() == '/' && strm.peek() == ';') {
strm.get();
goto StartOver;
}
}
fatalError("Unexpected EOF before the end of a multiline comment!");
}
// Single line comment.
while (strm.peek() != '\r' && strm.peek() != '\n' && strm.peek() != -1)
strm.get();
goto StartOver;
}
case '{':
{
std::ostringstream str;
// Trim all leading whitespace.
while (isspace(strm.peek()))
strm.get();
while (strm.peek() != '}' && strm.peek() != -1) {
// For sanity reasons, we only put out unix newlines in the
// doc comment string.
auto c2 = strm.get();
if (c2 == '\r' && strm.peek() == '\n') {
strm.get();
str.put('\n');
} else {
// Whether this is a Unix newline, or a normal character,
// we don't care, they both get written as-is.
str.put(c2);
}
}
if (strm.peek() == -1)
fatalError("Unexpected EOF before the end of a documentation comment!");
strm.get();
auto tok = Token(TokenType::DocComment);
tok.sValue = str.str();
// Trim trailing whitespace.
if (tok.sValue.length())
tok.sValue = tok.sValue.substr(0, tok.sValue.find_last_not_of(" \t\n\v\f\r") + 1);
return setTok(tok);
}
case '\\':
{
consume();
if (cur.type != TokenType::EOL)
fatalError("Unexpected '\'! Division is done with a forward slash '/'.");
goto StartOver;
}
case '\r':
case '\n':
{
if (c == '\r' && strm.peek() == '\n')
strm.get();
lineNum++;
return setTok(TokenType::EOL);
}
case ' ':
case '\t':
{
while (strm.peek() == ' ' || strm.peek() == '\t')
strm.get();
goto StartOver;
}
default:
fatalError((std::string)"Unexpected character '" + (char)c + "'!");
}
}
}}}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkArchetypeSeriesFileNames.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef _itkArchetypeSeriesFileNames_h
#define _itkArchetypeSeriesFileNames_h
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkArchetypeSeriesFileNames.h"
#include "itkRegularExpressionSeriesFileNames.h"
#include <itksys/SystemTools.hxx>
#include <stdio.h>
#include <algorithm>
namespace itk
{
ArchetypeSeriesFileNames
::ArchetypeSeriesFileNames() :
m_Archetype("")
{
}
void
ArchetypeSeriesFileNames
::SetArchetype( const std::string &archetype )
{
if (archetype != m_Archetype)
{
m_Archetype = archetype;
this->Modified();
m_ArchetypeMTime.Modified();
}
}
unsigned int
ArchetypeSeriesFileNames
::GetNumberOfGroupings()
{
if (m_ScanTime < m_ArchetypeMTime)
{
this->Scan();
}
return m_Groupings.size();
}
const std::vector<std::string> &
ArchetypeSeriesFileNames
::GetFileNames(unsigned int group)
{
if (m_ScanTime < m_ArchetypeMTime)
{
this->Scan();
}
if (group < m_Groupings.size())
{
m_FileNames = m_Groupings[group];
}
else
{
m_FileNames.clear();
}
return m_FileNames;
}
void
ArchetypeSeriesFileNames
::Scan()
{
// For each group of contiguous numbers in m_Archetype, create a
// regular expression that is identical to m_Archetype except that
// it replaces that group of numbers with the pattern ([0-9]+).
// Each of these new strings will then be passed into a
// RegularExpressionSeriesFileNames to generate the list of those
// files that fit that pattern.
m_Groupings.clear();
std::string unixArchetype = m_Archetype;
itksys::SystemTools::ConvertToUnixSlashes(unixArchetype);
if (itksys::SystemTools::FileIsDirectory( unixArchetype.c_str() ))
{
return;
}
// Parse the fileNameName and fileNamePath
std::string fileName = itksys::SystemTools::GetFilenameName( unixArchetype.c_str() );
std::string fileNamePath = itksys::SystemTools::GetFilenamePath( unixArchetype.c_str() );
std::string pathPrefix;
// If there is no "/" in the name, the directory is not specified.
// In that case, use the default ".". This is necessary for the RegularExpressionSeriesFileNames.
if (fileNamePath == "")
{
fileNamePath = ".";
pathPrefix = "./";
}
else
{
pathPrefix = "";
}
std::vector < std::string > regExpFileNameVector;
std::string regExpString = "([0-9]+)";
std::vector < int > numGroupStart;
std::vector < int > numGroupLength;
int sIndex;
std::string::iterator sit;
for (sit = fileName.begin(); sit < fileName.end(); sit++)
{
// If the element is a number, find its starting index and length.
if ((*sit) >= '0' && (*sit) <= '9')
{
sIndex = sit - fileName.begin();
numGroupStart.push_back( sIndex );
// Loop to one past the end of the group of numbers.
while ((*sit) >= '0' && (*sit) <= '9' && sit != fileName.end() )
{
++sit;
}
numGroupLength.push_back( (sit - fileName.begin()) - sIndex );
}
}
// Create a set of regular expressions, one for each group of
// numbers in m_FileName. We walk the regular expression groups
// from right to left since numbers at the end of filenames are more
// likely to be image numbers.
int i;
for (i = (int)numGroupLength.size()-1 ; i >= 0; i--)
{
std::string regExpFileName = fileName;
regExpFileName.replace(numGroupStart[i],numGroupLength[i],regExpString);
regExpFileName = "^" + regExpFileName + "$";
regExpFileNameVector.push_back( regExpFileName );
}
// Use a RegularExpressionSeriesFileNames to find the files to return
std::vector<std::string> names;
for (i = 0; i < (int) regExpFileNameVector.size(); i++)
{
itk::RegularExpressionSeriesFileNames::Pointer fit = itk::RegularExpressionSeriesFileNames::New();
fit->SetDirectory( fileNamePath.c_str() );
fit->SetRegularExpression( regExpFileNameVector[i].c_str() );
fit->SetSubMatch(1);
fit->NumericSortOn();
names = fit->GetFileNames();
std::vector<std::string>::iterator ait;
ait = std::find(names.begin(), names.end(), pathPrefix + unixArchetype);
// Accept the list if it contains the archetype and is not the
// "trivial" list (containing only the archetype)
if ( ait != names.end() && names.size() > 1)
{
m_Groupings.push_back(names);
}
}
// if the group list is empty, create a single group containing the
// archetype
if ( m_Groupings.size() == 0 && itksys::SystemTools::FileExists(unixArchetype.c_str()))
{
std::vector<std::string> tlist;
tlist.push_back( unixArchetype );
m_Groupings.push_back( tlist );
}
m_ScanTime.Modified();
}
void
ArchetypeSeriesFileNames
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Archetype: " << m_Archetype << std::endl;
os << indent << "Number of groupings: "
<< const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings() << std::endl;
for (unsigned int j = 0; j < const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings(); j++)
{
os << indent << "Grouping #" << j << std::endl;
std::vector<std::string> group = const_cast<ArchetypeSeriesFileNames*>(this)->GetFileNames(j);
for (unsigned int i = 0; i < group.size(); i++)
{
os << indent << indent << "Filenames[" << i << "]: " << group[i] << std::endl;
}
}
}
} //namespace ITK
#endif
<commit_msg>ENH: Allow filenames that include special characters<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkArchetypeSeriesFileNames.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef _itkArchetypeSeriesFileNames_h
#define _itkArchetypeSeriesFileNames_h
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkArchetypeSeriesFileNames.h"
#include "itkRegularExpressionSeriesFileNames.h"
#include <itksys/SystemTools.hxx>
#include <stdio.h>
#include <algorithm>
namespace itk
{
ArchetypeSeriesFileNames
::ArchetypeSeriesFileNames() :
m_Archetype("")
{
}
void
ArchetypeSeriesFileNames
::SetArchetype( const std::string &archetype )
{
if (archetype != m_Archetype)
{
m_Archetype = archetype;
this->Modified();
m_ArchetypeMTime.Modified();
}
}
unsigned int
ArchetypeSeriesFileNames
::GetNumberOfGroupings()
{
if (m_ScanTime < m_ArchetypeMTime)
{
this->Scan();
}
return m_Groupings.size();
}
const std::vector<std::string> &
ArchetypeSeriesFileNames
::GetFileNames(unsigned int group)
{
if (m_ScanTime < m_ArchetypeMTime)
{
this->Scan();
}
if (group < m_Groupings.size())
{
m_FileNames = m_Groupings[group];
}
else
{
m_FileNames.clear();
}
return m_FileNames;
}
void
ArchetypeSeriesFileNames
::Scan()
{
// For each group of contiguous numbers in m_Archetype, create a
// regular expression that is identical to m_Archetype except that
// it replaces that group of numbers with the pattern ([0-9]+).
// Each of these new strings will then be passed into a
// RegularExpressionSeriesFileNames to generate the list of those
// files that fit that pattern.
m_Groupings.clear();
std::string unixArchetype = m_Archetype;
itksys::SystemTools::ConvertToUnixSlashes(unixArchetype);
if (itksys::SystemTools::FileIsDirectory( unixArchetype.c_str() ))
{
return;
}
// Parse the fileNameName and fileNamePath
std::string origFileName = itksys::SystemTools::GetFilenameName( unixArchetype.c_str() );
std::string fileNamePath = itksys::SystemTools::GetFilenamePath( unixArchetype.c_str() );
std::string pathPrefix;
// "Clean" the filename by escaping any special characters with backslashes.
// This allows us to pass in filenames that include these special characters.
std::string fileName;
for( unsigned int j = 0; j < origFileName.length(); j++ )
{
char oneChar = origFileName[j];
if( oneChar == '^' ||
oneChar == '$' ||
oneChar == '.' ||
oneChar == '[' ||
oneChar == ']' ||
oneChar == '-' ||
oneChar == '*' ||
oneChar == '+' ||
oneChar == '?' ||
oneChar == '(' ||
oneChar == ')' )
{
fileName += "\\";
}
fileName += oneChar;
}
// If there is no "/" in the name, the directory is not specified.
// In that case, use the default ".". This is necessary for the RegularExpressionSeriesFileNames.
if (fileNamePath == "")
{
fileNamePath = ".";
pathPrefix = "./";
}
else
{
pathPrefix = "";
}
std::vector < std::string > regExpFileNameVector;
std::string regExpString = "([0-9]+)";
std::vector < int > numGroupStart;
std::vector < int > numGroupLength;
int sIndex;
std::string::iterator sit;
for (sit = fileName.begin(); sit < fileName.end(); sit++)
{
// If the element is a number, find its starting index and length.
if ((*sit) >= '0' && (*sit) <= '9')
{
sIndex = sit - fileName.begin();
numGroupStart.push_back( sIndex );
// Loop to one past the end of the group of numbers.
while ((*sit) >= '0' && (*sit) <= '9' && sit != fileName.end() )
{
++sit;
}
numGroupLength.push_back( (sit - fileName.begin()) - sIndex );
}
}
// Create a set of regular expressions, one for each group of
// numbers in m_FileName. We walk the regular expression groups
// from right to left since numbers at the end of filenames are more
// likely to be image numbers.
// It is also necessary to walk backward so that the numGroupStart
// indices remain correct since the length of numbers we are replacing may
// be different from the length of regExpString.
int i;
for (i = (int)numGroupLength.size()-1 ; i >= 0; i--)
{
std::string regExpFileName = fileName;
regExpFileName.replace(numGroupStart[i],numGroupLength[i],regExpString);
// Include only filenames that exactly match this regular expression. Don't
// match filenames that have this string as a substring (ie. that have extra
// prefixes or suffixes).
regExpFileName = "^" + regExpFileName + "$";
regExpFileNameVector.push_back( regExpFileName );
}
// Use a RegularExpressionSeriesFileNames to find the files to return
std::vector<std::string> names;
for (i = 0; i < (int) regExpFileNameVector.size(); i++)
{
itk::RegularExpressionSeriesFileNames::Pointer fit = itk::RegularExpressionSeriesFileNames::New();
fit->SetDirectory( fileNamePath.c_str() );
fit->SetRegularExpression( regExpFileNameVector[i].c_str() );
fit->SetSubMatch(1);
fit->NumericSortOn();
names = fit->GetFileNames();
std::vector<std::string>::iterator ait;
ait = std::find(names.begin(), names.end(), pathPrefix + unixArchetype);
// Accept the list if it contains the archetype and is not the
// "trivial" list (containing only the archetype)
if ( ait != names.end() && names.size() > 1)
{
m_Groupings.push_back(names);
}
}
// If the group list is empty, create a single group containing the
// archetype.
if ( m_Groupings.size() == 0 && itksys::SystemTools::FileExists(unixArchetype.c_str()))
{
std::vector<std::string> tlist;
tlist.push_back( unixArchetype );
m_Groupings.push_back( tlist );
}
m_ScanTime.Modified();
}
void
ArchetypeSeriesFileNames
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Archetype: " << m_Archetype << std::endl;
os << indent << "Number of groupings: "
<< const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings() << std::endl;
for (unsigned int j = 0; j < const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings(); j++)
{
os << indent << "Grouping #" << j << std::endl;
std::vector<std::string> group = const_cast<ArchetypeSeriesFileNames*>(this)->GetFileNames(j);
for (unsigned int i = 0; i < group.size(); i++)
{
os << indent << indent << "Filenames[" << i << "]: " << group[i] << std::endl;
}
}
}
} //namespace ITK
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: filecopy.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#if defined WNT
#ifndef _SVWIN_H
#include <io.h>
#include <tools/svwin.h>
#endif
#elif defined UNX
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#endif
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "comdep.hxx"
#include <tools/fsys.hxx>
#include <tools/stream.hxx>
#include <osl/file.hxx>
using namespace ::osl;
/*************************************************************************
|*
|* FileCopier::FileCopier()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
FileCopier::FileCopier() :
nBytesTotal ( 0 ),
nBytesCopied( 0 ),
nBlockSize ( 4096 ),
pImp ( new FileCopier_Impl )
{
}
// -----------------------------------------------------------------------
FileCopier::FileCopier( const DirEntry& rSource, const DirEntry& rTarget ) :
aSource ( rSource ),
aTarget ( rTarget ),
nBytesTotal ( 0 ),
nBytesCopied( 0 ),
nBlockSize ( 4096 ),
pImp ( new FileCopier_Impl )
{
}
// -----------------------------------------------------------------------
FileCopier::FileCopier( const FileCopier& rCopier ) :
aSource ( rCopier.aSource ),
aTarget ( rCopier.aTarget ),
nBytesTotal ( 0 ),
nBytesCopied ( 0 ),
aProgressLink ( rCopier.aProgressLink ),
nBlockSize ( 4096 ),
pImp ( new FileCopier_Impl )
{
}
/*************************************************************************
|*
|* FileCopier::~FileCopier()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
FileCopier::~FileCopier()
{
delete pImp;
}
/*************************************************************************
|*
|* FileCopier::operator =()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
FileCopier& FileCopier::operator = ( const FileCopier &rCopier )
{
aSource = rCopier.aSource;
aTarget = rCopier.aTarget;
nBytesTotal = rCopier.nBytesTotal;
nBytesCopied = rCopier.nBytesCopied;
nBytesCopied = rCopier.nBytesCopied;
nBlockSize = rCopier.nBlockSize;
aProgressLink = rCopier.aProgressLink;
*pImp = *(rCopier.pImp);
return *this;
}
/*************************************************************************
|*
|* FileCopier::Progress()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
BOOL FileCopier::Progress()
{
if ( !aProgressLink )
return TRUE;
else
{
if ( aProgressLink.Call( this ) )
return TRUE;
return ( 0 == Error( ERRCODE_ABORT, 0, 0 ) );
}
}
//---------------------------------------------------------------------------
ErrCode FileCopier::Error( ErrCode eErr, const DirEntry* pSource, const DirEntry* pTarget )
{
// kein Fehler oder kein ErrorHandler?
if ( !eErr || !pImp->aErrorLink )
// => Error beibehalten
return eErr;
// sonst gesetzten ErrorHandler fragen
pImp->pErrSource = pSource;
pImp->pErrTarget = pTarget;
pImp->eErr = eErr;
ErrCode eRet = (ErrCode) pImp->aErrorLink.Call( this );
pImp->pErrSource = 0;
pImp->pErrTarget = 0;
return eRet;
}
//---------------------------------------------------------------------------
const DirEntry* FileCopier::GetErrorSource() const
{
return pImp->pErrSource;
}
//---------------------------------------------------------------------------
const DirEntry* FileCopier::GetErrorTarget() const
{
return pImp->pErrTarget;
}
//---------------------------------------------------------------------------
ErrCode FileCopier::GetError() const
{
return pImp->eErr;
}
//---------------------------------------------------------------------------
void FileCopier::SetErrorHdl( const Link &rLink )
{
pImp->aErrorLink = rLink;
}
//---------------------------------------------------------------------------
const Link& FileCopier::GetErrorHdl() const
{
return pImp->aErrorLink ;
}
/*************************************************************************
|*
|* FileCopier::Execute()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung PB 16.06.00
|*
*************************************************************************/
FSysError FileCopier::DoCopy_Impl(
const DirEntry &rSource, const DirEntry &rTarget )
{
FSysError eRet = FSYS_ERR_OK;
ErrCode eWarn = FSYS_ERR_OK;
// HPFS->FAT?
FSysPathStyle eSourceStyle = DirEntry::GetPathStyle( rSource.ImpGetTopPtr()->GetName() );
FSysPathStyle eTargetStyle = DirEntry::GetPathStyle( rTarget.ImpGetTopPtr()->GetName() );
BOOL bMakeShortNames = ( eSourceStyle == FSYS_STYLE_HPFS && eTargetStyle == FSYS_STYLE_FAT );
// Zieldateiname ggf. kuerzen
DirEntry aTgt;
if ( bMakeShortNames )
{
aTgt = rTarget.GetPath();
aTgt.MakeShortName( rTarget.GetName() );
}
else
aTgt = rTarget;
// kein Move wenn Namen gekuerzt werden muessten
if ( bMakeShortNames && FSYS_ACTION_MOVE == ( pImp->nActions & FSYS_ACTION_MOVE ) && aTgt != rTarget )
return ERRCODE_IO_NAMETOOLONG;
// source is directory?
FileStat aSourceFileStat( rSource );
if ( aSourceFileStat.IsKind( FSYS_KIND_DIR ) )
{
// recursive copy
eRet = Error( aTgt.MakeDir() ? FSYS_ERR_OK : FSYS_ERR_UNKNOWN, 0, &aTgt );
Dir aSourceDir( rSource, FSYS_KIND_DIR|FSYS_KIND_FILE );
for ( USHORT n = 0; ERRCODE_TOERROR(eRet) == FSYS_ERR_OK && n < aSourceDir.Count(); ++n )
{
const DirEntry &rSubSource = aSourceDir[n];
DirEntryFlag eFlag = rSubSource.GetFlag();
if ( eFlag != FSYS_FLAG_CURRENT && eFlag != FSYS_FLAG_PARENT )
{
DirEntry aSubTarget( aTgt );
aSubTarget += rSubSource.GetName();
eRet = DoCopy_Impl( rSubSource, aSubTarget );
if ( eRet && !eWarn )
eWarn = eRet;
}
}
}
else if ( aSourceFileStat.IsKind(FSYS_KIND_FILE) )
{
if ( ( FSYS_ACTION_KEEP_EXISTING == ( pImp->nActions & FSYS_ACTION_KEEP_EXISTING ) ) &&
aTgt.Exists() )
{
// Do not overwrite existing file in target folder.
return ERRCODE_NONE;
}
// copy file
nBytesCopied = 0;
nBytesTotal = FileStat( rSource ).GetSize();
::rtl::OUString aFileName;
FileBase::getFileURLFromSystemPath( ::rtl::OUString(rSource.GetFull()), aFileName );
SvFileStream aSrc( aFileName, STREAM_READ|STREAM_NOCREATE|STREAM_SHARE_DENYNONE );
if ( !aSrc.GetError() )
{
#ifdef UNX
struct stat buf;
if ( fstat( aSrc.GetFileHandle(), &buf ) == -1 )
eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
::rtl::OUString aTargetFileName;
FileBase::getFileURLFromSystemPath( ::rtl::OUString(aTgt.GetFull()), aTargetFileName );
SvFileStream aTargetStream( aTargetFileName, STREAM_WRITE | STREAM_TRUNC | STREAM_SHARE_DENYWRITE );
if ( !aTargetStream.GetError() )
{
#ifdef UNX
if ( fchmod( aTargetStream.GetFileHandle(), buf.st_mode ) == -1 )
eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
size_t nAllocSize = 0, nSize = 0;
char *pBuf = 0;
while ( Progress() && nSize == nAllocSize && eRet == FSYS_ERR_OK )
{
// adjust the block-size
if ( nBlockSize > nAllocSize )
{
delete[] pBuf;
nAllocSize = nBlockSize;
pBuf = new char[nAllocSize];
}
// copy one block
nSize = aSrc.Read( pBuf, nBlockSize );
aTargetStream.Write( pBuf, nSize );
if ( aTargetStream.GetError() )
eRet = Error( aTargetStream.GetError(), 0, &aTgt );
// adjust counters
nBytesCopied += nSize;
if ( nBytesCopied > nBytesTotal )
nBytesTotal = nBytesCopied;
}
delete[] pBuf;
}
else
eRet = Error( aTargetStream.GetError(), 0, &aTgt );
// unvollstaendiges File wieder loeschen
aTargetStream.Close();
if ( nBytesCopied != nBytesTotal )
{
aTgt.Kill();
}
}
else
eRet = Error( aSrc.GetError(), &rSource, 0 );
}
else if ( aSourceFileStat.IsKind(FSYS_KIND_NONE) )
eRet = Error( ERRCODE_IO_NOTEXISTS, &rSource, 0 );
else
eRet = Error( ERRCODE_IO_NOTSUPPORTED, &rSource, 0 );
#ifdef WNT
// Set LastWriteTime and Attributes of the target identical with the source
if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) )
{
WIN32_FIND_DATA fdSource;
ByteString aFullSource(aSource.GetFull(), osl_getThreadTextEncoding());
ByteString aFullTarget(aTgt.GetFull(), osl_getThreadTextEncoding());
HANDLE hFind = FindFirstFile( aFullSource.GetBuffer() , &fdSource );
if ( hFind != INVALID_HANDLE_VALUE )
{
FindClose( hFind );
HANDLE hFile = CreateFile( aFullTarget.GetBuffer(), GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile != INVALID_HANDLE_VALUE )
{
SetFileTime( hFile, NULL, NULL, &fdSource.ftLastWriteTime );
CloseHandle( hFile );
}
SetFileAttributes( aFullTarget.GetBuffer(), fdSource.dwFileAttributes );
}
}
#endif
// bei Move ggf. das File/Dir loeschen
if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) && ( pImp->nActions & FSYS_ACTION_MOVE ) )
{
ErrCode eKillErr = Error( rSource.Kill() | ERRCODE_WARNING_MASK, &rSource, 0 );
if ( eKillErr != ERRCODE_WARNING_MASK )
{
if ( rSource.Exists() )
// loeschen ging nicht => dann die Kopie wieder loeschen
aTgt.Kill( pImp->nActions );
if ( !eWarn )
eWarn = eKillErr;
}
}
return !eRet ? eWarn : eRet;
}
// -----------------------------------------------------------------------
FSysError FileCopier::Execute( FSysAction nActions )
{
return ExecuteExact( nActions );
}
// -----------------------------------------------------------------------
FSysError FileCopier::ExecuteExact( FSysAction nActions, FSysExact eExact )
{
DirEntry aAbsSource = DirEntry( aSource);
DirEntry aAbsTarget = DirEntry( aTarget );
pImp->nActions = nActions;
// check if both pathes are accessible and source and target are different
if ( !aAbsTarget.ToAbs() || !aAbsSource.ToAbs() || aAbsTarget == aAbsSource )
return FSYS_ERR_ACCESSDENIED;
// check if copy would be endless recursive into itself
if ( FSYS_ACTION_RECURSIVE == ( nActions & FSYS_ACTION_RECURSIVE ) &&
aAbsSource.Contains( aAbsTarget ) )
return ERRCODE_IO_RECURSIVE;
// target is directory?
if ( eExact == FSYS_NOTEXACT &&
FileStat( aAbsTarget ).IsKind(FSYS_KIND_DIR) && FileStat( aAbsSource ).IsKind(FSYS_KIND_FILE) )
// append name of source
aAbsTarget += aSource.GetName();
// recursive copy
return DoCopy_Impl( aAbsSource, aAbsTarget );
}
<commit_msg>INTEGRATION: CWS os2port03 (1.8.54); FILE MERGED 2008/07/16 13:45:37 obr 1.8.54.2: RESYNC: (1.8-1.9); FILE MERGED 2008/04/15 14:41:15 ydario 1.8.54.1: Issue number: i85203 Submitted by: ydario Reviewed by: ydario<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: filecopy.cxx,v $
* $Revision: 1.10 $
*
* 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_tools.hxx"
#if defined WNT
#ifndef _SVWIN_H
#include <io.h>
#include <tools/svwin.h>
#endif
#elif defined(OS2)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <share.h>
#include <io.h>
#elif defined UNX
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#endif
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "comdep.hxx"
#include <tools/fsys.hxx>
#include <tools/stream.hxx>
#include <osl/file.hxx>
using namespace ::osl;
/*************************************************************************
|*
|* FileCopier::FileCopier()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
FileCopier::FileCopier() :
nBytesTotal ( 0 ),
nBytesCopied( 0 ),
nBlockSize ( 4096 ),
pImp ( new FileCopier_Impl )
{
}
// -----------------------------------------------------------------------
FileCopier::FileCopier( const DirEntry& rSource, const DirEntry& rTarget ) :
aSource ( rSource ),
aTarget ( rTarget ),
nBytesTotal ( 0 ),
nBytesCopied( 0 ),
nBlockSize ( 4096 ),
pImp ( new FileCopier_Impl )
{
}
// -----------------------------------------------------------------------
FileCopier::FileCopier( const FileCopier& rCopier ) :
aSource ( rCopier.aSource ),
aTarget ( rCopier.aTarget ),
nBytesTotal ( 0 ),
nBytesCopied ( 0 ),
aProgressLink ( rCopier.aProgressLink ),
nBlockSize ( 4096 ),
pImp ( new FileCopier_Impl )
{
}
/*************************************************************************
|*
|* FileCopier::~FileCopier()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
FileCopier::~FileCopier()
{
delete pImp;
}
/*************************************************************************
|*
|* FileCopier::operator =()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
FileCopier& FileCopier::operator = ( const FileCopier &rCopier )
{
aSource = rCopier.aSource;
aTarget = rCopier.aTarget;
nBytesTotal = rCopier.nBytesTotal;
nBytesCopied = rCopier.nBytesCopied;
nBytesCopied = rCopier.nBytesCopied;
nBlockSize = rCopier.nBlockSize;
aProgressLink = rCopier.aProgressLink;
*pImp = *(rCopier.pImp);
return *this;
}
/*************************************************************************
|*
|* FileCopier::Progress()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung MI 13.04.94
|*
*************************************************************************/
BOOL FileCopier::Progress()
{
if ( !aProgressLink )
return TRUE;
else
{
if ( aProgressLink.Call( this ) )
return TRUE;
return ( 0 == Error( ERRCODE_ABORT, 0, 0 ) );
}
}
//---------------------------------------------------------------------------
ErrCode FileCopier::Error( ErrCode eErr, const DirEntry* pSource, const DirEntry* pTarget )
{
// kein Fehler oder kein ErrorHandler?
if ( !eErr || !pImp->aErrorLink )
// => Error beibehalten
return eErr;
// sonst gesetzten ErrorHandler fragen
pImp->pErrSource = pSource;
pImp->pErrTarget = pTarget;
pImp->eErr = eErr;
ErrCode eRet = (ErrCode) pImp->aErrorLink.Call( this );
pImp->pErrSource = 0;
pImp->pErrTarget = 0;
return eRet;
}
//---------------------------------------------------------------------------
const DirEntry* FileCopier::GetErrorSource() const
{
return pImp->pErrSource;
}
//---------------------------------------------------------------------------
const DirEntry* FileCopier::GetErrorTarget() const
{
return pImp->pErrTarget;
}
//---------------------------------------------------------------------------
ErrCode FileCopier::GetError() const
{
return pImp->eErr;
}
//---------------------------------------------------------------------------
void FileCopier::SetErrorHdl( const Link &rLink )
{
pImp->aErrorLink = rLink;
}
//---------------------------------------------------------------------------
const Link& FileCopier::GetErrorHdl() const
{
return pImp->aErrorLink ;
}
/*************************************************************************
|*
|* FileCopier::Execute()
|*
|* Beschreibung FSYS.SDW
|* Ersterstellung MI 13.04.94
|* Letzte Aenderung PB 16.06.00
|*
*************************************************************************/
FSysError FileCopier::DoCopy_Impl(
const DirEntry &rSource, const DirEntry &rTarget )
{
FSysError eRet = FSYS_ERR_OK;
ErrCode eWarn = FSYS_ERR_OK;
// HPFS->FAT?
FSysPathStyle eSourceStyle = DirEntry::GetPathStyle( rSource.ImpGetTopPtr()->GetName() );
FSysPathStyle eTargetStyle = DirEntry::GetPathStyle( rTarget.ImpGetTopPtr()->GetName() );
BOOL bMakeShortNames = ( eSourceStyle == FSYS_STYLE_HPFS && eTargetStyle == FSYS_STYLE_FAT );
// Zieldateiname ggf. kuerzen
DirEntry aTgt;
if ( bMakeShortNames )
{
aTgt = rTarget.GetPath();
aTgt.MakeShortName( rTarget.GetName() );
}
else
aTgt = rTarget;
// kein Move wenn Namen gekuerzt werden muessten
if ( bMakeShortNames && FSYS_ACTION_MOVE == ( pImp->nActions & FSYS_ACTION_MOVE ) && aTgt != rTarget )
return ERRCODE_IO_NAMETOOLONG;
// source is directory?
FileStat aSourceFileStat( rSource );
if ( aSourceFileStat.IsKind( FSYS_KIND_DIR ) )
{
#ifdef OS2
CHAR szSource[CCHMAXPATHCOMP];
HOBJECT hSourceObject;
strcpy(szSource, ByteString(rSource.GetFull(), osl_getThreadTextEncoding()).GetBuffer());
hSourceObject = WinQueryObject(szSource);
if ( hSourceObject )
{
PSZ pszSourceName;
PSZ pszTargetName;
CHAR szTarget[CCHMAXPATHCOMP];
HOBJECT hTargetObject;
HOBJECT hReturn = NULLHANDLE;
strcpy(szTarget, ByteString(rTarget.GetFull(), osl_getThreadTextEncoding()).GetBuffer());
pszTargetName = strrchr(szTarget, '\\');
pszSourceName = strrchr(szSource, '\\');
hTargetObject = WinQueryObject(szTarget);
if ( hTargetObject )
WinDestroyObject(hTargetObject);
if ( pszTargetName && pszSourceName )
{
*pszTargetName = '\0';
pszSourceName++;
pszTargetName++;
if(strcmp(pszSourceName, pszTargetName) == 0)
{
hTargetObject = WinQueryObject(szTarget);
if(pImp->nActions & FSYS_ACTION_MOVE)
{
hReturn = WinMoveObject(hSourceObject, hTargetObject, 0);
}
else
{
hReturn = WinCopyObject(hSourceObject, hTargetObject, 0);
}
if ( bMakeShortNames && aTarget.Exists() )
aTarget.Kill();
return hReturn ? FSYS_ERR_OK : FSYS_ERR_UNKNOWN;
}
}
}
#endif
// recursive copy
eRet = Error( aTgt.MakeDir() ? FSYS_ERR_OK : FSYS_ERR_UNKNOWN, 0, &aTgt );
Dir aSourceDir( rSource, FSYS_KIND_DIR|FSYS_KIND_FILE );
for ( USHORT n = 0; ERRCODE_TOERROR(eRet) == FSYS_ERR_OK && n < aSourceDir.Count(); ++n )
{
const DirEntry &rSubSource = aSourceDir[n];
DirEntryFlag eFlag = rSubSource.GetFlag();
if ( eFlag != FSYS_FLAG_CURRENT && eFlag != FSYS_FLAG_PARENT )
{
DirEntry aSubTarget( aTgt );
aSubTarget += rSubSource.GetName();
eRet = DoCopy_Impl( rSubSource, aSubTarget );
if ( eRet && !eWarn )
eWarn = eRet;
}
}
}
else if ( aSourceFileStat.IsKind(FSYS_KIND_FILE) )
{
if ( ( FSYS_ACTION_KEEP_EXISTING == ( pImp->nActions & FSYS_ACTION_KEEP_EXISTING ) ) &&
aTgt.Exists() )
{
// Do not overwrite existing file in target folder.
return ERRCODE_NONE;
}
// copy file
nBytesCopied = 0;
nBytesTotal = FileStat( rSource ).GetSize();
::rtl::OUString aFileName;
FileBase::getFileURLFromSystemPath( ::rtl::OUString(rSource.GetFull()), aFileName );
SvFileStream aSrc( aFileName, STREAM_READ|STREAM_NOCREATE|STREAM_SHARE_DENYNONE );
if ( !aSrc.GetError() )
{
#ifdef UNX
struct stat buf;
if ( fstat( aSrc.GetFileHandle(), &buf ) == -1 )
eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
::rtl::OUString aTargetFileName;
FileBase::getFileURLFromSystemPath( ::rtl::OUString(aTgt.GetFull()), aTargetFileName );
SvFileStream aTargetStream( aTargetFileName, STREAM_WRITE | STREAM_TRUNC | STREAM_SHARE_DENYWRITE );
if ( !aTargetStream.GetError() )
{
#ifdef UNX
if ( fchmod( aTargetStream.GetFileHandle(), buf.st_mode ) == -1 )
eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
size_t nAllocSize = 0, nSize = 0;
char *pBuf = 0;
while ( Progress() && nSize == nAllocSize && eRet == FSYS_ERR_OK )
{
// adjust the block-size
if ( nBlockSize > nAllocSize )
{
delete[] pBuf;
nAllocSize = nBlockSize;
pBuf = new char[nAllocSize];
}
// copy one block
nSize = aSrc.Read( pBuf, nBlockSize );
aTargetStream.Write( pBuf, nSize );
if ( aTargetStream.GetError() )
eRet = Error( aTargetStream.GetError(), 0, &aTgt );
// adjust counters
nBytesCopied += nSize;
if ( nBytesCopied > nBytesTotal )
nBytesTotal = nBytesCopied;
}
delete[] pBuf;
}
else
eRet = Error( aTargetStream.GetError(), 0, &aTgt );
// unvollstaendiges File wieder loeschen
aTargetStream.Close();
if ( nBytesCopied != nBytesTotal )
{
aTgt.Kill();
}
}
else
eRet = Error( aSrc.GetError(), &rSource, 0 );
}
else if ( aSourceFileStat.IsKind(FSYS_KIND_NONE) )
eRet = Error( ERRCODE_IO_NOTEXISTS, &rSource, 0 );
else
eRet = Error( ERRCODE_IO_NOTSUPPORTED, &rSource, 0 );
#ifdef WNT
// Set LastWriteTime and Attributes of the target identical with the source
if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) )
{
WIN32_FIND_DATA fdSource;
ByteString aFullSource(aSource.GetFull(), osl_getThreadTextEncoding());
ByteString aFullTarget(aTgt.GetFull(), osl_getThreadTextEncoding());
HANDLE hFind = FindFirstFile( aFullSource.GetBuffer() , &fdSource );
if ( hFind != INVALID_HANDLE_VALUE )
{
FindClose( hFind );
HANDLE hFile = CreateFile( aFullTarget.GetBuffer(), GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile != INVALID_HANDLE_VALUE )
{
SetFileTime( hFile, NULL, NULL, &fdSource.ftLastWriteTime );
CloseHandle( hFile );
}
SetFileAttributes( aFullTarget.GetBuffer(), fdSource.dwFileAttributes );
}
}
#endif
// bei Move ggf. das File/Dir loeschen
if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) && ( pImp->nActions & FSYS_ACTION_MOVE ) )
{
ErrCode eKillErr = Error( rSource.Kill() | ERRCODE_WARNING_MASK, &rSource, 0 );
if ( eKillErr != ERRCODE_WARNING_MASK )
{
if ( rSource.Exists() )
// loeschen ging nicht => dann die Kopie wieder loeschen
aTgt.Kill( pImp->nActions );
if ( !eWarn )
eWarn = eKillErr;
}
}
return !eRet ? eWarn : eRet;
}
// -----------------------------------------------------------------------
FSysError FileCopier::Execute( FSysAction nActions )
{
return ExecuteExact( nActions );
}
// -----------------------------------------------------------------------
FSysError FileCopier::ExecuteExact( FSysAction nActions, FSysExact eExact )
{
DirEntry aAbsSource = DirEntry( aSource);
DirEntry aAbsTarget = DirEntry( aTarget );
pImp->nActions = nActions;
// check if both pathes are accessible and source and target are different
if ( !aAbsTarget.ToAbs() || !aAbsSource.ToAbs() || aAbsTarget == aAbsSource )
return FSYS_ERR_ACCESSDENIED;
// check if copy would be endless recursive into itself
if ( FSYS_ACTION_RECURSIVE == ( nActions & FSYS_ACTION_RECURSIVE ) &&
aAbsSource.Contains( aAbsTarget ) )
return ERRCODE_IO_RECURSIVE;
// target is directory?
if ( eExact == FSYS_NOTEXACT &&
FileStat( aAbsTarget ).IsKind(FSYS_KIND_DIR) && FileStat( aAbsSource ).IsKind(FSYS_KIND_FILE) )
// append name of source
aAbsTarget += aSource.GetName();
// recursive copy
return DoCopy_Impl( aAbsSource, aAbsTarget );
}
<|endoftext|> |
<commit_before><commit_msg>tools: check for data loss in WriteFraction<commit_after><|endoftext|> |
<commit_before><commit_msg>coverity#708548 Uninitialized pointer field<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2016 Matthias Fuchs
*
* 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 "stromx/zbar/Scan.h"
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/Image.h>
#include <stromx/runtime/List.h>
#include <stromx/runtime/OperatorException.h>
#include <stromx/runtime/Matrix.h>
#include <stromx/runtime/MatrixDescription.h>
#include <stromx/runtime/ReadAccess.h>
#include <stromx/runtime/Variant.h>
#include "stromx/zbar/Locale.h"
#include <zbar.h>
using namespace stromx::runtime;
namespace stromx
{
namespace zbar
{
const std::string Scan::TYPE("SCAN");
const std::string Scan::PACKAGE(STROMX_ZBAR_PACKAGE_NAME);
const runtime::Version Scan::VERSION(0, 1, 0);
Scan::Scan()
: OperatorKernel(TYPE, PACKAGE, VERSION, setupInputs(), setupOutputs(), setupParameters())
, m_zbarScanner(new ::zbar::ImageScanner)
{
}
Scan::~Scan()
{
delete m_zbarScanner;
}
const runtime::DataRef Scan::getParameter(const unsigned int id) const
{
switch(id)
{
default:
throw WrongParameterId(id, *this);
}
}
void Scan::setParameter(const unsigned int id, const runtime::Data& value)
{
try
{
switch(id)
{
default:
throw WrongParameterId(id, *this);
}
}
catch(std::bad_cast&)
{
throw WrongParameterType(parameter(id), *this);
}
}
void Scan::execute(runtime::DataProvider& provider)
{
Id2DataPair inputMapper(INPUT);
provider.receiveInputData(inputMapper);
ReadAccess access(inputMapper.data());
const runtime::Image & image = access.get<runtime::Image>();
if (! image.variant().isVariant(runtime::Variant::MONO_8_IMAGE))
throw runtime::InputError(INPUT, *this, "Wrong input data variant.");
runtime::List* symbols = new runtime::List();
DataContainer result(symbols);
provider.sendOutputData(runtime::Id2DataPair(SYMBOLS, result));
}
const std::vector<const runtime::Description*> Scan::setupInputs()
{
std::vector<const Description*> inputs;
runtime::Description* input = new runtime::Description(INPUT, runtime::Variant::MONO_8_IMAGE);
input->setTitle(L_("Input"));
inputs.push_back(input);
return inputs;
}
const std::vector<const runtime::Description*> Scan::setupOutputs()
{
std::vector<const runtime::Description*> outputs;
runtime::Description* symbols = new runtime::Description(SYMBOLS, runtime::Variant::LIST);
symbols->setTitle(L_("Symbols"));
outputs.push_back(symbols);
return outputs;
}
const std::vector<const runtime::Parameter*> Scan::setupParameters()
{
std::vector<const runtime::Parameter*> parameters;
return parameters;
}
}
}
<commit_msg>Try to scan for barcodes<commit_after>/*
* Copyright 2016 Matthias Fuchs
*
* 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 "stromx/zbar/Scan.h"
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/Image.h>
#include <stromx/runtime/List.h>
#include <stromx/runtime/OperatorException.h>
#include <stromx/runtime/Matrix.h>
#include <stromx/runtime/MatrixDescription.h>
#include <stromx/runtime/ReadAccess.h>
#include <stromx/runtime/String.h>
#include <stromx/runtime/Variant.h>
#include "stromx/zbar/Locale.h"
#include <zbar.h>
using namespace stromx::runtime;
namespace stromx
{
namespace zbar
{
const std::string Scan::TYPE("SCAN");
const std::string Scan::PACKAGE(STROMX_ZBAR_PACKAGE_NAME);
const runtime::Version Scan::VERSION(0, 1, 0);
Scan::Scan()
: OperatorKernel(TYPE, PACKAGE, VERSION, setupInputs(), setupOutputs(), setupParameters())
, m_zbarScanner(new ::zbar::ImageScanner)
{
}
Scan::~Scan()
{
delete m_zbarScanner;
}
const runtime::DataRef Scan::getParameter(const unsigned int id) const
{
switch(id)
{
default:
throw WrongParameterId(id, *this);
}
}
void Scan::setParameter(const unsigned int id, const runtime::Data& /*value*/)
{
try
{
switch(id)
{
default:
throw WrongParameterId(id, *this);
}
}
catch(std::bad_cast&)
{
throw WrongParameterType(parameter(id), *this);
}
}
void Scan::execute(runtime::DataProvider& provider)
{
Id2DataPair inputMapper(INPUT);
provider.receiveInputData(inputMapper);
ReadAccess access(inputMapper.data());
const runtime::Image & image = access.get<runtime::Image>();
if (! image.variant().isVariant(runtime::Variant::MONO_8_IMAGE))
throw runtime::InputError(INPUT, *this, "Wrong input data variant.");
::zbar::Image zbarImage(image.width(), image.height(), "YUV8", image.data(),
image.height() * image.stride());
::zbar::ImageScanner scanner;
scanner.set_config(::zbar::zbar_symbol_type_t(0), ::zbar::ZBAR_CFG_ENABLE, 1);
scanner.scan(zbarImage);
runtime::List* symbols = new runtime::List();
const ::zbar::SymbolSet & zbarSymbols = scanner.get_results();
for (::zbar::SymbolIterator iter = zbarSymbols.symbol_begin();
iter != zbarSymbols.symbol_end();
++iter)
{
symbols->content().push_back(new String(iter->get_data()));
}
DataContainer result(symbols);
provider.sendOutputData(runtime::Id2DataPair(SYMBOLS, result));
}
const std::vector<const runtime::Description*> Scan::setupInputs()
{
std::vector<const Description*> inputs;
runtime::Description* input = new runtime::Description(INPUT, runtime::Variant::MONO_8_IMAGE);
input->setTitle(L_("Input"));
inputs.push_back(input);
return inputs;
}
const std::vector<const runtime::Description*> Scan::setupOutputs()
{
std::vector<const runtime::Description*> outputs;
runtime::Description* symbols = new runtime::Description(SYMBOLS, runtime::Variant::LIST);
symbols->setTitle(L_("Symbols"));
outputs.push_back(symbols);
return outputs;
}
const std::vector<const runtime::Parameter*> Scan::setupParameters()
{
std::vector<const runtime::Parameter*> parameters;
return parameters;
}
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.